-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinux_layout.py
More file actions
executable file
·995 lines (858 loc) · 37.7 KB
/
linux_layout.py
File metadata and controls
executable file
·995 lines (858 loc) · 37.7 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
#!/usr/bin/env python3
"""
Linux layout script for VS Code: window positioning and side panel resizing.
Uses Chrome DevTools Protocol (CDP) for cursor-free sash drag, with fallback
to state.vscdb modification. Supports KDE multi-monitor via kscreen-doctor.
# reprompty-mcp: {"toolName":"dual_monitor_layout_bottom","label":"Dual monitor layout (bottom)","description":"Run the Ctrl+Alt+V dual monitor bottom layout","args":["--once","--dual"]}
# reprompty-mcp: {"toolName":"top_monitors_layout_panel_full","label":"Top monitors layout (panel full)","description":"Run the Ctrl+Alt+N top monitors panel-full layout","args":["--once","--single"]}
Usage:
python3 linux_layout.py --once --dual
python3 linux_layout.py --once --single
python3 linux_layout.py --once --dual --window-title "MyProject"
python3 linux_layout.py --once --single --window-handle 12345678
python3 linux_layout.py --once --dual --panel-left
python3 linux_layout.py --once --dual --panel-right
"""
import argparse
import base64
import hashlib
import json
import os
import random
import re
import sqlite3
import socket
import struct
import subprocess
import sys
import time
import urllib.request
from typing import Optional, Dict, Any, Tuple
# =============================================================================
# Minimal stdlib WebSocket client for CDP
# =============================================================================
GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
class MinimalWebSocket:
"""A minimal WebSocket client using only Python stdlib."""
def __init__(self, url: str, timeout: float = 10.0):
self.url = url
self.timeout = timeout
self.sock: Optional[socket.socket] = None
self._connect()
def _connect(self):
m = re.match(r"ws://([^/:]+)(?::(\d+))?(.*)", self.url)
if not m:
raise ValueError(f"Unsupported WebSocket URL: {self.url}")
host = m.group(1)
port = int(m.group(2)) if m.group(2) else 80
path = m.group(3) or "/"
self.sock = socket.create_connection((host, port), timeout=self.timeout)
key = base64.b64encode(os.urandom(16)).decode("ascii")
handshake = (
f"GET {path} HTTP/1.1\r\n"
f"Host: {host}:{port}\r\n"
f"Upgrade: websocket\r\n"
f"Connection: Upgrade\r\n"
f"Sec-WebSocket-Key: {key}\r\n"
f"Sec-WebSocket-Version: 13\r\n"
f"\r\n"
)
self.sock.sendall(handshake.encode("ascii"))
# Read HTTP response
response = b""
while b"\r\n\r\n" not in response:
chunk = self.sock.recv(4096)
if not chunk:
raise ConnectionError("WebSocket handshake failed")
response += chunk
header, _ = response.split(b"\r\n\r\n", 1)
if b"101" not in header.split(b"\r\n", 1)[0]:
raise ConnectionError(f"WebSocket handshake failed: {header.decode()}")
# Validate accept key
expected = base64.b64encode(hashlib.sha1((key + GUID).encode()).digest()).decode()
if expected.encode() not in header:
raise ConnectionError("WebSocket accept key mismatch")
def send_text(self, text: str):
data = text.encode("utf-8")
mask = struct.pack("<I", random.getrandbits(32))
length = len(data)
# First byte: FIN=1, opcode=1 (text)
# Second byte: MASK=1, length
if length < 126:
header = struct.pack("!BB", 0x81, 0x80 | length)
elif length < 65536:
header = struct.pack("!BBH", 0x81, 0x80 | 126, length)
else:
header = struct.pack("!BBQ", 0x81, 0x80 | 127, length)
masked = bytes(b ^ mask[i % 4] for i, b in enumerate(data))
self.sock.sendall(header + mask + masked)
def recv_text(self) -> str:
# Read frame header
header = self._recv_exact(2)
b1, b2 = header[0], header[1]
fin = (b1 >> 7) & 1
opcode = b1 & 0x0F
masked = (b2 >> 7) & 1
length = b2 & 0x7F
if length == 126:
length = struct.unpack("!H", self._recv_exact(2))[0]
elif length == 127:
length = struct.unpack("!Q", self._recv_exact(8))[0]
if masked:
mask = self._recv_exact(4)
payload = self._recv_exact(length)
payload = bytes(b ^ mask[i % 4] for i, b in enumerate(payload))
else:
payload = self._recv_exact(length)
if opcode == 0x08: # close
raise ConnectionError("WebSocket closed by server")
if opcode == 0x09: # ping
# Send pong
self.sock.sendall(struct.pack("!BB", 0x8A, 0) + payload)
return self.recv_text()
if opcode == 0x01: # text
return payload.decode("utf-8")
if opcode == 0x02: # binary
return payload.decode("utf-8")
# For other opcodes (continuation), try to receive more
if not fin:
return self.recv_text()
return ""
def _recv_exact(self, n: int) -> bytes:
buf = b""
while len(buf) < n:
chunk = self.sock.recv(n - len(buf))
if not chunk:
raise ConnectionError("WebSocket connection closed unexpectedly")
buf += chunk
return buf
def close(self):
if self.sock:
try:
self.sock.sendall(struct.pack("!BB", 0x88, 0))
except Exception:
pass
self.sock.close()
self.sock = None
# =============================================================================
# Logging
# =============================================================================
def log(msg: str, log_file: Optional[str] = None):
line = f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {msg}"
print(line)
if log_file:
with open(log_file, "a") as f:
f.write(line + "\n")
# =============================================================================
# Monitor geometry detection
# =============================================================================
def get_monitor_geometry(log_file: Optional[str] = None) -> list:
"""Detect monitor layout using kscreen-doctor --json (KDE)."""
try:
result = subprocess.run(
["kscreen-doctor", "--json"],
capture_output=True, text=True, timeout=10
)
if result.returncode != 0:
raise RuntimeError(result.stderr)
data = json.loads(result.stdout)
outputs = data.get("outputs", [])
monitors = []
for out in outputs:
if not out.get("enabled") or not out.get("connected"):
continue
pos = out.get("pos", {})
size = out.get("size", {})
monitors.append({
"name": out.get("name", "unknown"),
"x": pos.get("x", 0),
"y": pos.get("y", 0),
"width": size.get("width", 1920),
"height": size.get("height", 1080),
})
# Sort left-to-right by x position
monitors.sort(key=lambda m: m["x"])
log(f"Detected {len(monitors)} monitor(s): {monitors}", log_file)
return monitors
except Exception as e:
log(f"Monitor detection failed: {e}, using fallback", log_file)
return [{"name": "fallback", "x": 0, "y": 0, "width": 1920, "height": 1080}]
def compute_layout(monitors: list, layout_mode: str, panel_side: str) -> dict:
"""Compute target window geometry based on monitors and layout mode."""
if not monitors:
monitors = [{"x": 0, "y": 0, "width": 1920, "height": 1080}]
# Sort monitors by area descending for single layout preference
monitors_by_area = sorted(monitors, key=lambda m: m["width"] * m["height"], reverse=True)
if layout_mode == "dual" and len(monitors) >= 2:
# Find the best pair of adjacent monitors
# Prefer same-size monitors, then largest total area
best_pair = None
best_score = -1
for i in range(len(monitors)):
for j in range(i + 1, len(monitors)):
left = monitors[i]
right = monitors[j]
# Check if they're adjacent horizontally (left edge of right == right edge of left)
if abs((left["x"] + left["width"]) - right["x"]) < 10 or abs((right["x"] + right["width"]) - left["x"]) < 10:
same_size = (left["width"] == right["width"] and left["height"] == right["height"])
y_aligned = abs(left["y"] - right["y"]) < 100
total_area = left["width"] * left["height"] + right["width"] * right["height"]
score = (1000000 if same_size else 0) + (500000 if y_aligned else 0) + total_area
if score > best_score:
best_score = score
# Ensure left is the leftmost monitor
if left["x"] <= right["x"]:
best_pair = (left, right)
else:
best_pair = (right, left)
# Fallback to first adjacent pair or first two
if best_pair is None:
for i in range(len(monitors) - 1):
left = monitors[i]
right = monitors[i + 1]
if abs((left["x"] + left["width"]) - right["x"]) < 10:
best_pair = (left, right)
break
if best_pair is None:
best_pair = (monitors[0], monitors[1])
left, right = best_pair
target_x = left["x"]
target_y = min(left["y"], right["y"])
target_w = (right["x"] + right["width"]) - left["x"]
target_h = max(left["y"] + left["height"], right["y"] + right["height"]) - target_y
panel_w = left["width"]
elif layout_mode == "single" and len(monitors) >= 1:
# Use largest monitor
m = monitors_by_area[0]
target_x = m["x"]
target_y = m["y"]
target_w = m["width"]
target_h = m["height"]
panel_w = m["width"] // 2
else:
# Default single monitor
m = monitors_by_area[0]
target_x = m["x"]
target_y = m["y"]
target_w = m["width"]
target_h = m["height"]
panel_w = m["width"] // 2
return {
"x": target_x,
"y": target_y,
"width": target_w,
"height": target_h,
"panel_width": panel_w,
"panel_side": panel_side,
}
# =============================================================================
# Tool detection
# =============================================================================
KDOTOOL_PATH = os.path.expanduser("~/.local/bin/kdotool")
def _has_kdotool() -> bool:
return os.path.isfile(KDOTOOL_PATH) and os.access(KDOTOOL_PATH, os.X_OK)
def _has_xdotool() -> bool:
try:
env = os.environ.copy()
env["LD_LIBRARY_PATH"] = os.path.expanduser("~/.local/lib") + ":" + env.get("LD_LIBRARY_PATH", "")
result = subprocess.run(["xdotool", "version"], capture_output=True, timeout=2, env=env)
return result.returncode == 0
except Exception:
return False
# =============================================================================
# Window finding
# =============================================================================
def get_active_window(log_file: Optional[str] = None) -> Optional[Tuple[str, str]]:
"""Get the currently active/focused window ID and title."""
# Try kdotool first (KDE Wayland native)
if _has_kdotool():
try:
result = subprocess.run(
[KDOTOOL_PATH, "getactivewindow"],
capture_output=True, text=True, timeout=5
)
if result.returncode == 0:
wid = result.stdout.strip()
if wid and wid.startswith("{"):
title = get_window_title(wid)
if title:
return (wid, title)
except Exception as e:
log(f"kdotool getactivewindow error: {e}", log_file)
# Fallback to xdotool (X11/XWayland)
if _has_xdotool():
env = os.environ.copy()
env["LD_LIBRARY_PATH"] = os.path.expanduser("~/.local/lib") + ":" + env.get("LD_LIBRARY_PATH", "")
try:
result = subprocess.run(
["xdotool", "getactivewindow"],
capture_output=True, text=True, timeout=5, env=env
)
if result.returncode == 0:
wid = result.stdout.strip()
if wid:
title_result = subprocess.run(
["xdotool", "getwindowname", wid],
capture_output=True, text=True, timeout=2, env=env
)
if title_result.returncode == 0:
title = title_result.stdout.strip()
return (wid, title)
except Exception as e:
log(f"xdotool getactivewindow error: {e}", log_file)
return None
def find_vscode_window(title: Optional[str] = None, handle: Optional[str] = None, log_file: Optional[str] = None) -> Optional[str]:
"""Find VS Code: window id using kdotool (Wayland) or xdotool (X11).
When no specific title or handle is given, prefers the currently active window."""
if handle is not None:
return handle
search_terms = [title] if title else ["Visual Studio Code", "Kilo Code", "Kimi Code", "VSCodium", "Code: - OSS"]
# If no specific title/handle requested, try active window first
if not title and not handle:
active = get_active_window(log_file)
if active:
wid, active_title = active
if any(term in active_title for term in search_terms):
log(f"Using active window: {wid} ('{active_title}')", log_file)
return wid
else:
log(f"Active window '{active_title}' is not a VS Code: editor, falling back to search", log_file)
# Try kdotool first (KDE Wayland native)
if _has_kdotool():
for search_term in search_terms:
try:
result = subprocess.run(
[KDOTOOL_PATH, "search", "--title", search_term, "--limit", "1"],
capture_output=True, text=True, timeout=5
)
if result.returncode == 0:
wid = result.stdout.strip()
if wid and wid.startswith("{"):
return wid
except Exception as e:
log(f"kdotool search error: {e}")
# Fallback to xdotool (X11/XWayland)
if _has_xdotool():
env = os.environ.copy()
env["LD_LIBRARY_PATH"] = os.path.expanduser("~/.local/lib") + ":" + env.get("LD_LIBRARY_PATH", "")
for search_term in search_terms:
try:
result = subprocess.run(
["xdotool", "search", "--name", search_term],
capture_output=True, text=True, timeout=5, env=env
)
if result.returncode == 0:
lines = [l.strip() for l in result.stdout.strip().split("\n") if l.strip()]
for line in lines:
try:
wid = int(line)
name_result = subprocess.run(
["xdotool", "getwindowname", str(wid)],
capture_output=True, text=True, timeout=2, env=env
)
if name_result.returncode == 0:
name = name_result.stdout.strip()
if any(k in name for k in ["Visual Studio Code", "Kilo Code", "Kimi Code", "VSCodium", "Code: - OSS"]):
return str(wid)
except Exception:
continue
except Exception as e:
log(f"xdotool search error: {e}")
return None
# =============================================================================
# Window manipulation
# =============================================================================
def get_window_title(wid: str) -> Optional[str]:
"""Get the title of a window using kdotool or xdotool."""
is_kdotool = wid.startswith("{")
if is_kdotool and _has_kdotool():
try:
result = subprocess.run(
[KDOTOOL_PATH, "getwindowname", wid],
capture_output=True, text=True, timeout=5
)
if result.returncode == 0:
return result.stdout.strip()
except Exception:
pass
# Fallback to xdotool
env = os.environ.copy()
env["LD_LIBRARY_PATH"] = os.path.expanduser("~/.local/lib") + ":" + env.get("LD_LIBRARY_PATH", "")
try:
result = subprocess.run(
["xdotool", "getwindowname", str(wid)],
capture_output=True, text=True, timeout=5, env=env
)
if result.returncode == 0:
return result.stdout.strip()
except Exception:
pass
return None
def move_window(wid: str, x: int, y: int, width: int, height: int, log_file: Optional[str] = None) -> bool:
"""Move and resize a window using kdotool (Wayland) or xdotool (X11)."""
is_kdotool = wid.startswith("{")
if is_kdotool and _has_kdotool():
try:
# KDE 6: windowsize requires the window to be active first, but
# windowmove must happen BEFORE activation to avoid desktop-switch drift.
subprocess.run(
[KDOTOOL_PATH, "windowmove", wid, str(x), str(y)],
capture_output=True, timeout=5,
)
time.sleep(0.1)
subprocess.run(
[KDOTOOL_PATH, "windowactivate", wid],
capture_output=True, timeout=5,
)
time.sleep(0.2)
subprocess.run(
[KDOTOOL_PATH, "windowsize", wid, str(width), str(height)],
capture_output=True, timeout=5,
)
log(f"Moved window {wid} to {x},{y} size {width}x{height}", log_file)
return True
except Exception as e:
log(f"ERROR moving window with kdotool: {e}", log_file)
return False
# Fallback to xdotool (X11/XWayland)
env = os.environ.copy()
env["LD_LIBRARY_PATH"] = os.path.expanduser("~/.local/lib") + ":" + env.get("LD_LIBRARY_PATH", "")
try:
subprocess.run(["xdotool", "windowmove", str(wid), str(x), str(y)], capture_output=True, timeout=5, env=env)
subprocess.run(["xdotool", "windowsize", str(wid), str(width), str(height)], capture_output=True, timeout=5, env=env)
log(f"Moved window {wid} to {x},{y} size {width}x{height}", log_file)
return True
except Exception as e:
log(f"ERROR moving window with xdotool: {e}", log_file)
return False
def trigger_layout_refresh(wid: str, log_file: Optional[str] = None) -> bool:
"""Trigger VS Code: to recalculate layout by briefly resizing the window."""
is_kdotool = wid.startswith("{")
try:
if is_kdotool and _has_kdotool():
result = subprocess.run(
[KDOTOOL_PATH, "getwindowgeometry", wid],
capture_output=True, text=True, timeout=5
)
# Parse: "Window {uuid}\n Position: x,y\n Geometry: wxh"
w, h = 1920, 1080
for line in result.stdout.strip().split("\n"):
if "Geometry:" in line:
parts = line.split("Geometry:")[1].strip().split("x")
if len(parts) == 2:
w, h = int(parts[0]), int(parts[1])
break
# Resize by 1 pixel and back using direct UUID
subprocess.run(
[KDOTOOL_PATH, "windowsize", wid, str(w + 1), str(h)],
capture_output=True, timeout=2
)
time.sleep(0.05)
subprocess.run(
[KDOTOOL_PATH, "windowsize", wid, str(w), str(h)],
capture_output=True, timeout=2
)
else:
env = os.environ.copy()
env["LD_LIBRARY_PATH"] = os.path.expanduser("~/.local/lib") + ":" + env.get("LD_LIBRARY_PATH", "")
result = subprocess.run(
["xdotool", "getwindowgeometry", str(wid)],
capture_output=True, text=True, timeout=5, env=env
)
if result.returncode != 0:
return False
for line in result.stdout.strip().split("\n"):
if "Geometry:" in line:
size = line.split("Geometry: ")[1]
w, h = map(int, size.split("x"))
break
subprocess.run(["xdotool", "windowsize", str(wid), str(w + 1), str(h)], capture_output=True, timeout=2, env=env)
time.sleep(0.05)
subprocess.run(["xdotool", "windowsize", str(wid), str(w), str(h)], capture_output=True, timeout=2, env=env)
log("Triggered layout refresh", log_file)
return True
except Exception as e:
log(f"ERROR triggering layout refresh: {e}", log_file)
return False
# =============================================================================
# state.vscdb fallback
# =============================================================================
def get_state_db_path() -> str:
home = os.environ.get("HOME", ".")
candidates = [
os.path.join(home, ".config", "Code", "User", "globalStorage", "state.vscdb"),
os.path.join(home, ".config", "VSCodium", "User", "globalStorage", "state.vscdb"),
os.path.join(home, ".config", "Code - OSS", "User", "globalStorage", "state.vscdb"),
]
for p in candidates:
if os.path.exists(p):
return p
raise FileNotFoundError("VS Code: state database not found")
def set_auxiliary_bar_width(width: int, log_file: Optional[str] = None) -> bool:
try:
db_path = get_state_db_path()
conn = sqlite3.connect(db_path)
try:
cur = conn.cursor()
cur.execute(
"UPDATE ItemTable SET value = ? WHERE key = 'workbench.auxiliaryBar.size'",
(str(width),),
)
size_updated = cur.rowcount
cur.execute(
"UPDATE ItemTable SET value = ? WHERE key = 'workbench.auxiliaryBar.lastNonMaximizedSize'",
(str(width),),
)
conn.commit()
if size_updated == 0:
log(f"WARNING: key 'workbench.auxiliaryBar.size' not found", log_file)
return False
log(f"Set auxiliaryBar.size = {width}", log_file)
return True
finally:
conn.close()
except Exception as e:
log(f"ERROR setting auxiliary bar width: {e}", log_file)
return False
# =============================================================================
# CDP (Chrome DevTools Protocol)
# =============================================================================
def get_cdp_port() -> int:
"""Get CDP port from DevToolsActivePort or argv.json."""
home = os.environ.get("HOME", ".")
# Try DevToolsActivePort files first
candidates = [
os.path.join(home, ".config", "Code", "DevToolsActivePort"),
os.path.join(home, ".config", "VSCodium", "DevToolsActivePort"),
os.path.join(home, ".config", "Code - OSS", "DevToolsActivePort"),
]
for port_file in candidates:
if os.path.exists(port_file):
try:
with open(port_file, "r") as f:
port = int(f.readline().strip())
if port > 0:
return port
except Exception:
pass
# Fallback to argv.json
argv_candidates = [
os.path.join(home, ".vscode", "argv.json"),
os.path.join(home, ".config", "VSCodium", "argv.json"),
os.path.join(home, ".config", "Code - OSS", "argv.json"),
]
for argv_file in argv_candidates:
if os.path.exists(argv_file):
try:
with open(argv_file, "r") as f:
data = json.load(f)
port = data.get("remote-debugging-port")
if port:
return int(str(port))
except Exception:
pass
return 9222
def get_cdp_targets(port: int, log_file: Optional[str] = None) -> list:
"""Fetch CDP target list from http://localhost:<port>/json."""
try:
req = urllib.request.Request(f"http://127.0.0.1:{port}/json")
with urllib.request.urlopen(req, timeout=3) as resp:
data = json.loads(resp.read().decode("utf-8"))
targets = [t for t in data if t.get("type") == "page"]
log(f"CDP: {len(targets)} page target(s) on port {port}", log_file)
return targets
except Exception as e:
log(f"CDP: Failed to fetch targets on port {port}: {e}", log_file)
return []
def find_matching_target(targets: list, window_title: Optional[str] = None) -> Optional[dict]:
"""Find the CDP target matching the given window title."""
workbench_targets = [t for t in targets if "workbench" in t.get("url", "")]
if window_title:
# Exact match
for t in targets:
if t.get("title") == window_title:
return t
# Partial match
for t in targets:
if window_title in t.get("title", ""):
return t
# Fallback to first workbench target
if workbench_targets:
return workbench_targets[0]
# Last resort: first page target
if targets:
return targets[0]
return None
def cdp_send(ws: MinimalWebSocket, method: str, params: dict) -> dict:
"""Send a CDP command and wait for the response."""
msg_id = random.randint(1, 1000000)
msg = json.dumps({"id": msg_id, "method": method, "params": params})
ws.send_text(msg)
while True:
response = ws.recv_text()
try:
data = json.loads(response)
if data.get("id") == msg_id:
return data
except Exception:
continue
def get_auxiliary_bar_sash_position(ws: MinimalWebSocket) -> Optional[dict]:
"""Query the DOM to find the auxiliary bar sash position and side."""
js = """
(() => {
const debug = [];
const auxBar = document.getElementById('workbench.parts.auxiliarybar');
if (!auxBar) return JSON.stringify({ error: 'no-auxiliary-bar', debug: ['auxBar element not found'] });
const auxRect = auxBar.getBoundingClientRect();
const isLeft = auxRect.left < window.innerWidth / 2;
debug.push('auxBar: left=' + Math.round(auxRect.left) + ' top=' + Math.round(auxRect.top) + ' w=' + Math.round(auxRect.width) + ' h=' + Math.round(auxRect.height));
debug.push('auxBar side=' + (isLeft ? 'LEFT' : 'RIGHT'));
if (auxRect.width === 0) return JSON.stringify({ error: 'auxiliary-bar-hidden', auxBarWidth: 0, debug: debug });
const allSashes = document.querySelectorAll('.monaco-sash');
const vertSashes = document.querySelectorAll('.monaco-sash.vertical');
debug.push('sashes: total=' + allSashes.length + ' vertical=' + vertSashes.length);
let bestSash = null;
let bestDist = Infinity;
for (const s of vertSashes) {
const r = s.getBoundingClientRect();
const sashCenter = r.left + r.width / 2;
const dist = isLeft
? Math.abs(sashCenter - (auxRect.left + auxRect.width))
: Math.abs(sashCenter - auxRect.left);
debug.push(' sash: x=' + Math.round(r.left) + ' w=' + Math.round(r.width) + ' h=' + Math.round(r.height) + ' dist=' + Math.round(dist));
if (dist < bestDist) {
bestDist = dist;
bestSash = s;
}
}
if (!bestSash || bestDist > 20) return JSON.stringify({ error: 'no-sash-found', bestDist: bestDist, debug: debug });
const sr = bestSash.getBoundingClientRect();
debug.push('bestSash: left=' + Math.round(sr.left) + ' w=' + Math.round(sr.width) + ' dist=' + Math.round(bestDist));
return JSON.stringify({
sashX: Math.round(sr.left + sr.width / 2),
sashY: Math.round(sr.top + sr.height / 2),
sashTop: Math.round(sr.top),
sashBottom: Math.round(sr.bottom),
auxBarLeft: Math.round(auxRect.left),
auxBarWidth: Math.round(auxRect.width),
windowWidth: window.innerWidth,
isLeft: isLeft,
debug: debug
});
})()
"""
resp = cdp_send(ws, "Runtime.evaluate", {"expression": js, "returnByValue": True})
result = resp.get("result", {}).get("result", {})
value = result.get("value")
if not value:
return None
try:
return json.loads(value)
except Exception:
return None
def cdp_drag_sash(ws: MinimalWebSocket, from_x: int, from_y: int, to_x: int, to_y: int):
"""Drag the sash from one position to another via CDP mouse events."""
# Mouse pressed at sash
cdp_send(ws, "Input.dispatchMouseEvent", {
"type": "mousePressed",
"x": from_x,
"y": from_y,
"button": "left",
"clickCount": 1,
})
# Send intermediate mouse moves for reliable large drags.
# 'buttons': 1 is required so VS Code: interprets these as drag events.
dx = to_x - from_x
dy = to_y - from_y
distance = max(abs(dx), abs(dy))
steps = max(3, distance // 40) # ~40px per step
for i in range(1, steps + 1):
ix = from_x + (dx * i // steps)
iy = from_y + (dy * i // steps)
cdp_send(ws, "Input.dispatchMouseEvent", {
"type": "mouseMoved",
"x": ix,
"y": iy,
"button": "left",
"buttons": 1,
})
time.sleep(0.01)
# Release
cdp_send(ws, "Input.dispatchMouseEvent", {
"type": "mouseReleased",
"x": to_x,
"y": to_y,
"button": "left",
"clickCount": 1,
})
def set_auxiliary_bar_width_cdp(
target_width: int,
window_title: Optional[str] = None,
expected_window_width: int = 0,
panel_side: str = "right",
log_file: Optional[str] = None,
) -> bool:
"""Resize auxiliary bar via CDP sash drag. Returns True on success."""
log("Resizing auxiliary bar via CDP...", log_file)
port = get_cdp_port()
targets = get_cdp_targets(port, log_file)
target = find_matching_target(targets, window_title)
if not target:
log("CDP: No suitable target found", log_file)
return False
ws_url = target.get("webSocketDebuggerUrl")
if not ws_url:
log("CDP: Target has no WebSocket URL", log_file)
return False
ws = None
try:
ws = MinimalWebSocket(ws_url)
log(f"CDP: Connected to {target.get('title', 'unknown')}", log_file)
sash_info = get_auxiliary_bar_sash_position(ws)
if not sash_info or sash_info.get("error"):
err = sash_info.get("error") if sash_info else "no response"
log(f"CDP: Sash error: {err}", log_file)
return False
current_sash_x = sash_info["sashX"]
sash_y = sash_info["sashY"]
effective_width = expected_window_width if expected_window_width > 0 else sash_info["windowWidth"]
is_left = sash_info.get("isLeft", False)
# Determine target sash position based on panel side
if is_left or panel_side == "left":
target_sash_x = target_width
else:
target_sash_x = effective_width - target_width
side_str = "LEFT" if (is_left or panel_side == "left") else "RIGHT"
log(f"CDP: Sash at X={current_sash_x}, target X={target_sash_x} (panel={target_width}px on {side_str})", log_file)
if abs(current_sash_x - target_sash_x) <= 5:
log("CDP: Already at target position", log_file)
return True
log(f"CDP: Dragging sash from X={current_sash_x} to X={target_sash_x}", log_file)
cdp_drag_sash(ws, current_sash_x, sash_y, target_sash_x, sash_y)
time.sleep(0.5)
# Verify
verify = get_auxiliary_bar_sash_position(ws)
if verify and not verify.get("error"):
new_width = verify["auxBarWidth"]
log(f"CDP: Auxiliary bar resized to {new_width}px", log_file)
return True
log("CDP: Drag sent (verification skipped)", log_file)
return True
except Exception as e:
log(f"CDP error: {e}", log_file)
return False
finally:
if ws:
ws.close()
# =============================================================================
# Main
# =============================================================================
def load_slot_from_config(slot_letter: str, log_file: Optional[str] = None) -> Optional[dict]:
"""Load layout coordinates from ~/.reprompty/layouts.json."""
try:
home = os.environ.get("HOME", ".")
config_path = os.path.join(home, ".reprompty", "layouts.json")
if not os.path.exists(config_path):
return None
with open(config_path, "r") as f:
data = json.load(f)
for slot in data.get("slots", []):
if slot.get("letter") == slot_letter:
return {
"x": slot.get("windowX", 0),
"y": slot.get("windowY", 0),
"width": slot.get("windowWidth", 1920),
"height": slot.get("windowHeight", 1080),
"panel_width": slot.get("panelWidth", 960),
}
return None
except Exception as e:
log(f"Failed to load slot {slot_letter} from layouts.json: {e}", log_file)
return None
def main():
parser = argparse.ArgumentParser(description="VS Code: Linux Layout")
parser.add_argument("--once", action="store_true", help="Run once and exit")
parser.add_argument("--dual", action="store_true", help="Dual monitor layout")
parser.add_argument("--single", action="store_true", help="Single monitor layout")
parser.add_argument("--slot", type=str, default=None, help="Load coordinates from layouts.json slot (A or B)")
parser.add_argument("--window-title", type=str, default=None)
parser.add_argument("--window-handle", type=str, default=None, help="Window ID (xdotool integer or kdotool UUID)")
parser.add_argument("--log-path", type=str, default=None)
parser.add_argument("--panel-left", action="store_true", help="Panel on left side")
parser.add_argument("--panel-right", action="store_true", help="Panel on right side (default)")
parser.add_argument("--cdp-port", type=int, default=None, help="CDP port override")
parser.add_argument("--x", type=int, default=None, help="Override window X position")
parser.add_argument("--y", type=int, default=None, help="Override window Y position")
parser.add_argument("--width", type=int, default=None, help="Override window width")
parser.add_argument("--height", type=int, default=None, help="Override window height")
parser.add_argument("--panel-width", type=int, default=None, help="Override panel width")
args = parser.parse_args()
log_file = args.log_path
panel_side = "left" if args.panel_left else "right"
# Load layout: slot config > auto-detect > fallback
if args.slot:
layout = load_slot_from_config(args.slot, log_file)
if layout:
log(f"Loaded slot {args.slot} from layouts.json", log_file)
else:
log(f"Slot {args.slot} not found in layouts.json, falling back to auto-detect", log_file)
layout = None
else:
layout = None
if not layout:
monitors = get_monitor_geometry(log_file)
layout_mode = "dual" if args.dual else "single"
layout = compute_layout(monitors, layout_mode, panel_side)
# Apply CLI overrides (highest priority)
if args.x is not None:
layout["x"] = args.x
if args.y is not None:
layout["y"] = args.y
if args.width is not None:
layout["width"] = args.width
if args.height is not None:
layout["height"] = args.height
if args.panel_width is not None:
layout["panel_width"] = args.panel_width
log(f"Layout: x={layout['x']} y={layout['y']} w={layout['width']} h={layout['height']} panel={layout['panel_width']} side={panel_side}", log_file)
# Find window
handle = args.window_handle if args.window_handle else None
wid = find_vscode_window(title=args.window_title, handle=handle, log_file=log_file)
if not wid:
log("ERROR: No VS Code: window found", log_file)
sys.exit(1)
log(f"Found window: {wid}", log_file)
# Resolve the actual window title so CDP targets the same window
resolved_title = args.window_title
if not resolved_title:
resolved_title = get_window_title(wid)
if resolved_title:
log(f"Resolved window title: {resolved_title}", log_file)
# Move and resize window FIRST so sash drag coordinates are correct
if not move_window(wid, layout["x"], layout["y"], layout["width"], layout["height"], log_file):
log("ERROR: Failed to move window", log_file)
sys.exit(1)
# Try CDP sash drag now that window is at final geometry
cdp_success = set_auxiliary_bar_width_cdp(
target_width=layout["panel_width"],
window_title=resolved_title,
expected_window_width=layout["width"],
panel_side=panel_side,
log_file=log_file,
)
if cdp_success:
log("CDP resize succeeded.", log_file)
else:
log("CDP resize failed, falling back to state.vscdb...", log_file)
db_updated = set_auxiliary_bar_width(layout["panel_width"], log_file)
if db_updated:
log("Panel width set in state DB.", log_file)
else:
log("WARNING: state DB fallback also failed.", log_file)
# Trigger layout refresh if we used state DB fallback
if not cdp_success:
trigger_layout_refresh(wid, log_file)
log("Layout applied successfully", log_file)
sys.exit(0)
if __name__ == "__main__":
main()