dsh-watch-together 0.3.3 → 0.3.5

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,78 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.3.5] - 2026-11-21
4
+
5
+ ### Fixed — 悬浮窗:顶边拉不高,输入框选不了字(#63)
6
+
7
+ - 顶边一直不能往上拉:`_edge_at` 里 `y <= edge` 整条返回 `None`,高度只能从底边改。
8
+ 现在最上面 `TOP_EDGE_PX = 14` 像素返回 `"n"`,再往下仍是拖窗(标题栏 item 从 y=17 起,
9
+ 不压它们;四角仍是 nw/ne)。
10
+ - 输入框选不了字:Entry 本体不可见、文字画在 Canvas 上,`sel` 的高亮用户根本看不见。
11
+ 现在 `_render_input` 读 `sel.first/sel.last` 在 Canvas 上画选区底色,有选区时不画光标;
12
+ 单击按字宽中点定位(含可见段起点),按住拖选,0.35 秒内连点两下全选;Ctrl+A 绑到
13
+ `_input_select_all` 并 `return "break"`(Tk 的类绑定里 Ctrl+A 是"跳到行首")。
14
+ - 去掉 `inputzone` 的 `<Button-1>` tag 绑定:Canvas 的 tag 绑定比 root 的 `_press` 先触发,
15
+ 它调 `_focus_input()` 会把光标挪回末尾,定位与拖选会全失效。点输入框统一走 `_press`。
16
+ - 光标从 1px `#b9d7ff` 改成 2px 圆头 `#7cc4ff`、高 20px —— 原来那条在玻璃上几乎看不见。
17
+
18
+ 新增 `scripts/check-input-select.py`(真导入 `window.py` 调真实方法,等宽假字体注入,
19
+ 无显示器时 Ctrl+A 一项 SKIP)。已知边界:双击只看 0.35s 不看两次点击的距离。
20
+
21
+ ### Fixed — 用户打的字写不进 `chat.jsonl` 时,消息就永远丢了(dsh-see-now#75)
22
+
23
+ 社区实报:同一台机器上 PowerShell 能写 `~/.dsh/see-now/chat.jsonl`、Python append 报
24
+ `Permission denied`。窗口里的表现是"字打出来了,按回车没反应",状态栏只有一行 errno。
25
+
26
+ `append_user` 现在会**自己修一次**:append 撞上 `PermissionError` 时,把整份读出来 + 新行
27
+ 写成同目录的临时文件,再 `os.replace()` 换掉原文件 —— 新文件的 ACL 由目录继承,坏 ACL
28
+ 跟着旧文件一起没了;读不出来就只写这一句(丢历史也不能丢这句话)。替换也失败时才把
29
+ **第一条** `PermissionError` 抛给状态栏,并提示"文件被占用或权限不足"。
30
+ 失败时输入框**不清空**,用户改完环境可以直接再按一次回车。
31
+
32
+ 新增 `scripts/check-chat-append.py`:正常 append / EACCES 自愈(历史一行不丢、临时文件不残留)/
33
+ 连 replace 都失败时抛真因。
34
+
35
+ ## [0.3.4] - 2026-11-16
36
+
37
+ > 三件都在 `examples/floating-chat/window.py`。前两条来自 see-now 那边的社区报告
38
+ > (`dsh-see-now#70` / `#71`),第三条是 B 站评论里的现场实测 —— 窗口脚本两个包共用,
39
+ > 所以一起在这里修。
40
+
41
+ ### Fixed — 「关」要关到底:最小化之后抓屏线程必须真的停
42
+
43
+ 社区原话:「状态位早就是 false,窗口还在全速抓屏,4 秒吃掉 5 秒的 CPU」。
44
+ 用户眼里的「关」是三件事 —— 指示灯灭、预览停、**CPU 落回 0**;只做第一件的话,
45
+ 后两件会安静地开着,那正是"被装上摄像头"的感觉来源。
46
+
47
+ - 根因:`_minimize()` 只 `withdraw()` 了窗口,**一个字都没碰抓屏线程**。`live` 样式下
48
+ `_work()` 每帧 `mss` 抓整屏 + 跑一遍模糊,屏幕上却什么都没有。而 `_stop_worker()`
49
+ 全文件只有两个调用点(换样式 / 关窗),最小化这条路一次都没走。
50
+ - `_minimize()` 收尾调 `_stop_worker()` —— 连 mss 句柄一起释放,不是让线程空转 `sleep`。
51
+ - `_restore()` 调 `_start_worker()` 重新拉起来;`_work()` 判据补 `or self._hidden` 当第三道闸。
52
+ - 对照实测(真起 live 窗口,`render` 换计数器):旧版最小化后 700ms 内**又画了 21 帧**,
53
+ 新版 **0 帧**且线程退出。判据不能只看 `_hidden` —— 旧版它也是 True。
54
+
55
+ ### Fixed — macOS:输入框打不进字 / 触控板双指不滚 / 输入法候选框被压住(see-now#70)
56
+
57
+ - **打不进字**:aqua 上 `overrideredirect(True)` 得到的不是 key window,操作系统根本不往
58
+ 这个进程送键盘事件(探针实测 `<KeyPress>` 0 条)。Tk 8.6 的老解法
59
+ `::tk::unsupported::MacWindowStyle` 在 Tk 9 里被整个删掉,没有等价入口 —— 所以 macOS 上
60
+ 不调 `overrideredirect`,保留系统标题栏。代价是顶部多一条系统栏,换"能打字"值。
61
+ - **触控板**:Tk 9 在 mac 上把触控板拆成独立的 `<TouchpadScroll>`,`%D` 是
62
+ `dx<<16 | dy`(低 16 位有符号像素增量),~60Hz、每次几个像素。按
63
+ `::tk::PreciseScrollDeltas` 解包,攒够 32px 滚一格,余量留到下一次。
64
+ Tk 8.6 没有这个事件类型,bind 失败就静默保持"只有滚轮"。
65
+ - **候选框**:`_keep_on_top()` 每 1.8s 抬一次 topmost,把普通窗口层的候选框压在底下。
66
+ 输入框有焦点期间跳过并撤掉 topmost,`<FocusOut>` 恢复。只对 mac 生效 —— Windows 上
67
+ 撤了会被宿主顶下去(#44),那边候选框是独立浮层,不受影响。
68
+
69
+ ### Fixed — 滚动时静态底板逐格重建,单格 45~60ms(see-now#71)
70
+
71
+ 滚动路径每换一次 `_geo.shapes` 就 `frame_for()` 重画一张底板,实测 11~12ms/次。
72
+ 改成停手 `STATIC_DEFER_MS`(=200ms) 后再重建,滚动期间只重画气泡;定时器只留一个
73
+ (连线滚十格不能十个 `after` 一起醒)。`_layout()` 里那两处仍立即重建 ——
74
+ 那是尺寸/折叠变化,不是滚动。
75
+
3
76
  ## [0.3.3] - 2026-11-11
4
77
 
5
78
  > #56 的第 3 条,也就是前几轮一直卡在"语义没定"的那一件:**标题栏加一个 ‖/▶**。
package/dsh.plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-watch-together",
3
3
  "description": "Watch a video together, in sync with the user's real playback: each segment arrives as one storyboard image plus its subtitle lines just before it ends, and the floating window carries spoken replies and live room audio.",
4
- "version": "0.3.3",
4
+ "version": "0.3.5",
5
5
  "entry": {
6
6
  "name": "dsh-watch-together",
7
7
  "inject": [
@@ -48,6 +48,9 @@ from pathlib import Path
48
48
  # `AttributeError: module 'ctypes' has no attribute 'windll'`,而且死在依赖预检
49
49
  # 之前,用户看到的是"启动后 700ms 退出,code=1"(issue #40)。
50
50
  IS_WIN = os.name == "nt"
51
+ # 是不是 macOS。aqua 上有一整套和 Windows 不一样的行为,**不能拿"不是 Windows"来代替**:
52
+ # 无边框窗收不到键盘、触控板走独立事件、输入法候选框是普通窗口层(#70 三条)。
53
+ IS_MAC = sys.platform == "darwin"
51
54
 
52
55
  # 窗口扩展样式:`noActivate` 用它(点窗不激活,见 `_apply_no_activate`)
53
56
  GWL_EXSTYLE = -20
@@ -154,6 +157,20 @@ INTERVAL_MS = max(4, int(1000 / MAX_FPS))
154
157
  # 降到 30fps 探针,有变化时 idle 立刻归零、下一拍恢复全速。
155
158
  PROBE_FPS = 30
156
159
 
160
+ # mac 触控板:`<TouchpadScroll>` 一次只给几个像素(~60Hz),攒够这么多才滚一行。
161
+ # 32 是社区实测的结果(#70 第 2 条):小于它一次滑动要等太久,大于它一格跳得太狠。
162
+ TOUCHPAD_ROW_PX = 32
163
+ # 滚动时把静态底板的**重建**推到停手之后这么久(#71)。底板一次 11~12ms,
164
+ # 每滚一格都重建会让单格 45~60ms;推到停手后,滚动期间只重画气泡。
165
+ STATIC_DEFER_MS = 200
166
+
167
+ TOP_EDGE_PX = 14
168
+
169
+ CARET_COLOR = "#7cc4ff"
170
+ CARET_W = 2
171
+ CARET_HALF_H = 10
172
+ SEL_FILL = "#2f6fb5"
173
+
157
174
  # 仅用于文档截图/CI 视觉检查:暂停抓屏并把 WDA 关掉,窗口才会出现在截图里
158
175
  PREVIEW = os.environ.get("DSH_GLASS_PREVIEW") == "1"
159
176
  # 文档截图:正常抓屏 2.5 秒后暂停并取消 WDA,保留最后一帧玻璃
@@ -444,10 +461,42 @@ def danmaku_options(cfg=None) -> dict:
444
461
 
445
462
 
446
463
  def append_user(text: str) -> None:
464
+ """把用户打的一句话追加进 `chat.jsonl`。
465
+
466
+ 正常路径就是 append。**EACCES 时退一步自己修**(issue #75):社区实报
467
+ `Permission denied: '...chat.jsonl'` —— 同一台机器上 PowerShell 能写、Python 不能,
468
+ 典型的"文件 ACL 坏了 / 被某个带独占语义的进程攥着"。
469
+
470
+ 修法不是重试 append(同一个句柄还是会被拒),而是**整份读出来 + 新行,写成临时文件
471
+ 再 `os.replace()` 换掉**:新文件的 ACL 由目录继承,坏 ACL 随旧 inode 一起没了。
472
+ 并发追加的风险只在失败路径上(本来这条就写不进去),可以接受。
473
+ """
447
474
  CHAT_FILE.parent.mkdir(parents=True, exist_ok=True)
448
- with open(CHAT_FILE, "a", encoding="utf-8") as f:
449
- f.write(json.dumps({"role": "user", "text": text, "at": int(time.time() * 1000)},
450
- ensure_ascii=False) + "\n")
475
+ line = json.dumps({"role": "user", "text": text, "at": int(time.time() * 1000)},
476
+ ensure_ascii=False) + "\n"
477
+ try:
478
+ with open(CHAT_FILE, "a", encoding="utf-8") as f:
479
+ f.write(line)
480
+ return
481
+ except PermissionError as exc:
482
+ first = exc
483
+ old = ""
484
+ try:
485
+ if CHAT_FILE.exists():
486
+ old = CHAT_FILE.read_text(encoding="utf-8")
487
+ except OSError:
488
+ old = "" # 读不出来只能丢掉历史,至少别把这一句也丢了
489
+ tmp = CHAT_FILE.with_name(f"{CHAT_FILE.name}.{os.getpid()}.tmp")
490
+ try:
491
+ with open(tmp, "w", encoding="utf-8") as f:
492
+ f.write(old + line)
493
+ os.replace(tmp, CHAT_FILE)
494
+ except OSError:
495
+ try:
496
+ tmp.unlink()
497
+ except OSError:
498
+ pass
499
+ raise first
451
500
 
452
501
 
453
502
  def asr_python() -> str:
@@ -565,7 +614,15 @@ class LiveGlass:
565
614
 
566
615
  self.root = tk.Tk()
567
616
  self.root.withdraw()
568
- self.root.overrideredirect(True)
617
+ # **macOS 上不能 overrideredirect**:aqua 里这样得到的不是一个 key window,
618
+ # 操作系统压根不往这个进程送键盘事件 —— 点输入区光标画得出来,敲键盘一个字
619
+ # 都不进(#70 第 1 条,用户探针实测 root/entry 的 <KeyPress> 0 条)。
620
+ # Tk 8.6 时代的老解法 `::tk::unsupported::MacWindowStyle style plain none`
621
+ # 在 Tk 9 里被整个删掉了(`invalid command name`),没有等价的 Tcl 入口。
622
+ # 所以留着系统标题栏:普通窗口能成为 key window,输入立刻可用 ——
623
+ # 视觉上多一条系统栏,但"打不进字"是硬伤,这个取舍只能这么取。
624
+ if not IS_MAC:
625
+ self.root.overrideredirect(True)
569
626
  self.root.title(self.name)
570
627
  self.root.attributes("-topmost", True)
571
628
  self.root.configure(bg=KEY)
@@ -619,6 +676,13 @@ class LiveGlass:
619
676
  self._drag = None
620
677
  self._resize = None
621
678
  self._preview_at = 0.0
679
+ # 触控板滚动的余量(像素)。mac 的 <TouchpadScroll> 每次只给几个像素、60Hz 一次,
680
+ # 攒够一行才滚 —— 见 `_touchpad_scroll`(#70 第 2 条)。
681
+ self._scroll_acc = 0
682
+ # 输入框有没有焦点。mac 上「正在输入」要撤掉 topmost,否则输入法候选框被压住(#70 第 3 条)。
683
+ self._ime_focus = False
684
+ # 滚动时底板重建的 after id(#71,见 `_schedule_static_frame`)
685
+ self._static_job = None
622
686
  # Entry 的真光标被关掉(insertwidth=0),画面上那条线是自己画的,
623
687
  # 所以闪烁也得自己来。_caret_job 存 after 的 id,重排时取消,避免叠定时器。
624
688
  self._caret_on = True
@@ -825,9 +889,15 @@ class LiveGlass:
825
889
  self.root.after(26, lambda: self._intro_step(n + 1))
826
890
 
827
891
  def _keep_on_top(self) -> None:
828
- """DSH 等置顶窗口被激活后会把悬浮窗压下去;定时重新抬到最上层。"""
892
+ """DSH 等置顶窗口被激活后会把悬浮窗压下去;定时重新抬到最上层。
893
+
894
+ **正在输入的时候不抬**(#70 第 3 条):输入法候选框是普通窗口层,
895
+ 窗口一 topmost 就把它压在底下 —— mac 上用户完全看不见自己在打什么。
896
+ `_focus_input` 会撤掉 topmost 并置起 `_ime_focus`,失焦(`_on_input_blur`)
897
+ 恢复。只对 mac 生效:Windows 上撤 topmost 会被 DSH 顶下去(#44 第 1 条)。
898
+ """
829
899
  try:
830
- if not self._hidden:
900
+ if not self._hidden and not self._ime_focus:
831
901
  self.root.attributes("-topmost", True)
832
902
  self.root.lift()
833
903
  except Exception:
@@ -957,7 +1027,9 @@ class LiveGlass:
957
1027
  try:
958
1028
  append_user(text)
959
1029
  except Exception as exc:
960
- self.feed.status = f"写不进去:{exc}"
1030
+ # 字**不清空**:写不进去的时候,用户最需要的就是改完环境再按一次回车。
1031
+ # `append_user` 里已经试过"换掉整份文件"这条路,还失败就真是权限/占用了。
1032
+ self.feed.status = f"写不进去:{exc}(文件被占用或权限不足;关掉多余的窗再试)"
961
1033
  self._refresh_feed()
962
1034
  return "break"
963
1035
  try:
@@ -979,6 +1051,29 @@ class LiveGlass:
979
1051
  # 连滚只重排最后一次:滚十格就白画九遍(#44 第 2 条,社区实测每格卡 ~1 秒)
980
1052
  self._schedule_feed_refresh()
981
1053
 
1054
+ def _touchpad_scroll(self, e):
1055
+ """mac 的触控板:`<MouseWheel>` 根本不来,来的是 `<TouchpadScroll>`(#70 第 2 条)。
1056
+
1057
+ `%D` 的语义也不是 `±120`:高 16 位是 dx,低 16 位是**有符号的 dy(像素增量)**。
1058
+ 事件约 60Hz、每次只有几个像素(实测 dy = -4 ~ -8),所以不能"一次事件滚一格" ——
1059
+ 攒够 `TOUCHPAD_ROW_PX` 才走一格,余量留着给下一次。解包方式照抄 Tk 自己的
1060
+ `::tk::PreciseScrollDeltas`。方向与 `_wheel` 一致:dy > 0 = 向上 = 看更早的消息。
1061
+ """
1062
+ try:
1063
+ raw = int(e.delta)
1064
+ except (TypeError, ValueError):
1065
+ return
1066
+ low = raw & 0xFFFF
1067
+ dy = low - 0x10000 if low >= 0x8000 else low
1068
+ self._scroll_acc += dy
1069
+ step = int(self._scroll_acc / TOUCHPAD_ROW_PX)
1070
+ if not step:
1071
+ return
1072
+ self._scroll_acc -= step * TOUCHPAD_ROW_PX
1073
+ if self.feed.scroll(step):
1074
+ self._collapse_expanded()
1075
+ self._schedule_feed_refresh()
1076
+
982
1077
  def _schedule_feed_refresh(self, delay: int = 40) -> None:
983
1078
  job = getattr(self, "_feed_job", None)
984
1079
  if job is not None:
@@ -1017,7 +1112,35 @@ class LiveGlass:
1017
1112
  self._draw_scrollbar()
1018
1113
  self.text.refresh()
1019
1114
  if self._geo.shapes != shapes_before:
1020
- self._sync_static_frame()
1115
+ self._schedule_static_frame()
1116
+
1117
+ def _schedule_static_frame(self) -> None:
1118
+ """把静态底板的重建推到「手停下来之后」(#71)。
1119
+
1120
+ 社区实测(macOS / Tk 9.1,issue 里有逐步计时):底板 `frame_for()` 一次
1121
+ 11~12ms,而滚动路径**每滚一格都会换 `_geo.shapes`**,于是每格都重建一张 ——
1122
+ 单格 45~60ms,滚动必然掉帧,而且靠调参救不了。
1123
+
1124
+ 推迟之后滚动期间只重画气泡,代价是滚动中短暂看到旧底板(形状差一点点),
1125
+ 停手 200ms 内就对上了。**语义没变**:`_sync_static_frame()` 本来就按 shapes
1126
+ 缓存,形状没变时是 0 成本,所以"多画一次"不亏。
1127
+
1128
+ 定时器必须只留一个:连线滚十格,十个 after 一起醒来等于把省下的又还回去。
1129
+ """
1130
+ job = getattr(self, "_static_job", None)
1131
+ if job is not None:
1132
+ try:
1133
+ self.root.after_cancel(job)
1134
+ except Exception:
1135
+ pass
1136
+ try:
1137
+ self._static_job = self.root.after(STATIC_DEFER_MS, self._run_static_frame)
1138
+ except Exception:
1139
+ self._static_job = None
1140
+
1141
+ def _run_static_frame(self) -> None:
1142
+ self._static_job = None
1143
+ self._sync_static_frame()
1021
1144
 
1022
1145
  def _toggle_mic(self):
1023
1146
  if self._mic_proc is not None and self._mic_proc.poll() is None:
@@ -1106,24 +1229,101 @@ class LiveGlass:
1106
1229
  x, y = x0 + 84, y0 + 27
1107
1230
  maxw = max(60, x1 - x0 - 100)
1108
1231
  cx = None
1232
+ sel = None
1233
+ try:
1234
+ if text and self._entry.select_present():
1235
+ sel = (self._entry.index("sel.first"), self._entry.index("sel.last"))
1236
+ except Exception:
1237
+ sel = None
1238
+ self._input_view = None
1109
1239
  if not text and not focused:
1110
1240
  self.text.draw(x, y, "在这里跟它说话…", anchor="w", fill="#8e9db2",
1111
1241
  size=11, tags=("inputtext", "inputzone"))
1112
1242
  elif text:
1113
1243
  font = self.fonts.get(11)
1114
1244
  shown, caret_in = self._visible_input(text, maxw, caret)
1245
+ lo = caret - caret_in
1246
+ self._input_view = (x, lo, shown)
1247
+ if sel and sel[1] > lo and sel[0] < lo + len(shown):
1248
+ a = max(0, sel[0] - lo)
1249
+ b = min(len(shown), sel[1] - lo)
1250
+ c.create_rectangle(x + font.measure(shown[:a]), y - 11,
1251
+ x + font.measure(shown[:b]), y + 11,
1252
+ fill=SEL_FILL, outline="", tags=("inputcursor", "inputzone"))
1115
1253
  self.text.draw(x, y, shown, anchor="w", fill="#eef6ff",
1116
1254
  size=11, tags=("inputtext", "inputzone"))
1117
- if focused:
1255
+ if focused and not sel:
1118
1256
  cx = x + font.measure(shown[:max(0, caret_in)])
1119
1257
  elif focused:
1120
1258
  cx = x
1259
+ self._input_view = (x, 0, "")
1121
1260
  if cx is not None and self._caret_on:
1122
- c.create_line(cx + 1, y - 9, cx + 1, y + 9,
1123
- fill="#b9d7ff", width=1, tags=("inputcursor",))
1261
+ c.create_line(cx + 1, y - CARET_HALF_H, cx + 1, y + CARET_HALF_H,
1262
+ fill=CARET_COLOR, width=CARET_W, capstyle="round",
1263
+ tags=("inputcursor",))
1264
+ c.tag_raise("inputtext")
1124
1265
  self._schedule_caret(cx is not None)
1125
1266
  self.text.refresh()
1126
1267
 
1268
+ def _input_index_at(self, px: int) -> int:
1269
+ view = getattr(self, "_input_view", None)
1270
+ if not view:
1271
+ return 0
1272
+ x, lo, shown = view
1273
+ font = self.fonts.get(11)
1274
+ acc = x
1275
+ for i, ch in enumerate(shown):
1276
+ w = font.measure(ch)
1277
+ if px < acc + w / 2:
1278
+ return lo + i
1279
+ acc += w
1280
+ return lo + len(shown)
1281
+
1282
+ def _input_press(self, e) -> None:
1283
+ self._focus_input(keep_caret=True)
1284
+ idx = self._input_index_at(e.x)
1285
+ now = time.time()
1286
+ double = now - getattr(self, "_input_click_at", 0.0) < 0.35
1287
+ self._input_click_at = now
1288
+ try:
1289
+ self._entry.selection_clear()
1290
+ if double:
1291
+ self._entry.selection_range(0, "end")
1292
+ self._entry.icursor("end")
1293
+ self._input_anchor = None
1294
+ else:
1295
+ self._entry.icursor(idx)
1296
+ self._input_anchor = idx
1297
+ except Exception:
1298
+ self._input_anchor = None
1299
+ self._caret_on = True
1300
+ self._render_input()
1301
+
1302
+ def _input_drag(self, e) -> None:
1303
+ a = getattr(self, "_input_anchor", None)
1304
+ if a is None:
1305
+ return
1306
+ b = self._input_index_at(e.x)
1307
+ try:
1308
+ self._entry.icursor(b)
1309
+ if a == b:
1310
+ self._entry.selection_clear()
1311
+ else:
1312
+ self._entry.selection_range(min(a, b), max(a, b))
1313
+ except Exception:
1314
+ return
1315
+ self._caret_on = True
1316
+ self._render_input()
1317
+
1318
+ def _input_select_all(self, _e=None):
1319
+ try:
1320
+ self._entry.selection_range(0, "end")
1321
+ self._entry.icursor("end")
1322
+ except Exception:
1323
+ pass
1324
+ self._render_input()
1325
+ return "break"
1326
+
1127
1327
  def _schedule_caret(self, active: bool) -> None:
1128
1328
  """只有输入框拿着焦点时才跑闪烁定时器;失焦就停,不白烧 after。"""
1129
1329
  if self._caret_job is not None:
@@ -1156,20 +1356,40 @@ class LiveGlass:
1156
1356
  self._render_input()
1157
1357
  return None
1158
1358
 
1159
- def _focus_input(self, _e=None):
1359
+ def _focus_input(self, _e=None, keep_caret: bool = False):
1160
1360
  # noActivate 开着时先摘掉那条样式,否则 focus_force 也拿不到键盘焦点
1161
1361
  # (WS_EX_NOACTIVATE 的窗口本来就不接受焦点)。摘掉后本次运行不再加回,
1162
1362
  # 理由见 `_apply_no_activate`。
1163
1363
  if getattr(self, "_no_activate_on", False):
1164
1364
  self._apply_no_activate(False)
1365
+ # mac:**输入期间必须撤 topmost**,否则输入法候选框被压在窗口底下看不见(#70 第 3 条)。
1366
+ # 只对 mac 生效 —— Windows 上撤了会被 DSH 顶下去(#44 第 1 条),而那边候选框
1367
+ # 是独立浮层,不受 topmost 影响。
1368
+ if IS_MAC and not self._ime_focus:
1369
+ self._ime_focus = True
1370
+ try:
1371
+ self.root.attributes("-topmost", False)
1372
+ except Exception:
1373
+ pass
1165
1374
  try:
1166
1375
  self._entry.focus_force()
1167
- self._entry.icursor("end")
1376
+ if not keep_caret:
1377
+ self._entry.icursor("end")
1168
1378
  except Exception:
1169
1379
  pass
1170
1380
  self._caret_on = True
1171
1381
  self._render_input()
1172
1382
 
1383
+ def _on_input_blur(self, _e=None):
1384
+ """输入框失焦:重画光标 + 把 topmost 还回去(mac,见 `_focus_input`)。"""
1385
+ if IS_MAC and self._ime_focus:
1386
+ self._ime_focus = False
1387
+ try:
1388
+ self.root.attributes("-topmost", True)
1389
+ except Exception:
1390
+ pass
1391
+ self._render_input()
1392
+
1173
1393
  # ---- 改名 ----
1174
1394
 
1175
1395
  def _edit_title(self, _event=None):
@@ -1365,6 +1585,15 @@ class LiveGlass:
1365
1585
  except Exception:
1366
1586
  self._hidden = False
1367
1587
  return
1588
+ # **抓屏线程必须一起停**(社区实报 2026-11-16)。
1589
+ #
1590
+ # `withdraw()` 只是把窗口从屏幕上拿走 —— `mss` 照样每帧抓整屏、再跑一遍模糊,
1591
+ # 用户看到的是"窗口关掉状态、CPU 却满载"(实测 4 秒墙钟吃掉 5 秒 CPU 时间)。
1592
+ # 他说的"关"是三件事:指示灯灭、预览停、**CPU 落回 0**。只做第一件的话,
1593
+ # 后两件会安静地开着 —— 这正是"被装上摄像头"的感觉来源。
1594
+ #
1595
+ # 放在 withdraw 之后:先让窗口消失,再花那 0.4s 的 join,用户感知不到卡。
1596
+ self._stop_worker()
1368
1597
  if self._tray is not None:
1369
1598
  self._tray.show()
1370
1599
  # 每次运行只提示一次:Windows 11 会把新图标塞进溢出区,不告诉用户
@@ -1386,6 +1615,9 @@ class LiveGlass:
1386
1615
  pass
1387
1616
  if self._tray is not None:
1388
1617
  self._tray.hide()
1618
+ # 回来要把抓屏线程重新拉起来 —— `_start_worker()` 会重建 CaptureSource;
1619
+ # 静态样式(solid / frost)下它自己会 return,不需要在这里分情况。
1620
+ self._start_worker()
1389
1621
  self._mark_read()
1390
1622
 
1391
1623
  def _sync_danmaku(self, cfg=None) -> None:
@@ -1593,8 +1825,10 @@ class LiveGlass:
1593
1825
  insertwidth=0, highlightthickness=0)
1594
1826
  self._entry.bind("<KeyRelease>", self._on_input_key)
1595
1827
  self._entry.bind("<Return>", self._send)
1828
+ for seq in ("<Control-a>", "<Control-A>"):
1829
+ self._entry.bind(seq, self._input_select_all)
1596
1830
  self._entry.bind("<FocusIn>", lambda _e: self._render_input())
1597
- self._entry.bind("<FocusOut>", lambda _e: self._render_input())
1831
+ self._entry.bind("<FocusOut>", self._on_input_blur)
1598
1832
  # 插入点还能被鼠标和选择改动,这些不发 KeyRelease:不补这几个,点一下
1599
1833
  # 输入框中间,画面上的光标就跟不过去。after_idle 等 Entry 自己先处理完。
1600
1834
  for seq in ("<ButtonRelease-1>", "<B1-Motion>", "<<Selection>>"):
@@ -1646,7 +1880,6 @@ class LiveGlass:
1646
1880
  self._draw_scrollbar()
1647
1881
  self._bind_header()
1648
1882
  c.tag_bind("send", "<Button-1>", self._send)
1649
- c.tag_bind("inputzone", "<Button-1>", self._focus_input)
1650
1883
  c.tag_raise("close")
1651
1884
  c.tag_raise("send")
1652
1885
 
@@ -2013,7 +2246,10 @@ class LiveGlass:
2013
2246
  idle = 0
2014
2247
  with mss.mss() as sct:
2015
2248
  while not stop.is_set() and not self._stop.is_set():
2016
- if self._pause.is_set() or self._collapsed:
2249
+ # `_hidden` 是**第三道闸**:正常路径上 `_minimize()` 会直接 `_stop_worker()`
2250
+ # 把线程杀掉,这里再判一次是防别的路径设了 `_hidden` 却没停线程
2251
+ # (状态位说"关了"、CPU 还在烧,正是社区报的那种假关)。
2252
+ if self._pause.is_set() or self._collapsed or self._hidden:
2017
2253
  time.sleep(0.03)
2018
2254
  continue
2019
2255
  t0 = time.perf_counter()
@@ -2185,7 +2421,7 @@ class LiveGlass:
2185
2421
  if x >= w - corner and y >= h - corner:
2186
2422
  return "se"
2187
2423
  if y <= edge:
2188
- return None # 顶部中间只拖动,不缩放
2424
+ return "n" if y <= TOP_EDGE_PX else None
2189
2425
  if x <= edge:
2190
2426
  return "w"
2191
2427
  if x >= w - edge:
@@ -2226,7 +2462,11 @@ class LiveGlass:
2226
2462
  return
2227
2463
  x0, y0, x1, y1, _r = self._geo.input_shape
2228
2464
  if x0 <= e.x <= x1 and y0 <= e.y <= y1:
2229
- self._focus_input()
2465
+ if e.x >= x0 + 76:
2466
+ self._input_press(e)
2467
+ self._input_selecting = True
2468
+ else:
2469
+ self._focus_input()
2230
2470
  return
2231
2471
  mode = self._edge_at(e.x, e.y)
2232
2472
  if mode:
@@ -2240,6 +2480,9 @@ class LiveGlass:
2240
2480
  e.y_root - self.root.winfo_y())
2241
2481
 
2242
2482
  def _motion(self, e):
2483
+ if getattr(self, "_input_selecting", False):
2484
+ self._input_drag(e)
2485
+ return
2243
2486
  if self._resize:
2244
2487
  mode, sx, sy, x0, y0, w0, h0 = self._resize
2245
2488
  dx, dy = e.x_root - sx, e.y_root - sy
@@ -2277,6 +2520,9 @@ class LiveGlass:
2277
2520
  self.root.geometry(f"+{nx}+{ny}")
2278
2521
 
2279
2522
  def _release(self, e):
2523
+ if getattr(self, "_input_selecting", False):
2524
+ self._input_selecting = False
2525
+ return
2280
2526
  if self._resize:
2281
2527
  self._resize = None
2282
2528
  self._preview_at = 0.0
@@ -2292,6 +2538,14 @@ class LiveGlass:
2292
2538
  def run(self):
2293
2539
  self.root.bind("<Escape>", self._close)
2294
2540
  self.root.bind("<MouseWheel>", self._wheel)
2541
+ # **mac 触控板不走 <MouseWheel>**:Tk 9 把它拆成了独立的 <TouchpadScroll>
2542
+ # (tk.h: `MappingNotify + 5`)。Tk 8.6 没有这个事件类型,bind 会当场抛
2543
+ # `bad event type or keysym`,所以只在 mac 上试,失败就保持"只有滚轮"。
2544
+ if IS_MAC:
2545
+ try:
2546
+ self.root.bind("<TouchpadScroll>", self._touchpad_scroll)
2547
+ except tk.TclError:
2548
+ pass
2295
2549
  self.root.bind("<Motion>", self._hover, add="+")
2296
2550
  self.root.bind("<Leave>", self._leave, add="+")
2297
2551
  self.root.bind("<ButtonPress-1>", self._press, add="+")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-watch-together",
3
- "version": "0.3.3",
3
+ "version": "0.3.5",
4
4
  "description": "Watch a video together, in sync with the user's real playback: every segment arrives as one storyboard image plus its subtitle lines just before it ends, while the floating window carries spoken replies and live room audio — picture and voice, not a transcript.",
5
5
  "keywords": [
6
6
  "dsh",
@@ -0,0 +1,130 @@
1
+ """`append_user` 在 EACCES 下要能自愈:python scripts/check-chat-append.py
2
+
3
+ 社区 issue(dsh-see-now#75):同一台机器上 PowerShell 能写 chat.jsonl、Python append 报
4
+ `Permission denied`。`append_user` 现在失败时会"整份读出来 + 新行写成临时文件再 os.replace",
5
+ 用目录继承的 ACL 把坏文件换掉。这个脚本把两条路都钉住:
6
+
7
+ 1. 正常 append:只多一行,历史不动
8
+ 2. append 抛 PermissionError:仍然写得进去,历史一行不丢,临时文件不残留
9
+ 3. 连 replace 都失败:把**第一个** PermissionError 抛给上层(状态栏要显示真因),临时文件清掉
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import builtins
14
+ import json
15
+ import os
16
+ import sys
17
+ import tempfile
18
+ import types
19
+ from pathlib import Path
20
+
21
+ HERE = Path(__file__).resolve().parent
22
+ sys.path.insert(0, str(HERE.parent / "examples" / "floating-chat"))
23
+
24
+ # 本机可能没装 mss(窗口只在抓屏时才用它,模块顶层却 import)
25
+ if "mss" not in sys.modules:
26
+ stub = types.ModuleType("mss")
27
+ stub.mss = lambda *a, **k: None
28
+ sys.modules["mss"] = stub
29
+
30
+ tmp = Path(tempfile.mkdtemp(prefix="chat-append-"))
31
+ os.environ["DSH_VIDEO_CACHE_DIR"] = str(tmp)
32
+ os.environ["DSH_HOME"] = str(tmp / "home")
33
+
34
+ import window # noqa: E402
35
+
36
+ failures: list[str] = []
37
+
38
+
39
+ def check(name, cond, detail=""):
40
+ if not cond:
41
+ failures.append(f"{name}{(': ' + detail) if detail else ''}")
42
+
43
+
44
+ def reset(text="历史一行\n"):
45
+ (tmp / "chat.jsonl").write_text(text, encoding="utf-8")
46
+
47
+
48
+ def lines():
49
+ return (tmp / "chat.jsonl").read_text(encoding="utf-8").splitlines()
50
+
51
+
52
+ def check_normal():
53
+ reset()
54
+ window.append_user("正常一句")
55
+ got = lines()
56
+ check(len(got) == 2, f"正常 append 只多一行({len(got)})")
57
+ check(json.loads(got[-1])["text"] == "正常一句", "最后一行是新消息")
58
+ check(json.loads(got[-1])["role"] == "user", "role 是 user")
59
+ check(not list(tmp.glob("*.tmp")), "正常路径不留临时文件")
60
+
61
+
62
+ def check_self_heal():
63
+ reset("assistant 写的\n")
64
+ real_open = builtins.open
65
+ target = Path(window.CHAT_FILE)
66
+
67
+ def blocked(file, mode="r", *a, **k):
68
+ if "a" in str(mode) and Path(file) == target:
69
+ raise PermissionError(13, "Permission denied", str(file))
70
+ return real_open(file, mode, *a, **k)
71
+
72
+ builtins.open = blocked
73
+ try:
74
+ window.append_user("坏了也要发出去")
75
+ except Exception as exc: # noqa: BLE001
76
+ check("append 被拒后仍能写进去", False, repr(exc))
77
+ finally:
78
+ builtins.open = real_open
79
+ got = lines()
80
+ check(len(got) == 2, f"自愈后历史 + 1 行({len(got)})")
81
+ check(got[0] == "assistant 写的", "历史一行没丢")
82
+ check(json.loads(got[-1])["text"] == "坏了也要发出去", "新消息真的落盘了")
83
+ check(not list(tmp.glob("*.tmp")), "自愈路径不留临时文件")
84
+
85
+
86
+ def check_replace_fails():
87
+ reset()
88
+ real_open = builtins.open
89
+ real_replace = os.replace
90
+ target = Path(window.CHAT_FILE)
91
+
92
+ def blocked(file, mode="r", *a, **k):
93
+ if "a" in str(mode) and Path(file) == target:
94
+ raise PermissionError(13, "Permission denied", "append")
95
+ return real_open(file, mode, *a, **k)
96
+
97
+ def no_replace(src, dst, *a, **k):
98
+ raise PermissionError(13, "Permission denied", "replace")
99
+
100
+ builtins.open = blocked
101
+ os.replace = no_replace
102
+ try:
103
+ window.append_user("写不进去")
104
+ check("replace 也失败时要抛出", False, "没抛异常")
105
+ except PermissionError as exc:
106
+ check("抛的是 append 那条 PermissionError", "append" in str(exc), str(exc))
107
+ except Exception as exc: # noqa: BLE001
108
+ check("抛的是 PermissionError", False, repr(exc))
109
+ finally:
110
+ builtins.open = real_open
111
+ os.replace = real_replace
112
+ check(not list(tmp.glob("*.tmp")), "失败路径也要清掉临时文件")
113
+ check(lines() == ["历史一行"], "失败时不动原文件")
114
+
115
+
116
+ def main() -> int:
117
+ check_normal()
118
+ check_self_heal()
119
+ check_replace_fails()
120
+ if failures:
121
+ print(f"FAIL: {len(failures)} 项")
122
+ for f in failures:
123
+ print(" -", f)
124
+ return 1
125
+ print("OK: 正常 append / EACCES 自愈 / 连 replace 都失败时抛真因")
126
+ return 0
127
+
128
+
129
+ if __name__ == "__main__":
130
+ raise SystemExit(main())
@@ -0,0 +1,144 @@
1
+ """顶边缩放与输入框选字的回归:python scripts/check-input-select.py"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ HERE = Path(__file__).resolve().parent
9
+ sys.path.insert(0, str(HERE.parent / "examples" / "floating-chat"))
10
+
11
+ CHAR_W = 10
12
+
13
+ failures: list[str] = []
14
+
15
+
16
+ def check(name, cond, detail=""):
17
+ if not cond:
18
+ failures.append(f"{name}{(': ' + detail) if detail else ''}")
19
+
20
+
21
+ class FakeFont:
22
+ def measure(self, s):
23
+ return len(s) * CHAR_W
24
+
25
+
26
+ class FakeFonts:
27
+ def get(self, _size, _bold=False):
28
+ return FakeFont()
29
+
30
+
31
+ class FakeRoot:
32
+ def __init__(self, w, h):
33
+ self.w, self.h = w, h
34
+
35
+ def winfo_width(self):
36
+ return self.w
37
+
38
+ def winfo_height(self):
39
+ return self.h
40
+
41
+
42
+ def stub(w=760, h=560):
43
+ from window import LiveGlass
44
+
45
+ s = object.__new__(LiveGlass)
46
+ s.root = FakeRoot(w, h)
47
+ s.fonts = FakeFonts()
48
+ return s
49
+
50
+
51
+ def check_top_edge():
52
+ import window
53
+ from window import LiveGlass
54
+
55
+ s = stub()
56
+ w = s.root.w
57
+ top = getattr(window, "TOP_EDGE_PX", 14)
58
+ for x in (40, w // 2, w - 40):
59
+ check(f"顶边 y=0 x={x} 往上拉", LiveGlass._edge_at(s, x, 0) == "n",
60
+ repr(LiveGlass._edge_at(s, x, 0)))
61
+ check(f"顶边 y={top} x={x} 往上拉", LiveGlass._edge_at(s, x, top) == "n")
62
+ check(f"顶边 y={top + 1} x={x} 拖窗", LiveGlass._edge_at(s, x, top + 1) is None,
63
+ repr(LiveGlass._edge_at(s, x, top + 1)))
64
+ check("左上角", LiveGlass._edge_at(s, 5, 5) == "nw")
65
+ check("右上角", LiveGlass._edge_at(s, w - 5, 5) == "ne")
66
+ check("右边", LiveGlass._edge_at(s, w - 3, 300) == "e")
67
+ check("左边", LiveGlass._edge_at(s, 3, 300) == "w")
68
+ check("底边", LiveGlass._edge_at(s, 300, s.root.h - 3) == "s")
69
+ check("中间", LiveGlass._edge_at(s, 300, 300) is None)
70
+ check("命中带不压到标题栏 item", top < 17, f"TOP_EDGE_PX={top}")
71
+
72
+
73
+ def check_index_at():
74
+ from window import LiveGlass
75
+
76
+ if not hasattr(LiveGlass, "_input_index_at"):
77
+ check("点击定位", False, "LiveGlass 没有 _input_index_at")
78
+ return
79
+ s = stub()
80
+ x0 = 100
81
+ s._input_view = (x0, 0, "abcdef")
82
+ cases = {x0 - 50: 0, x0: 0, x0 + 4: 0, x0 + 5: 1, x0 + 14: 1, x0 + 15: 2,
83
+ x0 + 59: 6, x0 + 500: 6}
84
+ for px, want in cases.items():
85
+ got = LiveGlass._input_index_at(s, px)
86
+ check(f"可见段从 0 起 px={px}", got == want, f"got {got} want {want}")
87
+ s._input_view = (x0, 7, "hijk")
88
+ check("可见段偏移 px=x0", LiveGlass._input_index_at(s, x0) == 7)
89
+ check("可见段偏移 px=x0+25", LiveGlass._input_index_at(s, x0 + 25) == 10)
90
+ check("可见段偏移 末尾", LiveGlass._input_index_at(s, x0 + 999) == 11)
91
+ s._input_view = None
92
+ check("没有视图时返回 0", LiveGlass._input_index_at(s, 123) == 0)
93
+
94
+
95
+ def check_ctrl_a():
96
+ try:
97
+ import tkinter as tk
98
+ root = tk.Tk()
99
+ except Exception as exc:
100
+ print(f"SKIP: Ctrl+A 需要 Tk({type(exc).__name__})")
101
+ return
102
+ try:
103
+ from window import LiveGlass
104
+
105
+ if not hasattr(LiveGlass, "_input_select_all"):
106
+ check("Ctrl+A 全选", False, "LiveGlass 没有 _input_select_all")
107
+ return
108
+ root.geometry("200x40+-3000+-3000")
109
+ entry = tk.Entry(root)
110
+ entry.pack()
111
+ s = object.__new__(LiveGlass)
112
+ s._entry = entry
113
+ s._render_input = lambda: None
114
+ for seq in ("<Control-a>", "<Control-A>"):
115
+ entry.bind(seq, lambda e: LiveGlass._input_select_all(s, e))
116
+ entry.insert(0, "你好世界 hello")
117
+ entry.icursor(3)
118
+ root.update()
119
+ entry.focus_force()
120
+ root.update()
121
+ entry.event_generate("<Control-a>")
122
+ root.update()
123
+ sel = (entry.index("sel.first"), entry.index("sel.last")) if entry.select_present() else None
124
+ check("Ctrl+A 选中全文", sel == (0, len("你好世界 hello")), repr(sel))
125
+ check("Ctrl+A 后插入点在末尾", entry.index("insert") == len("你好世界 hello"))
126
+ finally:
127
+ root.destroy()
128
+
129
+
130
+ def main() -> int:
131
+ check_top_edge()
132
+ check_index_at()
133
+ check_ctrl_a()
134
+ if failures:
135
+ print(f"FAIL: {len(failures)} 项")
136
+ for f in failures:
137
+ print(" -", f)
138
+ return 1
139
+ print("OK: 顶边可往上拉、标题栏照样拖窗、点击定位下标正确、Ctrl+A 全选")
140
+ return 0
141
+
142
+
143
+ if __name__ == "__main__":
144
+ raise SystemExit(main())