-
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathgremlinEx.py
More file actions
6080 lines (4882 loc) · 253 KB
/
Copy pathgremlinEx.py
File metadata and controls
6080 lines (4882 loc) · 253 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 - GremlinEx is (C) EMCS 2026
#
# 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/>.
"""
Main UI of JoystickGremlin.
"""
# # ruff: disable[E401]
from __future__ import annotations # deprecated with python 3.14+
# ruff: disable[F401]
import faulthandler
import ctypes
import logging
import os
import sys
import time
import uuid
import traceback
import threading
from threading import Lock
from typing import Callable
from collections.abc import Iterator
import webbrowser
import dinput
from dinput import DeviceSummary
import PySide6
from PySide6 import QtCore, QtGui, QtWidgets
from PySide6.QtCore import QThread
from gremlin.types import TabDeviceType, DeviceType, DeviceCategory
from shiboken6 import Shiboken
import gremlin.tabstate
import win32api
import win32con
import gremlin.joystick_handling
import gremlin.util
import gremlin.config
import gremlin.input_types
import gremlin.event_handler
import gremlin.base_classes
import gremlin.remote
import gremlin.raw_input
import gremlin.config
import gremlin.joystick_handling
import gremlin.input_devices
import gremlin.hid
import gremlin.process
import gremlin.shared_state
import gremlin.types
import gremlin.profile_graph
import gremlin.base_profile
import gremlin.ui.keyboard_device
import gremlin.ui.midi_device
import gremlin.ui.osc_device
import gremlin.ui.mode_device
import gremlin.ui.state_device
import gremlin.ui.theme
import gremlin.input_item
import gremlin.plugin_manager
import gremlin.process
import gremlin.execution_graph
import gremlin.gamepad_handling
import gremlin.import_profile
import gremlin.windows_event_hook # reference needed for packaging
import gremlin.macro_handler # reference needed for packaging
import gremlin.ui.octavi_device
import gremlin.ui.virpil_device
import gremlin.sound
import gremlin.ktts
from gremlin.worker import WorkManager
import gremlin.maestro
# Import QtMultimedia so pyinstaller doesn't miss it
from gremlin.input_types import InputType
import gremlin.types
from gremlin.util import load_icon, find_file
import gremlin.shared_state
import gremlin.base_profile
import gremlin.event_handler
import gremlin.config
import gremlin.code_runner
import gremlin.keyboard
import gremlin.process
import gremlin.code_runner
import gremlin.repeater
import gremlin.base_profile
# imports needed by pyinstaller to be included
import gremlin.control_action
import gremlin.tts
from gremlin.util import log_sys_error, compare_path
import gremlin.util
import graphviz
import gremlin.ui.axis_calibration
import gremlin.ui.ui_common
import gremlin.ui.joystick_device
import gremlin.ui.dialogs
import gremlin.ui.input_viewer
import gremlin.ui.merge_axis
import gremlin.ui.user_plugin_management
import gremlin.ui.profile_creator
import gremlin.ui.profile_settings
import gremlin.version
from gremlin.ui.ui_gremlin import Ui_Gremlin
import gremlin.reporting
from gremlin.singleton_decorator import SingletonDecorator
from gremlin.tabstate import TabData
syslog = logging.getLogger("system")
# Figure out the location of the code / executable and change the working
# directory accordingly
install_path = os.path.normcase(os.path.dirname(os.path.abspath(sys.argv[0])))
os.chdir(install_path)
class GremlinUi(gremlin.ui.ui_common.QRememberMainWindow):
"""Main window of the Joystick Gremlin user interface."""
ui = None
# input_lock = threading.Lock() # critical code operations - prevents reentry
def __init__(self, parent=None):
"""Creates a new main ui window.
:param parent the parent of this window
"""
self.instance = self
gremlin.shared_state.ui = self
self.initialized = False
super().__init__("main_window", parent)
self.ui = Ui_Gremlin()
# self.addWidget(QtWidgets.QLabel("TOP"))
self.ui.build(self) # build the main window
# self.addWidget(QtWidgets.QLabel("BOTTOM"))
self._is_active = False # status bar active flag
self._widget_device_index_map = {}
self._profile_load_stack = []
self._profile_load_temporary_files = []
self._profile_hash = None # active profile hash to detect changes
self.locked = False
self.activate_locked = False
self._selection_locked = False
self.joystick_event_lock = Lock() # lock for joystick events
self.device_change_locked = False
self._device_change_queue = 0 # count of device updates while the UI is already updating
self._runtime_mode_map = {} # map of runtime processes to their last runtime mode
self._process_runtime_map = {} # map of MODE to process associated with a profile - the process executable is the key
self._active_process_path = None # active mapped process path
self._last_toast_message = None
self._change_input_lock = threading.Lock() # true when changing inputs
self._ui_update_pending = False # flag = if True, UI updates are pending
self._suspend_ui_update = 0 # stack = if non zero, UI updates should be suspended
self._comparative_file = os.path.join(os.getenv("temp"), "8c71a5a6eae74f989cf903816868028e.xml")
self._loading_stack = 0
self._loading_stack_target = 0 # target index if a call to select a page is done while page cycling is suspended
# self.ui.device_page_widget.currentChanged.connect(self._handle_device_widget_index_changed)
self._last_selected_device_guid = None
self._last_selected_input_type = None
self._last_selected_input_id = None
self._resize_count = 0
# list of detected devices
self._active_devices = []
self._tab_dirty = True # True if tabs should be refreshed
self._tab_map = None # holds tabdata objects indexed by tab index
# cache of widget references so they don't get garbage collected by QT
self.ui.devices_tab_header_widget.tabChanged.connect(self._tab_selected)
self.ui.devices_tab_header_widget.tabMoveCompleted.connect(self._tab_moved_cb)
self.ui.devices_tab_header_widget.tabContextMenu.connect(self._tab_context_menu_cb)
self.ui.devices_tab_header_widget.currentChanged.connect(self._tab_changed)
self._last_input_item = None # last selected input item
self._last_state_device_guid = None
self._last_state_input_id = None
self._last_state_data = {} # holds data for axis highlight switching
gremlin.shared_state.application_version = gremlin.version.APPLICATION_VERSION
self.config = gremlin.config.Configuration()
self.config.changed.connect(self._config_filter_changed_cb)
# last input from last run to restore
self.restore_input = self.config.get_last_input()
# prevent saving anything until we have a profile loaded
el = gremlin.event_handler.EventListener()
el.push_input_selection()
el.request_activate.connect(self.activate) # hook activation / deactivation requests
el.refresh_devices.connect(self._create_tabs) # refresh device list
el.request_profile_reload.connect(self._reload_profile) # reload the profile from a temporary file
el.request_reload.connect(self._reload)
el.device_mapping_changed.connect(self._update_tab)
# el.mapping_changed.connect(self._mapping_changed)
el.show_container_id_changed.connect(self._show_container_id_visible_changed)
el.toolbar_changed.connect(self._update_toolbar)
el.update_mode_status_bar.connect(self._update_mode_status_bar)
el.request_ui_refresh.connect(self.refresh)
el.shutdown.connect(self.handle_shutdown)
el.feature_changed.connect(self._handle_feature_changed) # handle feature changes
# highlighing options
self._icon_on = gremlin.util.load_icon(
"mdi.checkbox-blank-circle",
qta_color=gremlin.ui.ui_common.Color.activeColor(),
)
self._icon_off = gremlin.util.load_icon(
"mdi.checkbox-blank-circle",
qta_color=gremlin.ui.ui_common.Color.inactiveColor(),
)
self._button_highlighting_enabled = self.config.highlight_input_buttons # true if highlighting on buttons
self._axis_highlighting_enabled = self.config.highlight_input_axis # true if highligthing on axes
self._input_highlighting_enabled = self.config.highlight_enabled # on/off global
el.enable_highlight_changed.connect(self._highlight_enable_changed) # fires when highlight mode is toggled
self._last_highlight_key = None # last event processed for input highlights
el.toggle_highlight.connect(self._handle_highlight_state) # input highlighting states
el.ui_ready.connect(self._ui_ready)
gremlin.shared_state.aborted = False
el.request_profile_stop.connect(lambda x: self.abort(x))
# Process monitor
self.process_monitor = gremlin.process.ProcessMonitor()
self.process_monitor.process_changed.connect(self._process_changed_cb)
self.current_process_path = None # current process
self._last_tts_notify_time = None # last autoload process change TTS time
self._process_change_in_progress = False
# Default path variable before any runtime changes
self._base_path = list(sys.path)
self._init_tab_data()
self._reset_tab_data()
self.runner = gremlin.code_runner.CodeRunner()
self.repeater = gremlin.repeater.Repeater([], self._update_statusbar_repeater)
self._status_bar_last_runtime_mode = None
self._status_bar_last_edit_mode = None
el.runtime_mode_changed.connect(self._runtime_mode_changed)
el.edit_mode_changed.connect(self._edit_mode_changed)
el.edit_mode_ui_update.connect(self._edit_mode_update)
self.tab_guids = []
self.mode_selector = gremlin.ui.ui_common.ModeWidget() # main UI mode selector
self.mode_selector.edit_mode_changed.connect(self._edit_mode_selector_changed)
self.mode_selector.setRuntimeDisabled(True)
self.ui.toolBar.addWidget(self.mode_selector)
# Setup profile storage
self.profile = gremlin.base_profile.Profile()
self._profile_auto_activated = False
# Input selection storage
self._last_input_timestamp = time.time()
self._last_input_change_timestamp = time.time()
self._last_input_event = None
self._last_input_identifier = None # input id of the last triggered device
# self._last_device_guid = None # string representation of the last GUID of the last triggered device
# self._last_input_type = None # last input type (InputType) selected
# self._last_input_id = None # last input id selected
self._last_tab_switch = None
self._input_delay = 0.25 # delay in seconds between joystick inputs for highlighting purposes
self._joystick_axis_highlight_deviation = 0.5 # deviation needed before registering a highlight on axis change (this is to avoid noisy inputs and prevent the UI from going crazy) 1.0 = half travel
self._joystick_axis_highlight_map = {} # map of device / axis values
self._event_process_registry = {}
self._temp_input_axis_override = False # flag that tracks device swaps on axis
self._temp_input_axis_only_override = False # flag that tracks device swaps but on axis only (shift + ctrl key)
# Create all required UI elements
self._create_system_tray()
self._setup_icons()
self._connect_actions()
self._create_statusbar()
self._update_status_bar_active(False)
# hook status bar to events
el = gremlin.event_handler.EventListener()
el.remote_control_state_change.connect(self._update_status_bar) # remote control state changes
el.keyboard_event.connect(self._kb_event_cb) # for repeaters
el.suspend_keyboard_input.connect(self._kb_suspend_cb)
el.profile_start.connect(self._profile_start)
el.profile_stop.connect(self._profile_stop)
el.profile_changed.connect(self._profile_changed_cb)
el.button_state_change.connect(self._button_state_change)
el.axis_state_change.connect(self._axis_state_change)
el.input_selection_changed.connect(self._input_changed_handler)
el.remote_control_changed(self._remote_control_changed)
# hook input selection
el.select_input.connect(self._select_input_handler)
# hook config changes
el.config_changed.connect(self._config_changed_cb)
# hook changes
eh = gremlin.event_handler.EventHandler()
eh.profile_changed.connect(self._profile_changed_cb)
self._context_menu_tab_index = None
# Load existing configuration or create a new one otherwise
# disable autoload if ctrl key is held
if win32api.GetKeyState(win32con.VK_CONTROL) < 0:
syslog.info("START: autoload profile disabled (ctrl key detected)")
self.config.auto_load_disabled = True
if not self.config.auto_load_disabled and self.config.last_profile and os.path.isfile(self.config.last_profile):
# check if this was a profile swap that we load the profile from the current user folder
current_profile_folder = gremlin.shared_state.data_path.casefold()
last_profile = self.config.last_profile.lower()
if current_profile_folder not in last_profile:
_, base_file = os.path.split(last_profile)
located_profile = find_file(base_file, current_profile_folder)
if located_profile:
self.config.last_profile = located_profile
self._do_load_profile(self.config.last_profile)
else:
self.new_profile()
# Setup the recent files menu
self._create_recent_profiles()
# Modal windows
self.modal_windows = {}
self.modal_windows["input_viewer"] = None
# Enable reloading for when a user connects / disconnects a
# device. Sleep for a bit to avert race with devices being added
# when they already exist.
el._init_joysticks()
self._profile_map = gremlin.base_profile.ProfileMap()
GremlinUi.ui = self
self.ui.update_toolbar()
self._update_status_bar()
el.config_option_changed.connect(self._config_option_changed)
el.device_change_event.connect(self._handle_devices_changed)
el.ui_initialized.connect(self._update_start_tab)
self.vjoy_state = gremlin.joystick_handling.VirtualDeviceUsageState()
self.initialized = True
gremlin.shared_state.initialized = True
el.ui_initialized.emit()
# def _handle_device_widget_index_changed(self, index):
# syslog.info(f"device page: index set to [{index}]")
def pushSuspendTabUpdate(self):
self._suspend_ui_update += 1
def popSuspendTabUpdate(self, reset=False):
if reset:
self._suspend_ui_update = 0
if self._suspend_ui_update > 0:
self._suspend_ui_update -= 1
if self._suspend_ui_update == 0 and self._ui_update_pending:
self._ui_update_pending = False
self._create_tabs() # recreate the UI tabs
def pushLoading(self):
if self._loading_stack == 0:
self.hideDeviceContent()
self._loading_stack += 1
def popLoading(self, device_guid: dinput.GUID = None, reset=False):
if self._loading_stack:
if reset:
self._loading_stack = 0
else:
self._loading_stack -= 1
if self._loading_stack == 0:
if self._loading_stack_target:
self.setDeviceContentIndex(self._loading_stack_target)
# syslog.info(f"loading: display saved index [{self._loading_stack_target}]")
self._loading_stack_target = 0
else:
self.showDeviceContent(device_guid)
def handle_shutdown(self):
# cleanup on shutdown
if os.path.isfile(self._comparative_file):
os.unlink(self._comparative_file)
def handle_tab_selected(self, device_guid):
"""persists the last selected device for the profile"""
if self.profile:
self.profile.saveLastDevice(device_guid)
def _update_start_tab(self):
"""forces a tab index reload on init"""
tab_index = self.ui.devices_tab_header_widget.currentIndex()
self._tab_selected(tab_index)
def _update_toolbar(self):
"""updates the toolbar when the toolbar changes"""
self.ui.update_toolbar()
def registerTemporaryProfileLoadFile(self, xml_file: str):
"""registers a temporary file that the profile loader will load"""
if xml_file not in self._profile_load_temporary_files:
self._profile_load_temporary_files.append(xml_file)
def _init_tab_data(self):
self._widget_device_index_map = {} # map of device widgets keyed by the device GUID
self._widget_index_device_map = {}
def _reset_tab_data(self):
self._tab_index_map = {} # map of device_guids indexed by their tab index from the tab header (index -> device_guid)
self._tab_device_map = {} # map of tab positions index mapped by device guid for the tab header (device_guid -> index)
self._tab_name_map = {} # map fo device guid to device name for tabs
# self._current_tab_widget = None # selected content widget for the current device
self._current_tab_input_id = None # selected input in the current tab
self._joystick_device_guids = []
self.tab_guids = []
self._clear_tabs()
def _clear_tabs(self):
gremlin.util.InvokeUiMethod(self._clear_tabs_ui) # ensure on UI thread
def getTabCount(self) -> int:
return self.ui.devices_tab_header_widget.count()
def _clear_tabs_ui(self):
# remove all tab headers
assert gremlin.util.is_ui_thread()
if self.ui.devices_tab_header_widget:
with QtCore.QSignalBlocker(self.ui.devices_tab_header_widget):
while self.ui.devices_tab_header_widget.count():
self.ui.devices_tab_header_widget.removeTab(0)
self._tab_device_map.clear()
self._tab_index_map.clear()
self._tab_name_map.clear()
def _get_device(self, device_guid) -> dinput.DeviceSummary:
"""gets the device for a given GUID, connected or not"""
return gremlin.joystick_handling.getDevice(device_guid)
def _get_device_name(self, device_guid):
"""gets the name of a device"""
device = self._get_device(device_guid)
if device:
return device.name
return None
def _add_tab(self, device_guid, tab_type, index=None, override_name=None) -> int:
"""adds a tab to the tab header
:param device_guid: the device guid of the device to add
:param index: optiona, if specified, the index to add
:returns int: the index of the tab added
"""
device_guid = gremlin.util.to_guid(device_guid)
device: dinput.DeviceSummary = self._get_device(device_guid)
if not device:
syslog.error(f"Unknown device GUID found in tabs: {device_guid}")
return
device_name = device.name
# ensure the device tab does not already exist
if device_guid in self._tab_device_map:
# already present - skip
syslog.info(f"ADDTAB: skip adding device [{device_name}] [{device_guid}] as this device already exists in the device list.")
return
ts = gremlin.tabstate.TabState()
tab_name = override_name if override_name else device_name
with QtCore.QSignalBlocker(self.ui.devices_tab_header_widget):
if index is None:
position = self.ui.devices_tab_header_widget.addTab(tab_name)
else:
position = self.ui.devices_tab_header_widget.insertTab(index, tab_name)
# tab data block
data = ts.addData(position, tab_type, device)
self.ui.devices_tab_header_widget.setTabData(position, data)
self._tab_device_map[device_guid] = position
self._tab_index_map[position] = device_guid
self._tab_name_map[device_guid] = tab_name
if tab_type == TabDeviceType.Joystick:
self._joystick_device_guids.append(device_guid)
verbose = gremlin.config.Configuration().verbose_mode_device
if verbose:
syslog.info(f"Add tab: index [{position}] [{device_name}] data: {self.ui.devices_tab_header_widget.tabData(position)}")
self._update_tab(device_guid)
return position
def _remove_tab(self, device_guid):
"""removes a device tab"""
device_guid = gremlin.util.to_guid(device_guid)
device: dinput.DeviceSummary = self._get_device(device_guid)
if not device:
syslog.error(f"Unknown device GUID found in tabs: {device_guid}")
return
# ensure the device tab does not already exist
if device_guid in self._tab_device_map:
widget = self.getRegisteredWidget(device_guid)
if widget:
widget.hide()
if hasattr(widget, "_cleanup_ui"):
widget._cleanup_ui()
widget.setParent(None)
widget.deleteLater()
index = self._tab_device_map[device_guid]
self.ui.devices_tab_header_widget.removeTab(index)
del self._tab_device_map[device_guid]
del self._tab_index_map[index]
del self._tab_name_map[device_guid]
def _has_mapping(self, device_guid, any_mode=False) -> bool:
"""true if the device has mappings"""
return self.profile.hasMapping(device_guid, any_mode)
def _get_mappings(self, device_guid) -> dict:
"""returns a map of [mode], has_mapping"""
if isinstance(device_guid, str):
device_guid = gremlin.util.parse_guid(device_guid)
profile = gremlin.shared_state.current_profile
edit_mode = gremlin.shared_state.edit_mode
devices = profile.devices
look_for_containers = True
# special devices
if device_guid == gremlin.shared_state.state_tab_guid:
# state
sd = gremlin.ui.state_device.StateData()
names = sd.getStateNames()
return {edit_mode: True} if names else {}
elif device_guid == gremlin.shared_state.settings_tab_guid:
return {}
elif device_guid == gremlin.shared_state.plugins_tab_guid:
# plugins
plugins = gremlin.shared_state.current_profile.plugins
return {edit_mode: True} if len(plugins) > 0 else {}
elif device_guid == gremlin.shared_state.keyboard_tab_guid:
look_for_containers = False
mode_map = {}
if device_guid in devices:
device_data = devices[device_guid]
for mode_name in device_data.modes:
mode_data = device_data.modes[mode_name]
mode_map[mode_name] = False
for input_type, input_items in mode_data.config.items():
# account for delay loaded input mappings
input_item_list = [item for item in input_items.values() if item is not None]
for input_item in input_item_list:
if look_for_containers:
if input_item.containers:
mode_map[mode_name] = True
break
else:
# input count indicates content
mode_map[mode_name] = True
break
return mode_map
def getTabMap(self) -> dict:
"""gets tab data as tupless"""
return self._get_tab_map()
def getTabDataMap(self) -> dict:
"""gets tab data as TabData object"""
return self._get_tab_data_map()
def getTabDataIndex(self, data: gremlin.tabstate.TabData):
for index in range(self.ui.devices_tab_header_widget.count()):
if self.ui.devices_tab_header_widget.tabData(index) == data:
return index
return -1
def _get_tab_map(self) -> dict[int, TabData]:
"""gets tab configuration data as a dictionary indexed by tab index holding device id, device name and device widget type
:returns: list of (device_guid, device_name, tabdevice_type, tab_index)
"""
tab_count = self.ui.devices_tab_header_widget.count()
tab_map = {}
for index in range(tab_count):
data: TabData = self.ui.devices_tab_header_widget.tabData(index)
tab_map[index] = data
return tab_map
def _get_tab_data_map(self) -> dict[dinput.GUID, TabData]:
"""returns the map of tab data objects associated with their device GUID"""
tab_count = self.ui.devices_tab_header_widget.count()
tab_map = {}
for index in range(tab_count):
data = self.ui.devices_tab_header_widget.tabData(index)
tab_map[data.device_guid] = data
return tab_map
def _get_tab_type(self, index):
"""gets the tab type for the given tab index"""
data = self.ui.devices_tab_header_widget.tabData(index)
return data.tab_type
def _get_tab_type_from_device_guid(self, device_guid: uuid.UUID | dinput.GUID | str) -> TabDeviceType:
device = gremlin.joystick_handling.getDevice(device_guid)
return self._get_tab_type_from_device(device)
def _get_tab_type_from_device(self, device: dinput.DeviceSummary) -> TabDeviceType:
if device:
match device.device_type:
case DeviceType.NotSet: # not set
return TabDeviceType.NotSet
case DeviceType.Keyboard: # keyboard special device
return TabDeviceType.Keyboard
case DeviceType.Joystick: # joystick or game controller
return TabDeviceType.Joystick
case DeviceType.VJoy: # vjoy (virtual)
return TabDeviceType.VjoyInput
case DeviceType.Midi: # midi special device
return TabDeviceType.Midi
case DeviceType.Osc: # open source control special device
return TabDeviceType.Osc
case DeviceType.ModeControl: # mode control special device
return TabDeviceType.ModeControl
case DeviceType.Settings: # settings special device
return TabDeviceType.Settings
case DeviceType.State: # state special device
return TabDeviceType.State
case DeviceType.Plugins: # plugins special device
return TabDeviceType.Plugins
case DeviceType.OctaviIFR1: # octavi IFR1 special device
return TabDeviceType.OctaviIFR1
raise ValueError(f"Don't know how to handle type: [{device.device_type}]")
return TabDeviceType.NotSet
def _reindex_tabs(self):
"""rebuilds the tab index"""
self._tab_index_map.clear()
self._tab_device_map.clear()
self._tab_name_map.clear()
verbose = gremlin.config.Configuration().verbose_mode_device
# syslog = logging.getLogger("system")
if verbose:
syslog.info("UI: tab reindex")
for index in range(self.ui.devices_tab_header_widget.count()):
data = self.ui.devices_tab_header_widget.tabData(index)
device_guid = gremlin.util.to_guid(data.device_guid)
device_name = self._get_device_name(device_guid)
self._tab_index_map[index] = device_guid
self._tab_device_map[device_guid] = index
self._tab_name_map[device_guid] = device_name
if verbose:
syslog.info(f"\t[{index}] {device_name} {device_guid}")
def _tabswitch_needed(self, device_guid) -> bool:
"""checks to see if the device tab is the current tab or not"""
tab_device_guid = self.getCurrentTabDeviceGuid()
if tab_device_guid is None:
# no tab selected yet
return True
device_guid = gremlin.util.to_guid(device_guid) # compare dinput.GUID objects
assert isinstance(tab_device_guid, dinput.GUID) and isinstance(device_guid, dinput.GUID), "device id comparison mismatch data types"
return tab_device_guid != device_guid
def getCurrentTabDeviceGuid(self) -> dinput.GUID:
"""updates the current tab tracking variables"""
tab_device_guid = gremlin.shared_state.current_tab_device_guid
if tab_device_guid is None:
tab_device_guid = self._tab_index_map.get(self.ui.devices_tab_header_widget.currentIndex())
gremlin.shared_state.current_tab_device_guid = tab_device_guid
gremlin.shared_state.current_tab_device_id = gremlin.util.normalize_guid(tab_device_guid)
assert isinstance(tab_device_guid, dinput.GUID), "current tab device guid is not a dinput.GUID"
return tab_device_guid
def _inputswitch_needed(self, device_guid: dinput.GUID, input_id) -> bool:
"""checks to see if an input switch is needed"""
tab_device_guid = self.getCurrentTabDeviceGuid()
assert isinstance(tab_device_guid, dinput.GUID) and isinstance(device_guid, dinput.GUID), "device id comparison mismatch"
tab_input_id = self._current_tab_input_id
return tab_device_guid != device_guid or tab_input_id != input_id
def _button_state_change(self, event):
"""button changed - triggered only at design time - look for highlighting triggers - HIGHLIGHT SYSTEM"""
if gremlin.shared_state.is_highlighting_suspended():
# highlighting disabled
return
el = gremlin.event_handler.EventListener()
is_shifted = el.get_shifted_state()
is_tabswitch_enabled = self.config.highlight_autoswitch
device_guid = event.device_guid
input_type = event.event_type
input_id = event.identifier
is_pressed = event.is_pressed
if not is_pressed:
# trigger only on presses
return
is_button = self.is_button_highlighting or is_shifted
if not is_button:
# highlight for buttons disabled
return
tab_switch_needed = self._tabswitch_needed(device_guid)
if tab_switch_needed and not is_tabswitch_enabled:
# tab switch is disabled
return
input_switch_needed = True # tab_switch_needed or self._inputswitch_needed(device_guid, input_id)
if not input_switch_needed:
# not setup to auto change tabs (override via shift/control keys)
return
# # see if input needs to change
# input_switch_needed = tab_switch_needed or self._inputswitch_needed(device_guid, input_id)
# if not input_switch_needed:
# return
# trigger switch
verbose = gremlin.config.Configuration().verbose_mode_ui
if verbose:
syslog.info(f"Button input switch to {device_guid} button {input_id}")
self._select_input_handler(device_guid, input_type, input_id, force_switch=True)
def _axis_state_change(self, event):
"""axis changed - triggered only at design time - HIGHLIGHT SYSTEM"""
if gremlin.shared_state.is_highlighting_suspended():
# highlighting disabled
return
el = gremlin.event_handler.EventListener()
is_control = el.get_control_shift_state()
if not self.is_axis_highlighting and not is_control:
# highlight disabled - reset tracking
self._last_state_device_guid = None
self._last_state_input_id = None
self._last_state_data = {}
return
device_guid = event.device_guid
input_type = event.event_type
input_id = event.identifier
value = event.value
if self._last_state_input_id == device_guid and self._last_state_input_id == input_id:
# same device as last selected, ignore
return
# to avoid instant triggers - compare deviation from last value for that specific axis
# this avoids a small change on a new axis from triggering a change
if device_guid not in self._last_state_data:
self._last_state_data[device_guid] = {}
if input_id not in self._last_state_data[device_guid]:
self._last_state_data[device_guid][input_id] = None
if self._last_state_data[device_guid][input_id] is not None:
last_value = self._last_state_data[device_guid][input_id]
if abs(last_value - value) <= 0.2:
return # insufficient deviation to trigger
tab_switch_needed = self._tabswitch_needed(device_guid)
is_tabswitch_enabled = self.config.highlight_autoswitch
input_switch_needed = tab_switch_needed or self._inputswitch_needed(device_guid, input_id)
if tab_switch_needed and not is_tabswitch_enabled and not input_switch_needed:
# not setup to auto change tabs (override via shift/control keys)
return
# see if input needs to change
if not input_switch_needed:
return
# trigger - record last value
self._last_state_data[device_guid][input_id] = value
# trigger highlight switch
verbose = gremlin.config.Configuration().verbose_mode_ui
if verbose:
syslog.info(f"Axis input switch to {device_guid} axis {input_id}")
self._select_input_handler(device_guid, input_type, input_id, force_switch=True)
@QtCore.Slot(int)
def _tab_changed(self, index):
# syslog.info(f"tab changed : {index}")
self._tab_selected(index)
@QtCore.Slot(int)
def _tab_selected(self, index):
"""called when the device tab selection is changed
:param: index = the index of the tab that was selected
"""
if index == -1:
# not a valid tab
return
if self.ui.devices_tab_header_widget.moveInProgress:
# ignore if the tab is being dragged
return
self.pushLoading()
verbose = gremlin.config.Configuration().verbose_mode_ui
if verbose:
syslog.info(f"TAB CHANGED: selected : {index}")
device_guid = self.getDeviceGuidForTabIndex(index)
device = gremlin.joystick_handling.getDevice(device_guid)
assert device is not None, "invalid device"
if verbose:
syslog.info(f"TAB CHANGED: new tab [{index}] {self.ui.devices_tab_header_widget.tabText(index)} - device [{device.name}] id [{device.device_id}]")
self.last_tab_index = index
wm = WorkManager()
wm.submit(callback=self._tab_selected_worker, args=device_guid)
def _tab_selected_worker(self, args):
device_guid = args
device = gremlin.joystick_handling.getDevice(device_guid)
assert device is not None, "invalid device"
self._tab_selection_completed = False
_, restore_input_type, restore_input_id = self.config.get_last_input(device_guid)
verbose = gremlin.config.Configuration().verbose_mode_ui
if verbose:
syslog.info(f"TabSelectedWorker: start select device [{device.name}] id [{device.device_id}]")
self._select_input(
device_guid=device_guid,
input_type=restore_input_type,
input_id=restore_input_id,
force_update=True,
force_switch=True,
tab_changed=True,
extra_data={
"completion_callback": self._tab_selection_complete,
"source": "tab_selected",
},
)
# wait for the tab selection to complete
while not self._tab_selection_completed:
QThread.sleep(0)
# update the selected tab
assert isinstance(device_guid, dinput.GUID), "invalid device guid format"
assert gremlin.shared_state.current_tab_device_guid == device_guid
assert gremlin.shared_state.current_tab_device_id == gremlin.util.normalize_guid(device_guid)
if verbose:
syslog.info("tab selection worker complete")
def _tab_selection_complete(self, *args):
self._tab_selection_completed = True
self.popLoading()
def add_custom_tools_menu(self, menuTools):
"""adds custom tools to the menu"""
self._actionTabSort = QtGui.QAction("Sort Devices", self, triggered=self._tab_sort_cb)
self._actionTabSort.setToolTip("Sorts input hardware devices in alphabetical order")
self._ationTabCopyAssignments = QtGui.QAction("Copy to device...", self, triggered=self._tab_copy_cb)
self._ationTabCopyAssignments.setToolTip("Copies assignments to specified target device")
# self._actionTabSubstitute = QtGui.QAction("Device Swap...", self, triggered = self._tab_substitute_cb)
# self._actionTabSubstitute.setToolTip("Swap one device ID for another device ID")
self._actionTabClearMap = QtGui.QAction("Clear Mappings", self, triggered=self._tab_clear_map_cb)
self._actionTabClearMap.setToolTip("Clears all mappings from the current device")
# tab remove device moved to display options in m77
# self._actionTabRemoveDevice = QtGui.QAction("Change Visible Device...", self, triggered=self._tab_remove_device_cb)
# self._actionTabRemoveDevice.setToolTip("Removes the device from the profile")
# self._actionTabImport = QtGui.QAction("Import Profile...", self, triggered = self._tab_import_cb)
# self._actionTabImport.setToolTip("Import profile data into the current device")
menuTools.addSeparator()
menuTools.addAction(self._actionTabSort)
menuTools.addAction(self._ationTabCopyAssignments)
# menuTools.addAction(self._actionTabSubstitute)
# menuTools.addAction(self._actionTabRemoveDevice)
# menuTools.addAction(self._actionTabImport)
menuTools.addAction(self._actionTabClearMap)
def _tab_context_menu_cb(self, tab_index):
"""tab context menu"""
self._context_menu_tab_index = tab_index
data = self.ui.devices_tab_header_widget.tabData(tab_index)
_tab_type = data.tab_type
# device_guid = data.device_guid
# substitution is only available if the profile has been saved (a new profile matches the current devices by definition)
# is_enabled = tab_type == TabDeviceType.Joystick
# and self.profile is not None\
# and self.profile.profile_file is not None\
# and os.path.isfile(self.profile.profile_file)
# self._actionTabSubstitute.setEnabled(is_enabled)
menu = QtWidgets.QMenu(self)
menu.addAction(self._actionTabSort)
menu.addAction(self._ationTabCopyAssignments)
# menu.addAction(self._actionTabSubstitute)
# menu.addAction(self._actionTabImport)
# menu.addAction(self._actionTabRemoveDevice)
menu.addAction(self._actionTabClearMap)
advanced_menu = menu.addMenu("Advanced...")
action = QtGui.QAction(
"Copy Device ID",