-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfavorites.sh
1238 lines (1018 loc) · 34.9 KB
/
favorites.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
import os
import subprocess
import sys
import glob
import re
import zipfile
import configparser
FAVORITES_DEFAULT = "_@Favorites"
FAVORITES_NAMES = {"fav"}
CREATE_DEFAULT_FAVORITES = True
SETUP_ARCADE = True
CORE_PREFIX=""
SD_ROOT = "/media/fat"
STARTUP_SCRIPT = "/media/fat/linux/user-startup.sh"
EXTERNAL_FOLDER = "/media/usb0"
if os.path.exists(os.path.join(EXTERNAL_FOLDER, "games")):
EXTERNAL_FOLDER = os.path.join(EXTERNAL_FOLDER, "games")
# by default hide all the unnecessary files in the SD root when browsing
HIDE_SD_FILES = True
ALLOWED_SD_FILES = {
"_arcade",
"_console",
"_computer",
"_games",
"_other",
"_utility",
"_llapi",
"_ycarcade",
"cifs",
"games",
}
# shallow search of rbfs on sd
def all_rbfs() -> list[str]:
rbfs = []
for i in os.listdir(SD_ROOT):
if i.lower().endswith(".rbf"):
rbfs.append(i)
elif i.lower() in ALLOWED_SD_FILES:
for ic in os.listdir(os.path.join(SD_ROOT, i)):
if ic.lower().endswith(".rbf"):
rbfs.append(i + "/" + ic)
return rbfs
LLAPI_CORES = (
("ATARI7800", "Atari7800_LLAPI"),
("GAMEBOY", "Gameboy_LLAPI"),
("GBA2P", "GBA2P_LLAPI"),
("GBA", "GBA_LLAPI"),
("Genesis", "Genesis_LLAPI"),
("MegaCD", "MegaCD_LLAPI"),
("NeoGeo", "NeoGeo_LLAPI"),
("NES", "NES_LLAPI"),
("S32X", "S32X_LLAPI"),
("SGB", "SGB_LLAPI"),
("SMS", "SMS_LLAPI"),
("SNES", "SNES_LLAPI"),
("TGFX16-CD", "TurboGrafx16_LLAPI"),
("TGFX16", "TurboGrafx16_LLAPI"),
)
YC_CORES = (
("ATARI2600", "Atari7800YC"),
("ATARI7800", "Atari7800YC"),
("C64", "C64YC"),
("Coleco", "ColecoVisionYC"),
("GAMEBOY", "GameboyYC"),
("Genesis", "GenesisYC"),
("MegaCD", "MegaCDYC"),
("NeoGeo", "NeoGeoYC"),
("NES", "NESYC"),
("PSX", "PSXYC"),
("S32X", "S32XYC"),
("SGB", "SGBYC"),
("SMS", "SMSYC"),
("SNES", "SNESYC"),
("TGFX16-CD", "TurboGrafx16YC"),
("TGFX16", "TurboGrafx16YC"),
)
def find_alt_core(
alt_cores: tuple[tuple[str]], system_id: str, default_rbf: str
) -> str:
core = None
for rbf in alt_cores:
if rbf[0] == system_id:
core = rbf[1]
if core is None:
return default_rbf
for rbf in all_rbfs():
folder = os.path.dirname(rbf)
fn = os.path.basename(rbf)
if fn.startswith(core):
return os.path.join(folder, core)
return default_rbf
ALT_CORES = {
"llapi": lambda system_id, rbf: find_alt_core(LLAPI_CORES, system_id, rbf),
"yc": lambda system_id, rbf: find_alt_core(YC_CORES, system_id, rbf),
}
ALT_CORE_CONFIG = None
CORE_FILES = {".rbf", ".mra", ".mgl"}
# (<games folder name>, <relative rbf location>, (<set of file extensions>, <delay>, <type>, <index>)[])
MGL_MAP = (
("Amiga", "_Computer/Minimig", (({".adf"}, 1, "f", 0),)),
("Arcadia", "_Console/Arcadia", (({".bin"}, 1, "f", 1),)),
("AVision", "_Console/AdventureVision", (({".bin"}, 1, "f", 1),)),
("Astrocade", "_Console/Astrocade", (({".bin"}, 1, "f", 1),)),
("ATARI2600", "_Console/Atari7800", (({".a78", ".a26", ".bin"}, 1, "f", 1),)),
(
"ATARI5200",
"_Console/Atari5200",
(({".car", ".a52", ".bin", ".rom"}, 1, "s", 1),),
),
("ATARI7800", "_Console/Atari7800", (({".a78", ".a26", ".bin"}, 1, "f", 1),)),
("AtariLynx", "_Console/AtariLynx", (({".lnx"}, 1, "f", 0),)),
("C64", "_Computer/C64", (({".prg", ".crt", ".reu", ".tap"}, 1, "f", 1),)),
("ChannelF", "_Console/ChannelF", (({".rom", ".bin"}, 1, "f", 1),)),
(
"Coleco",
"_Console/ColecoVision",
(({".col", ".bin", ".rom"}, 1, "f", 1), ({".sg"}, 1, "f", 2)),
),
("CreatiVision", "_Console/CreatiVision", (({".rom", ".bin"}, 1, "f", 1),)),
("GAMEBOY2P", "_Console/Gameboy2P", (({".gb", ".gbc"}, 2, "f", 1),)),
("GAMEBOY", "_Console/Gameboy", (({".gb", ".gbc"}, 2, "f", 1),)),
("GBC", "_Console/Gameboy", (({".gbc"}, 2, "f", 1),)),
("Gamate", "_Console/Gamate", (({".bin"}, 1, "f", 1),)),
("GameNWatch", "_Console/GnW", (({".bin"}, 1, "f", 1),)),
("GameGear", "_Console/SMS", (({".gg"}, 1, "f", 2),)),
("GBA2P", "_Console/GBA2P", (({".gba"}, 2, "f", 0),)),
("GBA", "_Console/GBA", (({".gba"}, 2, "f", 1),)),
("MegaDrive", "_Console/MegaDrive", (({".bin", ".gen", ".md"}, 1, "f", 1),)),
("Genesis", "_Console/Genesis", (({".bin", ".gen", ".md"}, 1, "f", 1),)),
(
"Intellivision",
"_Console/Intellivision",
(({".rom", ".int", ".bin"}, 1, "f", 1),),
),
("MegaCD", "_Console/MegaCD", (({".cue", ".chd"}, 1, "s", 0),)),
("N64", "_Console/N64", (({".n64", ".z64"}, 1, "f", 1),)),
("NeoGeo-CD", "_Console/NeoGeo", (({".cue", ".chd"}, 1, "s", 1),),),
("NeoGeo", "_Console/NeoGeo", (({".neo"}, 1, "f", 1),),),
("NES", "_Console/NES", (({".nes", ".fds", ".nsf"}, 2, "f", 1),)),
("ODYSSEY2", "_Console/Odyssey2", (({".bin"}, 1, "f", 1),)),
("PSX", "_Console/PSX", (({".cue", ".chd"}, 1, "s", 1),)),
("PocketChallengeV2", "_Console/WonderSwan", (({".pc2"}, 1, "f", 1),)),
("PokemonMini", "_Console/PokemonMini", (({".min"}, 1, "f", 1),)),
("Saturn", "_Console/Saturn", (({".cue", ".chd"}, 1, "s", 0),)),
("S32X", "_Console/S32X", (({".32x"}, 1, "f", 1),)),
("SG1000", "_Console/ColecoVision", ({".sg"}, 1, "f", 2),),
("SGB", "_Console/SGB", (({".gb", ".gbc"}, 1, "f", 1),)),
("SMS", "_Console/SMS", (({".sms", ".sg"}, 1, "f", 1), ({".gg"}, 1, "f", 2))),
("SNES", "_Console/SNES", (({".sfc", ".smc", ".bin", ".bs"}, 2, "f", 0),)),
("SuperVision", "_Console/SuperVision", (({".bin", ".sv"}, 1, "s", 1),)),
(
"TGFX16-CD",
"_Console/TurboGrafx16",
(({".cue", ".chd"}, 1, "s", 0),),
),
(
"TGFX16",
"_Console/TurboGrafx16",
(
({".pce", ".bin"}, 1, "f", 0),
({".sgx"}, 1, "f", 1),
),
),
("VC4000", "_Console/VC4000", (({".bin"}, 1, "f", 1),)),
("VECTREX", "_Console/Vectrex", (({".ovr", ".vec", ".bin", ".rom"}, 1, "f", 1),)),
("WonderSwan", "_Console/WonderSwan", (({".wsc", ".ws"}, 1, "f", 1),)),
("WonderSwanColor", "_Console/WonderSwan", (({".wsc"}, 1, "f", 1),)),
)
SET_NAMES = {
"ATARI2600": "Atari2600",
"GBC": "GBC",
"GameGear": "GameGear",
"PocketChallengeV2": "PocketChallengeV2",
"SG1000": "SG1000",
"WonderSwanColor": "WonderSwanColor",
}
GAMES_FOLDERS = (
"/media/fat",
"/media/usb0",
"/media/usb1",
"/media/usb2",
"/media/usb3",
"/media/usb4",
"/media/usb5",
"/media/fat/cifs",
)
WINDOW_TITLE = "Favorites Manager"
WINDOW_DIMENSIONS = ["20", "75", "20"]
SELECTION_HISTORY = {
"__MAIN__": "1",
}
BAD_CHARS = '<>:"/\\|?*'
ZIP_CACHE = {}
INI_FILENAME = "favorites.ini"
INI_PATH = os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), INI_FILENAME)
if os.path.exists(INI_PATH):
ini = configparser.ConfigParser()
ini.read(INI_PATH)
ALT_CORE_CONFIG = ini.get("cores", "all", fallback=ALT_CORE_CONFIG)
if ALT_CORE_CONFIG not in ALT_CORES:
ALT_CORE_CONFIG = None
def get_system_core(system_id, rbf):
if ALT_CORE_CONFIG is None:
return rbf
else:
return ALT_CORES[ALT_CORE_CONFIG](system_id, rbf)
def get_selection(path: str):
if path in SELECTION_HISTORY:
return str(SELECTION_HISTORY[path])
else:
return ""
def set_selection(path, selection):
global SELECTION_HISTORY
SELECTION_HISTORY[path] = str(selection)
def relative_path(s: str):
return s.replace(SD_ROOT + "/", "")
# characters that aren't allowed in a filename
def has_bad_chars(s: str):
return any(i in s for i in BAD_CHARS)
def is_favorite_file(path: str):
name, ext = os.path.splitext(path)
ext = ext.lower()
if ext == ".mgl":
return True
elif (ext == ".rbf" or ext == ".mra") and os.path.islink(path):
return True
else:
return False
# check if symlink goes to an existing file
def link_valid(entry):
if os.path.islink(entry[1]):
path = os.readlink(entry[1])
else:
return False
def get_favorite_target(path: str):
name, ext = os.path.splitext(path)
if os.path.islink(path):
return os.readlink(path)
elif ext == ".mgl":
try:
with open(path, "r") as f:
match = re.search(r'path="\.\./\.\./\.\./\.\.(.+)"', f.read())
if match:
return match.group(1)
else:
match = re.search(r'path="(.+)"', f.read())
if match:
return match.group(1)
else:
return ""
except:
return ""
else:
return ""
def get_favorite_folders():
folders = []
for i in os.listdir(SD_ROOT):
path = os.path.join(SD_ROOT, i)
for part in FAVORITES_NAMES:
if os.path.isdir(path) and i.startswith("_") and part in i.lower():
folders.append(path)
return folders
def get_favorites():
favorites = []
for i in os.listdir(SD_ROOT):
path = os.path.join(SD_ROOT, i)
if is_favorite_file(path):
favorites.append([get_favorite_target(path), path])
for folder in get_favorite_folders():
for root, dirs, files in os.walk(folder):
for file in files:
path = os.path.join(root, file)
if is_favorite_file(path):
favorites.append([get_favorite_target(path), path])
return favorites
def add_favorite(core_path, favorite_path):
os.symlink(core_path, favorite_path)
def add_favorite_mgl(core_path, mgl_path, mgl_data):
entry = [core_path, mgl_path]
with open(mgl_path, "w") as f:
f.write(mgl_data)
def remove_favorite(path):
if is_favorite_file(path):
os.remove(path)
def rename_favorite(path, new_path):
os.rename(path, new_path)
# generate XML contents for MGL file
def make_mgl(rbf, delay, _type, index, path, setname):
if setname is not None:
mgl = '<mistergamedescription>\n\t' \
'<rbf>{}</rbf>\n\t' \
'<setname>{}</setname>\n\t' \
'<file delay="{}" type="{}" index="{}" path="{}"/>\n' \
'</mistergamedescription>'
return mgl.format(rbf, setname, delay, _type, index, path)
else:
mgl = '<mistergamedescription>\n\t' \
'<rbf>{}</rbf>\n\t' \
'<file delay="{}" type="{}" index="{}" path="{}"/>\n' \
'</mistergamedescription>'
return mgl.format(rbf, delay, _type, index, path)
def create_default_favorites():
default_path = os.path.join(SD_ROOT, FAVORITES_DEFAULT)
if len(get_favorite_folders()) == 0 and not os.path.exists(default_path):
os.mkdir(default_path)
def cleanup_default_favorites():
default_path = os.path.join(SD_ROOT, FAVORITES_DEFAULT)
cores_path = os.path.join(default_path, "cores")
if (
os.path.exists(default_path)
and len(os.listdir(default_path)) == 1
and os.path.exists(cores_path)
):
os.remove(cores_path)
os.rmdir(default_path)
def get_menu_output(output):
try:
return int(output)
except ValueError:
return None
# return system name from mgl file
def get_mgl_system(path):
if os.path.exists(path):
with open(path, "r") as f:
core = re.search("<rbf>.+/(.+)</rbf>", f.read())
if core:
return core.groups()[0]
def get_mgl_setname(path):
if os.path.exists(path):
try:
with open(path, "r") as f:
core = re.search("<setname>(.+)</setname>", f.read())
if core:
return core.groups()[0]
except UnicodeDecodeError:
return None
def dialog_env():
return dict(os.environ, DIALOGRC="/media/fat/Scripts/.dialogrc")
def display_main_menu():
config = get_favorites()
for folder in get_favorite_folders():
for root, dirs, files in os.walk(folder):
for dir in dirs:
path = os.path.join(root, dir)
if dir.startswith("_"):
config.append(["", path])
config.sort(key=lambda x: x[1].lower())
def menu():
args = [
"dialog",
"--title",
WINDOW_TITLE,
"--ok-label",
"Select",
"--cancel-label",
"Exit",
"--default-item",
get_selection("__MAIN__"),
"--extra-button",
"--extra-label",
"Create Folder",
"--menu",
"Add a new favorite or select an existing one to modify.",
WINDOW_DIMENSIONS[0],
WINDOW_DIMENSIONS[1],
WINDOW_DIMENSIONS[2],
"1",
"<ADD NEW FAVORITE>",
"",
"------------------",
]
if len(config) == 0:
args.append("")
args.append("No favorites found.")
number = 2
for entry in config:
args.append(str(number))
fav_file = relative_path(entry[1])
name, ext = os.path.splitext(fav_file)
if os.path.isdir(entry[1]):
name = name + "/"
if len(name) >= 65:
display = "..." + name[-62:]
else:
display = name
args.append(display)
number += 1
result = subprocess.run(args, env=dialog_env(), stderr=subprocess.PIPE)
selection = get_menu_output(result.stderr.decode())
button = get_menu_output(result.returncode)
set_selection("__MAIN__", selection)
return selection, button
selection, button = menu()
# ignore separator menu items
while selection is None and button == 0:
selection, button = menu()
if button == 0:
if selection == 1:
return "__ADD__"
else:
return config[selection - 2][1]
elif button == 3:
display_create_folder()
return display_main_menu()
else:
return None
def display_add_favorite_name(item, msg=None):
# display a message box first if there's a problem
if msg is not None:
msg_args = [
"dialog",
"--title",
WINDOW_TITLE,
"--msgbox",
msg,
WINDOW_DIMENSIONS[0],
WINDOW_DIMENSIONS[1],
]
subprocess.run(msg_args, env=dialog_env())
args = [
"dialog",
"--title",
WINDOW_TITLE,
"--inputbox",
"Enter a display name for the favorite. Dates and names.txt replacements will still apply.",
WINDOW_DIMENSIONS[0],
WINDOW_DIMENSIONS[1],
]
orig_name, ext = os.path.splitext(os.path.basename(item))
args.append(orig_name)
result = subprocess.run(args, env=dialog_env(), stderr=subprocess.PIPE)
name = str(result.stderr.decode())
button = get_menu_output(result.returncode)
if button == 0:
return name + ext
else:
return None
def display_set_name(file_type):
args = [
"dialog",
"--title",
WINDOW_TITLE,
"--inputbox",
"[Optional] Enter an alternative core name (setname). This will be used to make the core use a new config "
"file and folder with the entered name. Leave blank, or the default value, for no change.",
WINDOW_DIMENSIONS[0],
WINDOW_DIMENSIONS[1],
]
setname = ""
if file_type in SET_NAMES:
setname = SET_NAMES[file_type]
args.append(setname)
result = subprocess.run(args, env=dialog_env(), stderr=subprocess.PIPE)
name = str(result.stderr.decode())
button = get_menu_output(result.returncode)
if button == 0:
return name
else:
return None
def display_edit_folder_name(parent, default_name=None, msg=None):
if msg is not None:
msg_args = [
"dialog",
"--title",
WINDOW_TITLE,
"--msgbox",
msg,
WINDOW_DIMENSIONS[0],
WINDOW_DIMENSIONS[1],
]
subprocess.run(msg_args, env=dialog_env())
args = [
"dialog",
"--title",
WINDOW_TITLE,
"--inputbox",
"Enter a name for the folder. It must start with an underscore (_).",
WINDOW_DIMENSIONS[0],
WINDOW_DIMENSIONS[1],
default_name or "_",
]
result = subprocess.run(args, env=dialog_env(), stderr=subprocess.PIPE)
name = str(result.stderr.decode())
button = get_menu_output(result.returncode)
if button == 0:
if not name.startswith("_"):
return display_edit_folder_name(
parent, msg="Name must start with an underscore (_)."
)
elif name == "_":
return display_edit_folder_name(parent, msg="Display name cannot be empty.")
elif has_bad_chars(name):
return display_edit_folder_name(
parent,
default_name=name,
msg="Name cannot contain any of these characters: " + BAD_CHARS,
)
elif os.path.exists(os.path.join(parent, name)):
return display_edit_folder_name(
parent, default_name=name, msg="Folder with this name already exists."
)
else:
return os.path.join(parent, name)
else:
return
def display_create_folder():
parent = display_add_favorite_folder(
include_root=False, msg="Select a parent folder for the new folder."
)
if parent is None:
return
path = display_edit_folder_name(os.path.join(SD_ROOT, parent))
if path is None:
return
os.mkdir(path)
setup_arcade_files()
def display_add_favorite_folder(
include_root=True, msg="Select a folder to place favorite.", ignore_path=None
):
args = [
"dialog",
"--title",
WINDOW_TITLE,
]
if include_root:
args = args + [
"--extra-button",
"--extra-label",
"Create Folder",
]
args = args + [
"--ok-label",
"Select",
"--menu",
msg,
WINDOW_DIMENSIONS[0],
WINDOW_DIMENSIONS[1],
WINDOW_DIMENSIONS[2],
]
if include_root:
args.append("1")
args.append("<TOP LEVEL>")
idx = 2
else:
idx = 1
favorite_folders = get_favorite_folders()
folders = []
for folder in favorite_folders:
folders.append(relative_path(folder))
for root, dirs, files in os.walk(folder):
for d in dirs:
path = os.path.join(root, d)
if os.path.isdir(path) and d.startswith("_") and path != ignore_path:
folders.append(relative_path(path))
folders.sort(key=str.lower)
for item in folders:
args.append(str(idx))
args.append("{}/".format(item))
idx += 1
result = subprocess.run(args, env=dialog_env(), stderr=subprocess.PIPE)
selection = get_menu_output(result.stderr.decode())
button = get_menu_output(result.returncode)
if button == 0:
if include_root and selection == 1:
return "__ROOT__"
elif include_root:
return folders[selection - 2]
else:
return folders[selection - 1]
elif button == 3:
display_create_folder()
return display_add_favorite_folder()
else:
return None
def display_edit_favorite_name(path, msg=None, default_name=None):
if msg is not None:
msg_args = [
"dialog",
"--title",
WINDOW_TITLE,
"--msgbox",
msg,
WINDOW_DIMENSIONS[0],
WINDOW_DIMENSIONS[1],
]
subprocess.run(msg_args, env=dialog_env())
args = [
"dialog",
"--title",
WINDOW_TITLE,
"--inputbox",
"Enter a display name for the favorite. Dates and names.txt replacements will apply.",
WINDOW_DIMENSIONS[0],
WINDOW_DIMENSIONS[1],
]
orig_name, ext = os.path.splitext(os.path.basename(path))
if default_name:
args.append(default_name)
else:
args.append(orig_name)
result = subprocess.run(args, env=dialog_env(), stderr=subprocess.PIPE)
name = str(result.stderr.decode())
button = get_menu_output(result.returncode)
if button == 0:
new_path = os.path.join(os.path.dirname(path), name + ext)
if name == "":
return display_edit_favorite_name(path, msg="Name cannot be empty.")
elif has_bad_chars(name):
return display_edit_favorite_name(
path,
msg="Name cannot contain any of these characters: " + BAD_CHARS,
default_name=name,
)
elif os.path.exists(new_path):
return display_edit_favorite_name(
path, msg="Favorite with this name already exists.", default_name=name
)
rename_favorite(path, new_path)
def display_delete_favorite(path):
if os.path.isdir(path) and len(os.listdir(path)) > 1:
msg_args = [
"dialog",
"--title",
WINDOW_TITLE,
"--msgbox",
"Folder is not empty.",
WINDOW_DIMENSIONS[0],
WINDOW_DIMENSIONS[1],
]
subprocess.run(msg_args, env=dialog_env())
return
if os.path.isdir(path):
msg = f"Delete folder {relative_path(path)}?"
else:
msg = f"Delete favorite {relative_path(path)}?"
args = [
"dialog",
"--title",
WINDOW_TITLE,
"--yesno",
msg,
WINDOW_DIMENSIONS[0],
WINDOW_DIMENSIONS[1],
]
result = subprocess.run(args, env=dialog_env(), stderr=subprocess.PIPE)
button = get_menu_output(result.returncode)
if button == 0:
if os.path.isdir(path):
os.remove(os.path.join(path, "cores"))
os.rmdir(path)
else:
remove_favorite(path)
def display_modify_item(path):
name, ext = os.path.splitext(os.path.basename(path))
ext = ext.lower()
info = f"Name: {name}\n"
folder = relative_path(os.path.dirname(path))
if folder == SD_ROOT:
folder = "<TOP LEVEL>"
info += f"Folder: {folder}\n"
if ext == ".rbf":
info += "Type: Core\n"
elif ext == ".mra":
info += "Type: Arcade Core\n"
elif ext == ".mgl":
info += "Type: Game\n"
info += f"System: {get_mgl_system(path)}\n"
setname = get_mgl_setname(path)
if setname:
info += f"Set name: {setname}\n"
if os.path.isdir(path):
info += "Type: Folder\n"
else:
info += f"File: {get_favorite_target(path)}"
args = [
"dialog",
"--title",
WINDOW_TITLE,
"--ok-label",
"Select",
"--menu",
info,
WINDOW_DIMENSIONS[0],
WINDOW_DIMENSIONS[1],
WINDOW_DIMENSIONS[2],
"1",
"Rename",
"2",
"Move",
"3",
"Delete",
]
result = subprocess.run(args, env=dialog_env(), stderr=subprocess.PIPE)
selection = get_menu_output(result.stderr.decode())
button = get_menu_output(result.returncode)
if button == 0:
if selection == 1:
if os.path.isdir(path):
new_path = display_edit_folder_name(
os.path.dirname(path), default_name=name
)
if new_path:
os.rename(path, new_path)
else:
display_edit_favorite_name(path)
elif selection == 2:
folder = display_add_favorite_folder(
include_root=not os.path.isdir(path), ignore_path=path
)
if folder is not None:
if folder == "__ROOT__":
folder = ""
os.rename(path, os.path.join(SD_ROOT, folder, os.path.basename(path)))
elif selection == 3:
display_delete_favorite(path)
# go through all favorites, delete broken ones and attempt to fix updated cores
def refresh_favorites():
broken = []
for entry in get_favorites():
if not os.path.islink(entry[1]):
continue
linked = os.readlink(entry[1])
if not os.path.exists(linked):
broken.append(entry)
for entry in broken:
remove_favorite(entry[1])
# ignore core files that aren't versioned
if re.search("_\d{8}\.", entry[1]) is None:
continue
link = entry[1].rsplit("_", 1)[0]
old_target = entry[0].rsplit("_", 1)[0]
new_search = glob.glob("{}_*".format(old_target))
if len(new_search) > 0:
new_target = new_search[0]
new_link = "_".join([link, new_target.rsplit("_", 1)[1]])
add_favorite(new_target, new_link)
# run a refresh on each boot
def try_add_to_startup():
if not os.path.exists(STARTUP_SCRIPT):
return
with open(STARTUP_SCRIPT, "r") as f:
if "Startup favorites" in f.read():
return
with open(STARTUP_SCRIPT, "a") as f:
f.write(
"\n# Startup favorites\n[[ -e /media/fat/Scripts/favorites.sh ]] && /media/fat/Scripts/favorites.sh refresh\n"
)
def match_games_folder(folder: str):
for system in MGL_MAP:
for parent in GAMES_FOLDERS:
base_folder = os.path.join(parent, system[0]).lower()
games_subfolder = os.path.join(parent, "games", system[0]).lower()
folder = folder.lower()
if folder.startswith(base_folder) or folder.startswith(games_subfolder):
return system[0], system
return "__CORE__", None
def zip_path(path: str):
if path.lower().endswith(".zip"):
if zipfile.is_zipfile(path):
return path, ""
else:
return
match = re.match(r"(.*\.zip)/(.*)", path, re.IGNORECASE)
if match:
if zipfile.is_zipfile(match.group(1)):
return match.group(1), match.group(2)
def zip_files(zip_path: str, zip_folder: str):
# FIXME: is there a more efficient way to do this? it's pretty slow
full_path = os.path.join(zip_path, zip_folder)
cache = ZIP_CACHE.get(os.path.join(full_path), None)
if cache is not None:
return cache
zip = zipfile.ZipFile(zip_path)
root = zipfile.Path(zip, zip_folder + "/")
files = []
for i in root.iterdir():
if i.is_dir():
files.append(i.name + "/")
else:
files.append(i.name)
ZIP_CACHE[full_path] = files
return files
# display menu to browse for and select launcher file
def display_launcher_select(start_folder):
def menu(folder: str):
subfolders = []
files = []
file_type, mgl = match_games_folder(folder)
in_zip = zip_path(folder)
if in_zip:
dir = zip_files(*in_zip)
else:
dir = os.listdir(folder)
# pick out and sort folders and valid files
for fn in dir:
# system roms
if file_type != "__CORE__" and mgl is not None:
name, ext = os.path.splitext(fn)
if os.path.isdir(os.path.join(folder, fn)):
subfolders.append(fn)
continue
elif in_zip and fn.endswith("/"):
subfolders.append(fn[:-1])
continue
else:
for rom_type in mgl[2]:
if ext in rom_type[0] or (ext == ".zip" and not in_zip):
files.append(fn)
break
# make an exception on sd root to show a clean version
if HIDE_SD_FILES and folder == SD_ROOT:
if fn.lower() in ALLOWED_SD_FILES:
subfolders.append(fn)
continue
else:
continue
# default list/rbf and mra cores
name, ext = os.path.splitext(fn)