-
-
Notifications
You must be signed in to change notification settings - Fork 160
Expand file tree
/
Copy pathbackend.py
More file actions
2108 lines (1885 loc) · 79 KB
/
Copy pathbackend.py
File metadata and controls
2108 lines (1885 loc) · 79 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
"""
QML Backend Bridge — connects the QML UI to the engine and config.
Exposes properties, signals, and slots for two-way data binding.
"""
import os
import json
import re
import shutil
import sys
import threading
import time
import urllib.error
import webbrowser
from pathlib import Path
from PySide6.QtCore import QCoreApplication, QMetaObject, QObject, Property, QTimer, Signal, Slot, Qt, QUrl
from core.accessibility import is_process_trusted
from core.config import (
BUTTON_NAMES, load_config, save_config, get_active_mappings,
PROFILE_BUTTON_NAMES, set_mapping, create_profile, delete_profile,
get_icon_for_exe,
)
from core import app_catalog
from core.device_layouts import get_device_layout, get_manual_layout_choices
from core.key_registry import (
ShortcutParseError,
canonical_shortcut_text,
is_reserved_risky_shortcut,
pretty_key_name,
)
from core.logi_devices import (
DEFAULT_DPI_MAX,
DEFAULT_DPI_MIN,
build_evdev_connected_device_info,
clamp_dpi,
get_buttons_for_layout,
)
from core.key_simulator import (
ACTIONS,
custom_action_label,
normalize_captured_shortcut_parts,
valid_custom_key_names,
)
from core.startup import (
apply_login_startup,
supports_login_startup,
sync_from_config as sync_login_startup_from_config,
)
from core.updater import (
DEFAULT_AUTO_CHECK_INTERVAL_SECONDS,
DEFAULT_RELEASE_REPO,
UpdateCheckState,
check_latest_release,
is_newer,
)
from core.update_installer import (
ArchiveRequirements,
UpdateInstallError,
WindowsUpdatePlan,
cleanup_stale_update_state,
extract_validated_zip,
fetch_update_manifest_for_release,
launch_windows_update_helper,
locate_runtime,
plan_install_for_platform,
prepare_downloaded_asset,
read_update_result,
same_volume_windows_stage_dir,
write_windows_update_plan,
)
from core.version import APP_VERSION
from ui.screenshot_common import screenshot_file_path, screenshot_file_paths, screenshots_dir
def _action_label(action_id):
if action_id.startswith("custom:"):
return custom_action_label(action_id)
return ACTIONS.get(action_id, {}).get("label", "Do Nothing")
def _qt_shortcut_modifier_name(name):
"""Return the raw Qt semantic name for a modifier."""
return (name or "").strip().lower()
def _qt_enum_int(value):
"""Coerce Qt enum and flag values from QML into plain integers."""
if hasattr(value, "value"):
return int(value.value)
return int(value)
def _qt_shortcut_key_name(key, text=""):
"""Translate a Qt key value into a raw Qt semantic shortcut name."""
key = _qt_enum_int(key)
text = text or ""
if key == _qt_enum_int(Qt.Key_Shift):
return "shift"
if key == _qt_enum_int(Qt.Key_Control):
return "ctrl"
if key == _qt_enum_int(Qt.Key_Alt):
return "alt"
if key == _qt_enum_int(Qt.Key_Meta):
return "super"
if key == _qt_enum_int(Qt.Key_Escape):
return "esc"
if key == _qt_enum_int(Qt.Key_Tab):
return "tab"
if key == _qt_enum_int(Qt.Key_Space):
return "space"
if key in (_qt_enum_int(Qt.Key_Return), _qt_enum_int(Qt.Key_Enter)):
return "enter"
if key == _qt_enum_int(Qt.Key_Backspace):
return "backspace"
if key == _qt_enum_int(Qt.Key_Delete):
return "delete"
if key == _qt_enum_int(Qt.Key_Left):
return "left"
if key == _qt_enum_int(Qt.Key_Right):
return "right"
if key == _qt_enum_int(Qt.Key_Up):
return "up"
if key == _qt_enum_int(Qt.Key_Down):
return "down"
if key == _qt_enum_int(Qt.Key_Home):
return "home"
if key == _qt_enum_int(Qt.Key_End):
return "end"
if key == _qt_enum_int(Qt.Key_PageUp):
return "pageup"
if key == _qt_enum_int(Qt.Key_PageDown):
return "pagedown"
if key == _qt_enum_int(Qt.Key_Insert):
return "insert"
for n in range(1, 25):
qt_key = getattr(Qt, f"Key_F{n}", None)
if qt_key is not None and key == _qt_enum_int(qt_key):
return f"f{n}"
if _qt_enum_int(Qt.Key_A) <= key <= _qt_enum_int(Qt.Key_Z):
return chr(ord("a") + (key - _qt_enum_int(Qt.Key_A)))
if _qt_enum_int(Qt.Key_0) <= key <= _qt_enum_int(Qt.Key_9):
return chr(ord("0") + (key - _qt_enum_int(Qt.Key_0)))
if len(text) == 1:
lowered = text.lower()
try:
canonical_shortcut_text(lowered, allow_modifier_only=False)
except ShortcutParseError:
pass
else:
return lowered
return ""
def _qt_shortcut_combo(key, modifiers, text=""):
"""Build the stored custom-shortcut string from Qt event parts."""
modifiers = _qt_enum_int(modifiers)
parts = []
if modifiers & _qt_enum_int(Qt.ControlModifier):
parts.append(_qt_shortcut_modifier_name("ctrl"))
if modifiers & _qt_enum_int(Qt.ShiftModifier):
parts.append("shift")
if modifiers & _qt_enum_int(Qt.AltModifier):
parts.append("alt")
if modifiers & _qt_enum_int(Qt.MetaModifier):
parts.append(_qt_shortcut_modifier_name("super"))
key_name = _qt_shortcut_key_name(key, text)
return normalize_captured_shortcut_parts(parts, key_name)
def _open_url(url: str) -> bool:
"""Open a URL without importing QtGui during backend module import."""
if not url:
return False
qurl = QUrl(url)
try:
from PySide6.QtGui import QDesktopServices
if QDesktopServices.openUrl(qurl):
return True
except Exception:
pass
return bool(webbrowser.open(qurl.toString()))
def _update_install_enabled() -> bool:
value = os.environ.get("MOUSER_ENABLE_UPDATE_INSTALL", "")
return value.strip().lower() in {"1", "true", "yes", "on"}
def _normalize_directory_path(path: str) -> str:
expanded = os.path.expanduser((path or "").strip())
if not expanded:
return ""
if sys.platform == "linux":
return os.path.realpath(expanded)
return os.path.normpath(expanded)
class Backend(QObject):
"""QML-exposed backend that bridges the engine and configuration."""
# ── Signals ────────────────────────────────────────────────
mappingsChanged = Signal()
settingsChanged = Signal()
profilesChanged = Signal()
activeProfileChanged = Signal()
statusMessage = Signal(str)
dpiFromDevice = Signal(int)
smartShiftChanged = Signal()
mouseConnectedChanged = Signal()
hidFeaturesReadyChanged = Signal()
batteryLevelChanged = Signal()
debugLogChanged = Signal()
debugEventsEnabledChanged = Signal()
gestureStateChanged = Signal()
gestureRecordsChanged = Signal()
deviceInfoChanged = Signal()
deviceLayoutChanged = Signal()
knownAppsChanged = Signal()
updateAvailable = Signal(str, str)
updateInstallChanged = Signal()
# Internal cross-thread signals
_profileSwitchRequest = Signal(str)
_dpiReadRequest = Signal(int)
_connectionChangeRequest = Signal(bool)
_batteryChangeRequest = Signal(int)
_debugMessageRequest = Signal(str)
_gestureEventRequest = Signal(object)
_smartShiftReadRequest = Signal()
_statusMessageRequest = Signal(str)
_updateAvailableRequest = Signal(str, str, bool, object)
_updateCheckFinishedRequest = Signal(bool, bool, object)
_updateInstallStateRequest = Signal(str, str, bool)
_updateInstallProgressRequest = Signal(int)
def __init__(self, engine=None, parent=None, root_dir=None):
super().__init__(parent)
self._engine = engine
self._root_dir = root_dir or os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
self._cfg = load_config()
self._mouse_connected = False
self._device_display_name = "Logitech mouse"
self._connected_device_key = ""
self._device_layout_override_key = ""
self._device_layout = get_device_layout("generic_mouse")
self._device_dpi_min = DEFAULT_DPI_MIN
self._device_dpi_max = DEFAULT_DPI_MAX
self._connected_device_source = ""
self._connected_device_transport = ""
self._battery_level = -1
self._hid_features_ready = False
self._debug_lines = []
self._debug_events_enabled = bool(
self._cfg.get("settings", {}).get("debug_mode", False)
)
self._record_mode = False
self._gesture_records = []
self._gesture_active = False
self._gesture_move_seen = False
self._gesture_move_source = ""
self._gesture_move_dx = 0
self._gesture_move_dy = 0
self._gesture_status = "Idle"
self._current_attempt = None
self._pending_smart_shift_state = None # thread-safe staging area
self._effective_supported_buttons = None # set by _apply_device_layout
self._connected_device_refresh_pending = False
self._connected_device_refresh_attempts = 0
self._latest_update_url = ""
self._latest_update_version = ""
self._update_check_in_progress = False
self._update_install_status = "idle"
self._update_install_message = ""
self._update_install_can_install = False
self._update_install_progress = 0
self._update_cancel = threading.Event()
self._pending_update_plan = None
self._pending_update_plan_path = None
self._pending_update_helper_dir = None
self._update_state = UpdateCheckState.from_dict(
self._cfg.get("settings", {}).get("update_check_state", {})
)
self._update_timer = QTimer(self)
self._update_timer.setInterval(DEFAULT_AUTO_CHECK_INTERVAL_SECONDS * 1000)
self._update_timer.timeout.connect(lambda: self._startUpdateCheck(manual=False))
# Cross-thread signal connections
self._profileSwitchRequest.connect(
self._handleProfileSwitch, Qt.QueuedConnection)
self._dpiReadRequest.connect(
self._handleDpiRead, Qt.QueuedConnection)
self._connectionChangeRequest.connect(
self._handleConnectionChange, Qt.QueuedConnection)
self._batteryChangeRequest.connect(
self._handleBatteryChange, Qt.QueuedConnection)
self._debugMessageRequest.connect(
self._handleDebugMessage, Qt.QueuedConnection)
self._gestureEventRequest.connect(
self._handleGestureEvent, Qt.QueuedConnection)
self._smartShiftReadRequest.connect(
self._handleSmartShiftRead, Qt.QueuedConnection)
self._statusMessageRequest.connect(
self._handleStatusMessage, Qt.QueuedConnection)
self._updateAvailableRequest.connect(
self._handleUpdateAvailable, Qt.QueuedConnection)
self._updateCheckFinishedRequest.connect(
self._handleUpdateCheckFinished, Qt.QueuedConnection)
self._updateInstallStateRequest.connect(
self._handleUpdateInstallState, Qt.QueuedConnection)
self._updateInstallProgressRequest.connect(
self._handleUpdateInstallProgress, Qt.QueuedConnection)
# Wire engine callbacks
if engine:
engine.set_profile_change_callback(self._onEngineProfileSwitch)
engine.set_dpi_read_callback(self._onEngineDpiRead)
engine.set_connection_change_callback(self._onEngineConnectionChange)
if hasattr(engine, "set_battery_callback"):
engine.set_battery_callback(self._onEngineBatteryRead)
if hasattr(engine, "set_debug_callback"):
engine.set_debug_callback(self._onEngineDebugMessage)
if hasattr(engine, "set_gesture_event_callback"):
engine.set_gesture_event_callback(self._onEngineGestureEvent)
if hasattr(engine, "set_smart_shift_read_callback"):
engine.set_smart_shift_read_callback(self._onEngineSmartShiftRead)
if hasattr(engine, "set_status_callback"):
engine.set_status_callback(self._onEngineStatusMessage)
if hasattr(engine, "set_debug_enabled"):
engine.set_debug_enabled(self.debugMode)
self._mouse_connected = bool(getattr(engine, "device_connected", False))
self._hid_features_ready = bool(
getattr(engine, "hid_features_ready", False)
)
if supports_login_startup():
try:
sync_login_startup_from_config(self.startAtLogin)
except Exception as exc:
print(f"[startup] Failed to sync desktop integration: {exc}", file=sys.stderr)
if self.startAtLogin:
self._cfg.setdefault("settings", {})["start_at_login"] = False
try:
save_config(self._cfg)
except Exception as save_exc:
print(
"[startup] Failed to save start-at-login recovery state: "
f"{save_exc}",
file=sys.stderr,
)
self.settingsChanged.emit()
self.statusMessage.emit(
"Start at login could not be enabled. Please try again."
)
else:
self._cfg.setdefault("settings", {})["start_at_login"] = False
self._sync_connected_device_info()
self._configureUpdateChecks()
self._consumeUpdateResultMarker()
self._cleanupStaleUpdatePreparation()
# ── Properties ─────────────────────────────────────────────
@Property(list, notify=mappingsChanged)
def buttons(self):
"""List of button dicts for the active profile, filtered by device."""
mappings = get_active_mappings(self._cfg)
device_buttons = set(
self._effective_supported_buttons or BUTTON_NAMES.keys()
)
result = []
idx = 0
for key, name in BUTTON_NAMES.items():
if key not in device_buttons:
continue
aid = mappings.get(key, "none")
idx += 1
result.append({
"key": key,
"name": name,
"actionId": aid,
"actionLabel": _action_label(aid),
"index": idx,
})
return result
def _hidden_actions(self):
"""Return set of action IDs to hide based on effective device buttons."""
btns = self._effective_supported_buttons
hidden = set()
if btns and "mode_shift" not in btns:
hidden.add("toggle_smart_shift")
hidden.add("switch_scroll_mode")
return hidden
@Property(list, notify=deviceLayoutChanged)
def actionCategories(self):
"""Actions grouped by category, filtered by device capabilities."""
from collections import OrderedDict
hidden = self._hidden_actions()
cats = OrderedDict()
for aid in sorted(
ACTIONS,
key=lambda a: (
"0" if ACTIONS[a]["category"] == "Other" else "1" + ACTIONS[a]["category"],
ACTIONS[a]["label"],
),
):
if aid in hidden:
continue
data = ACTIONS[aid]
cat = data["category"]
cats.setdefault(cat, []).append({"id": aid, "label": data["label"]})
result = [{"category": c, "actions": a} for c, a in cats.items()]
result.append({"category": "Custom", "actions": [
{"id": "__custom__", "label": "Custom Shortcut\u2026"}
]})
return result
@Property(list, notify=deviceLayoutChanged)
def allActions(self):
"""Flat sorted action list (Do Nothing first), filtered by device."""
hidden = self._hidden_actions()
result = []
none_data = ACTIONS.get("none")
if none_data:
result.append({"id": "none", "label": none_data["label"],
"category": "Other"})
for aid in sorted(
ACTIONS,
key=lambda a: (ACTIONS[a]["category"], ACTIONS[a]["label"]),
):
if aid == "none" or aid in hidden:
continue
data = ACTIONS[aid]
result.append({"id": aid, "label": data["label"],
"category": data["category"]})
result.append({"id": "__custom__", "label": "Custom Shortcut\u2026",
"category": "Custom"})
return result
@Property(list, constant=True)
def validKeyNames(self):
"""List of valid key names for custom shortcuts."""
return valid_custom_key_names()
@Property(int, notify=settingsChanged)
def dpi(self):
return self._cfg.get("settings", {}).get("dpi", 1000)
_DEFAULT_DPI_PRESETS = [800, 1200, 1600, 2400]
@Property(list, notify=settingsChanged)
def dpiPresets(self):
return self._cfg.get("settings", {}).get(
"dpi_presets", list(self._DEFAULT_DPI_PRESETS)
)
@Slot(int, int)
def setDpiPreset(self, index, value):
"""Set a single DPI preset slot (0-3) to *value*."""
device = getattr(self._engine, "connected_device", None) if self._engine else None
clamped = clamp_dpi(value, device)
presets = list(self._cfg.get("settings", {}).get(
"dpi_presets", list(self._DEFAULT_DPI_PRESETS)
))
while len(presets) < 4:
presets.append(self._DEFAULT_DPI_PRESETS[len(presets) % 4])
if 0 <= index < len(presets):
presets[index] = clamped
self._cfg.setdefault("settings", {})["dpi_presets"] = presets
save_config(self._cfg)
if self._engine:
self._engine.cfg = self._cfg
self.settingsChanged.emit()
@Property(str, notify=smartShiftChanged)
def smartShiftMode(self):
return self._cfg.get("settings", {}).get("smart_shift_mode", "ratchet")
@Property(bool, notify=smartShiftChanged)
def smartShiftEnabled(self):
return bool(self._cfg.get("settings", {}).get("smart_shift_enabled", False))
@Property(int, notify=smartShiftChanged)
def smartShiftThreshold(self):
return int(self._cfg.get("settings", {}).get("smart_shift_threshold", 25))
@Property(bool, notify=hidFeaturesReadyChanged)
def smartShiftSupported(self):
return self._engine.smart_shift_supported if self._engine else False
@Property(bool, notify=deviceLayoutChanged)
def deviceHasSmartShift(self):
"""Whether the effective device has a mode_shift button (SmartShift)."""
btns = self._effective_supported_buttons
return btns is None or "mode_shift" in btns
@Property(bool, notify=settingsChanged)
def startMinimized(self):
return bool(self._cfg.get("settings", {}).get("start_minimized", True))
@Property(bool, notify=settingsChanged)
def startAtLogin(self):
return bool(self._cfg.get("settings", {}).get("start_at_login", False))
@Property(bool, constant=True)
def supportsStartAtLogin(self):
return supports_login_startup()
@Property(bool, notify=settingsChanged)
def invertVScroll(self):
return self._cfg.get("settings", {}).get("invert_vscroll", False)
@Property(bool, notify=settingsChanged)
def invertHScroll(self):
return self._cfg.get("settings", {}).get("invert_hscroll", False)
@Property(bool, notify=settingsChanged)
def ignoreTrackpad(self):
return self._cfg.get("settings", {}).get("ignore_trackpad", True)
@Property(int, notify=settingsChanged)
def gestureThreshold(self):
return int(self._cfg.get("settings", {}).get("gesture_threshold", 50))
@Property(str, notify=settingsChanged)
def appearanceMode(self):
mode = self._cfg.get("settings", {}).get("appearance_mode", "system")
return mode if mode in {"system", "light", "dark"} else "system"
@Property(bool, notify=settingsChanged)
def debugMode(self):
return bool(self._cfg.get("settings", {}).get("debug_mode", False))
@Property(bool, notify=settingsChanged)
def checkForUpdates(self):
return bool(self._cfg.get("settings", {}).get("check_for_updates", True))
@Property(str, notify=settingsChanged)
def screenshotDirectory(self):
return self._configured_screenshot_directory()
@Property(str, notify=settingsChanged)
def screenshotDirectoryLabel(self):
return self._configured_screenshot_directory()
@Property(bool, notify=settingsChanged)
def hasCustomScreenshotDirectory(self):
return self.has_custom_screenshot_directory()
@Property(bool, constant=True)
def isWindows(self):
return sys.platform.startswith("win")
@Property(bool, constant=True)
def isLinux(self):
return sys.platform.startswith("linux")
@Property(str, notify=updateInstallChanged)
def latestUpdateVersion(self):
return self._latest_update_version
@Property(str, notify=updateInstallChanged)
def updateInstallStatus(self):
return self._update_install_status
@Property(str, notify=updateInstallChanged)
def updateInstallMessage(self):
return self._update_install_message
@Property(int, notify=updateInstallChanged)
def updateInstallProgress(self):
return int(self._update_install_progress)
@Property(bool, notify=updateInstallChanged)
def updateInstallCanInstall(self):
return self._update_install_can_install
@Property(bool, constant=True)
def updateInstallEnabled(self):
return _update_install_enabled()
@Property(bool, notify=updateInstallChanged)
def updateInstallInProgress(self):
return self._update_install_status in {
"checking",
"downloading",
"verifying",
"installing",
}
@Property(bool, notify=debugEventsEnabledChanged)
def debugEventsEnabled(self):
return self._debug_events_enabled
@Property(bool, constant=True)
def supportsGestureDirections(self):
return sys.platform in ("darwin", "win32", "linux")
@Property(bool, constant=True)
def isMacOS(self):
return sys.platform == "darwin"
@Property(bool, constant=True)
def accessibilityGranted(self):
"""Whether macOS Accessibility permission is granted (always True on other platforms)."""
if sys.platform != "darwin":
return True
try:
return bool(is_process_trusted())
except Exception:
return True
@Property(str, notify=activeProfileChanged)
def activeProfile(self):
return self._cfg.get("active_profile", "default")
@Property(bool, notify=mouseConnectedChanged)
def mouseConnected(self):
return self._mouse_connected
@Property(bool, notify=hidFeaturesReadyChanged)
def hidFeaturesReady(self):
return self._hid_features_ready
@Property(str, notify=deviceInfoChanged)
def deviceDisplayName(self):
return self._device_display_name
@Property(str, notify=deviceInfoChanged)
def connectedDeviceKey(self):
return self._connected_device_key
@Property(str, notify=deviceInfoChanged)
def connectionType(self):
return self._connected_device_transport
@Property(int, notify=deviceInfoChanged)
def deviceDpiMin(self):
return self._device_dpi_min
@Property(int, notify=deviceInfoChanged)
def deviceDpiMax(self):
return self._device_dpi_max
@Property(str, notify=deviceLayoutChanged)
def deviceImageAsset(self):
return self._device_layout.get("image_asset", "mouse.png")
@Property(str, notify=deviceLayoutChanged)
def deviceImageSource(self):
asset = self._device_layout.get("image_asset", "mouse.png")
path = os.path.join(self._root_dir, "images", asset)
return QUrl.fromLocalFile(os.path.abspath(path)).toString()
@Property(int, notify=deviceLayoutChanged)
def deviceImageWidth(self):
return int(self._device_layout.get("image_width", 460))
@Property(int, notify=deviceLayoutChanged)
def deviceImageHeight(self):
return int(self._device_layout.get("image_height", 360))
@Property(bool, notify=deviceLayoutChanged)
def hasInteractiveDeviceLayout(self):
return bool(self._device_layout.get("interactive", True))
@Property(str, notify=deviceLayoutChanged)
def deviceLayoutNote(self):
return self._device_layout.get("note", "")
@Property(list, notify=deviceLayoutChanged)
def deviceHotspots(self):
return list(self._device_layout.get("hotspots", []))
@Property(list, constant=True)
def manualLayoutChoices(self):
return get_manual_layout_choices()
@Property(str, notify=deviceLayoutChanged)
def deviceLayoutOverrideKey(self):
return self._device_layout_override_key
@Property(str, notify=deviceLayoutChanged)
def effectiveDeviceLayoutKey(self):
return self._device_layout.get("key", "generic_mouse")
@Property(int, notify=batteryLevelChanged)
def batteryLevel(self):
return self._battery_level
@Property(str, notify=debugLogChanged)
def debugLog(self):
return "\n".join(self._debug_lines)
@Property(bool, notify=gestureStateChanged)
def recordMode(self):
return self._record_mode
@Property(bool, notify=gestureStateChanged)
def gestureActive(self):
return self._gesture_active
@Property(bool, notify=gestureStateChanged)
def gestureMoveSeen(self):
return self._gesture_move_seen
@Property(str, notify=gestureStateChanged)
def gestureMoveSource(self):
return self._gesture_move_source
@Property(int, notify=gestureStateChanged)
def gestureMoveDx(self):
return self._gesture_move_dx
@Property(int, notify=gestureStateChanged)
def gestureMoveDy(self):
return self._gesture_move_dy
@Property(str, notify=gestureStateChanged)
def gestureStatus(self):
return self._gesture_status
@Property(str, notify=gestureRecordsChanged)
def gestureRecords(self):
return "\n\n".join(self._gesture_records)
@Property(list, notify=profilesChanged)
def profiles(self):
result = []
active = self._cfg.get("active_profile", "default")
for pname, pdata in self._cfg.get("profiles", {}).items():
apps = pdata.get("apps", [])
result.append({
"name": pname,
"label": pdata.get("label", pname),
"apps": apps,
"appIcons": [get_icon_for_exe(ex) for ex in apps],
"displayApps": [app_catalog.get_app_label(ex) for ex in apps],
"isActive": pname == active,
})
return result
@Property(list, notify=knownAppsChanged)
def knownApps(self):
result = []
for entry in app_catalog.get_app_catalog():
icon = get_icon_for_exe(entry.get("path", ""))
result.append({
"id": entry["id"],
"label": entry.get("label", entry["id"]),
"aliases": entry.get("aliases", []),
"path": entry.get("path", ""),
"iconSource": icon,
})
return result
def _catalog_app_id(self, spec):
entry = app_catalog.resolve_app_spec(spec)
if not entry:
return ""
entry_id = entry.get("id", "")
for catalog_entry in app_catalog.get_app_catalog():
if catalog_entry.get("id", "").lower() == entry_id.lower():
return catalog_entry["id"]
return ""
def _profile_app_identity(self, spec):
catalog_id = self._catalog_app_id(spec)
if catalog_id:
return ("catalog", catalog_id.lower())
entry = app_catalog.resolve_app_spec(spec)
path = entry.get("path", "") if entry else ""
if not path:
path = spec or ""
if not path:
return ("", "")
if sys.platform == "linux":
normalized = os.path.realpath(path)
else:
normalized = os.path.normpath(path)
return ("path", normalized.lower())
def _profile_has_app(self, spec):
target_kind, target_value = self._profile_app_identity(spec)
if not target_value:
return False
for pdata in self._cfg.get("profiles", {}).values():
for existing in pdata.get("apps", []):
existing_kind, existing_value = self._profile_app_identity(existing)
if existing_kind == target_kind and existing_value == target_value:
return True
return False
def _stored_profile_app_spec(self, entry, fallback_spec):
catalog_id = self._catalog_app_id(entry.get("id", ""))
if catalog_id:
return catalog_id
return entry.get("path") or fallback_spec
def _configured_screenshot_directory(self) -> str:
settings = self._cfg.setdefault("settings", {})
return _normalize_directory_path(settings.get("screenshot_directory", ""))
def has_custom_screenshot_directory(self) -> bool:
return bool(self._configured_screenshot_directory())
def next_screenshot_file_path(self) -> Path:
custom_directory = self._configured_screenshot_directory()
if custom_directory:
return screenshot_file_path(directory=Path(custom_directory))
return screenshot_file_path()
def next_screenshot_file_paths(self, count: int) -> list[Path]:
custom_directory = self._configured_screenshot_directory()
if custom_directory:
return screenshot_file_paths(count, directory=Path(custom_directory))
return screenshot_file_paths(count)
def _configureUpdateChecks(self):
if self.checkForUpdates:
if not self._update_timer.isActive():
self._update_timer.start()
QTimer.singleShot(3000, lambda: self._startUpdateCheck(manual=False))
else:
self._update_timer.stop()
def _startUpdateCheck(self, manual=False):
if not manual and not self.checkForUpdates:
return
if self._update_check_in_progress:
if manual:
self.statusMessage.emit("Update check already running")
return
self._update_check_in_progress = True
if manual:
self.statusMessage.emit("Checking for updates...")
thread = threading.Thread(
target=self._runUpdateCheck,
args=(bool(manual), self._update_state),
name="MouserUpdateCheck",
daemon=True,
)
thread.start()
def _runUpdateCheck(self, manual=False, state=None):
result = check_latest_release(
DEFAULT_RELEASE_REPO,
timeout=5.0,
state=state,
manual=bool(manual),
)
release = result.release
state_data = result.state.to_dict()
if release and is_newer(APP_VERSION, release.tag_name):
version = (
release.tag_name[1:]
if release.tag_name.startswith("v")
else release.tag_name
)
self._updateAvailableRequest.emit(
version, release.html_url, bool(manual), state_data
)
return
self._updateCheckFinishedRequest.emit(
bool(manual),
bool(result.reachable or result.not_modified or result.throttled),
state_data,
)
def _persistUpdateCheckState(self, state_data):
self._update_state = UpdateCheckState.from_dict(state_data)
self._cfg.setdefault("settings", {})["update_check_state"] = (
self._update_state.to_dict()
)
save_config(self._cfg)
@Slot(str, str, bool, object)
def _handleUpdateAvailable(self, version, url, manual, state_data):
self._update_check_in_progress = False
self._persistUpdateCheckState(state_data)
self._latest_update_version = str(version or "")
self._latest_update_url = str(url or "")
self._update_install_status = "available"
self._update_install_message = ""
self._update_install_can_install = False
self._pending_update_plan = None
self._pending_update_plan_path = None
self.updateInstallChanged.emit()
self.updateAvailable.emit(self._latest_update_version, self._latest_update_url)
self.statusMessage.emit(f"Mouser {self._latest_update_version} is available")
@Slot(bool, bool, object)
def _handleUpdateCheckFinished(self, manual, reachable, state_data):
self._update_check_in_progress = False
self._persistUpdateCheckState(state_data)
if manual:
if reachable:
self.statusMessage.emit("Mouser is up to date")
else:
self.statusMessage.emit("Could not check for updates")
def _setUpdateInstallState(self, status, message="", can_install=False):
self._update_install_status = str(status or "idle")
self._update_install_message = str(message or "")
self._update_install_can_install = bool(can_install)
if status not in {"downloading", "verifying", "ready_to_install"}:
self._update_install_progress = 0
self.updateInstallChanged.emit()
@Slot(str, str, bool)
def _handleUpdateInstallState(self, status, message, can_install):
self._setUpdateInstallState(status, message, can_install)
@Slot(int)
def _handleUpdateInstallProgress(self, value):
self._update_install_progress = max(0, min(100, int(value)))
self.updateInstallChanged.emit()
def _trustedBuildNumber(self):
try:
return int(self._update_state.highest_trusted_build or 0)
except (TypeError, ValueError):
return 0
def _updateErrorCode(self, exc):
if isinstance(exc, UpdateInstallError):
return exc.code
if isinstance(exc, urllib.error.HTTPError):
return "metadata_missing" if exc.code == 404 else "network_error"
if isinstance(exc, (urllib.error.URLError, TimeoutError)):
return "network_error"
if isinstance(exc, (json.JSONDecodeError, UnicodeDecodeError)):
return "metadata_invalid"
if isinstance(exc, PermissionError):
return "permission_denied"
if isinstance(exc, OSError):
return "file_error"
return "error"
def _updateProgressCallback(self, expected_size):
def _progress(downloaded):
if expected_size:
self._updateInstallProgressRequest.emit(
int(min(100, max(0, downloaded * 100 / expected_size)))
)
return _progress
def _raiseIfUpdateCancelled(self):
if self._update_cancel.is_set():
raise UpdateInstallError("cancelled", "Update cancelled.")
def _cleanupUpdatePreparation(self, stage_dir=None):
try:
cleanup_stale_update_state(locate_runtime().app_data_dir)
except Exception:
pass
if stage_dir is not None:
try:
shutil.rmtree(stage_dir, ignore_errors=True)
except Exception:
pass
def _consumeUpdateResultMarker(self):
try:
runtime = locate_runtime()
marker = runtime.app_data_dir / "last-update-result.txt"
result = read_update_result(marker)
if not result:
return
try:
marker.unlink()
except OSError:
pass
status = str(result.get("status") or "")
version = str(result.get("version") or "")
build_number = int(result.get("build_number") or 0)
if status == "installed":
if build_number > self._trustedBuildNumber():
next_state = UpdateCheckState(
**{
**self._update_state.to_dict(),
"highest_trusted_build": build_number,
}
)
self._persistUpdateCheckState(next_state.to_dict())
self._setUpdateInstallState("installed", version, False)
self.statusMessage.emit(
f"Updated to {version}" if version else "Update installed"