forked from funkypitt/Tinta4Plus-Universal
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDisplayManager.py
More file actions
1739 lines (1501 loc) · 70.3 KB
/
Copy pathDisplayManager.py
File metadata and controls
1739 lines (1501 loc) · 70.3 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
"""
Copyright (c) 2025 Jon Cox (joncox123). All rights reserved.
WARNING: This software is provided "AS IS", without any warranty of any kind. It may contain bugs or other defects
that result in data loss, corruption, hardware damage or other issues. Use at your own risk.
It may temporarily or permanently render your hardware inoperable.
It may corrupt or damage the Embedded Controller or eInk T-CON controller in your laptop.
The author is not responsible for any damage, data loss or lost productivity caused by use of this software.
By downloading and using this software you agree to these terms and acknowledge the risks involved.
"""
import subprocess
import os
import time
import json
class DisplayManager:
"""Manage display switching and configuration (no root required).
Supports X11 (via xrandr) and Wayland (via Mutter D-Bus DisplayConfig).
Auto-detects session type and desktop environment at startup.
"""
# ThinkBook Plus Gen 4 IRU hardware specifications
OLED_RESOLUTION_WH = [2880, 1800]
EINK_RESOLUTION_WH = [2560, 1600]
# Connector names as seen by the kernel / display server
OLED_CONNECTOR = "eDP-1"
EINK_CONNECTOR = "eDP-2"
def __init__(self, logger):
self.logger = logger
self.session_type = self._detect_session_type()
self.desktop_env = self._detect_desktop_environment()
self.logger.info(f"DisplayManager: session={self.session_type}, desktop={self.desktop_env}")
# ------------------------------------------------------------------
# Session / DE detection
# ------------------------------------------------------------------
def _detect_session_type(self):
"""Detect whether we are running under X11 or Wayland.
Returns 'x11', 'wayland', or 'unknown'.
"""
session = os.environ.get('XDG_SESSION_TYPE', '').lower()
if session in ('x11', 'wayland'):
return session
# Fallback: WAYLAND_DISPLAY is set when a Wayland compositor is running
if os.environ.get('WAYLAND_DISPLAY'):
return 'wayland'
# Fallback: DISPLAY is typically set for X11
if os.environ.get('DISPLAY'):
return 'x11'
return 'unknown'
def _detect_desktop_environment(self):
"""Detect the running desktop environment.
Returns 'gnome', 'cinnamon', 'xfce', 'kde', or 'unknown'.
"""
desktop = os.environ.get('XDG_CURRENT_DESKTOP', '').lower()
if 'cinnamon' in desktop:
return 'cinnamon'
if 'gnome' in desktop or 'ubuntu' in desktop:
return 'gnome'
if 'kde' in desktop:
return 'kde'
if 'xfce' in desktop:
return 'xfce'
return 'unknown'
# ------------------------------------------------------------------
# Public API — dispatchers
# ------------------------------------------------------------------
def _use_kde_wayland(self):
"""Check if we should use KDE Wayland (kscreen) backend."""
return self.session_type == 'wayland' and self.desktop_env == 'kde'
def _use_mutter_wayland(self):
"""Check if we should use Mutter (GNOME) Wayland backend."""
return self.session_type == 'wayland' and self.desktop_env in ('gnome', 'unknown')
def get_displays(self):
"""Get list of connected displays."""
if self._use_kde_wayland():
return self._get_displays_kde()
if self._use_mutter_wayland():
return self._get_displays_wayland()
return self._get_displays_x11()
def is_display_active(self, display_name):
"""Check if a display is currently active (enabled and has geometry)."""
if self._use_kde_wayland():
return self._is_display_active_kde(display_name)
if self._use_mutter_wayland():
return self._is_display_active_wayland(display_name)
return self._is_display_active_x11(display_name)
def enable_display(self, display_name, scale=None):
"""Enable/turn on a display with optional scaling.
Args:
display_name: Name of the display (e.g., 'eDP-1', 'eDP-2')
scale: Optional scale factor (e.g., 1.60 means UI appears 1.6x larger)
"""
if self._use_kde_wayland():
return self._enable_display_kde(display_name, scale)
if self._use_mutter_wayland():
return self._enable_display_wayland(display_name, scale)
return self._enable_display_x11(display_name, scale)
def disable_display(self, display_name):
"""Disable/turn off a display."""
if self._use_kde_wayland():
return self._disable_display_kde(display_name)
if self._use_mutter_wayland():
return self._disable_display_wayland(display_name)
return self._disable_display_x11(display_name)
def get_display_scale(self, display_name):
"""Get the current scale factor of a display.
Returns the scale as a float (e.g., 1.0, 1.25, 1.5), or None if
the display is not active or the scale cannot be determined.
"""
if self._use_kde_wayland():
return self._get_display_scale_kde(display_name)
if self._use_mutter_wayland():
return self._get_display_scale_wayland(display_name)
return self._get_display_scale_x11(display_name)
def _get_display_scale_x11(self, display_name):
"""Get display scale from xrandr --verbose (Transform matrix)."""
try:
result = subprocess.run(
['xrandr', '--query', '--verbose'],
capture_output=True, text=True, timeout=5
)
if result.returncode != 0:
return None
# Parse output: find the display section, then its Transform matrix
in_display = False
for line in result.stdout.split('\n'):
if display_name in line and 'connected' in line:
in_display = True
continue
if in_display and line and not line[0].isspace():
# Reached next display section
break
if in_display and 'Transform:' in line:
# Transform matrix first row: "Transform: 0.571429 0.000000 0.000000"
# The (0,0) element is the inverse of the scale
parts = line.split()
if len(parts) >= 2:
try:
scale_inv = float(parts[1])
if scale_inv > 0:
return round(1.0 / scale_inv, 2)
except ValueError:
pass
return None
except Exception as e:
self.logger.warning(f"Failed to get X11 display scale: {e}")
return None
def _get_display_scale_wayland(self, display_name):
"""Get display scale from Mutter logical monitor state."""
state = self._mutter_get_current_state()
if not state:
return None
lm = self._find_logical_monitor(state, display_name)
if lm:
return lm['scale']
return None
def _get_display_scale_kde(self, display_name):
"""Get display scale from kscreen-doctor."""
out = self._kscreen_find_output(display_name)
if out and out.get('scale'):
return out['scale']
return None
def wake_display(self):
"""Force the physical panel out of DPMS standby and unlock.
On X11 this uses ``xset dpms force on``.
On Wayland it deactivates the GNOME screensaver, unlocks the
session, and activates it via loginctl.
Disabling eDP-2 can cause GNOME to lock the session (as if
the lid was closed), so we must both unlock and activate.
"""
if self.session_type != 'wayland':
# X11 path
try:
subprocess.run(['xset', 'dpms', 'force', 'on'],
capture_output=True, timeout=5)
self.logger.info("X11: sent DPMS force on")
except Exception as e:
self.logger.warning(f"xset dpms force on failed: {e}")
return
# Wayland / GNOME path
# 1. Deactivate GNOME Screensaver via D-Bus
try:
subprocess.run(
['gdbus', 'call', '--session',
'--dest', 'org.gnome.ScreenSaver',
'--object-path', '/org/gnome/ScreenSaver',
'--method', 'org.gnome.ScreenSaver.SetActive', 'false'],
capture_output=True, timeout=5)
self.logger.info("Wayland: deactivated GNOME ScreenSaver")
except Exception as e:
self.logger.warning(f"Wayland: GNOME ScreenSaver D-Bus failed: {e}")
# 2. Unlock and activate all login sessions — disabling a display
# can trigger GNOME to lock the session, producing a black screen
# that only flashes content briefly when the lid moves.
try:
result = subprocess.run(['loginctl', 'show-user', os.environ.get('USER', ''),
'--property=Sessions', '--value'],
capture_output=True, text=True, timeout=5)
sessions = result.stdout.strip().split()
for session in sessions:
subprocess.run(['loginctl', 'unlock-session', session],
capture_output=True, timeout=5)
subprocess.run(['loginctl', 'activate', session],
capture_output=True, timeout=5)
self.logger.info("Wayland: unlocked and activated session via loginctl")
except Exception as e:
self.logger.warning(f"Wayland: loginctl unlock/activate failed: {e}")
def get_display_geometry(self, display_name):
"""Get the geometry (position and size) of a display."""
if self._use_kde_wayland():
return self._get_display_geometry_kde(display_name)
if self._use_mutter_wayland():
return self._get_display_geometry_wayland(display_name)
return self._get_display_geometry_x11(display_name)
def display_fullscreen_image(self, display_name, image_path):
"""Display a fullscreen image on a specific display.
Args:
display_name: Name of the display (e.g., 'eDP-2')
image_path: Path to the image file
Returns:
subprocess.Popen object if successful, None otherwise
"""
if not os.path.exists(image_path):
self.logger.error(f"Image file not found: {image_path}")
return None
# Get display geometry (informational only — don't block on failure)
geometry = self.get_display_geometry(display_name)
if geometry:
self.logger.info(f"Display {display_name} geometry: {geometry['width']}x{geometry['height']}+{geometry['x']}+{geometry['y']}")
else:
self.logger.warning(f"Could not determine geometry for {display_name}, displaying image anyway")
if self.session_type == 'wayland':
return self._display_image_wayland(image_path, geometry)
return self._display_image_x11(image_path, geometry)
# ------------------------------------------------------------------
# X11 backend (xrandr)
# ------------------------------------------------------------------
def _get_displays_x11(self):
"""Get list of connected displays using xrandr."""
try:
result = subprocess.run(
['xrandr', '--query'],
capture_output=True,
text=True,
timeout=5
)
displays = []
for line in result.stdout.split('\n'):
if ' connected' in line:
parts = line.split()
name = parts[0]
primary = 'primary' in line
displays.append({'name': name, 'primary': primary})
return displays
except Exception as e:
self.logger.error(f"Failed to get displays: {e}")
return []
def _is_display_active_x11(self, display_name):
"""Check if a display is currently active using xrandr."""
try:
result = subprocess.run(
['xrandr', '--query'],
capture_output=True,
text=True,
timeout=5
)
for line in result.stdout.split('\n'):
if display_name in line and ' connected' in line:
parts = line.split()
for part in parts:
if 'x' in part and '+' in part:
return True
return False
return False
except Exception as e:
self.logger.error(f"Failed to check display status: {e}")
return False
def _enable_display_x11(self, display_name, scale=None):
"""Enable a display using xrandr with optional scaling."""
try:
if display_name == "eDP-1":
native_width, native_height = self.OLED_RESOLUTION_WH
elif display_name == "eDP-2":
native_width, native_height = self.EINK_RESOLUTION_WH
else:
self.logger.warning(f"Unknown display {display_name}, using auto mode")
native_width, native_height = None, None
cmd = ['xrandr', '--output', display_name]
if native_width and native_height:
cmd.extend(['--mode', f'{native_width}x{native_height}'])
# Explicit position at origin — without --pos xrandr may
# place the display beside the other output, creating an
# invisible extended desktop where the pointer can roam
# but clicks don't hit any visible window.
cmd.extend(['--pos', '0x0'])
if scale is not None and scale != 1.0:
scale_inv = 1.0 / scale
panning_width = int(native_width * scale_inv)
panning_height = int(native_height * scale_inv)
cmd.extend(['--panning', f'{panning_width}x{panning_height}'])
cmd.extend(['--scale', f'{scale_inv}x{scale_inv}'])
self.logger.info(f"Scaling: virtual desktop {panning_width}x{panning_height}, "
f"xrandr scale {scale_inv:.3f}x{scale_inv:.3f} (our scale={scale}), "
f"physical {native_width}x{native_height}")
else:
cmd.extend(['--panning', f'{native_width}x{native_height}'])
cmd.extend(['--scale', '1x1'])
else:
cmd.extend(['--auto', '--pos', '0x0'])
result = subprocess.run(cmd, capture_output=True, text=True, timeout=5)
if result.returncode != 0:
self.logger.warning(f"xrandr returned {result.returncode}: {result.stderr.strip()}")
time.sleep(0.5)
# Force DPMS on to wake the panel — xrandr may enable the output
# in the display server while the physical panel stays in standby.
try:
subprocess.run(['xset', 'dpms', 'force', 'on'],
capture_output=True, timeout=5)
except Exception as dpms_err:
self.logger.warning(f"xset dpms force on failed: {dpms_err}")
time.sleep(0.3)
if self._is_display_active_x11(display_name):
scale_info = f" with {scale}x scale" if scale and scale != 1.0 else ""
self.logger.info(f"Enabled display: {display_name}{scale_info}")
return True
else:
self.logger.error(f"Failed to enable display: {display_name} (display not active after command)")
return False
except Exception as e:
self.logger.error(f"Failed to enable display: {e}")
return False
def _disable_display_x11(self, display_name):
"""Disable a display using xrandr."""
try:
subprocess.run(
['xrandr', '--output', display_name, '--off'],
capture_output=True,
timeout=5
)
time.sleep(0.2)
if not self._is_display_active_x11(display_name):
self.logger.info(f"Disabled display: {display_name}")
return True
else:
self.logger.error(f"Failed to disable display: {display_name} (display still active after command)")
return False
except Exception as e:
self.logger.error(f"Failed to disable display: {e}")
return False
def _get_display_geometry_x11(self, display_name):
"""Get display geometry using xrandr."""
try:
result = subprocess.run(
['xrandr', '--query'],
capture_output=True,
text=True,
timeout=5
)
for line in result.stdout.split('\n'):
if display_name in line and 'connected' in line:
parts = line.split()
for part in parts:
if 'x' in part and '+' in part:
geo = part.split('+')
size = geo[0].split('x')
width = int(size[0])
height = int(size[1])
x_offset = int(geo[1]) if len(geo) > 1 else 0
y_offset = int(geo[2]) if len(geo) > 2 else 0
return {
'width': width,
'height': height,
'x': x_offset,
'y': y_offset
}
self.logger.warning(f"Could not find geometry for {display_name}")
return None
except Exception as e:
self.logger.error(f"Failed to get display geometry: {e}")
return None
def _display_image_x11(self, image_path, geometry):
"""Display fullscreen image using feh (preferred on X11), fallback to imv."""
if self._command_exists('feh'):
try:
geo = "{0}x{1}+{2}+{3}".format(geometry['width'], geometry['height'], geometry['x'], geometry['y']) if geometry else "2560x1600+0+0"
cmd = [
'feh',
'--auto-zoom',
'--no-menus',
'--hide-pointer',
'--borderless',
'--geometry', geo,
image_path
]
self.logger.info("Displaying fullscreen image using feh")
process = subprocess.Popen(cmd)
time.sleep(0.5)
return process
except Exception as e:
self.logger.error(f"Failed to display image with feh: {e}")
if self._command_exists('imv'):
try:
cmd = ['imv', '-f', image_path]
self.logger.info("Displaying image using imv (fallback)")
self.logger.warning("imv may not position on correct display automatically")
process = subprocess.Popen(cmd)
time.sleep(0.5)
return process
except Exception as e:
self.logger.error(f"Failed to display image with imv: {e}")
self.logger.error("Neither feh nor imv is installed. Please install one:")
self.logger.error(" For X11: sudo apt install feh")
self.logger.error(" For Wayland: sudo apt install imv")
return None
# ------------------------------------------------------------------
# Wayland backend (Mutter D-Bus DisplayConfig)
# ------------------------------------------------------------------
def _mutter_call(self, method, *args):
"""Call a method on org.gnome.Mutter.DisplayConfig via D-Bus.
Tries python3-dbus first, falls back to gdbus subprocess.
Returns the parsed result or None on failure.
"""
try:
import dbus
bus = dbus.SessionBus()
proxy = bus.get_object('org.gnome.Mutter.DisplayConfig',
'/org/gnome/Mutter/DisplayConfig')
iface = dbus.Interface(proxy, 'org.gnome.Mutter.DisplayConfig')
return getattr(iface, method)(*args)
except ImportError:
self.logger.debug("python3-dbus not available, using gdbus subprocess")
except Exception as e:
self.logger.debug(f"dbus call failed ({method}): {e}, trying gdbus")
return self._mutter_call_gdbus(method, *args)
def _mutter_call_gdbus(self, method, *args):
"""Fallback: call Mutter DisplayConfig via gdbus CLI."""
try:
cmd = [
'gdbus', 'call',
'--session',
'--dest', 'org.gnome.Mutter.DisplayConfig',
'--object-path', '/org/gnome/Mutter/DisplayConfig',
'--method', f'org.gnome.Mutter.DisplayConfig.{method}'
]
for arg in args:
cmd.append(str(arg))
result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
if result.returncode != 0:
self.logger.error(f"gdbus {method} failed: {result.stderr.strip()}")
return None
return result.stdout.strip()
except Exception as e:
self.logger.error(f"gdbus call failed ({method}): {e}")
return None
def _mutter_get_current_state(self):
"""Get current display state from Mutter.
Returns a dict with 'serial', 'monitors', and 'logical_monitors',
or None on failure.
Each monitor entry: {
'connector': str, # e.g. 'eDP-1'
'vendor': str,
'product': str,
'serial': str,
'modes': [{'id': str, 'width': int, 'height': int,
'refresh': float, 'preferred_scale': float,
'supported_scales': [float], 'is_current': bool,
'is_preferred': bool}],
}
Each logical_monitor entry: {
'x': int, 'y': int, 'scale': float, 'transform': int,
'primary': bool,
'monitors': [{'connector': str, 'vendor': str, 'product': str, 'serial': str}],
}
"""
try:
import dbus
return self._mutter_get_current_state_dbus()
except ImportError:
pass
except Exception:
pass
return self._mutter_get_current_state_gdbus()
def _mutter_get_current_state_dbus(self):
"""Parse GetCurrentState via python3-dbus."""
import dbus
bus = dbus.SessionBus()
proxy = bus.get_object('org.gnome.Mutter.DisplayConfig',
'/org/gnome/Mutter/DisplayConfig')
iface = dbus.Interface(proxy, 'org.gnome.Mutter.DisplayConfig')
state = iface.GetCurrentState()
serial = int(state[0])
raw_monitors = state[1]
raw_logical = state[2]
monitors = []
for mon in raw_monitors:
# mon = ((connector, vendor, product, serial), [modes], properties)
spec = mon[0]
connector = str(spec[0])
vendor = str(spec[1])
product = str(spec[2])
mon_serial = str(spec[3])
modes = []
for m in mon[1]:
# m = (id, width, height, refresh, preferred_scale, supported_scales, properties)
mode_props = dict(m[6]) if len(m) > 6 else {}
is_current = bool(mode_props.get('is-current', False))
is_preferred = bool(mode_props.get('is-preferred', False))
modes.append({
'id': str(m[0]),
'width': int(m[1]),
'height': int(m[2]),
'refresh': float(m[3]),
'preferred_scale': float(m[4]),
'supported_scales': [float(s) for s in m[5]],
'is_current': is_current,
'is_preferred': is_preferred,
})
monitors.append({
'connector': connector,
'vendor': vendor,
'product': product,
'serial': mon_serial,
'modes': modes,
})
logical_monitors = []
for lm in raw_logical:
# lm = (x, y, scale, transform, primary, [(connector, vendor, product, serial)], properties)
lm_mons = []
for ms in lm[5]:
lm_mons.append({
'connector': str(ms[0]),
'vendor': str(ms[1]),
'product': str(ms[2]),
'serial': str(ms[3]),
})
logical_monitors.append({
'x': int(lm[0]),
'y': int(lm[1]),
'scale': float(lm[2]),
'transform': int(lm[3]),
'primary': bool(lm[4]),
'monitors': lm_mons,
})
return {
'serial': serial,
'monitors': monitors,
'logical_monitors': logical_monitors,
}
def _mutter_get_current_state_gdbus(self):
"""Parse GetCurrentState via gdbus subprocess.
gdbus returns GVariant text format. We parse it with a best-effort approach
by calling gdbus and then extracting monitor info from the raw text.
"""
try:
cmd = [
'gdbus', 'call', '--session',
'--dest', 'org.gnome.Mutter.DisplayConfig',
'--object-path', '/org/gnome/Mutter/DisplayConfig',
'--method', 'org.gnome.Mutter.DisplayConfig.GetCurrentState'
]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
if result.returncode != 0:
self.logger.error(f"gdbus GetCurrentState failed: {result.stderr.strip()}")
return None
# The output is a complex GVariant. We use a Python helper to parse it
# by extracting key patterns. This is fragile but works as a fallback.
return self._parse_gdbus_state(result.stdout)
except Exception as e:
self.logger.error(f"Failed to get Mutter state via gdbus: {e}")
return None
def _parse_gdbus_state(self, raw_output):
"""Best-effort parse of gdbus GetCurrentState GVariant output.
Since GVariant text format is complex, we use a simplified approach:
extract connector names and basic info using subprocess + python3 eval.
"""
try:
# Use python3 to evaluate the GVariant-like output as a Python tuple
# gdbus output closely resembles Python tuple syntax
# Replace GVariant type annotations that python can't parse
cleaned = raw_output.strip()
if cleaned.startswith('(') and cleaned.endswith(')'):
# Try using python3 subprocess to safely parse
parse_script = r'''
import sys, ast, json
raw = sys.stdin.read().strip()
# Remove trailing comma before closing paren in top-level tuple
# GVariant uses @type annotations - strip them
import re
# Remove @type annotations like @au, @a(ss), etc.
cleaned = re.sub(r"@[a-z({}\[\])]+\s", "", raw)
# Remove uint32/int32/int64/uint64/double type casts
cleaned = re.sub(r"\b(uint32|int32|int64|uint64|double)\s+", "", cleaned)
# Replace 'true'/'false' with Python booleans
cleaned = cleaned.replace("true", "True").replace("false", "False")
try:
data = ast.literal_eval(cleaned)
serial = data[0]
monitors = []
for mon in data[1]:
spec = mon[0]
modes = []
for m in mon[1]:
props = dict(m[6]) if len(m) > 6 else {}
modes.append({
"id": str(m[0]),
"width": int(m[1]),
"height": int(m[2]),
"refresh": float(m[3]),
"preferred_scale": float(m[4]),
"supported_scales": [float(s) for s in m[5]],
"is_current": bool(props.get("is-current", False)),
"is_preferred": bool(props.get("is-preferred", False)),
})
monitors.append({
"connector": str(spec[0]),
"vendor": str(spec[1]),
"product": str(spec[2]),
"serial": str(spec[3]),
"modes": modes,
})
logical = []
for lm in data[2]:
lm_mons = [{"connector": str(ms[0]), "vendor": str(ms[1]),
"product": str(ms[2]), "serial": str(ms[3])} for ms in lm[5]]
logical.append({
"x": int(lm[0]), "y": int(lm[1]),
"scale": float(lm[2]), "transform": int(lm[3]),
"primary": bool(lm[4]),
"monitors": lm_mons,
})
print(json.dumps({"serial": serial, "monitors": monitors, "logical_monitors": logical}))
except Exception as e:
print(json.dumps(None))
'''
proc = subprocess.run(
['python3', '-c', parse_script],
input=cleaned, capture_output=True, text=True, timeout=10
)
if proc.returncode == 0 and proc.stdout.strip():
parsed = json.loads(proc.stdout.strip())
return parsed
self.logger.warning("Could not parse gdbus GetCurrentState output")
return None
except Exception as e:
self.logger.error(f"Failed to parse gdbus state: {e}")
return None
def _find_monitor_in_state(self, state, display_name):
"""Find a monitor entry by connector name in a Mutter state dict."""
if not state or 'monitors' not in state:
return None
for mon in state['monitors']:
if mon['connector'] == display_name:
return mon
return None
def _find_logical_monitor(self, state, display_name):
"""Find the logical monitor entry that contains a given connector."""
if not state or 'logical_monitors' not in state:
return None
for lm in state['logical_monitors']:
for ms in lm['monitors']:
if ms['connector'] == display_name:
return lm
return None
def _best_scale(self, supported_scales, target_scale):
"""Find the closest supported Mutter scale to the target.
Mutter only allows discrete scale values (e.g., 1.0, 1.25, 1.5, 1.75, 2.0).
"""
if not supported_scales:
return 1.0
return min(supported_scales, key=lambda s: abs(s - target_scale))
def _get_displays_wayland(self):
"""Get list of connected displays via Mutter D-Bus."""
state = self._mutter_get_current_state()
if not state:
self.logger.warning("Wayland: could not query Mutter, falling back to X11")
return self._get_displays_x11()
displays = []
for mon in state['monitors']:
# A monitor is "primary" if it appears in a logical monitor marked primary
primary = False
for lm in state.get('logical_monitors', []):
if lm.get('primary'):
for ms in lm['monitors']:
if ms['connector'] == mon['connector']:
primary = True
displays.append({'name': mon['connector'], 'primary': primary})
return displays
def _is_display_active_wayland(self, display_name):
"""Check if a display is active (has a logical monitor) via Mutter."""
state = self._mutter_get_current_state()
if not state:
self.logger.warning("Wayland: could not query Mutter, falling back to X11")
return self._is_display_active_x11(display_name)
return self._find_logical_monitor(state, display_name) is not None
def _enable_display_wayland(self, display_name, scale=None):
"""Enable a display via Mutter ApplyMonitorsConfig."""
state = self._mutter_get_current_state()
if not state:
self.logger.warning("Wayland: could not query Mutter, falling back to X11")
return self._enable_display_x11(display_name, scale)
monitor = self._find_monitor_in_state(state, display_name)
if not monitor:
self.logger.error(f"Monitor {display_name} not found in Mutter state")
return False
# Find the preferred or current mode
target_mode = None
for m in monitor['modes']:
if m.get('is_preferred'):
target_mode = m
break
if not target_mode and monitor['modes']:
target_mode = monitor['modes'][0]
if not target_mode:
self.logger.error(f"No modes available for {display_name}")
return False
# Determine the Mutter scale
if scale is not None and scale != 1.0:
mutter_scale = self._best_scale(target_mode.get('supported_scales', [1.0]), scale)
else:
mutter_scale = target_mode.get('preferred_scale', 1.0)
self.logger.info(f"Wayland: enabling {display_name} mode={target_mode['width']}x{target_mode['height']}"
f"@{target_mode['refresh']:.1f}Hz scale={mutter_scale}")
# Build the logical monitors config: keep all existing + add the new one
logical_configs = []
# Collect existing logical monitors (excluding any that already have this connector)
for lm in state.get('logical_monitors', []):
connectors_in_lm = [ms['connector'] for ms in lm['monitors']]
if display_name not in connectors_in_lm:
lm_monitors_spec = []
for ms in lm['monitors']:
# Find the current mode for this monitor
mon_info = self._find_monitor_in_state(state, ms['connector'])
mode_id = ''
if mon_info:
for mm in mon_info['modes']:
if mm.get('is_current'):
mode_id = mm['id']
break
if not mode_id and mon_info['modes']:
mode_id = mon_info['modes'][0]['id']
lm_monitors_spec.append((ms['connector'], mode_id, {}))
logical_configs.append({
'x': lm['x'], 'y': lm['y'],
'scale': lm['scale'],
'transform': lm['transform'],
'primary': lm['primary'],
'monitors': lm_monitors_spec,
})
# Place the new display at (0, 0) so it overlaps existing monitors
# (mirror-like). The OLED will be disabled shortly after, so this
# avoids a visible extended-desktop state on the eInk.
logical_configs.append({
'x': 0, 'y': 0,
'scale': mutter_scale,
'transform': 0,
'primary': False,
'monitors': [(display_name, target_mode['id'], {})],
})
return self._mutter_apply_config(state['serial'], logical_configs)
def _disable_display_wayland(self, display_name):
"""Disable a display via Mutter ApplyMonitorsConfig."""
state = self._mutter_get_current_state()
if not state:
self.logger.warning("Wayland: could not query Mutter, falling back to X11")
return self._disable_display_x11(display_name)
if not self._find_logical_monitor(state, display_name):
self.logger.info(f"Display {display_name} already disabled")
return True
# Rebuild logical monitors excluding the target
logical_configs = []
for lm in state.get('logical_monitors', []):
connectors_in_lm = [ms['connector'] for ms in lm['monitors']]
if display_name not in connectors_in_lm:
lm_monitors_spec = []
for ms in lm['monitors']:
mon_info = self._find_monitor_in_state(state, ms['connector'])
mode_id = ''
if mon_info:
for mm in mon_info['modes']:
if mm.get('is_current'):
mode_id = mm['id']
break
if not mode_id and mon_info['modes']:
mode_id = mon_info['modes'][0]['id']
lm_monitors_spec.append((ms['connector'], mode_id, {}))
logical_configs.append({
'x': lm['x'], 'y': lm['y'],
'scale': lm['scale'],
'transform': lm['transform'],
'primary': lm['primary'],
'monitors': lm_monitors_spec,
})
if not logical_configs:
self.logger.error("Cannot disable all displays")
return False
# Ensure at least one is primary
has_primary = any(lc['primary'] for lc in logical_configs)
if not has_primary:
logical_configs[0]['primary'] = True
success = self._mutter_apply_config(state['serial'], logical_configs)
if success:
self.logger.info(f"Disabled display: {display_name}")
return success
def _logical_width(self, logical_monitor, state):
"""Compute the logical width of a logical monitor."""
for ms in logical_monitor['monitors']:
mon_info = self._find_monitor_in_state(state, ms['connector'])
if mon_info:
for mm in mon_info['modes']:
if mm.get('is_current'):
return int(mm['width'] / logical_monitor['scale'])
if mon_info['modes']:
return int(mon_info['modes'][0]['width'] / logical_monitor['scale'])
return 0
def _mutter_apply_config(self, serial, logical_configs):
"""Apply a display configuration via Mutter ApplyMonitorsConfig.
Args:
serial: Config serial from GetCurrentState
logical_configs: List of logical monitor dicts
Uses python3-dbus if available, otherwise gdbus.
Method 1 = temporary (reverts after 20s if not confirmed).
Method 2 = persistent.
We use method 2 to match xrandr behavior.
"""
try:
import dbus
return self._mutter_apply_config_dbus(serial, logical_configs)
except ImportError:
pass
except Exception as e:
self.logger.debug(f"dbus ApplyMonitorsConfig failed: {e}, trying gdbus")
return self._mutter_apply_config_gdbus(serial, logical_configs)
def _mutter_apply_config_dbus(self, serial, logical_configs):
"""Apply config via python3-dbus."""
import dbus
bus = dbus.SessionBus()
proxy = bus.get_object('org.gnome.Mutter.DisplayConfig',
'/org/gnome/Mutter/DisplayConfig')
iface = dbus.Interface(proxy, 'org.gnome.Mutter.DisplayConfig')
# Build the D-Bus argument structure
# ApplyMonitorsConfig(serial, method, logical_monitors, properties)
# method: 2 = persistent
dbus_logical = []
for lc in logical_configs:
dbus_monitors = []
for mon_spec in lc['monitors']:
# (connector, mode_id, properties_dict)
dbus_monitors.append(dbus.Struct([
dbus.String(mon_spec[0]),
dbus.String(mon_spec[1]),
dbus.Dictionary(mon_spec[2] if len(mon_spec) > 2 else {},
signature='sv'),
], signature='ssa{sv}'))
dbus_logical.append(dbus.Struct([
dbus.Int32(lc['x']),
dbus.Int32(lc['y']),
dbus.Double(lc['scale']),
dbus.UInt32(lc['transform']),
dbus.Boolean(lc['primary']),
dbus.Array(dbus_monitors, signature='(ssa{sv})'),
], signature='iidub a(ssa{sv})'))
try:
iface.ApplyMonitorsConfig(
dbus.UInt32(serial),
dbus.UInt32(2), # method=2 persistent
dbus.Array(dbus_logical, signature='(iiduba(ssa{sv}))'),
dbus.Dictionary({}, signature='sv'),
)
time.sleep(0.3)
return True
except Exception as e: