-
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy path__init__.py
More file actions
4619 lines (3437 loc) · 184 KB
/
__init__.py
File metadata and controls
4619 lines (3437 loc) · 184 KB
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
# -*- coding: utf-8; -*-
# Based on original Joystick Gremlin work by Lionel Ott and other contributors - Joystick Gremlin Ex is (C) EMCS 2025
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import annotations
import os
from PySide6 import QtWidgets, QtCore, QtGui
import gremlin.base_profile
import gremlin.config
import gremlin.config
import gremlin.event_handler
from gremlin.input_types import InputType
from gremlin.input_devices import ButtonReleaseActions
import gremlin.macro
import gremlin.shared_state
import gremlin.shared_state
import gremlin.shared_state
import gremlin.singleton_decorator
import gremlin.ui.ui_common
import gremlin.ui.input_item
import gremlin.input_devices
#import gremlin.gated_handler
import enum
from gremlin.profile import safe_format, safe_read
import gremlin.util
from .SimConnectManager import *
import re
from lxml import etree
from lxml import etree as ElementTree
#from gremlin.gated_handler import *
from gremlin.ui.qdatawidget import QDataWidget
import gremlin.config
import gremlin.joystick_handling
import gremlin.actions
import gremlin.curve_handler
from gremlin.input_types import InputType
from action_plugins.map_to_simconnect.SimConnectManager import SimConnectManager
syslog = logging.getLogger("system")
class QHLine(QtWidgets.QFrame):
def __init__(self, parent = None):
super().__init__(parent)
self.setFrameShape(QtWidgets.QFrame.Shape.HLine)
self.setFrameShadow(QtWidgets.QFrame.Shadow.Sunken)
class CommandValidator(QtGui.QValidator):
''' validator for command selection '''
def __init__(self):
super().__init__()
self.commands = SimConnectManager().get_command_name_list()
def validate(self, value, pos):
clean_value = value.upper().strip()
if not clean_value or clean_value in self.commands:
# blank is ok
return QtGui.QValidator.State.Acceptable
# match all values starting with the text given
try:
r = re.compile(clean_value + "*")
for _ in filter(r.match, self.commands):
return QtGui.QValidator.State.Intermediate
except:
# invalid regex - probably a special char
pass
return QtGui.QValidator.State.Invalid
class LvarValidator(QtGui.QValidator):
''' validator for lvars selection '''
def __init__(self):
super().__init__()
self.manager = SimConnectManager()
def validate(self, value, pos):
clean_value = value.strip().casefold()
if not clean_value or clean_value in self.manager.lvars:
# blank is ok
return QtGui.QValidator.State.Acceptable
# match all values starting with the text given
try:
r = re.compile(clean_value + "*", re.IGNORECASE)
for _ in filter(r.match, self.manager.lvars):
return QtGui.QValidator.State.Intermediate
except:
# invalid regex - probably a special char
pass
return QtGui.QValidator.State.Invalid
@property
def lvars(self):
return self.manager.lvars
class SimconnectSortMode(Enum):
NotSet = auto()
AicraftAscending = auto()
AircraftDescending = auto()
Mode = auto()
class SimConnectCommandMode(Enum):
Simvar = 0 # simvar command mode
Calculator = 1 # lvar command mode
CalculatorParam = 2 # expression with parameter (axis)
@staticmethod
def to_string(value) -> str:
return _simconnect_command_mode_to_string[value]
@staticmethod
def to_enum(value):
return _simconnect_command_mode_to_enum[value]
@staticmethod
def to_display(value) -> str:
return _simconnect_command_mode_to_display[value]
@staticmethod
def to_description(value) -> str:
return _simconnect_command_mode_to_description[value]
_simconnect_command_mode_to_display = {
SimConnectCommandMode.Simvar : "SimVar",
SimConnectCommandMode.Calculator : "Calculator",
SimConnectCommandMode.CalculatorParam : "Calculator (value)",
}
_simconnect_command_mode_to_description = {
SimConnectCommandMode.Simvar : "Regular simVar",
SimConnectCommandMode.Calculator : "Evaluated RPN expression and calculator code",
SimConnectCommandMode.CalculatorParam : "Evaluated RPN expression and calculator code with axis parameter",
}
_simconnect_command_mode_to_string = {
SimConnectCommandMode.Simvar : "simvar",
SimConnectCommandMode.Calculator : "rpn",
SimConnectCommandMode.CalculatorParam : "rpnparam",
}
_simconnect_command_mode_to_enum = {
"simvar" : SimConnectCommandMode.Simvar,
"lvar" : SimConnectCommandMode.Calculator,
"rpn" : SimConnectCommandMode.Calculator,
"rpnparam" : SimConnectCommandMode.CalculatorParam,
}
class SimconnectManualDefinition():
''' holds a manual entry for a mode '''
def __init__(self,
id = None,
sim_name = None,
mode = None):
self.id = id if id else gremlin.util.get_guid()
self.sim_name = sim_name
self.mode = mode
# runtime item (not saved or loaded)
self.selected = False # for UI interation - selected mode
self.error_status = None
@property
def display_name(self):
return f"{self.sim_name}"
@property
def key(self):
if self.sim_name:
return self.sim_name.casefold()
return ""
class SimconnectAicraftDefinition():
''' holds the data entry for a single aicraft from the MSFS config data '''
class EntryType(IntEnum):
Scan = 0 # entry is coming from the manual scan of the community folder
Sim = 1 # entry is coming from the sim
def __init__(self, id = None,
mode = None, # attached GremlinEx mode for this aicraft
icao_type = None,
icao_manufacturer = None,
icao_model = None,
titles = [],
path = None,
community_path = None,
aircraft_path = None,
state_folder = None,
sim_name = None,
entry_type = None,
):
self.icao_type = icao_type
self.icao_manufacturer = icao_manufacturer
self.icao_model = icao_model
self.titles = titles
self.path = path.casefold() if path else ""
self.state_folder = state_folder.casefold() if state_folder else ""
self.mode = mode
self.sim_name = sim_name
self.id = id if id else gremlin.util.get_guid()
self.entry_type = SimconnectAicraftDefinition.EntryType.Scan if entry_type is None else entry_type
self.community_path = None
self.aircraft_path = None
if self.entry_type == SimconnectAicraftDefinition.EntryType.Scan:
assert community_path and aircraft_path,"Community path and Aircraft path are primary keys and cannot be NULL"
self.community_path = community_path.casefold() # AP
self.aircraft_path = aircraft_path.casefold() # CP
# runtime item (not saved or loaded)
self.selected = False # for UI interation - selected mode
self.error_status = None
@property
def is_scanned(self) -> bool:
''' true if the entry was scanned from the community folder '''
return self.entry_type == SimconnectAicraftDefinition.EntryType.Scan
@property
def is_scanned(self) -> bool:
''' true if the entry came from msfs user flyable data '''
return self.entry_type == SimconnectAicraftDefinition.EntryType.Sim
@property
def display_name(self):
if self.icao_manufacturer and self.icao_model:
return f"{self.icao_manufacturer} {self.icao_model}"
return self.sim_name
@property
def key(self):
''' key for this item (CP = community path, AP = aircraft path)'''
match self.entry_type:
case SimconnectAicraftDefinition.EntryType.Scan:
return (self.community_path, self.aircraft_path)
case SimconnectAicraftDefinition.EntryType.Sim:
return self.sim_name
return None
@property
def valid(self):
''' true if the item contains valid data '''
match self.entry_type:
case SimconnectAicraftDefinition.EntryType.Scan:
return not self.error_status and self.aircraft_path and self.mode
case SimconnectAicraftDefinition.EntryType.Sim:
return bool(self.sim_name) and not self.error_status
return False
def __hash__(self):
return hash(self.id)
@gremlin.singleton_decorator.SingletonDecorator
class SimconnectOptions():
''' holds simconnect mapper options for all actions '''
def __init__(self, manager : SimConnectManager):
self._manager : SimConnectManager = manager
el = gremlin.event_handler.EventListener()
el.profile_loaded.connect(self._profile_loaded) # trap profile load to update modes
el.profile_start.connect(self._profile_edit_mode_changed) # trap profile start to update modes
el.edit_mode_changed.connect(self._profile_edit_mode_changed) # trap edit mode mode changes to update modes
el.shutdown.connect(self.save) # save configuration on shutdown
self._handler = SimConnectEventHandler()
self._handler.simconnect_AircraftLiveriesReceived.connect(self._aircraft_list_loaded)
# configuration file stored in the user's GremlinEx profile
base_file = "simconnect_config.xml"
user_source = os.path.join(gremlin.util.userprofile_path(), base_file)
self._xml_source = user_source
self._auto_mode_select = True # if set, autoloads the mode associated with the aircraft if such a mode exists, on by default
self._auto_mode_lock = True # if set, mode changes other the mapped aicraft will be ignored
self._aircraft_definition_map = {} # holds definitions by aircraft container name, [name] = SimconnectAicraftDefinition
self._aircraft_manual_definitions = [] # holds manual aicraft entries
self._titles = []
self._base_community_folder = None # base of community folder
self._local_state_folder = None # local state folder for streaming data
self._community_folder = gremlin.shared_state.community_folder
self._update_folders()
# last command mode for the UI
self._last_command_mode = SimConnectCommandMode.Simvar
self._sort_mode = SimconnectSortMode.NotSet
self._mode_list = []
self._simconnect = manager.simconnect
self.parse_xml()
@property
def definitions(self) -> dict:
return self._aircraft_definition_map
def validateEntries(self) -> bool:
''' validates the manual entries to make sure they are unique '''
sim_names = []
for item in self._aircraft_manual_definitions:
if item.sim_name and item.sim_name in sim_names:
return False
sim_names.append(item.sim_name)
return True
@QtCore.Slot(dict)
def _aircraft_list_loaded(self, data):
''' triggered when simconnect sends aircraft data '''
added = False
verbose = gremlin.config.Configuration().verbose_mode_simconnect
name_list = [name for name in data.keys()]
name_list.sort(key = lambda x: x.casefold()) # sort case insensitive
for aircraft in name_list:
key = aircraft.casefold()
if "fsltl" in key or "passiveaircraft" in key:
# skip FSLTL AI aircraft
# skip passive aircraft
continue
if "a350" in key:
pass
if not key in self._aircraft_definition_map:
item = SimconnectAicraftDefinition(sim_name = aircraft,
entry_type=SimconnectAicraftDefinition.EntryType.Sim,
)
self._aircraft_definition_map[key] = item
if verbose: syslog.info(f"SIMCONNECT: add sim user aircraft: {aircraft}")
added = True
if added:
# fire the event the data changed
self._handler.AircraftDefinitionsChanged.emit()
@QtCore.Slot()
def _profile_loaded(self):
''' profile is loaded '''
self._mode_list = self.profile.get_modes()
@QtCore.Slot()
def _profile_edit_mode_changed(self):
''' profile modes changed '''
self._mode_list = self.profile.get_modes()
@property
def profile(self) -> gremlin.base_profile.Profile:
return gremlin.shared_state.current_profile
@property
def current_aircraft_folder(self):
return self._manager.current_aircraft_folder
@property
def current_aircraft_title(self):
return self._manager.current_aircraft_title
@property
def community_folder(self) -> str:
return self._community_folder
@community_folder.setter
def community_folder(self, value):
if os.path.isdir(value) and value != self._community_folder:
self._community_folder = value
gremlin.shared_state.community_folder = value
self._update_folders()
@property
def local_state_folder(self) -> str:
return self._local_state_folder
def _update_folders(self):
''' updates the folders from the community folder '''
community_folder = self._community_folder
if community_folder and os.path.isdir(community_folder):
basedir = os.path.dirname(community_folder)
base_folder = None
while basedir:
basename = os.path.basename(basedir)
if basename.startswith("Microsoft.Limitless"):
base_folder = basedir
break
basedir = os.path.dirname(basedir)
if base_folder:
self._base_community_folder = base_folder
# setup the local state folder
local_state_folder = os.path.join(base_folder, "MSFS2024 LocalState", "StreamedPackages")
if os.path.isdir(local_state_folder):
self._local_state_folder = local_state_folder
@property
def last_command_mode(self) -> SimConnectCommandMode:
return self._last_command_mode
@last_command_mode.setter
def last_command_mode(self, value: SimConnectCommandMode):
self._last_command_mode = value
def validate(self):
''' validates options are ok '''
a_list = []
valid = True
for item in self._aircraft_definition_map.values():
item.error_status = None
if item.key in a_list:
item.error_status = f"Duplicate entry found {item.display_name}"
valid = False
continue
a_list.append(item.key)
if not item.mode:
item.error_status = f"Mode not selected"
valid = False
continue
if not item.mode in self._mode_list:
item.error_status = f"Invalid mode {item.mode}"
valid = False
continue
if not item.display_name:
item.error_status = f"Aircraft name cannot be blank"
valid = False
return valid
def find_definition_by_state(self, state_string):
''' gets an item based on the state data which is a partial subfolder '''
# example: SimObjects\\Airplanes\\FNX_320_IAE\\aircraft.CFG
stub = os.path.dirname(state_string.casefold())
item : SimconnectAicraftDefinition
print (stub)
for item in self._aircraft_definition_map.values():
print (item.path)
if item.path.endswith(stub):
return item
return None
def dump(self):
''' dumps current data to the log file '''
# syslog = logging.getLogger("system")
syslog.info("Scanned entry mode configurations:")
for item in self._aircraft_definition_map.values():
syslog.info(f"\t{item.display_name} {item.sim_name} mode: {item.mode}")
syslog.info("Manual entry mode configurations:")
for item in self._aircraft_manual_definitions:
syslog.info(f"\t{item.display_name} {item.sim_name} mode: {item.mode}")
def find_definition_by_sim_name(self, key, is_scan = True, is_manual = True):
''' gets an item based on the state data which is a partial subfolder '''
key = key.casefold()
verbose = gremlin.config.Configuration().verbose_mode_details
if verbose: self.dump()
if is_scan:
# lookup scanned entries
if key in self._aircraft_definition_map:
return self._aircraft_definition_map[key]
return None
if is_manual:
# lookup manual entries
item = next((item for item in self._aircraft_manual_definitions if item.sim_name == key), None)
if item:
return item
return None
def find_definition_by_aicraft(self, aircraft) -> SimconnectAicraftDefinition:
''' gets an item by aircraft name (not case sensitive)'''
if not aircraft:
return None
key = aircraft.casefold().strip()
item : SimconnectAicraftDefinition
if key in self._aircraft_definition_map:
return self._aircraft_definition_map[key]
return None
def find_definition_by_title(self, title) -> SimconnectAicraftDefinition:
''' finds aircraft data by the loaded aircraft title '''
if not title:
return None
item = next((n for n in self._aircraft_definition_map.values() if n.title in item.titles), None)
return item
def find_definition_by_aicraft_folder(self, folder) -> SimconnectAicraftDefinition:
''' gets an item by aircraft name (not case sensitive)'''
if not folder:
return None
key = folder.casefold().strip()
item : SimconnectAicraftDefinition
item = next((n for n in self._aircraft_definition_map.values() if n.aircraft_path == key), None)
return item
@property
def auto_mode_select(self):
''' true if automatic mode selection for aicraft is enabled '''
return self._auto_mode_select
@auto_mode_select.setter
def auto_mode_select(self, value):
self._auto_mode_select = value
@property
def auto_mode_lock(self):
''' true if mode locking is enabled '''
return self._auto_mode_lock and self._auto_mode_select # both must be enabled to lock a profile
@auto_mode_lock.setter
def auto_mode_lock(self, value):
self._auto_mode_lock = value
def save(self):
''' saves the configuration data '''
self.to_xml()
def parse_xml(self, data = None):
xml_source = self._xml_source
if not os.path.isfile(xml_source):
# options not saved yet - ignore
return
self._titles = []
self._aircraft_manual_definitions = []
self._aircraft_definition_map.clear()
try:
parser = etree.XMLParser(remove_blank_text=True)
root = etree.parse(xml_source, parser)
nodes = root.xpath('//options')
for node in nodes:
if "auto_mode_select" in node.attrib:
self._auto_mode_select = safe_read(node,"auto_mode_select",bool,True)
if "auto_mode_lock" in node.attrib:
self._auto_mode_lock = safe_read(node,"auto_mode_lock",bool,True)
if "community_folder" in node.attrib:
self._community_folder = safe_read(node,"community_folder", str, "")
if "sort" in node.attrib:
try:
sort_mode = safe_read(node,"sort",int, SimconnectSortMode.NotSet.value)
self._sort_mode = SimconnectSortMode(sort_mode)
except:
self._sort_mode = SimconnectSortMode.NotSet
pass
if "last_command_mode" in node.attrib:
self._last_command_mode = SimConnectCommandMode.to_enum(node.get("last_command_mode"))
break
# reference items scanned from MSFS
node_items = None
nodes = root.xpath("//items")
for node in nodes:
node_items = node
break
profile = gremlin.shared_state.current_profile
default_mode = profile.get_default_mode() if profile else None
if node_items is not None:
for node in node_items:
icao_model = safe_read(node,"model", str, "")
icao_manufacturer = safe_read(node,"manufacturer", str, "")
icao_type = safe_read(node,"type", str, "")
path = safe_read(node,"path", str, "")
key = safe_read(node,"key", str, "")
if "mode" in node.attrib:
mode = node.get("mode")
else:
mode = default_mode
id = safe_read(node,"id", str, "")
entry_type_int = safe_read(node,"entry_type",int,0)
entry_type = SimconnectAicraftDefinition.EntryType(entry_type_int)
state_folder = safe_read(node,"state_folder",str,"")
community_path = safe_read(node,"community_path",str,"")
aircraft_path = safe_read(node,"aircraft_path",str,"")
sim_name = None
if "sim_name" in node.attrib:
sim_name = node.get("sim_name")
if not key and sim_name:
key = sim_name.casefold()
# print (f"automatic: read mode: {mode} for item: {sim_name}")
titles = []
node_titles = None
for child in node:
node_titles = child
if node_titles is not None:
for child in node_titles:
titles.append(child.text)
item = SimconnectAicraftDefinition(id = id,
icao_model = icao_model,
icao_manufacturer = icao_manufacturer,
icao_type = icao_type,
titles = titles,
path = path,
mode = mode,
community_path=community_path,
aircraft_path=aircraft_path,
state_folder = state_folder,
sim_name = sim_name,
entry_type = entry_type)
if not key in self._aircraft_definition_map:
self._aircraft_definition_map[key] = item
node_user_items = root.xpath("//user_items/item")
verbose = gremlin.config.Configuration().verbose_mode_details
for node in node_user_items:
mode = safe_read(node,"mode", str, "")
id = safe_read(node,"id", str, "")
sim_name = safe_read(node,"sim_name", str, "")
item =SimconnectManualDefinition(id, sim_name, mode)
self._aircraft_manual_definitions.append(item)
if verbose: syslog.info (f"SIMCONNECT: manual: read mode: {mode} for item: {sim_name}")
node_titles = None
nodes = root.xpath("//titles")
for node in nodes:
node_titles = node
break
if node_titles is not None:
for node in node_titles:
if node.tag == "title":
title = node.text
if title:
self._titles.append(title)
# sort the entries according to the current sort mode
self.sort()
except Exception as err:
syslog.error(f"Simconnect Config: XML read error: {xml_source}: {err}")
return False
def to_xml(self):
''' writes the simconnect options to the xml configuration file '''
root = etree.Element("simconnect_config")
node_options = etree.SubElement(root, "options")
# selection mode
node_options.set("auto_mode_select",str(self._auto_mode_select))
# autolock mode
node_options.set("auto_mode_lock", str(self._auto_mode_lock))
if self._community_folder and os.path.isdir(self._community_folder):
# save valid community folder
node_options.set("community_folder", self._community_folder)
node_options.set("sort", str(self._sort_mode.value))
node_options.set("last_command_mode", SimConnectCommandMode.to_string(self._last_command_mode))
# scanned aicraft titles (local content)
if self._aircraft_definition_map:
node_items = etree.SubElement(root,"items")
for sim_name, item in self._aircraft_definition_map.items():
node = etree.SubElement(node_items,"item")
if item.icao_model:
node.set("model", item.icao_model)
if item.icao_manufacturer:
node.set("manufacturer", item.icao_manufacturer)
if item.icao_type:
node.set("type",item.icao_type)
if item.path:
node.set("path", item.path)
node.set("id", item.id)
node.set("entry_type", str(item.entry_type.value))
if item.state_folder:
node.set("state_folder", item.state_folder)
if item.sim_name:
node.set("sim_name", item.sim_name)
node.set("key", sim_name)
if item.community_path:
node.set("community_path", item.community_path)
if item.aircraft_path:
node.set("aircraft_path", item.aircraft_path)
if item.mode:
node.set("mode", item.mode)
if item.titles:
node_titles = etree.SubElement(node, "titles")
for title in item.titles:
child = etree.SubElement(node_titles, "title")
child.text = title
# manual entries (usually for streamed entries) - this only has name and mode as we don't have any other info
if self._aircraft_manual_definitions:
node_items = etree.SubElement(root,"user_items")
for item in self._aircraft_manual_definitions:
node = etree.SubElement(node_items,"item")
node.set("id", item.id)
if item.sim_name:
node.set("sim_name", item.sim_name)
else:
node.set("sim_name", "")
if item.mode:
node.set("mode", item.mode)
else:
node.set("mode", "")
try:
# save the file
tree = etree.ElementTree(root)
tree.write(self._xml_source, pretty_print=True,xml_declaration=True,encoding="utf-8")
except Exception as err:
syslog.error(f"SimconnectData: unable to create XML simvars: {self._xml_source}: {err}")
def get_community_folder(self):
''' looks for the community folder '''
dir = QtWidgets.QFileDialog.getExistingDirectory(
None,
"Select Community Folder",
dir = self.community_folder
)
if dir and os.path.isdir(dir):
self.community_folder = dir
return dir
return None
def _getCommunityFolder(self):
''' gets the active community folder - this is user configured in options as there can be multiple installs and versions '''
from gremlin.ui import ui_common
if not self._community_folder or not os.path.isdir(self._community_folder):
folder = self.get_community_folder()
if os.path.isdir(folder):
folder = None
self._community_folder = folder
return self._community_folder
def addManualEntry(self, sim_name: str, mode : str = None):
''' adds a manual entry '''
assert sim_name
if not mode:
mode = gremlin.shared_state.current_profile.get_default_mode()
sim_name = sim_name.casefold()
item = SimconnectManualDefinition(sim_name = sim_name, mode = mode)
self._aircraft_manual_definitions.append(item)
def removeEntry(self, item):
''' deletes an entry, scanned or manual - returns True if the entry was deleted'''
if item:
if isinstance(item, SimconnectAicraftDefinition) and item in self._aircraft_definitions:
self._aircraft_definitions.remove(item)
return True
if isinstance(item, SimconnectManualDefinition) and item in self._aircraft_manual_definitions:
self._aircraft_manual_definitions.remove(item)
return True
return False
def removeManualEntry(self, sim_name: str):
''' removes a manual entry '''
assert sim_name
sim_name = sim_name.casefold()
item = next((item for item in self._aircraft_manual_definitions if item.sim_name == sim_name), None)
if item:
self._aircraft_manual_definitions.remove(item)
def scan_entry(self, folder):
''' scans a single aicraft folder entry '''
# syslog = logging.getLogger("system")
verbose = gremlin.config.Configuration().verbose_mode_simconnect
community_folder = self._getCommunityFolder()
if not community_folder:
syslog.error(f"SIMCONNECT: community folder not found: {community_folder}")
return
aicraft_folder = os.path.join(os.path.dirname(community_folder), folder)
item = self._read_aicraft_config(aicraft_folder)
if item:
if verbose:
syslog.error(f"SIMCONNECT: added aircraft definition: {item.display_name}")
return item
def _fix_entry(self, value):
if "\"" in value:
# remove double quotes
matches = re.findall('"(.*?)"', value)
if matches:
value = matches.pop()
# remove single quote
matches = re.findall('(.*?)"', value)
if matches:
value = matches.pop()
# value = re.sub(r'[^0-9a-zA-Z\s_-]+', '', value)
return value.strip()
def _read_aicraft_config(self, aircraft_cfg):
''' reads a configuration folder and extracts a configuration object '''
# syslog = logging.getLogger("system")
verbose = gremlin.config.Configuration().verbose_mode_simconnect
if not aircraft_cfg or not os.path.isfile(aircraft_cfg):
syslog.error(f"SIMCONNECT: aicraft configuration file not found: {aircraft_cfg}")
return
cmp_icao_type = r'(?i)icao_type_designator\s*=\s*\"?(.*?)\"?$'
cmp_icao_manuf = r'(?i)icao_manufacturer\s*=\s*\"?(.*?)\"?$'
cmp_icao_model = r'(?i)icao_model\s*=\s*\"?(.*?)\"?$'
cmp_title = r"(?i)title\s*=\s*\"?(.*?)\"?$"
titles = []
icao_type = None
icao_model = None
icao_manuf = None
if verbose:
syslog.info(f"File: {aircraft_cfg}")
with open(aircraft_cfg, "r", encoding="utf8") as f:
for line in f.readlines():
matches = re.findall(cmp_icao_type, line)
if matches:
icao_type = self._fix_entry(matches.pop())
continue
matches = re.findall(cmp_icao_manuf, line)
if matches:
icao_manuf = self._fix_entry(matches.pop())
continue
matches = re.findall(cmp_icao_model, line)
if matches:
icao_model = self._fix_entry(matches.pop())
continue
matches = re.findall(cmp_title, line)
if matches:
titles.extend(matches)
# extract the root folder in the community folder
aircraft_path = os.path.dirname(aircraft_cfg)
airplane_path = os.path.dirname(aircraft_path)
simobject_path = os.path.dirname(airplane_path)
community_path = os.path.dirname(simobject_path)
# rebuild the state folder returned by the sim when it has an active aicraft
state_folder = os.path.join(community_path, simobject_path, airplane_path, aircraft_path, "aicraft.cfg")
aircraft_name = os.path.basename(aircraft_path)
community_name = os.path.basename(community_path)
sim_name = None
work_cfg = aircraft_cfg.replace("/", os.sep).casefold()
splits = work_cfg.split(os.sep)
max_index = len(splits)
index = 0
while splits[index] != "simobjects" and index < max_index:
index+=1
index+=1
if index < max_index:
while splits[index] != "airplanes" and index < max_index:
index+=1
index+=1
if index < max_index:
sim_name = splits[index]
if titles:
titles = list(set(titles))
titles = [self._fix_entry(t) for t in titles]
titles.sort()
if icao_model and icao_type and icao_manuf:
path = os.path.dirname(aircraft_cfg)
item = SimconnectAicraftDefinition(icao_type=icao_type,
icao_manufacturer= icao_manuf,
icao_model= icao_model,
titles= titles,
path = path,
community_path = community_name,
aircraft_path = aircraft_name,
state_folder = state_folder,
sim_name = sim_name
)
return item
return None
def scan_aircraft_config(self, owner):
''' scans MSFS folders for the list of aircraft names '''
#options = SimconnectOptions()
community_folder = self.community_folder
if not community_folder:
return
# scan for lvars
#self._scan_lvars()
progress = QtWidgets.QProgressDialog(parent = owner, labelText ="Scanning folders... (this can take a while)", cancelButtonText = "Cancel", minimum = 0, maximum= 100) #, flags = QtCore.Qt.FramelessWindowHint)
progress.setWindowModality(QtCore.Qt.WindowModality.WindowModal)
progress.setValue(0)
progress.show()
QtWidgets.QApplication.processEvents()
# search_folder = os.path.dirname(community_folder)
# source_files = gremlin.util.find_files(search_folder,"aircraft.cfg")
# source_folders = [os.path.dirname(file) for file in source_files]
search_folders = [community_folder]
# if self._local_state_folder and os.path.isdir(self._local_state_folder):
# # add the streamd folders to the list
# search_folders.append(self._local_state_folder)
source_files = []
for root_folder in search_folders:
folders = gremlin.util.find_folders(root_folder)
for folder in folders:
# only process simobjects
ac_root = os.path.join(folder, "SimObjects","Airplanes")
if not os.path.isdir(ac_root):
continue
ac_folders = gremlin.util.find_folders(ac_root)
for sf in ac_folders:
ac_cfg = os.path.join(sf, "aircraft.cfg")
cp_cfg = os.path.join(sf, "cockpit.cfg")
if os.path.isfile(ac_cfg) and os.path.isfile(cp_cfg):
# valid configuration folder because it has an aicraft.cfg and is a player playable plane because it also has a cockpit.cfg
source_files.append(ac_cfg)
file_count = len(source_files)
progress.setLabelText = f"SIMCONNECT: Processing {file_count:,} aircraft..."
verbose = gremlin.config.Configuration().verbose