forked from supercoder186/SceneryPacksOrganiser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathorganiser.py
executable file
·1376 lines (1310 loc) · 64.2 KB
/
organiser.py
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 python3
import argparse
import collections
import copy
import hashlib
import locale
import os
import pathlib
import re
import shutil
import struct
import sys
import tempfile
import time
import typing
# TODO: automate these later
import py7zr
import py7zr.exceptions
import yaml
# Platform-specific imports
if sys.platform == "win32":
import win32com.client
if sys.platform == "darwin":
import Cocoa
# Global constant declarations
XP10_GLOBAL_AIRPORTS = "SCENERY_PACK Custom Scenery/Global Airports/\n"
XP12_GLOBAL_AIRPORTS = "SCENERY_PACK *GLOBAL_AIRPORTS*\n"
FILE_LINE_REL = "SCENERY_PACK Custom Scenery/"
FILE_LINE_ABS = "SCENERY_PACK "
FILE_DISAB_LINE_REL = "SCENERY_PACK_DISABLED Custom Scenery/"
FILE_DISAB_LINE_ABS = "SCENERY_PACK_DISABLED "
FILE_BEGIN = "I\n1000 Version\nSCENERY\n\n"
BUF_SIZE = 65536
# Named tuple declarations
SortPacksResult = collections.namedtuple("SortPacksResult", ["unsorted_registry", "quirks", "airports", "overlays", "meshes", "other"])
AirportData = collections.namedtuple("AirportData", ["icao_registry", "airport_registry"])
# TODO: Steam X-Plane support
class LocateXPlane:
# Ref: https://developer.x-plane.com/article/how-to-programmatically-locate-x-plane-9-or-10/
def __init__(self, verbose: int) -> None:
# External variable declarations
self.verbose = verbose
# Internal variable declarations
self.direct_lines = list()
self.steam_lines = list()
self.xplane_path = pathlib.Path()
# Find the preferences folder - this varies by system
self.prefs_folder = None
if sys.platform == "win32":
self.prefs_folder = pathlib.Path(os.path.expandvars("%USERPROFILE%/AppData/Local"))
elif sys.platform == "darwin":
self.prefs_folder = pathlib.Path(os.path.expanduser("~/Library/Preferences"))
elif sys.platform == "linux":
self.prefs_folder = pathlib.Path(os.path.expanduser("~/.x-plane"))
if self.prefs_folder is None:
print(f"Unsupported OS detected. Please report this error. Detected platform: {sys.platform}")
if self.verbose >= 1:
print(f" [I] LocateXPlane init: unsupported OS")
else:
if self.verbose >= 1:
print(f" [I] LocateXPlane init: using {self.prefs_folder}")
# Main code and return
def main(self) -> pathlib.Path:
# Fly my dear birds! Fly, and bring with you whatever X-Plane paths you could find!
self.direct_search()
self.direct_test()
self.steam_search()
# Now get user input
self.get_choice()
# Prepare data and return
return self.xplane_path
# Search direct X-Plane installs
def direct_search(self) -> None:
# Go through the text file for each X-Plane version...
if self.prefs_folder and self.prefs_folder.exists():
for version in ["_10", "_11", "_12"]:
formatted_version = version.strip("_") if version else "9"
try:
if self.verbose >= 2:
print(f" [I] LocateXPlane direct_search: reading {formatted_version}")
install_file = self.prefs_folder / f"x-plane_install{version}.txt"
with open(install_file, "r", encoding="utf-8") as file:
# ...and read its lines to get potential install paths
for install_line in file.readlines():
self.direct_lines.append([f"X-Plane {formatted_version}", install_line, install_file])
# In case the text file for this version doesn't exist
except FileNotFoundError:
if self.verbose >= 1:
print(f" [W] couldn't find {formatted_version}")
elif self.verbose >= 1:
print(" [I] LocateXPlane direct_search: folder doesn't exist")
# Search Steam X-Plane installs
def steam_search(self) -> None:
pass
# Test direct installs and remove stale paths
def direct_test(self) -> None:
# Create a copy of our record of direct lines to avoid errors with the iterable changing during iteration
direct_lines_copy = copy.deepcopy(self.direct_lines)
# Loop through the parsed lines...
for version, install_line, install_file in direct_lines_copy:
install_path = pathlib.Path(install_line.strip("\n"))
# ...and test each path to ensure it's not "old and stale". if it is...
if (install_path / "Custom Scenery").exists() and (install_path / "Resources").exists():
if self.verbose >= 2:
print(f" [I] LocateXPlane direct_test: validated {install_path}")
else:
# ...remove it from the text file!
print(f"Removing stale path {install_path} from {install_file}")
file_lines = list()
with open(self.prefs_folder / install_file, "r+", encoding="utf-8") as file:
for file_line in file.readlines():
if file_line == install_line:
continue
file_lines.append(file_line)
file.seek(0)
file.writelines(file_lines)
file.truncate()
# Oh and remove it from our record too :)
self.direct_lines.remove([version, install_line, install_file])
# Get user input
def get_choice(self) -> None:
# Add everything up to one list, then display it...
compiled_lines = self.direct_lines + self.steam_lines
if compiled_lines:
print("I found the following X-Plane installs:")
for i in range(len(compiled_lines)):
xplane_version = compiled_lines[i][0]
xplane_path = compiled_lines[i][1].strip("\n")
print(f" {i}: {xplane_version} at {xplane_path}")
print("If you want to use one of these, enter its number as shown in the list.")
print("Otherwise, enter the path to your X-Plane folder.")
# ...or if we didn't find any paths, just ask the user to input a path
else:
if self.verbose >= 1:
print(f" [I] LocateXPlane get_choice: couldn't locate any x-plane folders automatically")
print("Please enter the path to your X-Plane folder.")
# Get the user's selection, then validate it
while True:
choice = input("Enter selection here: ")
# See if it corresponds to our list. If not, treat it as its own path
try:
self.xplane_path = pathlib.Path(compiled_lines[int(choice)][1].strip("\n"))
except (ValueError, IndexError):
self.xplane_path = pathlib.Path(choice)
# Validate the path
if (self.xplane_path / "Custom Scenery").exists():
print(f" Selected path: {self.xplane_path}")
break
else:
print(" I couldn't see a Custom Scenery folder here! Please recheck your path. ")
# TODO: macOS Alias support
class SortPacks:
def __init__(self, verbose: int, xplane_path: pathlib.Path, temp_path: pathlib.Path) -> None:
# External variable declarations
self.verbose = verbose
self.xplane_path = xplane_path
self.temp_path = temp_path
# Internal variable declarations
self.icao_registry = {} # dict of ICAO codes and the number of packs serving each
self.disable_registry = {} # dict that holds the folder line and beginning line of disabled packs
self.dsferror_registry = [] # list of errored dsfs
self.unparsed_registry = [] # list of shortcuts/aliases that couldn't be parsed
self.airport_registry = {"path": [], "line": [], "icaos": []}
# Classification variable declarations
self.unsorted_registry = [] # list of packs that couldn't be classified
self.quirks = {"Prefab Apt": [], "AO Overlay": [], "AO Region": [], "AO Root": [], "SimHeaven": []}
self.airports = {"Custom": [], "Default": [], "Global": []}
self.overlays = {"Custom": [], "Default": []}
self.meshes = {"Ortho": [], "Terrain": []}
self.other = {"Plugin": [], "Library": []}
# Misc functions declarations
self.misc_functions = misc_functions(verbose)
# Main code and return
def main(self) -> tuple:
# Import disabled packs from old ini
self.import_disabled()
# Run the sorting algorithms
self.main_folders()
print()
self.main_shortcuts()
print()
self.main_aliases()
print()
# Clean up sort results
self.main_cleanup()
self.main_display()
# Prepare data and return
sort_result = SortPacksResult(
self.unsorted_registry,
self.quirks,
self.airports,
self.overlays,
self.meshes,
self.other
)
airport_data = AirportData(self.icao_registry, self.airport_registry)
return (sort_result, airport_data)
# Read old ini to get list of disabled packs
def import_disabled(self) -> None:
deployed_ini_path = self.xplane_path / "Custom Scenery" / "scenery_packs.ini"
unsorted_ini_path = self.xplane_path / "Custom Scenery" / "scenery_packs_unsorted.ini"
if deployed_ini_path.is_file():
with open(deployed_ini_path, "r", encoding="utf-8") as deployed_ini_file:
for line in deployed_ini_file.readlines():
for disabled in [FILE_DISAB_LINE_REL, FILE_DISAB_LINE_ABS]:
if line.startswith(disabled):
self.disable_registry[line.split(disabled, maxsplit=1)[1].strip("\n")[:-1]] = disabled
break
if self.verbose >= 1:
print(" [I] SortPacks import_disabled: loaded existing ini")
elif self.verbose >= 1:
print(" [I] SortPacks import_disabled: could not find ini")
# Read unsorted ini to remove packs disabled for being unclassified
if unsorted_ini_path.is_file():
with open(unsorted_ini_path, "r", encoding="utf-8") as unsorted_ini_file:
for line in unsorted_ini_file.readlines():
for disabled in [FILE_DISAB_LINE_REL, FILE_DISAB_LINE_ABS]:
if line.startswith(disabled):
try:
del self.disable_registry[line.split(disabled, maxsplit=1)[1].strip("\n")[:-1]]
break
except KeyError:
pass
if self.verbose >= 1:
print(" [I] SortPacks import_disabled: loaded unsorted ini")
elif self.verbose >= 1:
print(" [I] SortPacks import_disabled: could not find unsorted ini")
# Ask if user wants to carry these disabled packs over
if self.disable_registry:
print("I see you've disabled some packs in the current scenery_packs.ini")
while True:
choice_disable = input("Would you like to carry it over to the new ini? (yes/no or y/n): ").lower()
if choice_disable in ["y", "yes"]:
print("Ok, I will carry as much as possible over.")
break
elif choice_disable in ["n", "no"]:
print("Ok, I will not carry any of them over.")
self.disable_registry = {}
break
else:
print(" Sorry, I didn't understand.")
# Read uncompresssed DSF
# This code is adapted from https://gist.github.com/nitori/6e7be6c9f00411c12aacc1ee964aee88 - thank you very much!
# Ref: https://developer.x-plane.com/article/dsf-file-format-specification/
# Ref: https://developer.x-plane.com/article/dsf-usage-in-x-plane/
def mesh_dsf_decode(self, filepath: pathlib.Path) -> typing.Union[list, str]:
try:
size = os.stat(filepath).st_size
except FileNotFoundError:
if self.verbose >= 2:
print(f" [E] SortPacks mesh_dsf_decode: expected dsf '{str(filepath.name)}'")
print(f" extracted files from dsf: {self.misc_functions.dir_list(filepath.parent.absolute(), 'files')}")
return "ERR: DCDE: NameMatch"
footer_start = size - 16 # 16 byte (128bit) for md5 hash
digest = hashlib.md5()
try:
with open(filepath, "rb") as dsf:
# Read 8s = 8 byte string, and "i" = 1 32 bit integer (total: 12 bytes)
raw_header = dsf.read(12)
header, version = struct.unpack("<8si", raw_header)
digest.update(raw_header)
# Proceed only if the version and header match what we expect, else return a string
if version == 1 and header == b"XPLNEDSF":
# Process dsf, updating digest and dsf_data
dsf_data = []
while dsf.tell() < footer_start:
raw_atom_header = dsf.read(8)
digest.update(raw_atom_header)
# 32bit atom id + 32 bit atom_size.. total: 8 byte
atom_id, atom_size = struct.unpack("<ii", raw_atom_header)
atom_id = struct.pack(">i", atom_id) # "DAEH" -> "HEAD"
# Data size is atom_size excluding the just read 8 byte id+size header
atom_data = dsf.read(atom_size - 8)
digest.update(atom_data)
dsf_data.append((atom_id, atom_data))
# Remaining bit is the checksum, ensure it matches. If not, return a string
checksum = dsf.read()
if checksum != digest.digest():
if self.verbose >= 2:
print(f" [E] SortPacks mesh_dsf_decode: checksum mismatch")
return "ERR: DCDE: !Checksum"
# Return dsf_data
return dsf_data
# If something was wrong with the header
elif header != b"XPLNEDSF":
if header.startswith(b"7z"):
if self.verbose >= 2:
print(f" [E] SortPacks mesh_dsf_decode: got '7z' header. extraction failure?")
return "ERR: DCDE: NoExtract"
else:
if self.verbose >= 2:
print(f" [E] SortPacks mesh_dsf_decode: unknown header. got '{header}'")
return "ERR: DCDE: !XPLNEDSF"
# If something was wrong with the version
elif version != 1:
if self.verbose >= 2:
print(f" [E] SortPacks mesh_dsf_decode: unknown dsf version. got '{version}'")
return f"ERR: DCDE: v{((8 - len(str(version))) * ' ') + str(version)}"
# Safety net
except Exception as e:
if self.verbose >= 2:
print(f" [E] SortPacks mesh_dsf_decode: unhandled error '{e}'")
return "ERR: DCDE: BadDSFErr"
# Caching stuff for DSF
def mesh_dsf_cache(self, end_directory: pathlib.Path, tag: str, value: str = "", tile: str = "") -> typing.Union[str, None]:
# Attempt to fetch cache
try:
with open(end_directory.parent.absolute() / "sporganiser_cache.yaml", "r") as yaml_file:
dsf_cache_data = yaml.load(yaml_file, Loader=yaml.FullLoader)
if self.verbose >= 2:
print(f" [I] SortPacks mesh_dsf_cache: loaded cache")
except FileNotFoundError:
dsf_cache_data = {"version": 220}
# If value given, operate in write mode
if str(value) and str(tile):
# Generate hashes
sha1 = hashlib.sha1()
md5 = hashlib.md5()
with open(end_directory / tile, "rb") as dsf_file:
while True:
data = dsf_file.read(BUF_SIZE)
if not data:
break
sha1.update(data)
md5.update(data)
# Store result to speed up future runs
dsf_cache_data_new = {f"{tile}": {tag: value, "md5": md5.hexdigest(), "sha1": sha1.hexdigest()}}
dsf_cache_data.update(dsf_cache_data_new)
with open(end_directory.parent.absolute() / "sporganiser_cache.yaml", "w") as yaml_file:
yaml.dump(dsf_cache_data, yaml_file)
if self.verbose >= 2:
print(f" [I] SortPacks mesh_dsf_cache: new cache written")
# Otherwise, operate in read mode
else:
# Read cache
dsf_cache_data_iter = copy.deepcopy(dsf_cache_data)
try:
for dsf in dsf_cache_data_iter:
# Check version
if dsf == "version":
if not dsf_cache_data[dsf] == 220:
if self.verbose >= 2:
print(f" [W] SortPacks mesh_dsf_cache: unknown version tag. got '{dsf_cache_data[dsf]}'")
dsf_cache_data = {"version": 220}
break
continue
# Locate dsf cached and check that it exists
dsf_path = end_directory / dsf
if not dsf_path.exists():
if self.verbose >= 2:
print(f" [W] SortPacks mesh_dsf_cache: cached dsf '{str(dsf_path)}' doesn't exist")
del dsf_cache_data[dsf]
continue
# Hash dsf to ensure cached data is still valid
sha1 = hashlib.sha1()
md5 = hashlib.md5()
with open(dsf_path, "rb") as dsf_file:
while True:
data = dsf_file.read(BUF_SIZE)
if not data:
break
sha1.update(data)
md5.update(data)
if not (dsf_cache_data[dsf]["md5"] == md5.hexdigest() and dsf_cache_data[dsf]["sha1"] == sha1.hexdigest()):
if self.verbose >= 2:
print(f" [W] SortPacks mesh_dsf_cache: hash of cached dsf '{str(dsf_path)}' doesn't match")
del dsf_cache_data[dsf]
continue
# Attempt to get the tag data requested
try:
tag_data = dsf_cache_data[dsf][tag]
return tag_data
except KeyError:
pass
# Safety net
except Exception as e:
if self.verbose >= 2:
print(f" [E] SortPacks mesh_dsf_cache: unhandled error '{e}'")
dsf_cache_data = {"version": 220}
# Select and read DSF. Uncompress if needed and call mesh_dsf_decode()
def mesh_dsf_read(self, end_directory: pathlib.Path, tag: str, dirname: str) -> typing.Union[bool, str]:
data_flag = 0
# Attempt to fetch results from cache
dsf_read_result = self.mesh_dsf_cache(end_directory, tag)
if dsf_read_result:
data_flag = 3
# Get list of potential tile directories to search
list_dir = self.misc_functions.dir_list(end_directory, "dirs")
tile_dir = []
for dir in list_dir:
if re.search(r"[+-]\d{2}[+-]\d{3}", dir):
tile_dir.append(dir)
if not tile_dir:
if self.verbose >= 2:
print(f" [E] SortPacks mesh_dsf_read: earth nav dir is empty - '{end_directory}'")
return "ERR: READ: NDirEmpty"
# Going one tile at a time, attempt to extract a dsf from the tile
dsf_data = None
final_tile = None
final_dsf = None
for tile in tile_dir:
dsfs = self.misc_functions.dir_list(end_directory / tile, "files")
for dsf in dsfs:
# Check it's really a DSF
if not dsf.endswith(".dsf"):
continue
# Space to do per-dsf stuff, eg. dsf size map
pass
# Check if we already got what we need
if data_flag:
continue
# If not, proceed to parse the DSF
if self.verbose >= 2:
print(f" [I] SortPacks mesh_dsf_read: extracting '{end_directory / tile / dsf}'")
# Attempt to extract this DSF
try:
shutil.unpack_archive(end_directory / tile / dsf, self.temp_path / dirname / dsf[:-4])
uncomp_path = self.temp_path / dirname / dsf[:-4] / dsf
data_flag = 2
if self.verbose >= 2:
print(f" [I] SortPacks mesh_dsf_read: extracted")
# If we ran into an exception...
except Exception as e:
uncomp_path = end_directory / tile / dsf
# ...and the exception was in py7zr, it was probably uncompressed already
if isinstance(e, py7zr.exceptions.Bad7zFile) or isinstance(e, shutil.ReadError):
data_flag = 1
if self.verbose >= 2:
print(f" [I] SortPacks mesh_dsf_read: not a 7z archive. working on dsf directly")
# Otherwise, hit the safety net
else:
self.dsferror_registry.append([f"{dsf}' in '{end_directory.parent.absolute()}", "ERR: READ: MiscError"])
data_flag = 0
if self.verbose >= 2:
print(f" [E] SortPacks mesh_dsf_read: unhandled error '{e}'. working on dsf directly")
# Now attempt to decode this DSF
dsf_data = self.mesh_dsf_decode(uncomp_path)
# If it returns an error, try the next one. Else, declare the final tile and dsf
if str(dsf_data).startswith("ERR: ") or dsf_data is None:
self.dsferror_registry.append([f"{dsf} in {end_directory.parent.absolute()}", dsf_data])
data_flag = 0
if self.verbose >= 2:
print(f" [W] SortPacks mesh_dsf_read: caught '{str(dsf_data)}' from mesh_dsf_decode")
else:
final_tile = tile
final_dsf = dsf
if data_flag:
break
# If data_flag is 3, we managed to read the cache. So return it
if data_flag == 3:
return dsf_read_result
# If data_flag was never set, it means we couldn't read a dsf
elif not data_flag:
if self.verbose >= 2:
print(f" [E] SortPacks mesh_dsf_read: data flag never set, ie. no dsf could be read")
return "ERR: READ: TileEmpty"
# Search for sim/overlay in HEAD atom. If found, update cache and store result
if tag == "sim/overlay 1":
overlay = None
for atom_id, atom_data in dsf_data:
if atom_id == b"HEAD" and b"sim/overlay\x001" in atom_data:
overlay = True
break
else:
overlay = False
# Update cache
self.mesh_dsf_cache(end_directory, tag, overlay, f"{final_tile}/{final_dsf}")
# Return result
return overlay
else:
if self.verbose >= 2:
print(f" [E] SortPacks mesh_dsf_read: unspecified or unimplemented property to search - '{str(tag)}'")
return "ERR: READ: NoSpecify"
# Check if the pack is an airport
# Ref: https://developer.x-plane.com/article/airport-data-apt-dat-12-00-file-format-specification/
def process_type_apt(self, dirpath: pathlib.Path, dirname: str, file_line: str, disable: bool) -> str:
# Basic checks before we move further
apt_path = self.misc_functions.dir_contains(dirpath, None, "apt.dat")
if not apt_path:
if self.verbose >= 2:
print(" [I] SortPacks process_type_apt: 'apt.dat' file not found")
return
# Attempt several codecs starting with utf-8 in case of obscure apt.dat files
apt_lins = None
for codec in ("utf-8", "charmap", "cp1252", "cp850"):
try:
if self.verbose >= 2:
print(f" [I] SortPacks process_type_apt: reading apt.dat with '{codec}'")
with open(apt_path, "r", encoding=codec) as apt_file:
apt_lins = apt_file.readlines()
break
except UnicodeDecodeError:
pass
else:
if self.verbose >= 2:
print(f" [W] SortPacks process_type_apt: all codecs errored out")
# Loop through lines
apt_type = None
for line in apt_lins:
# Codes for airport, heliport, seaport
if line.startswith("1 ") or line.startswith("16 ") or line.startswith("17 "):
# Check if prefab, default, or global
apt_prefab = self.process_quirk_prefab(dirname)
if apt_prefab:
apt_type = apt_prefab
break
elif self.misc_functions.str_contains(dirname, ["Demo Area", "X-Plane Airports", "X-Plane Landmarks", "Aerosoft"]):
apt_type = "Default"
if self.verbose >= 2:
print(" [I] SortPacks process_type_apt: found to be default airport")
break
if apt_path and dirname == "Global Airports":
apt_type = "Global"
if self.verbose >= 2:
print(" [I] SortPacks process_type_apt: found to be global airport")
break
# Must be custom
else:
apt_type = "Custom"
# If pack is not to be disabled, note ICAO code from this line
if not disable:
splitline = line.split(maxsplit=5)
icao_code = splitline[4]
# Update icao registry
try:
self.icao_registry[icao_code] += 1
except KeyError:
self.icao_registry[icao_code] = 1
# Update airport registry
try:
reg_index = self.airport_registry["path"].index(dirpath)
self.airport_registry["icaos"][reg_index].append(icao_code)
except ValueError:
self.airport_registry["path"].append(dirpath)
self.airport_registry["line"].append(file_line)
self.airport_registry["icaos"].append([icao_code])
# Return result
return apt_type
# Classify as AutoOrtho, Ortho, Mesh, or Overlay after reading DSF and scanning folders
def process_type_mesh(self, dirpath: pathlib.Path, dirname: str) -> str:
end_path = self.misc_functions.dir_contains(dirpath, None, "Earth nav data")
# Basic check
if not end_path:
if self.verbose >= 2:
print(" [I] SortPacks process_type_mesh: 'Earth nav data' folder not found")
return
# Read DSF and check for sim/overlay. If error or None returned, log in dsf error registry
overlay = self.mesh_dsf_read(end_path, "sim/overlay 1", dirname)
if str(overlay).startswith("ERR: ") or overlay is None:
if self.verbose >= 2:
print(f" [W] SortPacks process_type_mesh: caught '{str(overlay)}' from mesh_dsf_read")
self.dsferror_registry.append([dirpath, overlay])
return
# Check for AutoOrtho and SimHeaven quirks
mesh_ao = self.process_quirk_ao(dirname)
mesh_simheaven = self.process_quirk_simheaven(dirname)
if overlay:
if mesh_ao in ["AO Overlay"]:
return mesh_ao
elif mesh_simheaven in ["SimHeaven"]:
return mesh_simheaven
elif self.misc_functions.str_contains(dirname, ["X-Plane Landmarks"]):
return "Default Overlay"
else:
return "Custom Overlay"
else:
if mesh_ao in ["AO Region", "AO Root"]:
return mesh_ao
elif self.misc_functions.dir_contains(dirpath, ["textures", "terrain"]):
return "Ortho Mesh"
else:
return "Terrain Mesh"
# Check misc types
def process_type_other(self, dirpath: pathlib.Path, dirname: str) -> str:
other_result = None
if self.misc_functions.dir_contains(dirpath, ["library.txt"], "generic"):
other_result = "Library"
# Check for SimHeaven
other_simheaven = self.process_quirk_simheaven(dirname)
if other_simheaven:
other_result = other_simheaven
if self.misc_functions.dir_contains(dirpath, ["plugins"]):
other_result = "Plugin"
if self.verbose >= 2 and other_result:
print(f" [I] SortPacks process_type_other: found to be {other_result}")
elif self.verbose >= 2:
print(f" [I] SortPacks process_type_other: neither library.txt nor plugins folder found")
return other_result
# Check if the pack is from AutoOrtho
# Called in process_type_apt after pack is confirmed to be airport
def process_quirk_ao(self, dirname: str) -> str:
ao_regions = ["na", "sa", "eur", "afr", "asi", "aus_pac"]
ao_result = None
if self.misc_functions.str_contains(dirname, ["yAutoOrtho_Overlays"]):
ao_result = "AO Overlay"
elif self.misc_functions.str_contains(dirname, [f"z_ao_{region}" for region in ao_regions]):
ao_result = "AO Region"
elif self.misc_functions.str_contains(dirname, ["z_autoortho"]):
ao_result = "AO Root"
if self.verbose >= 2 and ao_result:
print(f" [I] SortPacks process_quirk_ao: found to be {ao_result}")
return ao_result
# Check if the pack is a Prefab Airport
# Called in process_type_mesh and process_main
def process_quirk_prefab(self, dirname: str) -> str:
prefab_result = None
if self.misc_functions.str_contains(dirname, ["prefab"], casesensitive=False):
prefab_result = "Prefab Apt"
if self.verbose >= 2 and prefab_result:
print(f" [I] SortPacks process_quirk_prefab: found to be {prefab_result}")
return prefab_result
# Check if the pack is from SimHeaven
# Called in process_type_mesh and process_type_other
def process_quirk_simheaven(self, dirname: str) -> str:
simheaven_result = None
if self.misc_functions.str_contains(dirname, ["simheaven"], casesensitive=False):
simheaven_result = "SimHeaven"
if self.verbose >= 2 and simheaven_result:
print(f" [I] SortPacks process_quirk_simheaven: found to be {simheaven_result}")
return simheaven_result
# Classify the pack
def process_main(self, path, shortcut=False) -> None:
# Make sure we're not processing our own temp folder
if str(self.temp_path) in str(path):
return
# Bring data to formats required by classifier functions
abs_path = self.xplane_path / "Custom Scenery" / path
name = str(path)
classified = False
# Define path formatted for ini
if shortcut:
ini_path = str(abs_path)
else:
ini_path = str(path)
# Define line formatted for ini
disable = ini_path in self.disable_registry
if disable:
del self.disable_registry[ini_path]
if shortcut:
line = f"{FILE_DISAB_LINE_ABS}{ini_path}/\n"
else:
line = f"{FILE_DISAB_LINE_REL}{ini_path}/\n"
else:
if shortcut:
line = f"{FILE_LINE_ABS}{ini_path}/\n"
else:
line = f"{FILE_LINE_REL}{ini_path}/\n"
# First see if it's an airport
if not classified:
pack_type = self.process_type_apt(abs_path, name, line, disable)
classified = True
# Standard definitions
if pack_type in ["Global", "Default", "Custom"]:
self.airports[pack_type].append(line)
if self.verbose >= 2:
print(f" [I] SortPacks process_main: classified as '{pack_type} Airport'")
# Quirk handling
elif pack_type in ["Prefab Apt"]:
self.quirks[pack_type].append(line)
if self.verbose >= 2:
print(f" [I] SortPacks process_main: classified as quirk '{pack_type}'")
else:
classified = False
# Next, autortho, overlay, ortho or mesh
if not classified:
pack_type = self.process_type_mesh(abs_path, name)
if not pack_type:
pack_type = self.process_quirk_ao(name)
classified = True
# Standard definitions
if pack_type in ["Default Overlay", "Custom Overlay"]:
self.overlays[pack_type[:-8]].append(line)
if self.verbose >= 2:
print(f" [I] SortPacks process_main: classified as '{pack_type}'")
elif pack_type in ["Ortho Mesh", "Terrain Mesh"]:
self.meshes[pack_type[:-5]].append(line)
if self.verbose >= 2:
print(f" [I] SortPacks process_main: classified as '{pack_type}'")
# Quirk handling
elif pack_type in ["AO Overlay", "AO Region", "AO Root", "SimHeaven"]:
self.quirks[pack_type].append(line)
if self.verbose >= 2:
print(f" [I] SortPacks process_main: classified as quirk '{pack_type}'")
else:
classified = False
# Very lax checks for plugins and libraries
if not classified:
pack_type = self.process_type_other(abs_path, name)
classified = True
# Standard definitions
if pack_type in ["Plugin", "Library"]:
self.other[pack_type].append(line)
if self.verbose >= 2:
print(f" [I] SortPacks process_main: classified as '{pack_type}'")
# Quirk handling
elif pack_type in ["SimHeaven"]:
self.quirks[pack_type].append(line)
if self.verbose >= 2:
print(f" [I] SortPacks process_main: classified as quirk '{pack_type}'")
else:
classified = False
# Give up. Add this to the list of packs we couldn't sort
if not classified:
if self.verbose >= 2:
print(f" [W] SortPacks process_main: could not be classified")
if line.startswith(FILE_DISAB_LINE_ABS):
self.unsorted_registry.append(line[22:])
elif line.startswith(FILE_LINE_ABS):
self.unsorted_registry.append(line[13:])
else:
pass
# Process folders and symlinks
def main_folders(self) -> None:
maxlength = 0
folder_list = self.misc_functions.dir_list(self.xplane_path / "Custom Scenery", "dirs")
folder_list.sort()
for directory in folder_list:
if self.verbose >= 1:
print(f"Main: Starting dir: {directory}")
else:
# Whitespace padding to print in the shell
progress_str = f"Processing: {directory}"
if len(progress_str) <= maxlength:
progress_str = f"{progress_str}{' ' * (maxlength - len(progress_str))}"
else:
maxlength = len(progress_str)
print(f"\r{progress_str}", end="\r")
self.process_main(directory)
if self.verbose >= 1 and self.verbose < 2:
print(f"Main: Finished dir: {directory}")
# Process Windows Shortcuts
def main_shortcuts(self) -> None:
maxlength = 0
printed = False
shtcut_list = [
str(self.xplane_path / "Custom Scenery" / shtcut)
for shtcut in self.misc_functions.dir_list(self.xplane_path / "Custom Scenery", "files")
if shtcut.endswith(".lnk")
]
shtcut_list.sort()
if shtcut_list and sys.platform != "win32":
print(f"I found Windows .LNK shortcuts, but I'm not on Windows! Detected platform: {sys.platform}")
print("I will still attempt to read them, but I cannot guarantee anything. I would suggest you use symlinks instead.")
elif shtcut_list and sys.platform == "win32":
print("Reading .LNK shortcuts...")
# If the code raises an error internally or if we were given a garbled path, skip it and add to the list of unparsable shortcuts
for shtcut_path in shtcut_list:
try:
folder_path = self.misc_functions.parse_shortcut(shtcut_path)
if folder_path.exists():
if self.verbose >= 1:
print(f"Main: Starting shortcut: {folder_path}")
else:
# Whitespace padding to print in the shell
progress_str = f"Processing shortcut: {str(folder_path)}"
if len(progress_str) <= maxlength:
progress_str = f"{progress_str}{' ' * (maxlength - len(progress_str))}"
else:
maxlength = len(progress_str)
print(f"\r{progress_str}", end="\r")
printed = True
self.process_main(folder_path, shortcut=True)
if self.verbose >= 1 and self.verbose < 2:
print(f"Main: Finished shortcut: {folder_path}")
continue
else:
if self.verbose >= 1:
print(f"Main: Failed shortcut: {folder_path}")
# Safety net
except Exception as e:
if self.verbose >= 2:
print(f" [E] SortPacks main_shortcuts: unhandled error '{e}'")
if self.verbose >= 1:
print(f"Main: Failed shortcut: {shtcut_path}")
self.unparsed_registry.append(shtcut_path)
if printed:
print()
# Process macOS Aliases
def main_aliases(self) -> None:
maxlength = 0
printed = False
ali_list = []
files_list = self.misc_functions.dir_list(self.xplane_path / "Custom Scenery", "files")
files_list = [
str(self.xplane_path / "Custom Scenery" / file)
for file in files_list
if not file.endswith(".lnk")
]
for file_path in files_list:
try:
ali_target = self.misc_functions.parse_alias(file_path)
if ali_target and ali_target.exists():
ali_list.append((file_path, ali_target))
except Exception as e:
if self.verbose >= 2:
print(f" [E] SortPacks main_aliases: unhandled error '{e}'")
self.unparsed_registry.append(file_path)
if ali_list and sys.platform != "darwin":
print(f"I found macOS aliases, but I'm not on macOS! Detected platform: {sys.platform}")
print("I will still attempt to read them, but I cannot guarantee anything. I would suggest you use symlinks instead.")
elif ali_list and sys.platform == "darwin":
print("Reading macOS aliases...")
for ali_path, target_path in ali_list:
try:
if target_path.exists():
if self.verbose >= 1:
print(f"Main: Starting alias: {target_path}")
else:
progress_str = f"Processing alias: {str(target_path)}"
if len(progress_str) <= maxlength:
progress_str = f"{progress_str}{' ' * (maxlength - len(progress_str))}"
else:
maxlength = len(progress_str)
print(f"\r{progress_str}", end="\r")
printed = True
self.process_main(target_path, shortcut=True)
if self.verbose >= 1 and self.verbose < 2:
print(f"Main: Finished alias: {target_path}")
else:
if self.verbose >= 1:
print(f"Main: Failed alias (target does not exist): {target_path}")
self.unparsed_registry.append(ali_path)
except Exception as e:
if self.verbose >= 2:
print(f" [E] SortPacks main_aliases: unhandled error '{e}'")
if self.verbose >= 1:
print(f"Main: Failed alias: {ali_path}")
self.unparsed_registry.append(ali_path)
if printed:
print()
# Cleanup after processing
def main_cleanup(self) -> None:
# Sort tiers alphabetically
self.unsorted_registry.sort()
for key in self.quirks:
self.quirks[key].sort()
for key in self.airports:
self.airports[key].sort()
for key in self.overlays:
self.overlays[key].sort()
for key in self.meshes:
self.meshes[key].sort()
for key in self.other:
self.other[key].sort()
# Check to inject XP12 Global Airports
if not self.airports["Global"]:
if self.verbose >= 1:
print(" [I] SortPacks main_cleanup: XP10/11 global airports not found, injecting XP12 entry")
self.airports["Global"].append(XP12_GLOBAL_AIRPORTS)
# Display scary lists for the user
def main_display(self) -> None:
# Display all packs that errored when reading DSFs (if verbose)
if self.dsferror_registry and self.verbose >= 1:
print("\n[W] Main: I was unable to read DSF files from some scenery packs. Please check if they load correctly in X-Plane.")
print("[^] Main: This does not necessarily mean that the pack could not be classified. Such packs will be listed separately.")
print("[^] Main: I will list them out now with the error type.")
for dsffail in self.dsferror_registry:
print(f"[^] {dsffail[1]} in '{dsffail[0]}'")
# Display all disabled packs that couldn't be found
if self.disable_registry:
print("\nI was unable to find some packs that were tagged DISABLED in the old scenery_packs.ini.")
print("They have probably been deleted or renamed. I will list them out now:")
for pack in self.disable_registry:
print(f" {pack}")
# Display all shortcuts that couldn't be read
if self.unparsed_registry:
print("\nI was unable to parse these shortcuts:")
for shortcut in self.unparsed_registry:
print(f" {shortcut}")
print("You will need to manually paste the target location paths into the file in this format:")
print(f"{FILE_LINE_ABS}<path-to-target-location>/")
# Display all packs that couldn't be sorted and offer to write them at the top of the file
if self.unsorted_registry:
print("\nI was unable to classify some packs. Maybe the pack is empty? Otherwise, a folder-in-folder?")
print("I will list them out now")
for line in self.unsorted_registry:
line_stripped = line.strip("\n")
print(f" {line_stripped}")
print("Note that if you choose not to write them, they will be written as DISABLED packs to prevent unexpected errors.")
while True:
choice = input("Should I still write them into the ini? (yes/no or y/n): ").lower()
if choice in ["y", "yes"]:
print("Ok, I will write them at the top of the ini.")
tmp_unsorted_registry = []
for line in self.unsorted_registry:
tmp_unsorted_registry.append(f"{FILE_LINE_ABS}{line}")
self.unsorted_registry = copy.deepcopy(tmp_unsorted_registry)
break
elif choice in ["n", "no"]:
print("Ok, I will write them at the top of the ini as DISABLED packs.")
tmp_unsorted_registry = []
for line in self.unsorted_registry:
tmp_unsorted_registry.append(f"{FILE_DISAB_LINE_ABS}{line}")
self.unsorted_registry = copy.deepcopy(tmp_unsorted_registry)
break
else:
print(" Sorry, I didn't understand.")
class OverlapResolve:
def __init__(self, verbose: int, sort_result: SortPacksResult, airport_data=AirportData) -> None:
# External variable declarations
self.verbose = verbose
# Copy of sort result
self.sort_result = sort_result
# External Airport related declarations
self.icao_registry = airport_data.icao_registry
self.airport_registry = airport_data.airport_registry
self.airports = sort_result.airports
# Internal Airport related declarations
self.icao_overlaps = []
self.airport_list = {}
self.airport_list_num = 0
self.airport_resolve_choice = False
# Main code and return
def main(self) -> SortPacksResult:
# Airport overlap and resolution
self.airport_search()
self.airport_ask()
print()
self.airport_resolve()
# Prepare data and return
sort_result_new = SortPacksResult(self.sort_result.unsorted_registry,
self.sort_result.quirks,
self.airports,
self.sort_result.overlays,
self.sort_result.meshes,
self.sort_result.other)
return sort_result_new
# Go through airport registries, list out conflicts and add to our records
def airport_search(self) -> None:
# Check how many conflicting ICAOs we have and store them in icao_overlaps
for icao in self.icao_registry:
if self.icao_registry[icao] > 1:
self.icao_overlaps.append(icao)
# Display conflicting packs in a list
for reg_index in range(len(self.airport_registry["path"])):
airport_path = self.airport_registry["path"][reg_index]
airport_line = self.airport_registry["line"][reg_index]
airport_icaos = self.airport_registry["icaos"][reg_index]
# Check if this airport's ICAOs are among the conflicting ones. If not, skip it
airport_icaos_conflicting = list(set(airport_icaos) & set(self.icao_overlaps))
airport_icaos_conflicting.sort()
if airport_icaos_conflicting:
pass
else:
continue
# Print path and ICAOs
airport_icao_string = ""
for icao in airport_icaos_conflicting:
airport_icao_string += f"{icao} "
print(f" {self.airport_list_num}: '{airport_path}': {airport_icao_string[:-1]}")
# Log this with the number in list
self.airport_list[self.airport_list_num] = airport_line
# Incremenent i for the next pack
self.airport_list_num += 1
# Ask the user if they want to resolve airport overlaps
def airport_ask(self) -> None:
if self.icao_overlaps:
while True:
choice = input(f"I've listed out all airport packs with their overlapping ICAOs. Would you like to sort them now? (yes/no or y/n): ").lower()
if choice in ["y", "yes"]:
self.airport_resolve_choice = True
break
elif choice in ["n", "no"]:
print("Alright, I'll skip this part.")