dsh-watch-together 0.2.13 → 0.2.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,12 @@
1
1
  #!/usr/bin/env python3
2
2
  """陪看悬浮窗:不铺全屏背景图,实时抓窗口背后的桌面并模糊成液态玻璃。
3
3
 
4
- 三层,各自不知道对方的实现:
4
+ 四层,各自不知道对方的实现:
5
5
 
6
6
  glass_geometry.py 一套尺寸的全部贴图(不可变,尺寸/形状变了换一个新对象)
7
7
  glass_cpu.py CPU 合成:抓屏 → 模糊 → 边缘折射 → 内框透镜 → 染色 → 色散
8
8
  glass_gpu.py 同一件事搬到 GPU(moderngl / OpenGL 3.3+)
9
+ glass_static.py 不吃性能的底板:预生成一张磨砂/纯色,换尺寸才重画
9
10
  window.py 这个文件:Tk 窗口、聊天流、文字层、拖动/缩放/折叠/改名
10
11
 
11
12
  `glass_capture.py` 是两条渲染路径共用的抓屏与运动判定 —— 历史上同一条判断
@@ -19,7 +20,14 @@
19
20
  - 抓到的背景按需重合成(静止时跳帧),所以是实时模糊,不是静态截图。
20
21
  - 这不是 DWM Acrylic;Acrylic 需要系统「透明效果」开启,这里是软件实时模糊。
21
22
 
22
- 渲染后端:默认 CPU。`DSH_GLASS_NATIVE=1` 或 `DSH_GLASS_GPU=1` 走 GPU。
23
+ 样式预设(`~/.dsh/watch-window.json` 的 `glass`,设置页里可改,改完热切换):
24
+
25
+ live 实时玻璃:抓屏 + 模糊,跟着桌面走。最好看,也最吃 CPU。
26
+ frost 静态磨砂:一张预生成的底板,不抓屏、不逐帧合成 —— 不吃性能。
27
+ solid 纯色底板:远程桌面/录屏兜底,任何捕获方式都看得见。
28
+ auto 不写或写 auto:远程/录屏环境自动用 solid,其余用 live。
29
+
30
+ 渲染后端:默认 CPU。`DSH_GLASS_NATIVE=1` 或 `DSH_GLASS_GPU=1` 走 GPU(只对 live 有效)。
23
31
  """
24
32
  import ctypes
25
33
  import json
@@ -28,22 +36,31 @@ import queue
28
36
  import subprocess
29
37
  import threading
30
38
  import time
31
- from ctypes import wintypes
32
39
  from pathlib import Path
33
40
 
41
+ # 是不是 Windows。**所有 ctypes.windll / wintypes / WDA 都必须先问它**:
42
+ # `ctypes.windll` 在 macOS/Linux 上根本不存在,模块顶层摸一下就是
43
+ # `AttributeError: module 'ctypes' has no attribute 'windll'`,而且死在依赖预检
44
+ # 之前,用户看到的是"启动后 700ms 退出,code=1"(issue #40)。
45
+ IS_WIN = os.name == "nt"
46
+
47
+ if IS_WIN:
48
+ from ctypes import wintypes
49
+
34
50
  # 必须在 import tkinter / 创建任何窗口之前声明 per-monitor v2 DPI 感知。
35
- _u = ctypes.windll.user32
36
- try:
37
- _u.SetProcessDpiAwarenessContext.argtypes = [ctypes.c_void_p]
38
- _u.SetProcessDpiAwarenessContext.restype = ctypes.c_bool
39
- _u.SetProcessDpiAwarenessContext(ctypes.c_void_p(-4))
40
- except Exception:
41
- pass
51
+ if IS_WIN:
52
+ _u = ctypes.windll.user32
53
+ try:
54
+ _u.SetProcessDpiAwarenessContext.argtypes = [ctypes.c_void_p]
55
+ _u.SetProcessDpiAwarenessContext.restype = ctypes.c_bool
56
+ _u.SetProcessDpiAwarenessContext(ctypes.c_void_p(-4))
57
+ except Exception:
58
+ pass
42
59
 
43
- try:
44
- ctypes.windll.winmm.timeBeginPeriod(1)
45
- except Exception:
46
- pass
60
+ try:
61
+ ctypes.windll.winmm.timeBeginPeriod(1)
62
+ except Exception:
63
+ pass
47
64
 
48
65
  # ---------------------------------------------------------------- 依赖预检
49
66
  #
@@ -72,8 +89,10 @@ def _die_missing(missing: list) -> None:
72
89
  log_path.write_text(text + "\n", encoding="utf-8")
73
90
  except Exception:
74
91
  pass
92
+ # 弹窗标题跟着"谁拉起的这个窗"走:see-now 的用户看到 dsh-watch-together 会以为装错了包
75
93
  try:
76
- ctypes.windll.user32.MessageBoxW(None, text, "dsh-watch-together", 0x10)
94
+ ctypes.windll.user32.MessageBoxW(None, text,
95
+ os.environ.get("DSH_WINDOW_BRAND") or "dsh-watch-together", 0x10)
77
96
  except Exception:
78
97
  print(text, flush=True)
79
98
  raise SystemExit(2)
@@ -103,8 +122,25 @@ try: # 悬浮窗接口:插件写 window-events.jsonl,窗口回 window-outbo
103
122
  except Exception:
104
123
  WindowProtocol = None
105
124
 
106
- INTERVAL_MS = 4
107
- MAX_FPS = 120
125
+
126
+ def _max_fps() -> int:
127
+ """目标帧率上限,默认 60;120Hz 玻璃可显式开回 120。
128
+
129
+ 120fps 的一帧预算只有 8.3ms,而单次 mss 抓屏约 7ms,再叠 CPU 合成,
130
+ 预算已经贴边;低配机/高分屏/动态桌面会一直落在“差一点来得及”的区间。
131
+ 默认 60fps 把预算抬到 16.6ms,显示线程也不再用 4ms 定时器空转。
132
+ """
133
+ try:
134
+ fps = int(os.environ.get("DSH_GLASS_MAX_FPS", "60"))
135
+ except (TypeError, ValueError):
136
+ fps = 60
137
+ return max(30, min(120, fps))
138
+
139
+
140
+ MAX_FPS = _max_fps()
141
+ # 主线程按目标帧率唤醒;旧值固定 4ms(250Hz),后台却按 120fps 合成,
142
+ # 抓屏 + 合成一旦超过 8.3ms,主线程还在空转堆积 after 回调。
143
+ INTERVAL_MS = max(4, int(1000 / MAX_FPS))
108
144
  # 静止画面下「有没有变」只能靠抓屏看,单次 grab ~7ms;空转按 60fps 就是 40% 单核。
109
145
  # 降到 30fps 探针,有变化时 idle 立刻归零、下一拍恢复全速。
110
146
  PROBE_FPS = 30
@@ -120,6 +156,12 @@ USE_GPU = NATIVE or os.environ.get("DSH_GLASS_GPU") == "1"
120
156
  # 只用来拍新旧对比图,正常别动。
121
157
  PLATE = os.environ.get("DSH_GLASS_PLATE", "1") != "0"
122
158
 
159
+ # 样式预设。`auto` 只出现在配置里(表示"看环境自动选"),解析后只会是下面三个之一。
160
+ STYLE_LIVE, STYLE_FROST, STYLE_SOLID = "live", "frost", "solid"
161
+ GLASS_STYLES = (STYLE_LIVE, STYLE_FROST, STYLE_SOLID)
162
+ # 静态样式:不抓屏、不起渲染线程,只在换尺寸/换形状时重画一张底板。
163
+ STATIC_STYLES = (STYLE_FROST, STYLE_SOLID)
164
+
123
165
  HERE = Path(__file__).resolve().parent
124
166
 
125
167
 
@@ -195,6 +237,8 @@ REMOTE_MARKS = (
195
237
 
196
238
  def remote_capture_likely() -> bool:
197
239
  """当前是不是远程/捕获环境:RDP 标志位 + 常见远程软件窗口。"""
240
+ if not IS_WIN:
241
+ return False
198
242
  try:
199
243
  if ctypes.windll.user32.GetSystemMetrics(0x1000): # SM_REMOTESESSION
200
244
  return True
@@ -236,31 +280,43 @@ def remote_capture_likely() -> bool:
236
280
  return False
237
281
 
238
282
 
239
- def glass_mode() -> str:
240
- """玻璃背景模式:live(实时抓屏,默认)/ solid(纯色底板)。
283
+ def glass_style(cfg: dict | None = None) -> str:
284
+ """样式预设:live(实时玻璃)/ frost(静态磨砂)/ solid(纯色)。
241
285
 
242
286
  `WDA_EXCLUDEFROMCAPTURE` 会让窗口在远程桌面、OBS、截图工具里**整窗消失**
243
287
  (微软文档:“Everywhere else, the window does not appear at all”)。
244
288
  本机看起来正常,因为 mss 抓到的是窗口背后的像素;远程端却连文字都看不到。
289
+ 所以选了 live 也要在远程环境下兜底成 solid —— 好看不能压过"看得见"。
290
+
291
+ 性能反过来是另一头:live 每帧都要抓屏 + 模糊,低配机/高分屏上会明显掉帧。
292
+ frost 和 solid 都不碰屏幕,只在换尺寸时画一张(见 `glass_static.py`)。
245
293
 
246
- - `{ "glass": "solid" }`:不抓屏、不设 WDA,用纯色底板;任何捕获方式都能看到;
247
- - `{ "glass": "live" }`:原来的实时玻璃;
248
- - 不写 / `auto`:检测 `SM_REMOTESESSION` 和常见远程软件窗口,命中就用 solid。
294
+ 读 `~/.dsh/watch-window.json` 的 `glass`;不写 / `auto` = 按环境自动选。
295
+ 环境变量优先级更高,只对这一次启动有效(插件拉起窗口时不传环境变量)。
249
296
  """
250
297
  if os.environ.get("DSH_GLASS_SOLID") == "1":
251
- return "solid"
298
+ return STYLE_SOLID
299
+ if os.environ.get("DSH_GLASS_FROST") == "1":
300
+ return STYLE_FROST
252
301
  if os.environ.get("DSH_GLASS_LIVE") == "1":
253
- return "live"
302
+ return STYLE_LIVE
303
+ if cfg is None:
304
+ try:
305
+ cfg = read_config()
306
+ except Exception:
307
+ cfg = {}
254
308
  try:
255
- mode = str(read_config().get("glass") or "").strip().lower()
309
+ mode = str((cfg or {}).get("glass") or "").strip().lower()
256
310
  except Exception:
257
311
  mode = ""
258
- if mode in ("solid", "live"):
259
- return mode
312
+ if mode == STYLE_FROST:
313
+ return STYLE_FROST
314
+ if mode == STYLE_SOLID:
315
+ return STYLE_SOLID
316
+ if mode == STYLE_LIVE:
317
+ return STYLE_SOLID if remote_capture_likely() else STYLE_LIVE
260
318
  # 空值 / auto:RDP 标志位或常见远程软件窗口任一命中,就用 solid。
261
- if remote_capture_likely():
262
- return "solid"
263
- return "live"
319
+ return STYLE_SOLID if remote_capture_likely() else STYLE_LIVE
264
320
 
265
321
 
266
322
  def append_user(text: str) -> None:
@@ -377,27 +433,40 @@ class LiveGlass:
377
433
  self._excluded = False
378
434
  # 录屏模式(capturable)下 mss 会抓到窗口自己,必须每帧挖掉,见 fill_own_rect。
379
435
  # 缓存起来:读配置是磁盘 IO,不能每帧做。
380
- self._cappable = capturable()
381
- # solid:远程/录屏下 WDA 会让整窗在对面消失;不抓屏、不设 WDA。
382
- self._solid = glass_mode() == "solid"
436
+ # **非 Windows 一律按"能抓到自己"处理**:那边没有 WDA,不挖就是"透过自己看自己"。
437
+ self._cappable = capturable() or not IS_WIN
438
+ # 样式:live / frost / solid。静态样式不抓屏、不设 WDA、不起渲染线程。
439
+ self._style = glass_style(cfg)
440
+ self._static = self._style in STATIC_STYLES
441
+ self._solid = self._style == STYLE_SOLID
383
442
  self._drag = None
384
443
  self._resize = None
385
444
  self._preview_at = 0.0
445
+ # Entry 的真光标被关掉(insertwidth=0),画面上那条线是自己画的,
446
+ # 所以闪烁也得自己来。_caret_job 存 after 的 id,重排时取消,避免叠定时器。
447
+ self._caret_on = True
448
+ self._caret_job = None
449
+ # 长消息展开:被截断的气泡点一下独占整个消息区,再点收起。
450
+ # 存的是消息身份 (role, text, at) 而不是槽位下标 —— 新消息进来会让
451
+ # 同一条消息换槽,存下标会变成"展开的是另一条"。
452
+ self._expanded = None
453
+ self._fit_clipped = False
386
454
 
387
455
  self._q: queue.Queue = queue.Queue(maxsize=1)
388
456
  self._stop = threading.Event()
389
457
  self._pause = threading.Event()
390
458
  self._geo_lock = threading.Lock()
391
- self._source = CaptureSource((self._sw, self._sh), cappable=self._cappable,
392
- solid=self._solid,
393
- # 窗口落在副屏时,抓屏范围要按虚拟桌面钳
394
- bounds=(self._vx, self._vy, self._vw, self._vh))
459
+ # 抓屏源和渲染线程都是「换成 live 才有」的东西:静态样式下两条都不存在,
460
+ # 所以不在这里建,交给 `_start_worker()`(换样式时会再调用一次)。
461
+ self._source = None
395
462
  self._renderer = self._make_renderer(self._geo)
396
- self._worker = threading.Thread(target=self._work, daemon=True)
463
+ self._worker = None
464
+ self._worker_stop = None
397
465
 
398
466
  self._hz = display_hz()
399
467
  self._target_fps = min(MAX_FPS, self._hz)
400
468
  self._ema = 1.0 / max(1, self._target_fps)
469
+ self._draw_ms = 0.0 # Tk 主线程实际绘制耗时,用来给 after 留余量
401
470
  self._last_motion = 0.0
402
471
 
403
472
  self.feed.reload()
@@ -406,8 +475,8 @@ class LiveGlass:
406
475
  self.root.deiconify()
407
476
  self.root.update_idletasks()
408
477
  self.text.refresh()
409
- self._set_exclude(not capturable() and not self._solid)
410
- self._worker.start()
478
+ self._set_exclude(not capturable() and not self._static)
479
+ self._start_worker()
411
480
  self.root.lift()
412
481
  self.root.after(80, self.root.lift)
413
482
  self.root.after(120, self.root.focus_set)
@@ -421,6 +490,10 @@ class LiveGlass:
421
490
  # ---- 渲染后端 ----
422
491
 
423
492
  def _make_renderer(self, geo: Geometry):
493
+ """按样式给一个渲染器:静态样式完全不碰屏幕。"""
494
+ if self._static:
495
+ from glass_static import StaticRenderer
496
+ return StaticRenderer(geo, self._style)
424
497
  if USE_GPU:
425
498
  try:
426
499
  from glass_gpu import GpuRenderer
@@ -429,6 +502,66 @@ class LiveGlass:
429
502
  print("GPU 初始化失败,回落到 CPU:", repr(exc), flush=True)
430
503
  return CpuRenderer(geo)
431
504
 
505
+ def _start_worker(self) -> None:
506
+ """起抓屏/合成线程。静态样式没有东西要算,直接不起。"""
507
+ if self._static or self._worker is not None or self._stop.is_set():
508
+ return
509
+ self._source = CaptureSource((self._sw, self._sh), cappable=self._cappable,
510
+ solid=self._solid,
511
+ # 窗口落在副屏时,抓屏范围要按虚拟桌面钳
512
+ bounds=(self._vx, self._vy, self._vw, self._vh))
513
+ self._worker_stop = threading.Event()
514
+ self._worker = threading.Thread(target=self._work, args=(self._worker_stop,),
515
+ daemon=True)
516
+ self._worker.start()
517
+
518
+ def _stop_worker(self) -> None:
519
+ """停线程。先摘掉引用再 join:`_work` 里还会读 `self._source`。"""
520
+ worker, stop = self._worker, self._worker_stop
521
+ self._worker, self._worker_stop = None, None
522
+ if stop is not None:
523
+ stop.set()
524
+ if worker is not None:
525
+ worker.join(timeout=0.4)
526
+
527
+ def _apply_style(self, style: str) -> None:
528
+ """换样式(配置文件一变就调用,不用重开窗口)。
529
+
530
+ 从 live 切走要真把抓屏线程停掉 —— 只换渲染器而不停线程,等于"静态样式"
531
+ 还在后台每帧抓屏,用户切过去还是卡,只是看不见画面在变。
532
+ """
533
+ if style not in GLASS_STYLES:
534
+ style = STYLE_LIVE
535
+ if style == self._style:
536
+ return
537
+ self._style = style
538
+ self._static = style in STATIC_STYLES
539
+ self._solid = style == STYLE_SOLID
540
+ self._pause.set()
541
+ self._stop_worker()
542
+ try:
543
+ self._renderer.close()
544
+ except Exception:
545
+ pass
546
+ self._renderer = self._make_renderer(self._geo)
547
+ if self._static:
548
+ # 不再抓屏:WDA 没有意义,开着反而会让窗口在截图里消失
549
+ self._set_exclude(False)
550
+ self._last_frame = None
551
+ if self._collapsed:
552
+ # 折叠态贴的是 `_collapsed_frame`(不是 `_last_frame`)—— 清掉就是一块空白。
553
+ # 按折叠尺寸直接画一张:`slabs_for()` 在折叠高度下只返回标题栏那一块。
554
+ try:
555
+ self._collapsed_frame = self._renderer.frame_for(self._geo)
556
+ except Exception:
557
+ self._collapsed_frame = None
558
+ else:
559
+ self._collapsed_frame = None
560
+ else:
561
+ self._start_worker()
562
+ self._pause.clear()
563
+ self._layout(seed=True)
564
+
432
565
  # ---- 尺寸 ----
433
566
 
434
567
  def _initial_geometry(self, geo):
@@ -556,7 +689,7 @@ class LiveGlass:
556
689
 
557
690
  def _poll_chat(self) -> None:
558
691
  try:
559
- self._sync_visible()
692
+ self._sync_config()
560
693
  for event in self._drain_protocol():
561
694
  self._render_event(event)
562
695
  if self._mic_proc is not None and self._mic_proc.poll() is not None:
@@ -564,13 +697,19 @@ class LiveGlass:
564
697
  self.feed.status = ""
565
698
  self._refresh_feed()
566
699
  if self.feed.poll():
700
+ self._collapse_expanded()
567
701
  self._refresh_feed()
568
702
  except Exception as exc:
569
703
  print("chat poll error", exc, flush=True)
570
704
  if not self._stop.is_set():
571
705
  self.root.after(250, self._poll_chat)
572
706
 
573
- def _sync_visible(self) -> None:
707
+ def _sync_config(self) -> None:
708
+ """配置文件变了:样式和显隐都跟着改(不用重开窗口)。
709
+
710
+ 设置页把 `glass` 写进同一个文件,所以这里顺手一起处理 —— 用户点一下
711
+ 下拉,250ms 内窗口就换过来。读一次盘就够了,别为两个键各读一遍。
712
+ """
574
713
  try:
575
714
  st = CONFIG.stat()
576
715
  key = (st.st_mtime_ns, st.st_size)
@@ -579,7 +718,10 @@ class LiveGlass:
579
718
  if key == self._cfg_key:
580
719
  return
581
720
  self._cfg_key = key
582
- want = bool(read_config().get("hidden"))
721
+ cfg = read_config()
722
+ # 换样式会重建渲染器并重排窗口;`_layout` 里会重新贴帧,所以放在显隐之前
723
+ self._apply_style(glass_style(cfg))
724
+ want = bool(cfg.get("hidden"))
583
725
  if want == self._hidden:
584
726
  return
585
727
  self._hidden = want
@@ -622,6 +764,7 @@ class LiveGlass:
622
764
 
623
765
  def _wheel(self, e):
624
766
  if self.feed.scroll(1 if e.delta > 0 else -1):
767
+ self._collapse_expanded()
625
768
  self._refresh_feed()
626
769
 
627
770
  def _toggle_mic(self):
@@ -654,6 +797,36 @@ class LiveGlass:
654
797
  pass
655
798
  self._refresh_feed()
656
799
 
800
+ CARET_MS = 530 # 和 Windows 默认的光标闪烁周期一致
801
+ CARET_PAD = 3 # 光标右边至少留几个字符,别让它贴着可见段右缘
802
+
803
+ def _visible_input(self, text: str, maxw: int, caret: int):
804
+ """返回能放进 maxw 的那一段,以及光标在这一段里的字符下标。
805
+
806
+ 原来只从左边砍(`text = text[1:]`),等于永远把尾巴留在视野里:光标移到
807
+ 句首时会被推到看不见的地方。改成以光标为锚点开窗 —— 先保证光标可见,
808
+ 再尽量往两边补字。
809
+
810
+ 光标右边留 CARET_PAD 个字符:不留的话往左移动时光标会一直贴着右缘,
811
+ 看不出右边还有内容(20 字符文本 / 10 字符窗口实测,caret=10 和 caret=17
812
+ 的可见段右端都正好停在光标上)。
813
+ """
814
+ font = self.fonts.get(11)
815
+ if font.measure(text) <= maxw:
816
+ return text, caret
817
+ lo = min(caret, len(text))
818
+ hi = min(len(text), lo + self.CARET_PAD)
819
+ # 右边余量优先:先确保 caret..caret+PAD 进得去,再往左补已经打出来的内容
820
+ while hi > lo and font.measure(text[lo:hi]) > maxw:
821
+ hi -= 1
822
+ while lo > 0 and font.measure(text[lo - 1:hi]) <= maxw:
823
+ lo -= 1
824
+ while hi < len(text) and font.measure(text[lo:hi + 1]) <= maxw:
825
+ hi += 1
826
+ while lo > 0 and font.measure(text[lo - 1:hi]) <= maxw:
827
+ lo -= 1
828
+ return text[lo:hi], caret - lo
829
+
657
830
  def _render_input(self) -> None:
658
831
  """输入文字画在 Canvas 上;Entry 只负责 IME/键盘,永远不可见。"""
659
832
  if self._entry is None:
@@ -663,30 +836,62 @@ class LiveGlass:
663
836
  try:
664
837
  text = self._entry.get()
665
838
  focused = self.root.focus_get() is self._entry
839
+ # 光标位置必须读 Entry 的真实插入点:原来按整段文字宽度算,等于把
840
+ # 线永远钉在末尾,左右键移动时画面上的光标根本不动。
841
+ caret = self._entry.index("insert")
666
842
  except Exception:
667
- text, focused = "", False
843
+ text, focused, caret = "", False, 0
668
844
  x0, y0, x1, y1, _r = self._geo.input_shape
669
845
  x, y = x0 + 84, y0 + 27
670
846
  maxw = max(60, x1 - x0 - 100)
847
+ cx = None
671
848
  if not text and not focused:
672
849
  self.text.draw(x, y, "在这里跟它说话…", anchor="w", fill="#8e9db2",
673
850
  size=11, tags=("inputtext", "inputzone"))
674
851
  elif text:
675
852
  font = self.fonts.get(11)
676
- while text and font.measure(text) > maxw:
677
- text = text[1:]
678
- self.text.draw(x, y, text, anchor="w", fill="#eef6ff",
853
+ shown, caret_in = self._visible_input(text, maxw, caret)
854
+ self.text.draw(x, y, shown, anchor="w", fill="#eef6ff",
679
855
  size=11, tags=("inputtext", "inputzone"))
680
856
  if focused:
681
- cx = x + font.measure(text)
682
- c.create_line(cx + 1, y - 9, cx + 1, y + 9,
683
- fill="#b9d7ff", width=1, tags=("inputcursor",))
857
+ cx = x + font.measure(shown[:max(0, caret_in)])
684
858
  elif focused:
685
- c.create_line(x + 1, y - 9, x + 1, y + 9,
859
+ cx = x
860
+ if cx is not None and self._caret_on:
861
+ c.create_line(cx + 1, y - 9, cx + 1, y + 9,
686
862
  fill="#b9d7ff", width=1, tags=("inputcursor",))
863
+ self._schedule_caret(cx is not None)
687
864
  self.text.refresh()
688
865
 
866
+ def _schedule_caret(self, active: bool) -> None:
867
+ """只有输入框拿着焦点时才跑闪烁定时器;失焦就停,不白烧 after。"""
868
+ if self._caret_job is not None:
869
+ try:
870
+ self.root.after_cancel(self._caret_job)
871
+ except Exception:
872
+ pass
873
+ self._caret_job = None
874
+ if not active:
875
+ self._caret_on = True
876
+ return
877
+ self._caret_job = self.root.after(self.CARET_MS, self._blink_caret)
878
+
879
+ def _blink_caret(self) -> None:
880
+ self._caret_job = None
881
+ if self._entry is None:
882
+ return
883
+ try:
884
+ if self.root.focus_get() is not self._entry:
885
+ self._caret_on = True
886
+ return
887
+ except Exception:
888
+ return
889
+ self._caret_on = not self._caret_on
890
+ self._render_input()
891
+
689
892
  def _on_input_key(self, _e=None):
893
+ # 打字期间光标恒亮:这时闪烁反而碍事,和系统输入框一致
894
+ self._caret_on = True
690
895
  self._render_input()
691
896
  return None
692
897
 
@@ -696,6 +901,7 @@ class LiveGlass:
696
901
  self._entry.icursor("end")
697
902
  except Exception:
698
903
  pass
904
+ self._caret_on = True
699
905
  self._render_input()
700
906
 
701
907
  # ---- 改名 ----
@@ -794,7 +1000,10 @@ class LiveGlass:
794
1000
  lines.append(cur)
795
1001
  cur = ch
796
1002
  lines.append(cur)
797
- if len(lines) > max_lines:
1003
+ # 调用方要知道这条到底被砍了没有:省略号自己看不出是"全文正好以…结尾"
1004
+ # 还是"被截断了",而展开入口只该给真被砍的那几条。
1005
+ self._fit_clipped = len(lines) > max_lines
1006
+ if self._fit_clipped:
798
1007
  lines = lines[:max_lines]
799
1008
  last = lines[-1]
800
1009
  while last and measure(last + "…") > max_width:
@@ -802,6 +1011,29 @@ class LiveGlass:
802
1011
  lines[-1] = (last + "…") if last else "…"
803
1012
  return lines or [""]
804
1013
 
1014
+ @staticmethod
1015
+ def _msg_key(msg):
1016
+ """消息身份:(role, text, at),和 ChatFeed.add 的去重键一致。"""
1017
+ return (msg.get("role"), msg.get("text"), msg.get("at"))
1018
+
1019
+ def _expanded_index(self, shown):
1020
+ """当前展开的那条在 shown 里的下标;已经滚出视野就返回 None。"""
1021
+ if self._expanded is None:
1022
+ return None
1023
+ for i, msg in enumerate(shown):
1024
+ if self._msg_key(msg) == self._expanded:
1025
+ return i
1026
+ return None
1027
+
1028
+ def _toggle_expand(self, key) -> None:
1029
+ """点截断的气泡:展开成独占整个消息区;再点收起。"""
1030
+ self._expanded = None if self._expanded == key else key
1031
+ self._layout()
1032
+
1033
+ def _collapse_expanded(self) -> None:
1034
+ """新消息进来或翻页时自动收起:否则盯着一条老消息,新消息看不见。"""
1035
+ self._expanded = None
1036
+
805
1037
  def _message_shapes(self, shown):
806
1038
  """四个固定大框换成按正文文字测量的聊天气泡。
807
1039
 
@@ -818,12 +1050,21 @@ class LiveGlass:
818
1050
  fstamp = self.fonts.get(9)
819
1051
  ls = max(1, fbody.metrics("linespace"))
820
1052
  shapes, infos = [], []
1053
+ # 展开态:这条独占 4 个槽位的纵向范围,其余三条让位。槽位网格本身不动
1054
+ # (chat_layout 仍是 h 的纯函数),只是把"4 槽各放 1 条"换成"1 条占满",
1055
+ # 气泡边界照样受 base 约束,不会压到输入框。
1056
+ expanded_at = self._expanded_index(shown)
821
1057
  for i in range(MESSAGE_SLOTS):
1058
+ if expanded_at is not None and i != expanded_at:
1059
+ shapes.append((0, 0, 0, 0, 0)) # 展开态下其他消息让位
1060
+ continue
822
1061
  if i >= len(shown):
823
1062
  shapes.append((0, 0, 0, 0, 0)) # 没有这条消息:不画框
824
1063
  continue
825
1064
  msg = shown[i]
826
1065
  x0, y0, x1, y1, _r = base[i]
1066
+ if expanded_at is not None:
1067
+ y0, y1 = base[0][1], base[MESSAGE_SLOTS - 1][3]
827
1068
  slot_h = y1 - y0
828
1069
  is_user = str(msg.get("role") or "").lower() in ("user", "me", "human")
829
1070
  stamp = str(msg.get("stamp") or "")
@@ -851,6 +1092,10 @@ class LiveGlass:
851
1092
  "tx": tx, "ta": ta, "lines": lines,
852
1093
  "ty": by0 + max(4, (bh - len(lines) * ls) // 2),
853
1094
  "stamp_y": y0, "ls": ls,
1095
+ # 截断的气泡要能点开,也要看得出"这还没完"
1096
+ "clipped": self._fit_clipped,
1097
+ "expanded": expanded_at == i,
1098
+ "key": self._msg_key(msg),
854
1099
  })
855
1100
  shapes.extend(base[MESSAGE_SLOTS:])
856
1101
  return shapes, infos
@@ -868,6 +1113,10 @@ class LiveGlass:
868
1113
  self._entry.bind("<Return>", self._send)
869
1114
  self._entry.bind("<FocusIn>", lambda _e: self._render_input())
870
1115
  self._entry.bind("<FocusOut>", lambda _e: self._render_input())
1116
+ # 插入点还能被鼠标和选择改动,这些不发 KeyRelease:不补这几个,点一下
1117
+ # 输入框中间,画面上的光标就跟不过去。after_idle 等 Entry 自己先处理完。
1118
+ for seq in ("<ButtonRelease-1>", "<B1-Motion>", "<<Selection>>"):
1119
+ self._entry.bind(seq, lambda _e: self.root.after_idle(self._on_input_key), add="+")
871
1120
 
872
1121
  def _layout(self, seed: bool = False) -> None:
873
1122
  """整窗重排:标题栏 + 气泡 + 输入区 + 滚动条,然后把上一帧贴回去。
@@ -908,6 +1157,7 @@ class LiveGlass:
908
1157
  w // 2 + self._bar_len // 2, BAR_Y,
909
1158
  width=BAR_THICK, fill=self._bar_color,
910
1159
  capstyle="round")
1160
+ self._sync_static_frame()
911
1161
  self.text.refresh()
912
1162
  return
913
1163
 
@@ -925,8 +1175,36 @@ class LiveGlass:
925
1175
  w // 2 + self._bar_len // 2, BAR_Y,
926
1176
  width=BAR_THICK, fill="#b8cbe0", capstyle="round")
927
1177
  self._bar_color = "#b8cbe0"
1178
+ # 气泡宽度变了 → 形状变了 → 静态底板要重画(缓存按 shapes 命中,没变就是 0 成本)
1179
+ self._sync_static_frame()
928
1180
  self.text.refresh()
929
1181
 
1182
+ def _sync_static_frame(self) -> None:
1183
+ """静态样式:把当前尺寸/形状的底板贴上去(其余时间一帧都不算)。
1184
+
1185
+ `_draw_feed()` 会在 `_layout()` 中途换掉 `self._geo`(气泡宽度跟着文字走),
1186
+ 所以要在这里、在全部绘制之后再取一次帧 —— 否则贴上去的还是上一套气泡的
1187
+ 底板,文字换了位置而底板没换。
1188
+ """
1189
+ if not self._static or self._collapsed or self._resize:
1190
+ return
1191
+ if self._bg is None:
1192
+ return
1193
+ try:
1194
+ frame = self._renderer.frame_for(self._geo)
1195
+ except Exception as exc:
1196
+ print("static plate error", exc, flush=True)
1197
+ return
1198
+ if frame is None or (frame is self._last_frame and self._img is not None):
1199
+ return
1200
+ self._last_frame = frame
1201
+ try:
1202
+ self._img = ImageTk.PhotoImage(frame, master=self.canvas)
1203
+ self.canvas.itemconfigure(self._bg, image=self._img)
1204
+ self.canvas.tag_lower(self._bg)
1205
+ except Exception as exc:
1206
+ print("static draw error", exc, flush=True)
1207
+
930
1208
  def _draw_header(self) -> None:
931
1209
  c = self.canvas
932
1210
  w = self._geo.width
@@ -966,7 +1244,8 @@ class LiveGlass:
966
1244
  with self._geo_lock:
967
1245
  self._set_geometry(self._geo.with_shapes(shapes, plate=bool(shown)))
968
1246
  # 每条消息只按正文占一块;时间戳贴在气泡上方,不进框
969
- for info in infos:
1247
+ c = self.canvas
1248
+ for idx, info in enumerate(infos):
970
1249
  if info["stamp"]:
971
1250
  self.text.draw(info["tx"], info["stamp_y"], info["stamp"],
972
1251
  anchor=info["ta"], fill="#a8b7c9", size=9, tags=("feed",))
@@ -975,6 +1254,18 @@ class LiveGlass:
975
1254
  self.text.draw(info["tx"], info["ty"] + li * info["ls"], line,
976
1255
  anchor=info["ta"], fill="#edf6ff", size=11, tags=("feed",),
977
1256
  shadow=PLATE, adapt=not PLATE)
1257
+ if not (info["clipped"] or info["expanded"]):
1258
+ continue
1259
+ # 截断/展开的气泡给一块透明热区(fill="" 只占事件、不画像素)和一个
1260
+ # 角标:光靠省略号看不出是被砍了,更没有入口把剩下的读出来。
1261
+ bx0, by0, bx1, by1, _r = info["shape"]
1262
+ tag = f"bubble{idx}"
1263
+ c.create_rectangle(bx0, by0, bx1, by1, fill="", outline="",
1264
+ tags=("feed", "bubblehit", tag))
1265
+ self.text.draw(bx1 - 12, by1 - 11, "▴" if info["expanded"] else "▾",
1266
+ anchor="center", fill="#9fc7ff", size=9, tags=("feed", tag))
1267
+ c.tag_bind(tag, "<Button-1>",
1268
+ lambda _e, k=info["key"]: self._toggle_expand(k))
978
1269
  if not shown:
979
1270
  slot = self._geo.shapes[0]
980
1271
  self.text.draw(w // 2, slot[1] + (slot[3] - slot[1]) // 2,
@@ -1099,21 +1390,60 @@ class LiveGlass:
1099
1390
  self._set_exclude(False)
1100
1391
 
1101
1392
  def _beat(self) -> None:
1102
- """写心跳(每秒最多一次)。插件侧 `windowAlive()` 读它的 mtime。"""
1393
+ """写心跳(每秒最多一次)。
1394
+
1395
+ 以前写的是**空文件**,插件侧只能看 mtime —— 那只能回答"进程还在画吗",
1396
+ 回答不了"用户能不能看见"。于是出现最难受的一种状态:配置文件写
1397
+ `hidden:false`、进程活着、心跳在跳,屏幕上一片空,`status` 却说"显示中"
1398
+ (see-now issue #32 第 3 点)。
1399
+
1400
+ 现在把**窗口的真实可见性**一起写进去。mtime 仍然可用,老版本读法不受影响;
1401
+ 内容是多出来的一份事实。
1402
+
1403
+ 必须原子写:插件每秒都可能读它,读到半行 JSON 会被当成"没有可见性",
1404
+ 于是退回读配置文件 —— 那正好是这一版要修的东西。
1405
+ """
1103
1406
  now = time.time()
1104
1407
  if now - getattr(self, "_beat_at", 0.0) < HEARTBEAT_EVERY:
1105
1408
  return
1106
1409
  self._beat_at = now
1107
1410
  try:
1108
1411
  HEARTBEAT.parent.mkdir(parents=True, exist_ok=True)
1109
- HEARTBEAT.write_bytes(b"")
1412
+ tmp = HEARTBEAT.with_name("window-heartbeat.tmp")
1413
+ tmp.write_bytes(self._beat_payload(now))
1414
+ os.replace(tmp, HEARTBEAT)
1110
1415
  except Exception:
1111
1416
  pass
1112
1417
 
1418
+ def _beat_payload(self, now: float) -> bytes:
1419
+ """心跳内容:`{at, visible, hidden, state}`。
1420
+
1421
+ `hidden` 是**意图**(配置文件要求藏),`visible` 是**事实**(Tk 说了算)。
1422
+ 两个都要写 —— 只写事实的话,插件分不清"用户故意藏的"和"想显示但没 map 出来"。
1423
+ """
1424
+ try:
1425
+ state = str(self.root.state())
1426
+ except Exception:
1427
+ state = "unknown"
1428
+ visible = (not self._hidden) and state == "normal"
1429
+ try:
1430
+ visible = visible and bool(self.root.winfo_ismapped())
1431
+ except Exception:
1432
+ visible = False
1433
+ return json.dumps(
1434
+ {"at": round(now, 3), "visible": visible, "hidden": bool(self._hidden), "state": state},
1435
+ ensure_ascii=False,
1436
+ ).encode("utf-8")
1437
+
1113
1438
  # ---- 主循环 ----
1114
1439
 
1115
1440
  def _tick(self) -> None:
1116
1441
  self._beat()
1442
+ if self._static:
1443
+ # 静态底板:没有帧要取、没有渐变要算。只留心跳(插件靠它判断窗口还活着)
1444
+ # 和低频定时器,CPU 占用基本为 0。
1445
+ self.root.after(500, self._tick)
1446
+ return
1117
1447
  if SNAPSHOT and self._snapshot_done:
1118
1448
  self._pause.set()
1119
1449
  if self._excluded:
@@ -1138,7 +1468,9 @@ class LiveGlass:
1138
1468
  out = self._q.get_nowait()
1139
1469
  except queue.Empty:
1140
1470
  out = None
1471
+ delay = INTERVAL_MS
1141
1472
  if out is not None:
1473
+ t_draw = time.perf_counter()
1142
1474
  try:
1143
1475
  self._last_frame = out
1144
1476
  self._img = ImageTk.PhotoImage(out, master=self.canvas)
@@ -1148,16 +1480,25 @@ class LiveGlass:
1148
1480
  self._adapt_bar(out)
1149
1481
  except Exception as exc:
1150
1482
  print("draw error", exc, flush=True)
1483
+ cost_ms = (time.perf_counter() - t_draw) * 1000.0
1484
+ self._draw_ms = self._draw_ms * 0.8 + cost_ms * 0.2
1485
+ # 主线程绘制本身超过一帧预算时,别按固定 16ms 硬塞下一帧:
1486
+ # 给 Tk 留出处理鼠标/键盘的时间,否则事件队列越积越长,手感就是卡。
1487
+ delay = max(INTERVAL_MS, min(100, int(self._draw_ms * 1.5)))
1488
+
1489
+ self.root.after(delay, self._tick)
1151
1490
 
1152
- self.root.after(INTERVAL_MS, self._tick)
1491
+ def _work(self, stop: threading.Event) -> None:
1492
+ """抓取 + 合成全在后台,主线程只负责显示最新一帧。
1153
1493
 
1154
- def _work(self) -> None:
1155
- """抓取 + 合成全在后台,主线程只负责显示最新一帧。"""
1494
+ `stop` 是**这一次线程**的开关(不是 `self._stop`):换样式时会停一次、
1495
+ 再换 live 时又要起一次,共用一个 Event 的话第二次一启动就退出。
1496
+ """
1156
1497
  import mss
1157
1498
 
1158
1499
  idle = 0
1159
1500
  with mss.mss() as sct:
1160
- while not self._stop.is_set():
1501
+ while not stop.is_set() and not self._stop.is_set():
1161
1502
  if self._pause.is_set() or self._collapsed:
1162
1503
  time.sleep(0.03)
1163
1504
  continue
@@ -1183,13 +1524,16 @@ class LiveGlass:
1183
1524
  dt = time.perf_counter() - t0
1184
1525
  self._ema = self._ema * 0.9 + dt * 0.1
1185
1526
  if self._ema > 0.026:
1186
- self._target_fps = 45
1527
+ target = 45
1187
1528
  elif self._ema > 0.016:
1188
- self._target_fps = 60
1529
+ target = 60
1189
1530
  elif self._ema > 0.011:
1190
- self._target_fps = 90
1531
+ target = 90
1191
1532
  else:
1192
- self._target_fps = min(MAX_FPS, self._hz)
1533
+ target = MAX_FPS
1534
+ # 自适应只能往下走;不能越过启动时的上限(默认 60),
1535
+ # 否则 120fps 的旧阈值会把已经设成 60 的窗口又抬回 90fps。
1536
+ self._target_fps = max(30, min(target, MAX_FPS, self._hz))
1193
1537
  # 静态画面:合成已经跳过,但「有没有变」只能靠抓屏看,单次 grab
1194
1538
  # 就要 ~7ms —— 按 60fps 空转等于白烧 40% 单核。探针降到 30fps,
1195
1539
  # 有变化时 idle 立刻归零、下一拍就恢复全速(最坏多等 33ms,
@@ -1200,11 +1544,22 @@ class LiveGlass:
1200
1544
  # ---- 窗口句柄 ----
1201
1545
 
1202
1546
  def _hwnd_root(self):
1547
+ if not IS_WIN:
1548
+ return None
1203
1549
  if self._hwnd is None:
1204
1550
  self._hwnd = ctypes.windll.user32.GetAncestor(self.root.winfo_id(), 2)
1205
1551
  return self._hwnd
1206
1552
 
1207
1553
  def _set_exclude(self, on: bool) -> None:
1554
+ """WDA:让窗口从屏幕捕获里消失,抓自己所在区域时抓到的是背后的桌面。
1555
+
1556
+ macOS/Linux 没有这个 API,**不能抓、也不能设**:硬调就是 AttributeError。
1557
+ 返回 False 之后 `_cappable` 会被打开,改走"抓到了就把自己那块填掉"那条路
1558
+ (见 `glass_capture.fill_own_rect`),否则会递归地拍到自己。
1559
+ """
1560
+ if not IS_WIN:
1561
+ self._excluded = False
1562
+ return
1208
1563
  hwnd = self._hwnd_root()
1209
1564
  fn = ctypes.windll.user32.SetWindowDisplayAffinity
1210
1565
  fn.argtypes = [wintypes.HWND, wintypes.DWORD]
@@ -1215,6 +1570,15 @@ class LiveGlass:
1215
1570
  print("WDA failed", ctypes.GetLastError(), flush=True)
1216
1571
 
1217
1572
  def _bbox(self):
1573
+ if not IS_WIN:
1574
+ # 非 Windows 没有 GetWindowRect;用 Tk 自己的屏幕坐标顶上。
1575
+ # Retina 上是逻辑像素,和 mss 的物理像素可能差一个缩放倍数 ——
1576
+ # 已知的遗留问题,那类机器上建议用 frost/solid(都不抓屏)。
1577
+ try:
1578
+ x, y = int(self.root.winfo_rootx()), int(self.root.winfo_rooty())
1579
+ return (x, y, x + int(self.root.winfo_width()), y + int(self.root.winfo_height()))
1580
+ except Exception:
1581
+ return (0, 0, 0, 0)
1218
1582
  rc = _RECT()
1219
1583
  ctypes.windll.user32.GetWindowRect(self._hwnd_root(), ctypes.byref(rc))
1220
1584
  return (rc.left, rc.top, rc.right, rc.bottom)
@@ -1245,12 +1609,13 @@ class LiveGlass:
1245
1609
  self._stop.set()
1246
1610
  self._pause.set()
1247
1611
  self._set_exclude(False)
1248
- self._worker.join(timeout=0.3)
1612
+ self._stop_worker()
1249
1613
  try:
1250
1614
  self._renderer.close()
1251
1615
  except Exception:
1252
1616
  pass
1253
- ctypes.windll.winmm.timeEndPeriod(1)
1617
+ if IS_WIN:
1618
+ ctypes.windll.winmm.timeEndPeriod(1)
1254
1619
  finally:
1255
1620
  self.root.destroy()
1256
1621
  return "break"