-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtab_switcher.py
More file actions
1597 lines (1451 loc) · 57 KB
/
tab_switcher.py
File metadata and controls
1597 lines (1451 loc) · 57 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
#!/usr/bin/env python3
from __future__ import annotations
import json
import ctypes
import os
import select
import sys
import termios
import time
import tty
import traceback
import socket
try:
from kitty import fast_data_types as _fdt # type: ignore
except Exception:
_fdt = None
from typing import Any, Callable, Iterable
from kittens.tui.handler import kitten_ui
from preview_gen import render_block_preview
from preview_capture import get_text_lines_from_rc
from theme_parser import Theme, load_theme
PREVIEW_COLS = 40
PREVIEW_ROWS = 12 # logical rows (will be rendered as block rows)
MIN_PREVIEW_COLS = 24
MIN_PREVIEW_ROWS = 6
MIN_TITLE_COLS = 20
MAX_VISIBLE_CARDS = 7
PREVIEW_NEIGHBORS = 1
PREVIEW_COLOR_MODE = "both" # none|fg|bg|both
THEME_ENV_VAR = "KTS_THEME"
CACHE_FILENAME = "kitty-tab-switcher.json"
PREVIEW_CACHE_FILENAME = "kitty-tab-switcher-previews.json"
PREVIEW_REFRESH_SECS = 0.5
SWITCHER_TITLE = "KTS_SWITCHER"
DEBUG_ENV = "KTS_DEBUG"
DEBUG_PATH_ENV = "KTS_DEBUG_PATH"
DEFAULT_DEBUG_PATH = os.path.expanduser("~/.cache/kitty-tab-switcher-debug.log")
PROFILE_ENV = "KTS_PROFILE"
PROFILE_PATH_ENV = "KTS_PROFILE_PATH"
PROFILE_SAMPLE_MS_ENV = "KTS_PROFILE_SAMPLE_MS"
CSI = "\x1b["
KEYBOARD_MODE_PUSH = f"{CSI}>1u"
KEYBOARD_MODE_POP = f"{CSI}<u"
# Enable disambiguation + report events + report all keys
KEYBOARD_ENHANCE_FLAGS = 1 | 2 | 8
KEYBOARD_MODE_SET = f"{CSI}={KEYBOARD_ENHANCE_FLAGS};1u"
TAB_CODE = 9
ESC_CODE = 27
CTRL_KEY_CODES = {57442, 57448}
MARKER_KEY_CODE = 57387 # f24 from kitty send-key
MARKER_SEQ = "\x1b[9999u"
class TabInfo:
def __init__(
self,
id: int,
title: str,
window_id: int,
is_active: bool,
layout: str | None = None,
last_focused: float | None = None,
) -> None:
self.id = id
self.title = title
self.window_id = window_id
self.is_active = is_active
self.layout = layout
self.last_focused = last_focused
class StateStore:
def __init__(self, os_window_id: int) -> None:
self.os_window_id = os_window_id
self.pid = int(os.environ.get("KITTY_PID", "0") or "0")
cache_dir = os.environ.get(
"KITTY_CACHE_DIRECTORY",
os.path.expanduser("~/.cache"),
)
self.path = os.path.join(cache_dir, CACHE_FILENAME)
def load(self) -> dict[int, float]:
if not os.path.exists(self.path):
return {}
try:
with open(self.path, "r", encoding="utf-8") as f:
data = json.load(f)
except Exception:
return {}
pid_key = str(self.pid)
if pid_key not in data:
return {}
raw = data.get(pid_key, {}).get(str(self.os_window_id), {})
if isinstance(raw, list):
now = time.time()
out: dict[int, float] = {}
for idx, tid in enumerate(raw):
try:
out[int(tid)] = now - idx
except Exception:
continue
return out
if isinstance(raw, dict):
out = {}
for k, v in raw.items():
try:
out[int(k)] = float(v)
except Exception:
continue
return out
return {}
def save(self, last_used: dict[int, float]) -> None:
data: dict[str, Any] = {}
if os.path.exists(self.path):
try:
with open(self.path, "r", encoding="utf-8") as f:
data = json.load(f)
except Exception:
data = {}
pid_key = str(self.pid)
osw_key = str(self.os_window_id)
data.setdefault(pid_key, {})
data[pid_key][osw_key] = {str(k): float(v) for k, v in last_used.items()}
os.makedirs(os.path.dirname(self.path), exist_ok=True)
with open(self.path, "w", encoding="utf-8") as f:
json.dump(data, f)
try:
ordered = sorted(last_used.items(), key=lambda kv: kv[1], reverse=True)
os.environ["KTS_MRU"] = ",".join(str(k) for k, _ in ordered)
except Exception:
pass
class PreviewStore:
def __init__(self, os_window_id: int) -> None:
self.os_window_id = os_window_id
self.pid = int(os.environ.get("KITTY_PID", "0") or "0")
cache_dir = os.environ.get(
"KITTY_CACHE_DIRECTORY",
os.path.expanduser("~/.cache"),
)
self.path = os.path.join(cache_dir, PREVIEW_CACHE_FILENAME)
def load(self) -> tuple[dict[int, list[str]], dict[int, float]]:
if not os.path.exists(self.path):
return {}, {}
try:
with open(self.path, "r", encoding="utf-8") as f:
data = json.load(f)
except Exception:
return {}, {}
pid_key = str(self.pid)
osw_key = str(self.os_window_id)
raw = data.get(pid_key, {}).get(osw_key, {})
out: dict[int, list[str]] = {}
ts_out: dict[int, float] = {}
if isinstance(raw, dict):
for k, v in raw.items():
try:
tid = int(k)
except Exception:
continue
if isinstance(v, dict):
lines = v.get("lines")
ts = v.get("ts")
else:
lines = v
ts = None
if isinstance(lines, list) and all(isinstance(s, str) for s in lines):
out[tid] = lines
if isinstance(ts, (int, float)):
ts_out[tid] = float(ts)
return out, ts_out
def save(self, previews: dict[int, list[str]], timestamps: dict[int, float]) -> None:
data: dict[str, Any] = {}
if os.path.exists(self.path):
try:
with open(self.path, "r", encoding="utf-8") as f:
data = json.load(f)
except Exception:
data = {}
pid_key = str(self.pid)
osw_key = str(self.os_window_id)
data.setdefault(pid_key, {})
payload: dict[str, Any] = {}
now = time.time()
for k, v in previews.items():
ts = timestamps.get(k, now)
payload[str(k)] = {"lines": v, "ts": ts}
data[pid_key][osw_key] = payload
os.makedirs(os.path.dirname(self.path), exist_ok=True)
with open(self.path, "w", encoding="utf-8") as f:
json.dump(data, f)
class KeyEvent:
def __init__(self, key_code: int, mods: int = 1, event_type: int = 1) -> None:
self.key_code = key_code
self.mods = mods
self.event_type = event_type
@property
def shift(self) -> bool:
return bool((self.mods - 1) & 1)
@property
def ctrl(self) -> bool:
return bool((self.mods - 1) & 4)
class RawSwitcher:
def __init__(
self,
tabs: list[TabInfo],
mru: dict[int, float],
os_window_id: int,
direction: int,
remote_control: Callable[..., Any],
command_server: "CommandServer | None",
theme: Theme,
profiler: SectionProfiler,
) -> None:
self.tabs = tabs
self.os_window_id = os_window_id
self.remote_control = remote_control
self.command_server = command_server
self.theme = theme
self.profiler = profiler
self.state = StateStore(os_window_id)
self.preview_state = PreviewStore(os_window_id)
self.preview_cache: dict[int, list[str]] = {}
self.preview_cache_ts: dict[int, float] = {}
cached, cached_ts = self.preview_state.load()
self.preview_cache.update(cached)
self.preview_cache_ts.update(cached_ts)
self.layout_restore_tab_id: int | None = None
self.layout_restore_name: str | None = None
self.layout_changed = False
self.last_used = self._reconcile_mru(mru)
self.original_tab_id = self._active_tab_id()
if self.original_tab_id is not None:
self.last_used[self.original_tab_id] = time.time()
self.mru_order = [t.id for t in self.tabs]
self.selected_index = self._initial_index(direction)
log(
"init_state",
direction=direction,
original=self.original_tab_id,
active=self._active_tab_id(),
tabs=[t.id for t in self.tabs],
mru_order=self.mru_order,
selected_index=self.selected_index,
selected_tab=self._current_tab_id(),
)
self.last_draw = 0.0
self.ctrl_down = False
self.start_time = time.time()
self.saw_tab_event = False
self.ctrl_seen = False
self.mod_query, self.ctrl_mask = resolve_mod_query()
self.last_input_time = time.time()
self.poll_ctrl_seen = False
self.any_key_event = False
self.ctrl_up_streak = 0
self.marker_seen = False
self.marker_sent = False
self.initial_mods_checked = False
self.initial_ctrl_down = False
self.preview_refresh_secs = max(0.05, float(self.theme.preview_refresh_ms) / 1000.0)
self.preview_fetch_budget_secs = max(0.005, float(self.theme.preview_fetch_budget_ms) / 1000.0)
self.mod_poll_fast_secs = max(0.005, float(self.theme.mod_poll_fast_ms) / 1000.0)
self.mod_poll_idle_secs = max(self.mod_poll_fast_secs, float(self.theme.mod_poll_idle_ms) / 1000.0)
self.last_mod_poll = 0.0
self.last_mod_poll_value: int | None = None
self.last_preview_fetch = 0.0
self.preview_dirty = False
self.last_preview_save = 0.0
self.preview_save_interval = 0.5
self.render_cache: dict[tuple[int, int, int, str, int], list[str]] = {}
def run(self) -> None:
log("switcher.run start", tabs=len(self.tabs), selected=self.selected_index)
self._maybe_stack_active_tab()
self._send_marker()
self._check_initial_mods()
self.draw()
self._schedule_preview_fetch()
fd = sys.stdin.fileno()
while True:
rlist = [fd]
if self.command_server is not None:
rlist.append(self.command_server.fileno())
idle_for = time.time() - self.last_input_time
timeout = self.mod_poll_fast_secs if idle_for < 0.3 else self.mod_poll_idle_secs
with self.profiler.scoped("loop.select_wait"):
r, _, _ = select.select(rlist, [], [], timeout)
if not r:
if self._drain_preview_queue():
self.draw()
now = time.time()
if self.mod_query is not None and self.ctrl_mask is not None and (now - self.last_mod_poll) >= timeout:
self.last_mod_poll = now
with self.profiler.scoped("loop.mod_poll"):
mods = self.mod_query()
if mods is not None:
if mods != self.last_mod_poll_value:
log("mods_poll", mods=mods)
self.last_mod_poll_value = mods
if ctrl_is_down(mods, self.ctrl_mask):
self.poll_ctrl_seen = True
self.ctrl_down = True
self.ctrl_up_streak = 0
else:
self.ctrl_up_streak += 1
if self.poll_ctrl_seen and self.ctrl_up_streak >= 2:
log("ctrl_poll_commit", seen=self.poll_ctrl_seen, streak=self.ctrl_up_streak)
self.commit()
return
if (self.marker_seen and not self.ctrl_down and not self.saw_tab_event
and (time.time() - self.start_time) > 0.15):
log("marker_no_ctrl_timeout_commit", elapsed=time.time() - self.start_time)
self.commit()
return
# If we know ctrl was not down at launch and nothing else happened, close quickly.
if (not self.marker_sent
and self.initial_mods_checked and not self.initial_ctrl_down and not self.saw_tab_event
and not self.marker_seen and not self.ctrl_seen
and (time.time() - self.start_time) > 0.08):
log("initial_ctrl_up_commit", elapsed=time.time() - self.start_time)
self.commit()
return
if (self.marker_sent and not self.any_key_event and not self.marker_seen
and (time.time() - self.start_time) > 0.2):
log("no_marker_timeout_commit", elapsed=time.time() - self.start_time)
self.commit()
return
# Fallback: if we never see a tab event, don't let the UI stick.
if (self.any_key_event and not self.saw_tab_event and not self.ctrl_down
and (time.time() - self.start_time) > 0.2):
log("no_tab_timeout_commit", elapsed=time.time() - self.start_time, ctrl_down=self.ctrl_down)
self.commit()
return
if self.command_server is not None and self.command_server.fileno() in r:
cmd = self.command_server.recv()
if cmd in {"next", "prev"}:
self._move(-1 if cmd == "prev" else 1)
log("move_cmd", cmd=cmd, selected=self.selected_index)
self.draw(force=True)
if fd not in r:
continue
with self.profiler.scoped("loop.read_key"):
ev = read_key(fd)
if ev is None:
continue
self.any_key_event = True
self.last_input_time = time.time()
try:
with self.profiler.scoped("event.handle"):
log("key", code=ev.key_code, mods=ev.mods, event=ev.event_type)
log("key_state", ctrl_down=self.ctrl_down, saw_tab=self.saw_tab_event)
if ev.key_code == MARKER_KEY_CODE and ev.event_type == 1:
self.marker_seen = True
self.ctrl_down = True
self.ctrl_seen = True
log("marker_seen")
continue
if ev.key_code == MARKER_KEY_CODE and ev.event_type == 3:
self.ctrl_down = False
log("marker_release")
continue
if ev.key_code in CTRL_KEY_CODES and ev.event_type == 1:
self.ctrl_down = True
self.ctrl_seen = True
if ev.key_code in CTRL_KEY_CODES and ev.event_type == 3:
self.ctrl_down = False
if ev.key_code in CTRL_KEY_CODES and ev.event_type == 3:
if self._should_commit_on_ctrl_release():
log("ctrl_release_commit")
log(
"ctrl_release_state",
selected_index=self.selected_index,
selected_tab=self._current_tab_id(),
tabs=[t.id for t in self.tabs],
)
self.commit()
return
log("ctrl_release_ignored", elapsed=time.time() - self.start_time, saw_tab=self.saw_tab_event)
if ev.key_code == ESC_CODE and ev.event_type == 1:
self.cancel()
return
if ev.key_code == TAB_CODE and ev.event_type in (1, 2):
log(
"tab_key",
event_type=ev.event_type,
mods=ev.mods,
ctrl=ev.ctrl,
shift=ev.shift,
selected_index=self.selected_index,
selected_tab=self._current_tab_id(),
)
self.saw_tab_event = True
if ev.ctrl:
self.ctrl_down = True
self._move(-1 if ev.shift else 1)
log(
"tab_move",
event_type=ev.event_type,
selected_index=self.selected_index,
selected_tab=self._current_tab_id(),
)
log("move", selected=self.selected_index)
self.draw(force=True)
self._schedule_preview_fetch()
continue
# Legacy shift-tab
if ev.key_code == -TAB_CODE:
self.saw_tab_event = True
self._move(-1)
log("move", selected=self.selected_index)
self.draw(force=True)
self._schedule_preview_fetch()
continue
if ev.key_code == ord("q") and ev.event_type == 1:
log("quit_q")
self.cancel()
return
except Exception as exc:
log("loop_exception", error=repr(exc))
log("loop_traceback", trace=traceback.format_exc())
raise
def draw(self, force: bool = False) -> None:
now = time.time()
if not force and now - self.last_draw < 0.016:
return
with self.profiler.scoped("draw.total"):
self.last_draw = now
rows, cols = screen_size()
log("draw", rows=rows, cols=cols, tabs=len(self.tabs), selected=self.selected_index)
write("\x1b[?25l")
write("\x1b[2J\x1b[H")
if debug_enabled():
write(f"\x1b[1;1H[DEBUG] size={rows}x{cols}")
if not self.tabs:
write("\x1b[HNo tabs")
flush()
return
layout = self._compute_layout(rows, cols)
cards = self._visible_cards(layout["max_cards"])
card_w = layout["card_w"]
card_h = layout["card_h"]
total_w = len(cards) * card_w + (len(cards) - 1) * 2
if self.theme.align == "left":
start_x = 1
elif self.theme.align == "right":
start_x = max(1, cols - total_w + 1)
else:
start_x = max(1, (cols - total_w) // 2 + 1)
if self.theme.vertical_align == "top":
start_y = 1
elif self.theme.vertical_align == "bottom":
start_y = max(1, rows - card_h + 1)
else:
start_y = max(1, (rows - card_h) // 2 + 1)
for idx, tab in enumerate(cards):
x = start_x + idx * (card_w + 2)
y = start_y
selected = self._current_tab_id() == tab.id
if self._preview_stale(tab.id):
if not hasattr(self, "preview_queue"):
self.preview_queue = []
if tab.id not in self.preview_queue:
self.preview_queue.append(tab.id)
log("card", idx=idx, tab_id=tab.id, title=tab.title, x=x, y=y, selected=selected)
self._draw_card(x, y, card_w, card_h, tab, selected, rows, cols, layout)
write("\x1b[?25l")
flush()
def commit(self) -> None:
tab_id = self._current_tab_id()
if tab_id is None:
self.cancel()
return
self._maybe_flush_preview_state(force=True)
log("commit", tab_id=tab_id)
self._update_mru(tab_id)
self._focus_tab(tab_id)
# Restore the source tab layout after switching focus so the user
# does not see a visible "snap back" in the current view.
self._restore_layout()
def cancel(self) -> None:
self._maybe_flush_preview_state(force=True)
self._restore_layout()
return
def _maybe_stack_active_tab(self) -> None:
if not self.theme.zoom_on_open:
return
active_id = self._active_tab_id()
if active_id is None:
return
active_tab = self._tab_by_id(active_id)
if active_tab is None:
return
layout = getattr(active_tab, "layout", None)
if not layout or layout == "stack":
return
try:
self._set_tab_layout(active_id, "stack")
self.layout_restore_tab_id = active_id
self.layout_restore_name = str(layout)
self.layout_changed = True
log("layout_stack", tab_id=active_id, previous=layout)
except Exception as exc:
log("layout_stack_error", tab_id=active_id, error=repr(exc))
def _restore_layout(self) -> None:
if not self.layout_changed or self.layout_restore_tab_id is None or not self.layout_restore_name:
return
try:
self._set_tab_layout(self.layout_restore_tab_id, self.layout_restore_name)
log("layout_restore", tab_id=self.layout_restore_tab_id, layout=self.layout_restore_name)
except Exception as exc:
log("layout_restore_error", tab_id=self.layout_restore_tab_id, error=repr(exc))
finally:
self.layout_changed = False
def _set_tab_layout(self, tab_id: int, layout: str) -> None:
if self.remote_control is None:
log("layout_set_skip", reason="no_remote_control", tab_id=tab_id, layout=layout)
return
match_candidates = [f"id:{tab_id}", f"tab_id:{tab_id}", f"tab-id:{tab_id}"]
last_cp = None
for match_expr in match_candidates:
for cmd in (
["goto-layout", "--match", match_expr, layout],
["action", "--match", match_expr, f"goto_layout {layout}"],
):
cp = self.remote_control(cmd, capture_output=True)
last_cp = cp
rc = getattr(cp, "returncode", 0)
out = getattr(cp, "stdout", b"")
err = getattr(cp, "stderr", b"")
if isinstance(out, bytes):
out = out.decode("utf-8", "replace")
if isinstance(err, bytes):
err = err.decode("utf-8", "replace")
log(
"layout_set_result",
tab_id=tab_id,
layout=layout,
match=match_expr,
cmd=" ".join(cmd),
returncode=rc,
stdout=out,
stderr=err,
)
if rc in (0, None):
return
if last_cp is not None:
rc = getattr(last_cp, "returncode", 0)
log("layout_set_failed", tab_id=tab_id, layout=layout, returncode=rc)
def _visible_cards(self, max_cards: int) -> list[TabInfo]:
if len(self.tabs) <= max_cards:
return self.tabs
half = max_cards // 2
start = max(0, self.selected_index - half)
end = min(len(self.tabs), start + max_cards)
start = max(0, end - max_cards)
return self.tabs[start:end]
def _draw_card(
self,
x: int,
y: int,
w: int,
h: int,
tab: TabInfo,
selected: bool,
rows: int,
cols: int,
layout: dict[str, Any],
) -> None:
border = self.theme.border_selected if selected else self.theme.border
title = self._format_title(tab.title, w - 4)
def write_at(row: int, col: int, text: str, invert: bool = False) -> None:
if row < 1 or row > rows or col < 1 or col > cols:
return
max_len = cols - col + 1
if max_len <= 0:
return
if "\x1b" not in text and len(text) > max_len:
text = text[:max_len]
if invert:
write(f"\x1b[{row};{col}H\x1b[7m{text}\x1b[0m")
else:
write(f"\x1b[{row};{col}H{text}")
top = border.tl + border.h * (w - 2) + border.tr
mid = border.v + " " * (w - 2) + border.v
bottom = border.bl + border.h * (w - 2) + border.br
write_at(y + 1, x + 1, top, selected)
write_at(y + 2, x + 1, mid, selected)
write_at(y + 2, x + 3, title, selected and self.theme.title_invert_selected)
if not layout["title_only"]:
for r in range(layout["preview_rows"]):
write_at(y + 3 + r, x + 1, mid, selected)
write_at(y + h, x + 1, bottom, selected)
if not layout["title_only"]:
raw_lines = self.preview_cache.get(tab.id) or []
cache_key = (
tab.id,
layout["preview_cols"],
layout["preview_rows"],
self.theme.preview_color_mode,
hash("\n".join(raw_lines)),
)
preview = self.render_cache.get(cache_key)
if preview is None:
with self.profiler.scoped("preview.render.block"):
preview = render_block_preview(
raw_lines,
layout["preview_cols"],
layout["preview_rows"],
color_mode=self.theme.preview_color_mode,
)
self.render_cache[cache_key] = preview
if len(self.render_cache) > 512:
self.render_cache.clear()
for r, line in enumerate(preview[: layout["preview_rows"]]):
write_at(y + 3 + r, x + 3, self._wrap_preview_line(line, layout["preview_cols"]), False)
def _should_commit_on_ctrl_release(self) -> bool:
elapsed = time.time() - self.start_time
if self.saw_tab_event:
return True
# ignore early ctrl release triggered by the invocation shortcut
return elapsed > 0.2
def _compute_layout(self, rows: int, cols: int) -> dict[str, Any]:
gap = self.theme.gap
preview_rows = self.theme.preview_rows
title_only = False
max_height = max(1, rows - 2)
max_width = max(1, cols - 2)
target_cards = max(1, len(self.tabs))
# Fit height
while preview_rows + 3 > max_height and preview_rows > self.theme.min_preview_rows:
preview_rows -= 1
def total_width(card_w: int, cards: int, gap_size: int) -> int:
return cards * card_w + max(0, cards - 1) * gap_size
# Ensure all cards fit by adapting gap and width
for gap_try in (gap, 1, 0):
gap = gap_try
available = max_width - gap * max(0, target_cards - 1)
if available <= 0:
continue
card_w = max(self.theme.card_min_width, available // target_cards)
if total_width(card_w, target_cards, gap) <= max_width:
break
else:
gap = 0
card_w = max(self.theme.card_min_width, max_width // target_cards)
preview_cols = max(0, card_w - 4)
card_h = preview_rows + 3
if preview_cols < self.theme.min_preview_cols or card_h > max_height or card_w < self.theme.card_min_width:
title_only = True
preview_cols = 0
preview_rows = 0
card_h = max(self.theme.card_min_height, 3)
if target_cards > 0:
available = max_width - gap * max(0, target_cards - 1)
card_w = max(self.theme.card_min_width, available // target_cards)
max_cards = target_cards
return {
"preview_cols": preview_cols,
"preview_rows": preview_rows,
"card_w": card_w,
"card_h": card_h,
"max_cards": max_cards,
"title_only": title_only,
}
def _truncate(self, text: str, max_len: int, ellipsis: str | None = None) -> str:
if max_len <= 0:
return ""
if len(text) <= max_len:
return text
if max_len <= 3:
return text[:max_len]
ell = ellipsis if ellipsis is not None else "..."
if len(ell) >= max_len:
return text[:max_len]
return text[: max_len - len(ell)] + ell
def _truncate_ansi(self, text: str, max_len: int) -> str:
if max_len <= 0:
return ""
if "\x1b" not in text:
return self._truncate(text, max_len)
out: list[str] = []
visible = 0
i = 0
while i < len(text) and visible < max_len:
ch = text[i]
if ch == "\x1b":
end = text.find("m", i + 1)
if end == -1:
break
out.append(text[i:end + 1])
i = end + 1
continue
out.append(ch)
visible += 1
i += 1
out.append("\x1b[0m")
return "".join(out)
def _wrap_preview_line(self, text: str, max_len: int) -> str:
if self.theme.wrap_preview == "clip":
line = self._truncate_ansi(text, max_len)
else:
line = self._truncate_ansi(text, max_len)
return f"\x1b[0m{line}\x1b[0m"
def _format_title(self, text: str, width: int) -> str:
if width <= 0:
return ""
pad = max(0, self.theme.title_padding)
inner = max(0, width - pad * 2)
if self.theme.wrap_title == "clip":
content = text[:inner]
else:
content = self._truncate(text, inner, self.theme.ellipsis)
if self.theme.title_align == "center":
content = content.center(inner)
elif self.theme.title_align == "right":
content = content.rjust(inner)
else:
content = content.ljust(inner)
return (" " * pad) + content + (" " * pad)
def _move(self, delta: int) -> None:
if not self.tabs:
return
before_idx = self.selected_index
before_id = self._current_tab_id()
self.selected_index = (self.selected_index + delta) % len(self.tabs)
after_id = self._current_tab_id()
log("move_detail", delta=delta, before_idx=before_idx, after_idx=self.selected_index, before_id=before_id, after_id=after_id)
self._ensure_preview_cache()
def _current_tab_id(self) -> int | None:
if not self.tabs:
return None
return self.tabs[self.selected_index].id
def _active_tab_id(self) -> int | None:
for tab in self.tabs:
if tab.is_active:
return tab.id
return self.tabs[0].id if self.tabs else None
def _initial_index(self, direction: int) -> int:
if not self.tabs:
return 0
if direction >= 0:
return 1 % len(self.tabs)
return (len(self.tabs) - 1) % len(self.tabs)
def _reconcile_mru(self, last_used: dict[int, float]) -> dict[int, float]:
base_tabs = list(self.tabs)
base_order = [t.id for t in base_tabs]
base_rank = {tid: idx for idx, tid in enumerate(base_order)}
by_id = {t.id: t for t in base_tabs}
# Prefer kitty-provided focus timestamps if available
if any(t.last_focused is not None for t in self.tabs):
now = time.time()
out: dict[int, float] = {}
for t in self.tabs:
if t.last_focused is not None:
out[t.id] = t.last_focused
else:
out[t.id] = 0.0
active_id = self._active_tab_id()
if active_id is not None:
out[active_id] = max(out.get(active_id, 0.0), now)
ordered = sorted(
out.items(),
key=lambda kv: (-kv[1], base_rank.get(kv[0], 10**9)),
)
log("mru_order", ordered=[k for k, _ in ordered], source="last_focused")
self.tabs = [by_id[tid] for tid, _ in ordered if tid in by_id]
return {tid: out[tid] for tid in base_order}
now = time.time()
out: dict[int, float] = {}
for tid in base_order:
if tid in last_used:
out[tid] = last_used[tid]
if tid not in out:
out[tid] = 0.0
active_id = self._active_tab_id()
if active_id is not None:
out[active_id] = max(out.get(active_id, 0.0), now)
ordered = sorted(
out.items(),
key=lambda kv: (-kv[1], base_rank.get(kv[0], 10**9)),
)
log("mru_order", ordered=[k for k, _ in ordered], source="cache")
self.tabs = [by_id[tid] for tid, _ in ordered if tid in by_id]
return out
def _tab_by_id(self, tab_id: int) -> TabInfo | None:
for tab in self.tabs:
if tab.id == tab_id:
return tab
return None
def _ensure_preview_cache(self) -> None:
if not self.tabs:
return
indices = {
self.selected_index,
(self.selected_index - 1) % len(self.tabs),
(self.selected_index + 1) % len(self.tabs),
}
for idx in indices:
tab = self.tabs[idx]
if tab.id not in self.preview_cache:
log("preview_fetch", tab_id=tab.id, window_id=tab.window_id)
self.preview_cache[tab.id] = self._fetch_preview(tab)
self.preview_cache_ts[tab.id] = time.time()
self.preview_dirty = True
self._maybe_flush_preview_state(force=False)
def _schedule_preview_fetch(self) -> None:
if not self.tabs:
return
if not hasattr(self, "preview_queue"):
self.preview_queue: list[int] = []
targets = [
self.selected_index,
(self.selected_index - 1) % len(self.tabs),
(self.selected_index + 1) % len(self.tabs),
]
for idx in targets:
tab_id = self.tabs[idx].id
if not self._preview_stale(tab_id):
continue
if tab_id not in self.preview_queue:
self.preview_queue.append(tab_id)
log("preview_queue", queued=self.preview_queue)
def _preview_stale(self, tab_id: int) -> bool:
if tab_id not in self.preview_cache:
return True
ts = self.preview_cache_ts.get(tab_id, 0.0)
return (time.time() - ts) >= self.preview_refresh_secs
def _drain_preview_queue(self) -> bool:
queue = getattr(self, "preview_queue", [])
if not queue:
return False
now = time.time()
if (now - self.last_preview_fetch) < self.preview_fetch_budget_secs:
self._maybe_flush_preview_state(force=False)
return False
tab_id = queue.pop(0)
tab = self._tab_by_id(tab_id)
if tab is not None and self._preview_stale(tab.id):
log("preview_refresh", tab_id=tab.id, window_id=tab.window_id)
self.last_preview_fetch = now
self.preview_cache[tab.id] = self._fetch_preview(tab)
self.preview_cache_ts[tab.id] = time.time()
self.preview_dirty = True
self._maybe_flush_preview_state(force=False)
return True
self._maybe_flush_preview_state(force=False)
return False
def _fetch_preview(self, tab: TabInfo) -> list[str]:
try:
with self.profiler.scoped("preview.fetch.remote"):
lines = get_text_lines_from_rc(self.remote_control, tab.window_id, ansi=True)
if not lines:
log("preview_error", tab_id=tab.id, returncode=1)
return [" " * PREVIEW_COLS] * PREVIEW_ROWS
except Exception as exc:
log("preview_exception", tab_id=tab.id, error=repr(exc))
return [" " * PREVIEW_COLS] * PREVIEW_ROWS
log("preview_lines", tab_id=tab.id, lines=len(lines))
return lines
def _maybe_flush_preview_state(self, force: bool) -> None:
if not self.preview_dirty:
return
now = time.time()
if not force and (now - self.last_preview_save) < self.preview_save_interval:
return
with self.profiler.scoped("cache.save.preview"):
self.preview_state.save(self.preview_cache, self.preview_cache_ts)
self.preview_dirty = False
self.last_preview_save = now
def _focus_tab(self, tab_id: int) -> None:
self.remote_control(
[
"focus-tab",
"--match",
f"id:{tab_id}",
"--no-response",
],
capture_output=True,
)
def _update_mru(self, tab_id: int) -> None:
base = [tid for tid in self.mru_order if tid not in {tab_id, self.original_tab_id}]
new_order = [tab_id]
if self.original_tab_id is not None and self.original_tab_id != tab_id:
new_order.append(self.original_tab_id)
new_order.extend(base)
self.mru_order = new_order
now = time.time()
self.last_used = {tid: now - (idx * 0.001) for idx, tid in enumerate(self.mru_order)}
log("mru_commit", ordered=self.mru_order, committed=tab_id, original=self.original_tab_id)
with self.profiler.scoped("cache.save.state"):
self.state.save(self.last_used)
def _send_marker(self) -> None:
try:
win_id = os.environ.get("KITTY_WINDOW_ID")
if not win_id:
return
cp = self.remote_control(
[
"send-key",
"--match",
f"id:{win_id}",
"f24",
],
capture_output=True,
)
self.marker_sent = (cp.returncode == 0)
log("marker_send", sent=self.marker_sent, returncode=cp.returncode)
except Exception as exc:
log("marker_send_error", error=repr(exc))
def _check_initial_mods(self) -> None:
if self.mod_query is None or self.ctrl_mask is None:
return
try:
mods = self.mod_query()
except Exception:
mods = None
if mods is None:
return
self.initial_mods_checked = True
self.initial_ctrl_down = ctrl_is_down(mods, self.ctrl_mask)
log("initial_mods", mods=mods, ctrl_down=self.initial_ctrl_down)
def _parse_switcher_args(args: list[str]) -> tuple[int, str | None, bool]:
direction = 1
theme_path: str | None = None
profile = False
it = iter(args)
for raw in it:
arg = raw.strip()
low = arg.lower()
if low in {"prev", "previous", "left", "-1"}:
direction = -1
continue
if low in {"next", "right", "1"}:
direction = 1