dsh-watch-together 0.3.4 → 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,37 @@
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
+
3
35
  ## [0.3.4] - 2026-11-16
4
36
 
5
37
  > 三件都在 `examples/floating-chat/window.py`。前两条来自 see-now 那边的社区报告
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.4",
4
+ "version": "0.3.5",
5
5
  "entry": {
6
6
  "name": "dsh-watch-together",
7
7
  "inject": [
@@ -164,6 +164,13 @@ TOUCHPAD_ROW_PX = 32
164
164
  # 每滚一格都重建会让单格 45~60ms;推到停手后,滚动期间只重画气泡。
165
165
  STATIC_DEFER_MS = 200
166
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
+
167
174
  # 仅用于文档截图/CI 视觉检查:暂停抓屏并把 WDA 关掉,窗口才会出现在截图里
168
175
  PREVIEW = os.environ.get("DSH_GLASS_PREVIEW") == "1"
169
176
  # 文档截图:正常抓屏 2.5 秒后暂停并取消 WDA,保留最后一帧玻璃
@@ -454,10 +461,42 @@ def danmaku_options(cfg=None) -> dict:
454
461
 
455
462
 
456
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
+ """
457
474
  CHAT_FILE.parent.mkdir(parents=True, exist_ok=True)
458
- with open(CHAT_FILE, "a", encoding="utf-8") as f:
459
- f.write(json.dumps({"role": "user", "text": text, "at": int(time.time() * 1000)},
460
- 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
461
500
 
462
501
 
463
502
  def asr_python() -> str:
@@ -988,7 +1027,9 @@ class LiveGlass:
988
1027
  try:
989
1028
  append_user(text)
990
1029
  except Exception as exc:
991
- self.feed.status = f"写不进去:{exc}"
1030
+ # 字**不清空**:写不进去的时候,用户最需要的就是改完环境再按一次回车。
1031
+ # `append_user` 里已经试过"换掉整份文件"这条路,还失败就真是权限/占用了。
1032
+ self.feed.status = f"写不进去:{exc}(文件被占用或权限不足;关掉多余的窗再试)"
992
1033
  self._refresh_feed()
993
1034
  return "break"
994
1035
  try:
@@ -1188,24 +1229,101 @@ class LiveGlass:
1188
1229
  x, y = x0 + 84, y0 + 27
1189
1230
  maxw = max(60, x1 - x0 - 100)
1190
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
1191
1239
  if not text and not focused:
1192
1240
  self.text.draw(x, y, "在这里跟它说话…", anchor="w", fill="#8e9db2",
1193
1241
  size=11, tags=("inputtext", "inputzone"))
1194
1242
  elif text:
1195
1243
  font = self.fonts.get(11)
1196
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"))
1197
1253
  self.text.draw(x, y, shown, anchor="w", fill="#eef6ff",
1198
1254
  size=11, tags=("inputtext", "inputzone"))
1199
- if focused:
1255
+ if focused and not sel:
1200
1256
  cx = x + font.measure(shown[:max(0, caret_in)])
1201
1257
  elif focused:
1202
1258
  cx = x
1259
+ self._input_view = (x, 0, "")
1203
1260
  if cx is not None and self._caret_on:
1204
- c.create_line(cx + 1, y - 9, cx + 1, y + 9,
1205
- 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")
1206
1265
  self._schedule_caret(cx is not None)
1207
1266
  self.text.refresh()
1208
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
+
1209
1327
  def _schedule_caret(self, active: bool) -> None:
1210
1328
  """只有输入框拿着焦点时才跑闪烁定时器;失焦就停,不白烧 after。"""
1211
1329
  if self._caret_job is not None:
@@ -1238,7 +1356,7 @@ class LiveGlass:
1238
1356
  self._render_input()
1239
1357
  return None
1240
1358
 
1241
- def _focus_input(self, _e=None):
1359
+ def _focus_input(self, _e=None, keep_caret: bool = False):
1242
1360
  # noActivate 开着时先摘掉那条样式,否则 focus_force 也拿不到键盘焦点
1243
1361
  # (WS_EX_NOACTIVATE 的窗口本来就不接受焦点)。摘掉后本次运行不再加回,
1244
1362
  # 理由见 `_apply_no_activate`。
@@ -1255,7 +1373,8 @@ class LiveGlass:
1255
1373
  pass
1256
1374
  try:
1257
1375
  self._entry.focus_force()
1258
- self._entry.icursor("end")
1376
+ if not keep_caret:
1377
+ self._entry.icursor("end")
1259
1378
  except Exception:
1260
1379
  pass
1261
1380
  self._caret_on = True
@@ -1706,6 +1825,8 @@ class LiveGlass:
1706
1825
  insertwidth=0, highlightthickness=0)
1707
1826
  self._entry.bind("<KeyRelease>", self._on_input_key)
1708
1827
  self._entry.bind("<Return>", self._send)
1828
+ for seq in ("<Control-a>", "<Control-A>"):
1829
+ self._entry.bind(seq, self._input_select_all)
1709
1830
  self._entry.bind("<FocusIn>", lambda _e: self._render_input())
1710
1831
  self._entry.bind("<FocusOut>", self._on_input_blur)
1711
1832
  # 插入点还能被鼠标和选择改动,这些不发 KeyRelease:不补这几个,点一下
@@ -1759,7 +1880,6 @@ class LiveGlass:
1759
1880
  self._draw_scrollbar()
1760
1881
  self._bind_header()
1761
1882
  c.tag_bind("send", "<Button-1>", self._send)
1762
- c.tag_bind("inputzone", "<Button-1>", self._focus_input)
1763
1883
  c.tag_raise("close")
1764
1884
  c.tag_raise("send")
1765
1885
 
@@ -2301,7 +2421,7 @@ class LiveGlass:
2301
2421
  if x >= w - corner and y >= h - corner:
2302
2422
  return "se"
2303
2423
  if y <= edge:
2304
- return None # 顶部中间只拖动,不缩放
2424
+ return "n" if y <= TOP_EDGE_PX else None
2305
2425
  if x <= edge:
2306
2426
  return "w"
2307
2427
  if x >= w - edge:
@@ -2342,7 +2462,11 @@ class LiveGlass:
2342
2462
  return
2343
2463
  x0, y0, x1, y1, _r = self._geo.input_shape
2344
2464
  if x0 <= e.x <= x1 and y0 <= e.y <= y1:
2345
- 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()
2346
2470
  return
2347
2471
  mode = self._edge_at(e.x, e.y)
2348
2472
  if mode:
@@ -2356,6 +2480,9 @@ class LiveGlass:
2356
2480
  e.y_root - self.root.winfo_y())
2357
2481
 
2358
2482
  def _motion(self, e):
2483
+ if getattr(self, "_input_selecting", False):
2484
+ self._input_drag(e)
2485
+ return
2359
2486
  if self._resize:
2360
2487
  mode, sx, sy, x0, y0, w0, h0 = self._resize
2361
2488
  dx, dy = e.x_root - sx, e.y_root - sy
@@ -2393,6 +2520,9 @@ class LiveGlass:
2393
2520
  self.root.geometry(f"+{nx}+{ny}")
2394
2521
 
2395
2522
  def _release(self, e):
2523
+ if getattr(self, "_input_selecting", False):
2524
+ self._input_selecting = False
2525
+ return
2396
2526
  if self._resize:
2397
2527
  self._resize = None
2398
2528
  self._preview_at = 0.0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-watch-together",
3
- "version": "0.3.4",
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())