dsh-watch-together 0.2.0 → 0.2.2

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,3372 +1,1454 @@
1
- #!/usr/bin/env python3
2
- """floating-chat — 一个**独立悬浮**的陪看聊天窗,不需要浏览器。
3
-
4
- 为什么不用浏览器:浏览器那条路(`documentPictureInPicture`)能置顶,但要先开一个标签页;
5
- 而且它只是"把标签页搬进小窗",关掉标签页就没了。这里是真·独立进程的原生窗口。
6
-
7
- 读的是同一份 `chat.jsonl`(插件写的统一文本流:剧本台词 / 插话 / 你自己的话),
8
- 写回去的也是同一份 —— 所以浏览器那个框开着也不会冲突,两个前端看的是同一条时间线。
9
-
10
- 用法(**必须用带 tkinter 的 Python**,Windows 商店版自带):
11
-
12
- pythonw examples/floating-chat/window.py # 无控制台
13
- python examples/floating-chat/window.py # 有控制台,方便看报错
14
-
15
- 窗口:无边框圆角、置顶、按住顶部拖动、右下角可拉伸;回车发送;Esc 关闭。
16
- 「麦」按钮:开实时语音输入(说的每句话自动转成文字,写进同一条流)。
17
-
18
- 依赖:标准库 tkinter(不装任何第三方包)。
19
- 「麦」会另起 `mic.py` 进程,那条路需要 sounddevice+numpy+sherpa-onnx,
20
- 所以用 **ASR 的 venv**(可用 `DSH_ASR_PYTHON` 指定)来跑,跟本窗口的解释器无关。
21
-
22
- ## 2026-10-31 重做
23
-
24
- 用户的原话是"这个悬浮窗太丑了"。四件事一起改:
25
-
26
- 1. **DPI 感知**:不声明 DPI 的 Tk 窗口在高分屏上被系统整块拉伸(125%/150%),
27
- 字和线条全是虚的 —— 这是"丑"最大的一个来源。现在先 `SetProcessDpiAwareness(2)`
28
- 再建窗口,尺寸/字号按真实 DPI 缩放。
29
- 2. **真·气泡**:以前是往一个 Text 里塞带背景色的行,整段满宽、右对齐时像一条色带。
30
- 现在每条消息是一块**圆角气泡**(Canvas 画底 + Label 排版),宽度贴着内容:
31
- 我说话靠右、台词带一条竖线、系统提示是一行灰字。
32
- 3. **不再整份重读**:以前每 200ms 把 chat.jsonl 全解析一遍,两小时一场几千条会越来越慢。
33
- 现在只读上次之后新追加的字节(和 `src/chat-store.js` 的 watcher 同一套思路),
34
- 开场只回放最后 60 条。
35
- 4. **不抢焦点、不抢滚动**:以前窗口一开就把系统焦点从浏览器抢走(敲空格想暂停,
36
- 结果打进了聊天框);现在只在窗口内部指定焦点。往上翻历史时,新台词也不把你拽回底部。
37
- """
38
-
39
- import json
40
- import math
41
- import queue
42
- import os
43
- import subprocess
44
- import sys
45
- import threading
46
- import time
47
-
48
- try:
49
- import tkinter as tk
50
- except Exception as exc: # pragma: no cover - 环境问题,直接说清楚
51
- sys.stderr.write(
52
- "这个 Python 没有 tkinter,换一个。\n"
53
- " Windows 商店版 Python 自带;也可以用 python.org 的官方安装包(勾选 tcl/tk)。\n"
54
- f" 当前解释器:{sys.executable}\n 错误:{exc}\n"
55
- )
56
- raise SystemExit(2)
57
-
58
- # ---------------------------------------------------------------- 真模糊(可选依赖)
59
- #
60
- # ## 为什么需要 Pillow
61
- #
62
- # tkinter 的控件**必须填不透明底色**,所以窗口级模糊(Win11 亚克力 / Mica /
63
- # CSS backdrop-filter)都会被控件整块挡住 —— 换语言也一样,问题在渲染层不在语言。
64
- #
65
- # 唯一能在 tkinter 上做出**真毛玻璃**的办法:把窗口背后的桌面截下来、高斯模糊、
66
- # 当成底板贴进窗口。背后内容真的被糊掉了,不是模拟。
67
- #
68
- # 实测成本(本机 2560×1600 / 150% 缩放):区域截屏 44ms + 裁剪缩放模糊放大 8ms。
69
- # 所以只在**开窗**和**移动/缩放结束时**各截一次,平时零开销 —— 底板糊成色块以后,
70
- # 背后视频怎么变都看不出来,没必要持续刷新。
71
- #
72
- # Pillow 没装就自动回退到原来的纯色玻璃(`HAVE_PIL = False`),绝不因此起不来。
73
- try:
74
- from PIL import Image, ImageChops, ImageDraw, ImageEnhance, ImageFilter, ImageGrab, ImageStat
75
- try:
76
- from PIL import ImageTk
77
- HAVE_PIL = True
78
- except Exception: # 没有 tkinter 支持的 Pillow(少见)
79
- HAVE_PIL = False
80
- except Exception: # 压根没装 Pillow
81
- HAVE_PIL = False
82
-
83
- # **mss 是可选的**:同样整屏抓取,它 38ms、ImageGrab 71ms(本机 2560×1600 / 150% 缩放实测),
84
- # 装了就自动用;没装就退回 ImageGrab,行为不变。它给的是**物理分辨率**,
85
- # 而 `_grab_backdrop` 用 `small.size / (sw, sh)` 算比例,DPI 缩放会自动被吸收。
86
- try:
87
- import mss as _mss
88
- HAVE_MSS = True
89
- except Exception:
90
- _mss = None
91
- HAVE_MSS = False
92
-
93
- # ---------------------------------------------------------------- 配色
94
- #
95
- # ## 2026-11-01 二版:真正的液态玻璃(Apple Liquid Glass)
96
- #
97
- # 一版被用户判为"太丑了"。复盘下来不是圆角不够大,是四件事同时错了:
98
- #
99
- # ① **整体发蓝**。一版的玻璃底色是 `#171a21`(蓝灰)。玻璃的颜色应该**全部来自背后
100
- # 的画面**,一旦自己带色相,背后再怎么鲜艳都要先跟这层蓝打架 —— 出来就是"脏"。
101
- # 二版底色改成中性黑 (10,11,13),只做明度,不碰色相。
102
- # ② **斜纹**。一版的高光是用 `create_line` 一条条斜线堆出来的,步进 3px、线宽 3px,
103
- # 在暗底上直接长出一片"麻布纹",是截图里最刺眼的瑕疵。二版所有渐变都在 16×16 上
104
- # 算完再双三次放大,天然平滑。
105
- # ③ **气泡是实心色块**。一版气泡填死色 `#3a4459`,等于在玻璃上贴了张不透明卡纸,
106
- # 背后画面一到气泡就断。二版气泡是**从同一张底板裁出来的真玻璃**(见 `plate()`),
107
- # 只是额外加一层白/蓝 wash —— 它透出来的就是身后的画面,只是更亮一点。
108
- # ④ **标题栏和输入栏是不透明条**。一版靠 `tk.Frame` 摆控件,而 Tk 的 Frame 必须填
109
- # 不透明白底,直接把玻璃盖成一块死黑。二版把标题栏和输入栏**全部画在 Canvas 上**,
110
- # 只留 `Entry` 一个真控件(它必须实心,正好塞进"内凹槽"里)。
111
- #
112
- # 三条硬指标(照着 HIG 做的,不是凭感觉调色):
113
- # • **自适应压暗**:先量这块底板的平均亮度 L,再反解"要压到 L'≤84 需要多少不透明度"
114
- # —— `a = (L-84)/(L-12)`,夹在 0.34~0.74。背后是白网页时自动加深、是暗场景时保持
115
- # 通透。这是白字在任何画面上都读得清的前提,也是 HIG 说的 adaptive self-tinting。
116
- # • **一条真的边**:1px 超椭圆环,亮度从左上 92% 衰减到右下 14%,再叠一道内侧底部
117
- # 暗线。苹果的玻璃"有厚度"全靠这两条;四条直 chord 画不出圆角,一眼假。
118
- # • **镜片感**:底板先放大再按边缘权重盖回去(`refract`),边缘会被"掰"进去一点,
119
- # 加上通道错位(`chromatic`),才有了隔着一层玻璃看东西的物理线索。
120
-
121
- BG = GLASS_FILL = "#0b0c0e"
122
- BORDER = "#22252b"
123
- TEXT = "#f2f3f5"
124
- MUTED = "#9aa2af"
125
- TIME_FG = "#8c94a1" # 时间戳:比正文暗、但要在模糊背景上读得出来
126
- DIM = "#6e7683"
127
- ACCENT = "#0a84ff" # iOS 深色模式系统蓝
128
- ACCENT_HI = "#4ca6ff"
129
- DANGER = "#ff453a"
130
- KEY = "#010203" # 圆角抠图用的透明键色(只给根窗口和画布用)
131
-
132
- INK = (10, 11, 13) # 玻璃本体(中性;色相交给背后的画面)
133
- WHITE = (255, 255, 255)
134
- ACCENT_RGB = (10, 132, 255)
135
-
136
- HEAD_BG = "#0b0c0e" # 兜底色(拿不到截图、走纯色回退时用)
137
- FIELD_BG = "#15171c" # 输入槽:Entry 只能是不透明平色,这里做成"内凹"的深一档
138
-
139
- # 圆角:苹果的同心半径 —— 外面 26、悬浮条 20、气泡 16(都小于 1/2 高,不进胶囊区)
140
- PANEL_R = 26
141
- SLAB_R = 20
142
- BUBBLE_R = 16
143
- # 窗口最小宽度(逻辑像素,未乘 DPI)。**不能比这个再窄**:中文正文一行
144
- # 只放得下 9 个字,一段 100 字的台词会撑成 15 行、比视口还高,排版直接崩。
145
- MIN_W = 460
146
-
147
- # 角色 → (玻璃类型, 文字色, 竖线色 或 None, 抬头)
148
- #
149
- # **`line` 和 `assistant` 必须完全相同**(2026-11-01 用户要求):以前台词是暖黄、陪看是冷灰,
150
- # 一条流里两种配色,读起来像两个人在说话。现在只有"它说的"和"我说的"两种。
151
- ROLE = {
152
- "line": ("bubble", TEXT, None, ""),
153
- "assistant": ("bubble", TEXT, None, ""),
154
- "user": ("me", "#eaf2ff", None, ""),
155
- }
156
-
157
- SS = 96.0 # 基准 dpi
158
-
159
-
160
- # ---------------------------------------------------------------- 数据
161
-
162
- def cache_dir():
163
- d = os.environ.get("DSH_VIDEO_CACHE_DIR")
164
- if d:
165
- return d
166
- local = os.environ.get("LOCALAPPDATA")
167
- if os.name == "nt" and local:
168
- return os.path.join(local, "dsh-video-storyboard", "cache")
169
- return os.path.join(os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache"),
170
- "dsh-video-storyboard")
171
-
172
-
173
- CHAT_FILE = os.path.join(cache_dir(), "chat.jsonl")
174
-
175
- HERE = os.path.dirname(os.path.abspath(__file__))
176
- MIC_SCRIPT = os.path.join(HERE, "mic.py")
177
- CONFIG = os.path.join(os.environ.get("DSH_HOME") or os.path.expanduser("~/.dsh"),
178
- "watch-window.json")
179
-
180
-
181
- def read_config():
182
- try:
183
- with open(CONFIG, "r", encoding="utf-8") as f:
184
- return json.load(f) or {}
185
- except Exception:
186
- return {}
187
-
188
-
189
- def write_config(patch):
190
- """合进 ~/.dsh/watch-window.json(插件那边也读它,所以只加键、不覆盖)"""
191
- cfg = read_config()
192
- cfg.update(patch or {})
193
- try:
194
- os.makedirs(os.path.dirname(CONFIG), exist_ok=True)
195
- tmp = CONFIG + ".tmp"
196
- with open(tmp, "w", encoding="utf-8") as f:
197
- json.dump(cfg, f, ensure_ascii=False, indent=2)
198
- os.replace(tmp, CONFIG)
199
- except Exception:
200
- pass
201
-
202
-
203
- def asr_python():
204
- """跑 mic.py 的解释器:要有 numpy/sounddevice/sherpa-onnx,本机就是 ASR 的 venv。
205
-
206
- 为什么不能直接用本窗口这个解释器:悬浮窗必须用**带 tkinter** 的那个
207
- (商店版 Python),而它多半没有 numpy —— 两边不是同一个 Python。
208
- """
209
- for cand in (os.environ.get("DSH_ASR_PYTHON"),
210
- r"D:/asr-local/.venv/Scripts/python.exe",
211
- os.path.join(HERE, "..", "..", "..", "asr-local", ".venv", "Scripts", "python.exe")):
212
- if cand and os.path.exists(cand):
213
- return os.path.abspath(cand)
214
- return sys.executable # 兜底:缺依赖时 mic.py 自己会打印清楚缺什么
215
-
216
-
217
- def append_user(text):
218
- os.makedirs(os.path.dirname(CHAT_FILE), exist_ok=True)
219
- with open(CHAT_FILE, "a", encoding="utf-8") as f:
220
- f.write(json.dumps({"role": "user", "text": text, "at": int(time.time() * 1000)},
221
- ensure_ascii=False) + "\n")
222
-
223
-
224
- def mmss(t):
225
- """播放秒 → mm:ss.d(按**视频位置**显示台词时间)。
226
-
227
- **当前没有调用方**:时间戳已统一成墙钟(见 `_render`)。留着是因为
228
- "按播放位置显示"是一个随时可能被要回去的选项,删了还得再写一遍。
229
- """
230
- try:
231
- s = max(0.0, float(t))
232
- except (TypeError, ValueError):
233
- return ""
234
- return f"{int(s // 60):02d}:{s % 60:04.1f}"
235
-
236
-
237
- def clock(ms):
238
- """墙钟毫秒 → HH:MM:SS(这句话是什么时候说出来的)。
239
-
240
- **带秒**:陪看里一段是 2–5 分钟,同一段里可能连着好几条,只到分钟的话
241
- 一屏全是同一个 `03:36`,时间戳就失去区分作用了。
242
- """
243
- try:
244
- return time.strftime("%H:%M:%S", time.localtime(float(ms) / 1000.0))
245
- except (TypeError, ValueError, OSError):
246
- return ""
247
-
248
-
249
- # ---------------------------------------------------------------- 绘制
250
-
251
- def dpi_aware():
252
- """先声明 DPI 感知,再建任何窗口。不声明的话 Windows 会把整窗当 96dpi 位图拉伸。"""
253
- if os.name != "nt":
254
- return
255
- try:
256
- import ctypes
257
- try:
258
- ctypes.windll.shcore.SetProcessDpiAwareness(2) # per-monitor v2
259
- except Exception:
260
- ctypes.windll.user32.SetProcessDPIAware()
261
- except Exception:
262
- pass
263
-
264
-
265
- def round_rect(cv, x1, y1, x2, y2, r, n=2.2, **kw):
266
- """Canvas 画圆角矩形。
267
-
268
- **不用 `smooth=True` 的多边形**:smooth 是把折线的角"抹圆",实际半径明显小于设定值
269
- (要 22 出来只有 14),做液态玻璃时圆角是主角,量不准就全歪。这里直接按四个角
270
- 采样圆弧(每角 12 段),`smooth=False` 拼接 —— 半径是多少就是多少。
271
-
272
- `n` 走和 `squircle_mask` 同一个超椭圆(2.2 = 比正圆饱满一点点)。**一版这里是 5**,
273
- 指数 2/n=0.4 会把角"撑"到矩形的对角线上,画出来的胶囊两端几乎是方的 ——
274
- 输入框看着"没有圆角"就是这个原因。
275
- """
276
- r = max(0, min(r, (x2 - x1) / 2, (y2 - y1) / 2))
277
- if r <= 0.5:
278
- return cv.create_rectangle(x1, y1, x2, y2, **kw)
279
- pts = []
280
- for cx, cy, a0 in ((x2 - r, y1 + r, -90), (x2 - r, y2 - r, 0),
281
- (x1 + r, y2 - r, 90), (x1 + r, y1 + r, 180)):
282
- for i in range(13):
283
- a = math.radians(a0 + i * (90.0 / 12))
284
- ca, sa = math.cos(a), math.sin(a)
285
- dx = r * (abs(ca) ** (2.0 / n)) * (1 if ca >= 0 else -1)
286
- dy = r * (abs(sa) ** (2.0 / n)) * (1 if sa >= 0 else -1)
287
- pts.extend([cx + dx, cy + dy])
288
- return cv.create_polygon(pts, smooth=False, **kw)
289
-
290
-
291
- def text_on_glass(cv, x, y, text, *, font, fill, tags, anchor="nw",
292
- width=None, offset=1, shadow="#05070a", **kw):
293
- """**带影子的文字**:先画一个右下偏移的深色副本,再画正文。
294
-
295
- 为什么要影子:玻璃变清晰以后,背后的字会透上来和正文打架(1/8 底板那会儿糊成
296
- 一片反而干净)。真玻璃上的字都有这层 —— 它不挑背景明暗,白字压在亮处也立得住。
297
- 取自 PR #15 的 `_add_text_shadows()`,但那边是**逐字**建 item(每个字一个 canvas
298
- 对象),我们这里整段一个影子:item 数不翻倍,滚动列表时才不会卡。
299
- """
300
- if shadow:
301
- cv.create_text(x + offset, y + offset, text=text, font=font,
302
- fill=shadow, anchor=anchor, width=width, tags=tags, **kw)
303
- return cv.create_text(x, y, text=text, font=font, fill=fill,
304
- anchor=anchor, width=width, tags=tags, **kw)
305
-
306
-
307
- def _mix(c1, c2, t):
308
- """两个 #rrggbb 之间取 t(0→c1,1→c2)。用来做渐变和高光。"""
309
- t = 0.0 if t < 0 else (1.0 if t > 1 else t)
310
- a = [int(c1[i:i + 2], 16) for i in (1, 3, 5)]
311
- b = [int(c2[i:i + 2], 16) for i in (1, 3, 5)]
312
- return "#%02x%02x%02x" % tuple(int(round(a[k] + (b[k] - a[k]) * t)) for k in range(3))
313
-
314
-
315
- def squircle_mask(size, radius, n=2.2, ss=2):
316
- """生成**超椭圆圆角**遮罩(苹果的连续曲率圆角)。
317
-
318
- ## 为什么不是 `rounded_rectangle`
319
- 普通圆角矩形是"直边 + 四分之一圆"。直线曲率 0、圆弧曲率 1/r,两者接缝处
320
- 曲率**突然跳变**(G1 断点)—— 眼睛能看出那道"棱"。超椭圆把曲率从直边的 0
321
- 连续长到角上的峰值(G2),过渡是"化"开的。
322
-
323
- ## n 的取值
324
- `|x/r|^n + |y/r|^n = 1`。n=2 是正圆(= CSS 的 border-radius),n 越大角越"方"。
325
- **一版取了 5,结果四个角几乎就是直角**(n=5 时 y 到半径一半,向内只收 0.6%),
326
- 远处看就是一块板子 —— 这是"太丑"里最隐蔽的一条。2.2 比正圆饱满一点点。
327
-
328
- ## 为什么按行扫、为什么用 BOX 缩小
329
- 逐像素判内外是 O(w·h) 次幂运算;超椭圆可以解出每行的左右边界,一行一条横线,
330
- 复杂度 O(h)。2 倍超采样之后按 2×2 取平均(`Image.BOX`)—— 和 LANCZOS 在"整数倍
331
- 缩小"上结果几乎一致,但快 4 倍(面板遮罩 15ms → 4ms)。
332
- """
333
- w, h = max(1, int(size[0])), max(1, int(size[1]))
334
- if w < 3 or h < 3:
335
- return Image.new("L", (w, h), 255)
336
- ss = max(1, int(ss))
337
- W, H = w * ss, h * ss
338
- r = max(0.5, min(float(radius) * ss, W / 2.0, H / 2.0))
339
- m = Image.new("L", (W, H), 0)
340
- d = ImageDraw.Draw(m)
341
- for y in range(H):
342
- dy = min(y, H - 1 - y)
343
- if dy >= r:
344
- x = 0.0
345
- else:
346
- t = 1.0 - dy / r
347
- x = r * (1.0 - (1.0 - t ** n) ** (1.0 / n))
348
- d.line([(x, y), (W - 1 - x, y)], fill=255)
349
- if ss > 1:
350
- m = m.resize((w, h), Image.BOX)
351
- return m
352
-
353
-
354
- def _row_edge(y, o, H, R, n=2.2):
355
- """超椭圆在**第 y 行**、整体内缩 `o` 之后的左边界(右边界对称)。
356
-
357
- 内缩后的形状是"同样的超椭圆缩小 o、角半径也小 o",它在 y 方向只覆盖
358
- `[o, H-o)`;这一行落在外面时返回 None(那说明整行都在环里)。
359
- """
360
- yy = y - o
361
- span = H - 2 * o
362
- if span <= 0 or yy < 0 or yy > span - 1:
363
- return None
364
- rr = R - o
365
- if rr <= 0.5:
366
- return o
367
- dd = min(yy, span - 1 - yy)
368
- if dd >= rr:
369
- return o
370
- t = 1.0 - dd / rr
371
- return o + rr * (1.0 - (1.0 - t ** n) ** (1.0 / n))
372
-
373
-
374
- def _ring(w, h, radius, inset=0.0, width=1.4, ss=2):
375
- """贴轮廓的等宽环:距外沿 `inset` 起、宽 `width`,一遍扫完,不建中间图。
376
-
377
- ⚠️ 这里踩过一个很隐蔽的坑:第一版只解了"外沿"和"内沿(内缩 inset)"两条边界,
378
- **`width` 根本没参与计算** —— 结果画出来的是"从边上到 inset 的一条带",`inset=0`
379
- 时宽度为零(白边整条消失),`inset=2` 时变成外侧 2px 的带(内侧暗线跑到边上去,
380
- 把白边压暗)。表现就是"玻璃没边、看着发灰"。现在按 inset 和 inset+width 两条
381
- 真边界算,中间那段才是环。
382
-
383
- 以前(0.1.0)是"两个填充遮罩相减":每块玻璃 5~6 个环,每个环建两张 w×h 的 L 图
384
- 再相减,665×594 的面板单这一项 ~100ms。现在每行两根短线,O(h),快 25 倍。
385
- """
386
- w, h = max(4, int(w)), max(4, int(h))
387
- ss = max(1, int(ss))
388
- W, H = w * ss, h * ss
389
- R = max(0.5, min(float(radius) * ss, W / 2.0, H / 2.0))
390
- o1 = max(0.0, float(inset) * ss)
391
- o2 = o1 + max(0.6, float(width) * ss)
392
- m = Image.new("L", (W, H), 0)
393
- d = ImageDraw.Draw(m)
394
- for y in range(H):
395
- xa = _row_edge(y, o1, H, R)
396
- if xa is None:
397
- continue # 整行在环的垂直范围之外(不会发生,兜底)
398
- lo_l, lo_r = xa, W - 1 - xa
399
- xb = _row_edge(y, o2, H, R)
400
- if xb is None: # 内沿还没开始 → 这一行整段都是环(顶/底带)
401
- d.line([(lo_l, y), (lo_r, y)], fill=255)
402
- continue
403
- hi_l, hi_r = xb, W - 1 - xb
404
- if hi_l > lo_l:
405
- d.line([(lo_l, y), (hi_l, y)], fill=255)
406
- if lo_r > hi_r:
407
- d.line([(hi_r, y), (lo_r, y)], fill=255)
408
- if ss > 1:
409
- m = m.resize((w, h), Image.BOX)
410
- return m
411
-
412
-
413
- def _ramp(size, wx=0.42, wy=0.90, lo=0.0, hi=1.0, gamma=1.0):
414
- """线性渐变(L 图):`(wx, wy)` 是"最亮的方向",默认左上最亮。
415
-
416
- **在 16×16 上算再双三次放大**。直接按像素画渐变的边(就是把线一条条叠起来)
417
- 会在暗底上留下规则的斜纹 —— 一版那片"麻布"就是这么来的。
418
- """
419
- w, h = max(1, int(size[0])), max(1, int(size[1]))
420
- n = 16
421
- raw = [[0.0] * n for _ in range(n)]
422
- lo_v = hi_v = None
423
- for j in range(n):
424
- for i in range(n):
425
- u = (i + 0.5) / n * 2.0 - 1.0
426
- v = (j + 0.5) / n * 2.0 - 1.0
427
- t = -(wx * u + wy * v) # 左上最大
428
- raw[j][i] = t
429
- lo_v = t if lo_v is None else min(lo_v, t)
430
- hi_v = t if hi_v is None else max(hi_v, t)
431
- small = Image.new("L", (n, n), 0)
432
- px = small.load()
433
- span = max(1e-6, hi_v - lo_v)
434
- for j in range(n):
435
- for i in range(n):
436
- t = (raw[j][i] - lo_v) / span
437
- t = lo + (hi - lo) * (t ** gamma)
438
- px[i, j] = int(round(255 * _clamp(t, 0.0, 1.0)))
439
- return small.resize((w, h), Image.BICUBIC)
440
-
441
-
442
- def _clamp(v, lo, hi):
443
- return lo if v < lo else (hi if v > hi else v)
444
-
445
-
446
- def _scale_channel(ch, k, size):
447
- """把单个通道按比例 k 缩放后居中裁回原尺寸(k>1 放大、k<1 缩小)"""
448
- w, h = size
449
- nw, nh = max(1, int(round(w * k))), max(1, int(round(h * k)))
450
- z = ch.resize((nw, nh), Image.BICUBIC)
451
- left, top = (nw - w) // 2, (nh - h) // 2
452
- return z.crop((left, top, left + w, top + h))
453
-
454
-
455
- def chromatic(img, strength):
456
- """**色散(chromatic aberration)**:三个颜色通道各自缩放一点点。
457
-
458
- 真实玻璃对不同波长折射率不同(红光 n=1.5143 / 蓝光 1.5224,差 1%),
459
- 越靠边偏移越大,于是高对比边缘会渗出红蓝彩边 —— 这是"隔着玻璃看"
460
- 最难伪造、也最容易被眼睛认出来的线索。
461
-
462
- 物理上 1% 在 UI 尺度根本看不见,所以要放大约 8 倍(`strength` 就是那个倍数)。
463
- 只做整体缩放、不做逐像素位移:在模糊图上够了,且 CPU 成本可以忽略。
464
- """
465
- if strength <= 0:
466
- return img
467
- try:
468
- w, h = img.size
469
- r, g, b, a = img.split()
470
- d = strength * 0.004 # 1% 的物理差异 × 放大倍数
471
- r = _scale_channel(r, 1.0 - d, (w, h)) # 红:略放大(往里收)
472
- b = _scale_channel(b, 1.0 + d, (w, h)) # 蓝:略缩小(往外散)
473
- return Image.merge("RGBA", (r, g, b, a))
474
- except Exception:
475
- return img
476
-
477
-
478
- def refract(img, bevel_px, amount=0.76):
479
- """**边缘折射**:沿圆角矩形的 SDF 法线**向外采样**,把框外的画面折进边缘一带。
480
-
481
- 这是从 PR #15 换掉原来那套的结果。原来那套是"整图放大一点、再按边缘权重把放大版
482
- 盖回原图" —— 边缘显示的是**自己靠中心的内容被放大**,像贴了层凸透镜贴纸;真玻璃
483
- 不是这样:边上那一窄条里塞的是**框外**的场景,被压扁了折进来。
484
-
485
- 做法(和 #15 同源,参数按我们的 1/8 底板换算):
486
- · 圆角矩形的 signed distance field(SDF),梯度就是指向外的法线;
487
- · `t = clamp(1 - d/band)`,`mag = amp * t²` —— 贴边位移最大,往内二阶衰减到 0;
488
- · 采样坐标沿法线**向外**偏 `mag`,于是边缘取到的是框外的像素。
489
-
490
- 没有 numpy 就退回原来那套(`_refract_legacy`):numpy 只是让这件事便宜,
491
- 不该为了一个视觉效果把整个窗口变成装不上 numpy 就跑不起来。
492
- """
493
- if bevel_px < 2:
494
- return img
495
- try:
496
- import numpy as np
497
- except Exception:
498
- return _refract_legacy(img, bevel_px, amount)
499
- try:
500
- w, h = img.size
501
- band = max(2.0, float(bevel_px) * 1.6) # 折射带宽度
502
- amp = max(1.0, float(bevel_px) * 0.8 * amount) # 贴边处的最大位移
503
- # 小图上再缩就没内容可取了,所以 1/8 底板直接原尺寸算
504
- f = 1 if min(w, h) < 160 else 2
505
- hw, hh = max(4, w // f), max(4, h // f)
506
- yy, xx = np.mgrid[0:hh, 0:hw].astype(np.float32)
507
- r = max(1.0, min(hw, hh) * 0.14) # 圆角半径按尺寸估(底板不带半径)
508
- cx, cy = hw / 2.0, hh / 2.0
509
- qx = np.abs(xx - cx) - (cx - r)
510
- qy = np.abs(yy - cy) - (cy - r)
511
- sdf = (np.hypot(np.maximum(qx, 0.0), np.maximum(qy, 0.0))
512
- + np.minimum(np.maximum(qx, qy), 0.0) - r)
513
- gy, gx = np.gradient(sdf)
514
- nrm = np.maximum(np.hypot(gx, gy), 1e-6)
515
- d = -sdf # 到边的距离(内部为正)
516
- t = np.clip(1.0 - d / (band / f), 0.0, 1.0)
517
- mag = (amp / f) * t * t
518
- sx = np.rint(xx + gx / nrm * mag).astype(np.int32)
519
- sy = np.rint(yy + gy / nrm * mag).astype(np.int32)
520
- np.clip(sx, 0, hw - 1, out=sx)
521
- np.clip(sy, 0, hh - 1, out=sy)
522
- small = img if f == 1 else img.resize((hw, hh), Image.BILINEAR)
523
- arr = np.asarray(small.convert("RGB"))
524
- out = Image.fromarray(arr[sy, sx])
525
- if f != 1:
526
- out = out.resize((w, h), Image.BILINEAR)
527
- return out.convert(img.mode)
528
- except Exception:
529
- return _refract_legacy(img, bevel_px, amount)
530
-
531
-
532
- def _refract_legacy(img, bevel_px, amount=0.76):
533
- """老的"整体放大再按边缘权重盖回"。没有 numpy 时的兜底。"""
534
- try:
535
- w, h = img.size
536
- k = 1.0 + (amount * bevel_px / max(w, h)) * 2.0
537
- big = img.resize((max(1, int(w * k)), max(1, int(h * k))), Image.BICUBIC)
538
- bw, bh = big.size
539
- big = big.crop(((bw - w) // 2, (bh - h) // 2,
540
- (bw - w) // 2 + w, (bh - h) // 2 + h))
541
- f = 4 if min(w, h) >= 160 else 2
542
- ew, eh = max(8, w // f), max(8, h // f)
543
- edge = Image.new("L", (ew, eh), 0)
544
- ed = ImageDraw.Draw(edge)
545
- steps = max(2, int(bevel_px / f))
546
- for i in range(steps):
547
- v = int(255 * (1.0 - i / float(steps)) ** 1.6)
548
- ed.rectangle([i, i, ew - 1 - i, eh - 1 - i], outline=v, width=1)
549
- edge = edge.resize((w, h), Image.BILINEAR)
550
- return Image.composite(big, img, edge)
551
- except Exception:
552
- return img
553
-
554
-
555
- def _edge_weight(w, h, radius, band):
556
- """贴边一圈的权重(L 图):边上 255、往里 band 像素衰减到 0。
557
-
558
- **在 1/4 尺寸上算再放大**:这是个光滑的软边,缩上去看不出差别,但高斯模糊的成本
559
- 直接降到 1/16(面板那一块从 40ms 掉到 3ms)。
560
- """
561
- f = 4 if min(w, h) >= 160 else (2 if min(w, h) >= 80 else 1)
562
- sw, sh = max(8, w // f), max(8, h // f)
563
- m = _ring(sw, sh, max(1.0, radius / f), 0, max(1.0, band / f), ss=1)
564
- m = m.filter(ImageFilter.GaussianBlur(max(0.8, band / f * 0.45)))
565
- return m.resize((w, h), Image.BILINEAR) if f > 1 else m
566
-
567
-
568
- def _corner_weight(w, h, radius, spread=1.4, base=0.82):
569
- """色散的强度权重:**整圈倒角都有,四个角再强一档**。
570
-
571
- 物理依据:这块板的边缘不是刀口,是一条**圆倒角(fillet)**——从正面看是"四条直边
572
- 加四个圆角",但从侧面看,整圈都是同一个半径的圆弧。光从那圈弧上出去时每一处都会
573
- 偏折、都会分光,所以彩边应该是**绕一圈**的;四个角是"两个方向同时在弯"(复合曲率),
574
- 偏折更狠,彩边也就更明显。
575
-
576
- 所以这里不是"只给角",而是:底座 0.82 铺满(靠 `_ring` 自己限制在边上),
577
- 角上四个团叠到 1.0。一版我按"只有角才有曲率"写成角独占,那是把倒角当成刀口了。
578
- """
579
- # 同样是"光滑的团",在 1/4 尺寸上算再放大(成本 1/16)
580
- f = 4 if min(w, h) >= 160 else (2 if min(w, h) >= 80 else 1)
581
- sw, sh = max(8, w // f), max(8, h // f)
582
- m = Image.new("L", (sw, sh), int(255 * base))
583
- d = ImageDraw.Draw(m)
584
- r = max(1.5, float(radius) / f)
585
- rad = r * spread
586
- for cx, cy in ((r, r), (sw - r, r), (r, sh - r), (sw - r, sh - r)):
587
- d.ellipse([cx - rad, cy - rad, cx + rad, cy + rad], fill=255)
588
- m = m.filter(ImageFilter.GaussianBlur(max(0.8, r * 0.55)))
589
- return m.resize((w, h), Image.BILINEAR) if f > 1 else m
590
-
591
-
592
- def chroma_edge(img, radius, amount, bend=None):
593
- """**边缘色散**:只在玻璃的边上把红/蓝通道各缩放一点点。
594
-
595
- 真实玻璃对不同波长折射率不同(n_红 1.5143 / n_蓝 1.5224),隔着它看东西,越靠边
596
- 色差越大,于是高对比的边界会渗出橙/青彩边 —— 这是"隔着玻璃"最难伪造、也最容易
597
- 被眼睛认出来的线索。整图做没意义(中间位移为 0 才符合物理),所以用**同心缩放**
598
- 当位移:红通道放大、蓝通道缩小,中心不动、越靠边偏得越多,再按 `_edge_weight`
599
- 只保留边框那一圈。成本是 2 次通道 resize,比逐像素位移便宜一个量级。
600
- """
601
- if amount <= 0.05:
602
- return img
603
- try:
604
- w, h = img.size
605
- r, g, b, a = img.split()
606
- k = amount / float(max(w, h))
607
- r2 = _scale_channel(r, 1.0 + k, (w, h))
608
- b2 = _scale_channel(b, 1.0 - k, (w, h))
609
- edge = _edge_weight(w, h, radius, max(6.0, amount * 6.0))
610
- if bend is not None:
611
- edge = ImageChops.multiply(edge, bend)
612
- r = Image.composite(r2, r, edge)
613
- b = Image.composite(b2, b, edge)
614
- return Image.merge("RGBA", (r, g, b, a))
615
- except Exception:
616
- return img
617
-
618
-
619
- _MASKS = {}
620
-
621
-
622
- def _cached_mask(w, h, radius):
623
- """超椭圆遮罩(按尺寸缓存)。同一尺寸在整窗重绘里会被反复用到,算一次就够。"""
624
- key = (int(w), int(h), int(round(radius * 8)))
625
- hit = _MASKS.get(key)
626
- if hit is not None:
627
- return hit
628
- m = squircle_mask((w, h), radius)
629
- if len(_MASKS) > 12:
630
- _MASKS.clear()
631
- _MASKS[key] = m
632
- return m
633
-
634
-
635
- _OVERLAYS = {}
636
-
637
-
638
- def _light_overlay(sw, sh, radius, sk):
639
- """玻璃"光"的那一层:斜向光泽 + 边光 + 内侧暗线 + 暖冷彩边,**与底板无关**。
640
-
641
- 按 (尺寸, 圆角, 线宽) 缓存。合成顺序必须和以前逐层叠加时一模一样:
642
- 光泽 → 边光(rim ∪ soft)→ 底部暗线 → 冷边 → 暖边(暖最后,压在最外圈)。
643
- """
644
- key = (int(sw), int(sh), int(radius * 8), int(sk * 50))
645
- hit = _OVERLAYS.get(key)
646
- if hit is not None:
647
- return hit
648
- ov = Image.new("RGBA", (sw, sh), (0, 0, 0, 0))
649
- try:
650
- # ③ 表面光泽:135° 斜向白光,左上最亮往右下散掉
651
- sheen = _ramp((sw, sh), 0.46, 0.92, 0.0, 1.0,
652
- gamma=2.3).point(lambda v: int(v * 0.11))
653
- glow = Image.new("RGBA", (sw, sh), WHITE + (0,))
654
- glow.putalpha(sheen)
655
- ov = Image.alpha_composite(ov, glow)
656
-
657
- # ④ 边:上左亮 → 下右暗的一条等宽带 + 内侧自然衰减 + 底部暗线
658
- w1 = max(1.2, 1.5 * sk)
659
- rim = ImageChops.multiply(_ring(sw, sh, radius, 0, w1),
660
- _ramp((sw, sh), 0.26, 1.0, 0.18, 1.0, gamma=0.75))
661
- soft = ImageChops.multiply(_ring(sw, sh, radius, w1, max(1.6, 2.6 * sk)),
662
- _ramp((sw, sh), 0.26, 1.0, 0.0, 0.24))
663
- glow = Image.new("RGBA", (sw, sh), WHITE + (0,))
664
- glow.putalpha(ImageChops.lighter(rim, soft))
665
- ov = Image.alpha_composite(ov, glow)
666
-
667
- shade = ImageChops.multiply(_ring(sw, sh, radius, w1, max(1.6, 2.0 * sk)),
668
- _ramp((sw, sh), -0.25, -1.0, 0.0, 0.5))
669
- dark = Image.new("RGBA", (sw, sh), (0, 0, 0, 0))
670
- dark.putalpha(shade)
671
- ov = Image.alpha_composite(ov, dark)
672
-
673
- # ⑤ 色散:整圈倒角都分光,四角复合曲率更强;**暖外冷内**(红偏折少)
674
- bend = _corner_weight(sw, sh, radius, 1.4)
675
- d1 = max(1.0, 1.2 * sk)
676
- sharp = ImageFilter.GaussianBlur(0.9) # 硬环会看成"描边",糊半像素才像光
677
- cool_m = ImageChops.multiply(_ring(sw, sh, radius, d1 * 1.1, d1 * 1.6).filter(sharp),
678
- _ramp((sw, sh), 0.26, 1.0, 0.0, 0.45))
679
- cool = Image.new("RGBA", (sw, sh), (150, 196, 255, 0))
680
- cool.putalpha(ImageChops.multiply(cool_m, bend))
681
- ov = Image.alpha_composite(ov, cool)
682
-
683
- warm_m = ImageChops.multiply(_ring(sw, sh, radius, 0, d1).filter(sharp),
684
- _ramp((sw, sh), 0.26, 1.0, 0.0, 0.85))
685
- warm = Image.new("RGBA", (sw, sh), (255, 178, 100, 0))
686
- warm.putalpha(ImageChops.multiply(warm_m, bend))
687
- ov = Image.alpha_composite(ov, warm)
688
- except Exception:
689
- return None
690
- if len(_OVERLAYS) > 12: # 尺寸变来变去时别把内存吃干
691
- _OVERLAYS.clear()
692
- _OVERLAYS[key] = ov
693
- return ov
694
-
695
-
696
- def build_stage(shot, sw, sh, s_scale=1.0):
697
- """把截屏结果做成底板。**降采样倍率跟着模糊半径走**。
698
-
699
- - `DSH_WATCH_GLASS_BLUR > 0`(默认 13):走 1/8 降采样再糊,就是原来那套液态玻璃。
700
- - `DSH_WATCH_GLASS_BLUR = 0`:**"只要一层不透明度、不要糊"**。这时 1/8 会把背景
701
- 放大成 8 倍的色块 —— 那是马赛克,不是玻璃。所以改成 1:1 逐像素采样,
702
- 同时把色散 / 边缘折射 / 提饱和全部关掉(清晰图上做这些一眼就假)。
703
-
704
- 两处 `_stage` 各自抄过一遍这段,改动容易只改一边;统一到这里。
705
- """
706
- try:
707
- blur_r = max(0.0, float(os.environ.get("DSH_WATCH_GLASS_BLUR") or 13))
708
- except Exception:
709
- blur_r = 13.0
710
- crisp = blur_r <= 0.5
711
- # **1/4,不是 1/8**(取自 PR #15):1/8 那层放大 8 倍,边缘折射和背景细节都发虚;
712
- # 1/4 面积是 4 倍但换来的清晰度是肉眼可见的。成本靠"静态跳帧"抵掉 ——
713
- # 背景不动时这里根本不会被调用。
714
- ds = 1 if crisp else 4
715
- small = shot.resize((max(4, sw // ds), max(4, sh // ds)), Image.BILINEAR)
716
- if not crisp:
717
- small = small.filter(ImageFilter.GaussianBlur(blur_r))
718
- try:
719
- chroma = float(os.environ.get("DSH_WATCH_GLASS_CHROMA") or 8.0)
720
- except Exception:
721
- chroma = 8.0
722
- if chroma > 0.01 and not crisp:
723
- # 强度要按降采样比例换算,否则换倍率时色散量会变
724
- small = chromatic(small.convert("RGBA"), chroma * 16.0 / ds)
725
- try:
726
- sat = float(os.environ.get("DSH_WATCH_GLASS_SAT") or (1.0 if crisp else 1.75))
727
- small = ImageEnhance.Color(small).enhance(max(0.0, sat))
728
- small = ImageEnhance.Brightness(small).enhance(1.0 if crisp else 1.06)
729
- except Exception:
730
- pass
731
- if not crisp:
732
- try:
733
- small = refract(small, max(2.0, 14 * s_scale / 4.0))
734
- except Exception:
735
- pass
736
- return small
737
-
738
-
739
- def plate(src, rect, radius, mode="panel", s=1.0):
740
- """从模糊底板**裁一块**下来,做成一片真玻璃。返回 (RGBA 图, (x, y))。
741
-
742
- ## 为什么每块玻璃都从底板裁
743
- tkinter 没有"半透明填充"这种东西:Canvas 的填充色必须是不透明色。所以想做出
744
- "气泡透出背后的画面",唯一的办法就是**把背后的那张(已经糊过的)图裁下来**,
745
- 再往上叠薄薄一层白/蓝 —— 它透出来的确实是身后的画面,不是模拟。
746
-
747
- 于是三样东西共用同一套合成:主体 / 悬浮条 / 气泡。区别只在四个参数:
748
-
749
- | mode | 压暗 a | wash | 说明 |
750
- |----------|---------------|-----------------|----------------------------|
751
- | `panel` | 0.34 – 0.74 | 无 | 主体,最通透(要看画面) |
752
- | `slab` | 0.40 – 0.78 | 白 6% | 标题 / 输入条,要读字 |
753
- | `bubble` | 0.30 – 0.62 | 白 7% | 陪看 / 台词 |
754
- | `me` | 0.28 – 0.58 | 系统蓝 26% | 我说的 |
755
-
756
- 压暗量按**这块自己的平均亮度**反解(不是整窗一个值):标题栏可能压着白网页、
757
- 主体压着暗场景,各调各的才对。
758
- """
759
- x1, y1, x2, y2 = (int(round(v)) for v in rect)
760
- x1, y1 = max(0, x1), max(0, y1)
761
- x2 = min(src.size[0], max(x1 + 2, x2))
762
- y2 = min(src.size[1], max(y1 + 2, y2))
763
- w, h = max(2, x2 - x1), max(2, y2 - y1)
764
- img = src.crop((x1, y1, x1 + w, y1 + h)).convert("RGBA")
765
-
766
- # **不再降采样烘焙**。试过按 0.52 倍算完再放大(成本 1/4),但 1px 的边光被放大成
767
- # 2px 半强度的软带,玻璃立刻"没边了"。既然叠加层(边光/光泽/彩边)和遮罩现在都
768
- # 按尺寸缓存,全分辨率下每次重烘只需要一次合成,反而又快又锐。
769
- sw, sh = w, h
770
- sk = s
771
- radius = max(1.5, float(radius))
772
-
773
- # ---- ① 自适应压暗:把这块的平均亮度压到 84 以下,白字才立得住 ----
774
- try:
775
- # 平均亮度在 48×48 上算就够(均值对分辨率不敏感),省掉一次全尺寸转灰 + 全像素遍历
776
- lum = ImageStat.Stat(img.resize((48, 48), Image.BILINEAR).convert("L")).mean[0]
777
- except Exception:
778
- lum = 128.0
779
- lo_a, hi_a = {"panel": (0.30, 0.70), "slab": (0.38, 0.76),
780
- "bubble": (0.22, 0.50), "me": (0.20, 0.46)}.get(mode, (0.30, 0.70))
781
- a = _clamp((lum - 84.0) / max(1.0, lum - float(INK[0])), lo_a, hi_a)
782
-
783
- # ---- ② wash:把"浮在上面"这件事说出来(纯压暗会显得脏、塌) ----
784
- # **压暗和 wash 都是纯色叠纯色,先算成一个色再一次贴上**:两次全尺寸
785
- # alpha_composite 合成一次,面板上省 4ms。
786
- wash = {"panel": (WHITE, 6), "slab": (WHITE, 16), "bubble": (WHITE, 34),
787
- "me": (ACCENT_RGB, 104)}.get(mode, (WHITE, 0))
788
- ta = int(255 * a)
789
- if wash[1] > 0:
790
- wb = wash[1] / 255.0
791
- mix = tuple(int(round(INK[i] * (1 - wb) + wash[0][i] * wb)) for i in range(3))
792
- eff = ta + wash[1] * (1 - ta / 255.0)
793
- img = Image.alpha_composite(img, Image.new("RGBA", img.size, mix + (int(round(eff)),)))
794
- else:
795
- img = Image.alpha_composite(img, Image.new("RGBA", img.size, INK + (ta,)))
796
-
797
- # ---- ②' 曲率权重(色散强度) + 可选的通道位移 ----
798
- try:
799
- bend = _corner_weight(sw, sh, radius, 1.4)
800
- except Exception:
801
- bend = None
802
- # 通道位移(红/蓝各自缩放)默认**不开**:底板已经糊过又压过暗,边上几乎没有对比,
803
- # 位移出来的彩边肉眼看不见,却要付 2 次全尺寸 resize —— 面板上实测 +18ms/块。
804
- # 真正看得见的是下面 ⑤ 那两条"暖外冷内"的边,那才是这套玻璃的色散来源。
805
- if os.environ.get("DSH_WATCH_CHROMA_EDGE") == "1":
806
- img = chroma_edge(img, radius, max(1.2, 2.2 * sk), bend)
807
-
808
- # ---- ③④⑤ 光的部分:与背后的画面无关,整张叠加层按尺寸缓存 ----
809
- # 光泽 / 边光 / 内侧暗线 / 暖冷彩边 **全都是纯几何**,同一尺寸下永远一样。
810
- # 以前每烘一次都在这张 w×h 的图上做 6 次 alpha_composite(面板上 ~24ms),
811
- # 而真正随底板变的只有下面的压暗。现在合成一张叠加层缓存起来,重烘时只付 1 次。
812
- try:
813
- ov = _light_overlay(sw, sh, radius, sk)
814
- if ov is not None:
815
- img = Image.alpha_composite(img, ov)
816
- except Exception:
817
- pass
818
-
819
- # ---- ⑥ 超椭圆遮罩(角上抗锯齿) ----
820
- img.putalpha(_cached_mask(sw, sh, radius))
821
- return img, (x1, y1)
822
-
823
-
824
- class Opt:
825
- """一组排版参数(已按 DPI 缩放),气泡和窗口共用"""
826
-
827
- def __init__(self, s, avail, family):
828
- self.s = s
829
- self.avail = avail
830
- self.radius = int(BUBBLE_R * s)
831
- self.padx = int(14 * s)
832
- self.pady = int(10 * s)
833
- self.gap = int(14 * s)
834
- self.font = (family, max(8, int(11 * s)))
835
- self.font_small = (family, max(7, int(8.5 * s)))
836
- # 时间戳专用:**不加粗**。一版是 9pt bold,压在模糊背景上比正文还抢眼,
837
- # 一排粗体数字看着像仪表盘。苹果的 caption 是细体 + 低对比,现在照这个来。
838
- self.font_time = (family, max(7, int(8.5 * s)))
839
-
840
-
841
- class Bubble:
842
- """一条消息 = 一行时间 + 一块玻璃片,**直接画在父 Canvas 上**。
843
-
844
- ## 为什么不用 Frame + Label(2026-11-01 改版)
845
- tkinter 的窗口部件(Frame / Label / Canvas)**必须填一个不透明底色**,所以只要
846
- 消息还挂在部件上,毛玻璃底板就永远被整块盖住 —— 这是"真模糊"做不出来的真正原因,
847
- 跟用哪个库、哪种语言都无关。只有 Canvas 的**原生元素**(create_text / create_image)
848
- 能浮在图片之上,所以这里全部自绘。
849
-
850
- ## 气泡本身也是玻璃(2026-11-01 二版)
851
- 一版给气泡填了个死色 `#3a4459`,等于在玻璃上贴卡纸 —— 背后画面一到气泡就断,
852
- 整窗那点通透全废了。二版从底板裁一块下来(`plate()`),只加一层白/蓝 wash:
853
- 气泡里透出来的就是它身后的画面,只是更亮更实一点。缓存按尺寸 + 底板版本走,
854
- 同一块气泡不会每帧重烘。
855
-
856
- `measure()` 只算尺寸不画(排版要先知道总高),`paint()` 才真正落到画布上。
857
- 文字高度用 `create_text` + `bbox` 实测 —— 中英文混排的折行交给 Tk 自己算,
858
- 不自己实现换行算法(那才是 bug 温床)。
859
- """
860
-
861
- def __init__(self, role, text, stamp, opt, host=None):
862
- self.role = role
863
- self.opt = opt
864
- self.host = host
865
- kind, fg, bar, who = ROLE.get(role, ROLE["assistant"])
866
- self.kind, self.fg, self.bar = kind, fg, bar
867
- self.text = text
868
- # 实际画出来的那段(可能被 max_h 截断成 "开头…");`text` 永远是原文
869
- self.shown = text
870
- self._mkey = None
871
- self.right = role == "user"
872
- self.head = " ".join(x for x in (who, stamp) if x)
873
- self.tag = f"msg{next(_COUNTER)}"
874
- # 尺寸(measure 之后有值)
875
- self.bw = self.bh = self.h = 0
876
- self._limit = 0
877
- self._img = None
878
- self._img_key = None
879
- self._head_h = 0
880
- # 入场进度:1.0 = 已在位(历史回放直接是 1,只有新来的才走动画)
881
- self._anim = 1.0
882
- self._fade = 1.0
883
- self._gx = None
884
-
885
- def measure(self, cv, avail, max_h=0):
886
- """算出这块占多高、气泡多宽(不落任何 item)。
887
-
888
- `max_h` 给了就把正文截到塞得进这个高度的长度(末尾补省略号)。
889
- **画布裁不了文字**:比视口还高的一条如果整段画出来,它就得从视口顶上起画,
890
- 后面几条同理 —— 结果全叠在同一个 y 上,用户看到的是"字压字、还顶到
891
- 输入栏外面"。截断之后它的 h 永远不超过视口,`_reflow` 那条超高分支只当兜底。
892
- """
893
- opt = self.opt
894
- limit = max(int(120 * opt.s), int(avail * 0.84) - 2 * opt.padx)
895
- self._limit = limit
896
- # **时间戳占多高要实测,不能拿字号顶**:`font_time[1]` 是磅值,中文 9pt 的
897
- # 实际行高是它的 1.4 倍左右 —— 按磅值留位置,多出来的那半行正好落在气泡底下,
898
- # 字被气泡啃掉一截(用户看到的就是"字太靠下、被气泡挡住了")。
899
- if self.head:
900
- probe = cv.create_text(-4000, -4000, text=self.head, font=opt.font_time,
901
- anchor="nw")
902
- hb = cv.bbox(probe)
903
- cv.delete(probe)
904
- head_h = ((hb[3] - hb[1]) if hb else opt.font_time[1]) + int(6 * opt.s)
905
- else:
906
- head_h = 0
907
- self._head_h = int(head_h)
908
- text = self.text
909
- self.shown = text
910
- tw, th = self._probe(cv, text, limit)
911
- if max_h:
912
- room = max_h - self._head_h - 2 * opt.pady - opt.gap
913
- if th > room:
914
- text = self._fit(cv, text, limit, room) if room > 0 else "…"
915
- self.shown = text
916
- tw, th = self._probe(cv, text, limit)
917
- self.bw = int(min(limit, max(1, tw)) + 2 * opt.padx)
918
- self.bh = int(max(1, th) + 2 * opt.pady)
919
- self.h = head_h + self.bh + opt.gap
920
- return self.h
921
-
922
- def _probe(self, cv, text, limit):
923
- """量一段文字的像素尺寸(create → bbox → delete,一次一个 item)"""
924
- probe = cv.create_text(-4000, -4000, text=text, width=limit,
925
- font=self.opt.font, anchor="nw")
926
- box = cv.bbox(probe) or (0, 0, 1, 1)
927
- cv.delete(probe)
928
- return box[2] - box[0], box[3] - box[1]
929
-
930
- def _fit(self, cv, text, limit, room):
931
- """二分出"塞进 room 像素的最长前缀",末尾补省略号。
932
-
933
- 折行照样交给 Tk(每次都用同一套字体真量一遍),这里只决定"切到第几个字"。
934
- 太短就退化成 "…",至少不会把一个字挤成两行。
935
- """
936
- lo, hi, best = 0, len(text), -1
937
- while lo <= hi:
938
- mid = (lo + hi) // 2
939
- if self._probe(cv, text[:mid].rstrip() + "…", limit)[1] <= room:
940
- best, lo = mid, mid + 1
941
- else:
942
- hi = mid - 1
943
- if best < 0:
944
- return "…"
945
- return text[:best].rstrip() + "…"
946
-
947
- def _photo(self, bx, yy, r):
948
- """裁一块玻璃(按尺寸 + 底板版本 + 入场进度缓存:滚动时不重烘)"""
949
- host = self.host
950
- if host is None or not getattr(host, "glass_ready", lambda: False)():
951
- return None
952
- blur = getattr(host, "_blurred", None)
953
- if blur is None:
954
- return None
955
- try:
956
- wh = (host.canvas.winfo_width(), host.canvas.winfo_height())
957
- except Exception:
958
- wh = blur.size
959
- if blur.size != wh:
960
- # 底板还是上一档尺寸(折叠/展开/缩放的过渡帧):这时候裁出来的片是错的,
961
- # 宁可这一帧不画玻璃,下一帧再补。
962
- return None
963
- # 入场进度量化成 12 档:0 = 全透明(不画图),12 = 实体
964
- step = max(1, min(12, int(round(self._opacity() * 12))))
965
- key = (self.kind, self.bw, self.bh, r, host.chat_glass_ver(), step)
966
- if self._img_key == key and self._img is not None:
967
- return self._img
968
- try:
969
- img = host.plate_image(self.kind, (bx, yy, bx + self.bw, yy + self.bh), r)
970
- if img is None:
971
- return None
972
- if step < 12:
973
- # Tk 的 image item 没有透明度可调,只能**重新合成一张淡一点的图** ——
974
- # 每档一次 `putalpha`,一张气泡 ~4ms,8 帧摊在 200ms 里够用。
975
- img = img.copy()
976
- img.putalpha(img.getchannel("A").point(lambda v: int(v * step / 12.0)))
977
- photo = ImageTk.PhotoImage(img)
978
- except Exception:
979
- return None
980
- self._img, self._img_key = photo, key
981
- return photo
982
-
983
- def _opacity(self):
984
- """当前该有多实:入场进度 × 滚动边缘的淡出系数"""
985
- return max(0.0, min(1.0, self._anim * self._fade))
986
-
987
- def repaint(self, cv):
988
- """按上次的位置重画(入场动画每帧走这里,不重排整个列表)"""
989
- if not self._gx:
990
- return
991
- x0, y, w, fade = self._gx
992
- self.paint(cv, x0, y, w, fade)
993
-
994
- def paint(self, cv, x0, y, width, fade=1.0):
995
- """在画布上从 (x0, y) 开始画(y 是这一条的顶端,fade 是滚动边缘的淡出)"""
996
- opt = self.opt
997
- self._fade = fade
998
- self._gx = (x0, y, width, fade)
999
- cv.delete(self.tag)
1000
- # 入场:从下方 10px、三成透明度"浮"到位。**不能只做 alpha 不做位移** ——
1001
- # 纯淡入在暗背景上几乎看不出来,位移才让人看见"来了"。
1002
- a = self._opacity()
1003
- yy = y + (0 if self._anim >= 0.999 else int(round((1.0 - self._anim) * 10 * opt.s)))
1004
- fg = self.fg if a >= 0.999 else _mix(BG, self.fg, max(0.15, a))
1005
- time_fg = TIME_FG if a >= 0.999 else _mix(BG, TIME_FG, max(0.15, a))
1006
- # **时间戳贴着气泡自己的边缘**,不能用画布宽度:气泡左边缘在 `x0`
1007
- # (= 窗口内缩 + 8px),而画布原点是 0,两者差 30 多像素 ——
1008
- # 之前时间戳永远是"浮在气泡左边外面",看着就是错位。
1009
- bx = (x0 + width - self.bw) if self.right else x0
1010
- if self.head:
1011
- hx = (bx + self.bw) if self.right else bx
1012
- cv.create_text(hx, yy, text=self.head, font=opt.font_time, fill=time_fg,
1013
- anchor="ne" if self.right else "nw", tags=self.tag)
1014
- yy += self._head_h
1015
- r = max(6, int(min(opt.radius, self.bh / 2)))
1016
- photo = self._photo(bx, yy, r)
1017
- if photo is not None:
1018
- cv.create_image(bx, yy, image=photo, anchor="nw", tags=self.tag)
1019
- else:
1020
- # 兜底:没有 Pillow / 拿不到底板时退回纯色片,至少不塌
1021
- round_rect(cv, bx, yy, bx + self.bw, yy + self.bh, r,
1022
- fill=_mix(GLASS_FILL, "#1b1e24", a), outline="", tags=self.tag)
1023
- if self.bar:
1024
- x = bx + max(2, opt.padx // 3)
1025
- round_rect(cv, x, yy + opt.pady, x + max(2, int(3 * opt.s)),
1026
- yy + self.bh - opt.pady, 2, fill=self.bar, outline="", tags=self.tag)
1027
- text_on_glass(cv, bx + opt.padx, yy + opt.pady, self.shown,
1028
- width=self._limit, font=opt.font, fill=fg,
1029
- anchor="nw", tags=self.tag,
1030
- offset=max(1, int(opt.s)))
1031
-
1032
-
1033
- _COUNTER = iter(range(1, 10 ** 9))
1034
-
1035
-
1036
- class Meta:
1037
- """系统行(麦克风状态、报错):一行灰字,不做气泡。同样是**画在 Canvas 上**,
1038
- 理由和 Bubble 一样(窗口部件会挡住毛玻璃)。"""
1039
-
1040
- def __init__(self, text, opt, center=False):
1041
- self.opt = opt
1042
- self.text = text
1043
- self.center = center
1044
- self.tag = f"meta{next(_COUNTER)}"
1045
- self.h = 0
1046
- self._limit = 0
1047
-
1048
- def measure(self, cv, avail, max_h=0):
1049
- opt = self.opt
1050
- if self.center:
1051
- self._limit = avail
1052
- self.h = int(72 * opt.s) * 2 + opt.font_small[1] * 3
1053
- if max_h:
1054
- self.h = min(self.h, max_h)
1055
- return self.h
1056
- self._limit = max(80, int(avail))
1057
- probe = cv.create_text(-4000, -4000, text=self.text, width=self._limit,
1058
- font=opt.font_small, anchor="nw")
1059
- box = cv.bbox(probe) or (0, 0, 1, 1)
1060
- cv.delete(probe)
1061
- self.h = (box[3] - box[1]) + opt.gap
1062
- if max_h:
1063
- self.h = min(self.h, max_h)
1064
- return self.h
1065
-
1066
- def paint(self, cv, x0, y, width, fade=1.0):
1067
- opt = self.opt
1068
- cv.delete(self.tag)
1069
- # Canvas 的文字没有 alpha,只能把颜色往底板上插值 —— 视觉上等价于淡出
1070
- fg = DIM if fade >= 0.999 else _mix(GLASS_FILL, DIM, max(0.05, fade))
1071
- # 系统行也是压在玻璃上的灰字,同样要影子("叫醒失败"这类行最容易被背景吃掉)。
1072
- # **这里不按背景翻色**:`Meta` 拿不到 host,而且它本来就是低对比的灰字,
1073
- # 翻成深色反而更糊 —— 只加影子。
1074
- if self.center:
1075
- text_on_glass(cv, x0 + width / 2, y + int(72 * opt.s), self.text,
1076
- font=opt.font_small, fill=fg, anchor="n",
1077
- justify="center", width=width, tags=self.tag,
1078
- offset=max(1, int(opt.s)))
1079
- else:
1080
- text_on_glass(cv, x0 + 3 * opt.s, y, self.text, font=opt.font_small,
1081
- fill=fg, anchor="nw", width=self._limit, tags=self.tag,
1082
- offset=max(1, int(opt.s)))
1083
-
1084
-
1085
- class GlassButton:
1086
- """画在宿主 Canvas 上的按钮(胶囊 / 圆盘 / 图标)。
1087
-
1088
- 为什么不用 `tk.Button` / `tk.Label`:它们只有直角 + 不透明底色,贴在玻璃上就是
1089
- 一块死色块("麦"和"发送"周围那圈黑边就是这么来的)。tkinter 又给不了半透明填充,
1090
- 所以玻璃底是**从底板裁下来的**(`plate()`),悬停时换成同一块裁片的白一档版本
1091
- —— 提亮是真提亮,不是换一个近似色蒙事。
1092
-
1093
- 三种 kind:
1094
- `ghost` 玻璃胶囊(麦 / 发送的底)
1095
- `accent` 实心强调胶囊(主操作;苹果的 tinted glass 就是这个意思)
1096
- `icon` 只有字/符号,悬停浮出一个圆形井(✕ / ▾)
1097
- """
1098
-
1099
- def __init__(self, host, key, text="", kind="ghost", fg=None, fill=None,
1100
- command=None, size=9.5, group=None):
1101
- self.host = host
1102
- self.tag = key
1103
- self.text = text
1104
- self.kind = kind
1105
- self.fg = fg or TEXT
1106
- self.fill = fill
1107
- self.command = command
1108
- self.size = size
1109
- self.group = group
1110
- self.rect = None
1111
- self.radius = 0.0
1112
- self.hover = False
1113
- self._photo = None
1114
- self._label = None
1115
- self._bound = False
1116
-
1117
- # ---- 状态 ----
1118
- def set(self, text=None, bg=None, fg=None):
1119
- if text is not None:
1120
- self.text = text
1121
- if fg is not None:
1122
- self.fg = fg
1123
- if bg is not None:
1124
- self.fill = bg
1125
- self._paint()
1126
-
1127
- def set_bg(self, bg):
1128
- self.fill = bg
1129
- self._paint()
1130
-
1131
- def hide(self):
1132
- self.host.canvas.itemconfigure(self.tag, state="hidden")
1133
-
1134
- def show(self):
1135
- self.host.canvas.itemconfigure(self.tag, state="normal")
1136
-
1137
- # ---- 几何 ----
1138
- def layout(self, rect, radius=None):
1139
- self.rect = tuple(int(round(v)) for v in rect)
1140
- x1, y1, x2, y2 = self.rect
1141
- self.radius = float(radius if radius is not None
1142
- else min(x2 - x1, y2 - y1) / 2.0)
1143
- if not self._bound:
1144
- self._bind()
1145
- self._bound = True
1146
- self._paint()
1147
-
1148
- def _bind(self):
1149
- cv = self.host.canvas
1150
- cv.tag_bind(self.tag, "<Enter>", lambda _e: self._set_hover(True))
1151
- cv.tag_bind(self.tag, "<Leave>", lambda _e: self._set_hover(False))
1152
- cv.tag_bind(self.tag, "<Button-1>", self._click)
1153
-
1154
- def _click(self, _e=None):
1155
- if self.command:
1156
- try:
1157
- self.command()
1158
- except Exception:
1159
- pass
1160
- return "break" # 别让画布把这次点击当成"拖窗"
1161
-
1162
- def _set_hover(self, on):
1163
- if self.hover == on:
1164
- return
1165
- self.hover = on
1166
- try:
1167
- self.host.canvas.configure(cursor="hand2" if on else "")
1168
- except Exception:
1169
- pass
1170
- self._paint()
1171
-
1172
- # ---- 绘制 ----
1173
- def _paint(self):
1174
- if not self.rect:
1175
- return
1176
- cv = self.host.canvas
1177
- cv.delete(self.tag)
1178
- tags = (self.tag,) + ((self.group,) if self.group else ())
1179
- x1, y1, x2, y2 = self.rect
1180
- h = max(2, y2 - y1)
1181
- r = max(2.0, min(self.radius, h / 2.0))
1182
-
1183
- if self.kind == "accent":
1184
- base = self.fill or ACCENT
1185
- round_rect(cv, x1, y1, x2, y2, r, fill=base, outline="", tags=tags)
1186
- # 顶部一道亮边:实心胶囊也要有"受光面",否则像贴纸
1187
- cv.create_line(x1 + r * 0.9, y1 + 0.7, x2 - r * 0.9, y1 + 0.7,
1188
- fill=_mix(base, "#ffffff", 0.42 if not self.hover else 0.62),
1189
- width=1, tags=tags)
1190
- elif self.kind == "icon":
1191
- if self.hover and self.host.glass_ready():
1192
- photo = self.host.plate_photo("hover", self.rect, r)
1193
- if photo is not None:
1194
- self._photo = photo
1195
- cv.create_image(x1, y1, image=photo, anchor="nw", tags=tags)
1196
- else:
1197
- photo = None
1198
- if self.fill is None and self.host.glass_ready() and not getattr(self.host, "acrylic", False):
1199
- photo = self.host.plate_photo("hover" if self.hover else "slab",
1200
- self.rect, r)
1201
- if photo is not None:
1202
- self._photo = photo
1203
- cv.create_image(x1, y1, image=photo, anchor="nw", tags=tags)
1204
- else:
1205
- round_rect(cv, x1, y1, x2, y2, r,
1206
- fill=self.fill or ("#262a31" if self.hover else "#1b1e24"),
1207
- outline="", tags=tags)
1208
-
1209
- self._label = cv.create_text((x1 + x2) / 2.0, (y1 + y2) / 2.0, text=self.text,
1210
- font=self.host._f(self.size), fill=self.fg,
1211
- anchor="center", tags=tags)
1212
-
1213
-
1214
- # ---------------------------------------------------------------- 窗口
1215
-
1216
- class FloatChat:
1217
- def __init__(self):
1218
- dpi_aware()
1219
- cfg = read_config()
1220
- geo = cfg.get("geometry") if isinstance(cfg.get("geometry"), str) else ""
1221
- # 插件开窗前会把 `hidden` 清成 false,所以新进程总是从"看得见"开始;
1222
- # 这里只跟文件变化(`_sync_visible`),不猜"第一次"
1223
- self.hidden = False
1224
- # 窗口的名字:用户可改,存 `~/.dsh/watch-window.json` 的 `name`(默认"陪看")
1225
- raw_name = cfg.get("name")
1226
- self.name = (raw_name.strip()[:24] if isinstance(raw_name, str) and raw_name.strip()
1227
- else "陪看")
1228
-
1229
- self.root = tk.Tk()
1230
- self.root.title(self.name)
1231
- self.root.overrideredirect(True) # 无边框
1232
- self.root.attributes("-topmost", True) # 置顶
1233
- self.root.configure(bg=KEY)
1234
-
1235
- try:
1236
- self.s = max(1.0, min(2.2, float(self.root.winfo_fpixels("1i")) / SS))
1237
- except Exception:
1238
- self.s = 1.0
1239
- S = self.s
1240
-
1241
- # 液态玻璃的几何:窗口边 → 玻璃 12px(玻璃是"浮"在桌面上的,不是贴着窗口边),
1242
- # 玻璃之间 10px 的缝透出真实桌面 —— iOS 26 那种"几块悬浮玻璃"的分层感就是这么来的。
1243
- self.radius = int(PANEL_R * S)
1244
- self.out = int(12 * S) # 窗口边 → 玻璃
1245
- self.pad = self.out + int(14 * S) # 窗口边 → 文字(玻璃内边距)
1246
-
1247
- self.w, self.h = int(468 * S), int(540 * S)
1248
- self._parse_geometry(geo)
1249
-
1250
- # 圆角:Windows 才有 -transparentcolor;拿不到就直角,不报错
1251
- self.rounded = True
1252
- try:
1253
- self.root.attributes("-transparentcolor", KEY)
1254
- # **不要和 -alpha 一起用**:抠色 + 整窗 alpha 会让抠掉的地方变成半透明黑(脏边)
1255
- except Exception:
1256
- self.rounded = False
1257
- self.root.configure(bg=BG)
1258
- try:
1259
- self.root.attributes("-alpha", 0.97)
1260
- except Exception:
1261
- pass
1262
-
1263
- # 玻璃的"通透":整窗轻微透明,透出背后一点点桌面。
1264
- # 0.96 是试出来的上限 —— 再低字就开始发灰、背后内容会抢注意力。
1265
- # 拿不到(平台不支持 / 和抠色冲突)就安静地跳过,绝不因为一个视觉效果起不来。
1266
- # `DSH_WATCH_GLASS_ALPHA` 可调,设 1 完全关掉。
1267
- if self.rounded:
1268
- try:
1269
- a = float(os.environ.get("DSH_WATCH_GLASS_ALPHA") or 0.975)
1270
- if 0.5 <= a < 1.0:
1271
- self.root.attributes("-alpha", a)
1272
- except Exception:
1273
- pass
1274
-
1275
- # **磨砂(GPU)模式**:让 DWM 自己做背景模糊,我们一次屏都不截。
1276
- # 代价是 canvas 上不能有半透明叠加(Tk 不支持),所以气泡/悬浮条退化成
1277
- # 实心卡片 —— 但那本来就是"磨砂玻璃上的卡片"该有的样子。
1278
- # 收益:背景由 GPU 逐帧糊,60fps,CPU 占用接近 0。
1279
- self.acrylic = False
1280
- if os.environ.get("DSH_GLASS_ACRYLIC") == "1":
1281
- self.acrylic = self._apply_acrylic()
1282
-
1283
- self.family = self._pick_font()
1284
- self.opt = Opt(S, max(160, self.w - 2 * self.pad - int(16 * S)), self.family)
1285
-
1286
- self.mic_proc = None
1287
- self._drag = None
1288
- self._resize = None
1289
- self.rows = []
1290
- self.empty = None
1291
- # 真毛玻璃底板(PIL.Image)与它的 Tk 句柄。
1292
- # **PhotoImage 必须留引用**:只 create_image 不持有的话,下一帧就被 GC,
1293
- # 画布上立刻变成空白 —— 这是 Tk 里贴图最常见的坑。
1294
- self.backdrop = None # 已经压暗 + 带圆角 alpha 的整窗玻璃图
1295
- self._blurred = None # 只糊不压暗的原图:每块玻璃自己裁它再调亮度
1296
- self._backdrop_photo = None
1297
- self._bot_slab_h = 0 # 输入栏玻璃片的高度(量到之后回填)
1298
- self._backdrop_job = None
1299
- # 裁片缓存:(mode, w, h, r, 版本) → PhotoImage。
1300
- # 滚动/重排时不重烘 —— 一张气泡玻璃 ~10ms,一屏七八条就是一次明显的卡顿。
1301
- self._resizing = False
1302
- self._resize_job = None
1303
- self._last_panel = None # 上一张整窗玻璃(缩放时临时顶上)
1304
- self._plates = {} # (mode,w,h,r,版本) → PhotoImage
1305
- self._plate_imgs = {} # 同上,但存 PIL 图(入场动画要改 alpha)
1306
- self._last_plate_imgs = {} # 每个 mode 最近一张(缩放时缩放顶上)
1307
- self._glass_v = 0
1308
- self._chat_v = 0
1309
- self._stage_cache = None # 带留白、已糊好的底板(1/4 分辨率)
1310
- self._painted_size = None # 上一次整窗重绘用的尺寸(判断 Configure 是不是"纯搬家")
1311
- self._dpik = None # DPI 系数(缓存)
1312
- self._last_origin = None # 上一帧窗口原点(判断挪了多远)
1313
-
1314
- self._build()
1315
-
1316
- # 开窗第一次截图:此刻窗口还没显示(下面才 deiconify),所以截到的是干净桌面,
1317
- # **完全不会闪**。之后只在拖动/缩放结束时重截。
1318
- # 磨砂模式跳过:背景交给 DWM,一次屏都不用截(连带省掉那次 withdraw/deiconify)。
1319
- if HAVE_PIL and self.rounded and not self.acrylic:
1320
- self.root.withdraw()
1321
- self.root.update_idletasks()
1322
- self.backdrop = self._grab_backdrop((self.w, self.h))
1323
- self._paint()
1324
- self.root.deiconify()
1325
- # 必须在 map 之后;失败就退回"隐藏窗口再截"的老路(`_refresh_backdrop` 会判断)
1326
- # 抓屏排除(WDA_EXCLUDEFROMCAPTURE):默认开,抓"自己背后"时不递归、不闪。
1327
- # **但它同时也让窗口从用户的截图/录屏里消失** —— 录演示视频必须能关掉。
1328
- # 三级开关:env `DSH_GLASS_WDA=0` > 配置 `"capturable": true` > 默认排除。
1329
- _cap = read_config().get("capturable") is True
1330
- self._excluded = self._set_exclude(
1331
- not _cap and os.environ.get("DSH_GLASS_WDA") != "0")
1332
-
1333
- self._offset = 0
1334
- self._carry = ""
1335
- self.seen = 0
1336
- self._reset_cursor()
1337
- self.poll()
1338
-
1339
- # **磨砂必须在窗口真 show 出来之后再挂**:`SetWindowCompositionAttribute` 在
1340
- # 窗口还没 map 时调用**返回 True 但什么也不做**(实测:map 前挂 → 背景原样穿透,
1341
- # 条纹 std 183.6;map 后挂 → std 1.8,糊成一片)。这和上一个 `SetWindowRgn`
1342
- # 的黑屏是同一个家族的错误:**在 map 之前摸 hwnd / 尺寸**。
1343
- if self.acrylic:
1344
- self.root.after(60, self._acrylic_late)
1345
-
1346
- self.root.bind("<Escape>", lambda _e: self.close())
1347
- self.root.after(220, self._focus_entry)
1348
-
1349
- # ---- 基础 ----
1350
- def _pick_font(self):
1351
- try:
1352
- from tkinter import font as tkfont
1353
- families = set(tkfont.families())
1354
- except Exception:
1355
- families = set()
1356
- for name in ("Microsoft YaHei UI", "Microsoft YaHei", "PingFang SC",
1357
- "Noto Sans CJK SC", "WenQuanYi Micro Hei"):
1358
- if name in families:
1359
- return name
1360
- return "TkDefaultFont"
1361
-
1362
- def _parse_geometry(self, geo):
1363
- """`468x540+120+80` → 尺寸与位置;坏字符串就用默认值"""
1364
- sw = self.root.winfo_screenwidth()
1365
- sh = self.root.winfo_screenheight()
1366
- try:
1367
- size, rest = geo.split("+", 1)
1368
- w, h = (int(x) for x in size.split("x"))
1369
- x, y = (int(v) for v in rest.split("+")[:2])
1370
- self.w = max(int(MIN_W * self.s), min(sw - 40, w))
1371
- # 高度下限**按三段玻璃算**,不写死 220:写死的那个比固定栏本身还矮,
1372
- # 恢复出来就是把消息区压成一条缝(用户实报"整窗被压扁、字顶出来")。
1373
- lo = min(self._min_h(), sh - 40)
1374
- self.h = max(lo, min(sh - 40, h))
1375
- # **位置必须按窗口自己的尺寸夹**:以前写的是 `sw - 120`,窗口 700 宽时
1376
- # 允许 x 到 sw-120,右边 580px 直接跑到屏幕外(用户看到的是"半截窗")。
1377
- self.x = max(0, min(sw - self.w - int(8 * self.s), x))
1378
- self.y = max(0, min(sh - self.h - int(48 * self.s), y))
1379
- except Exception:
1380
- self.x = max(0, sw - self.w - int(36 * self.s))
1381
- self.y = max(0, sh - self.h - int(96 * self.s))
1382
- self.root.geometry(f"{self.w}x{self.h}+{self.x}+{self.y}")
1383
-
1384
- def _f(self, size, weight="normal"):
1385
- return (self.family, max(7, int(size * self.s)), weight)
1386
-
1387
- # ---- 组装 ----
1388
- def _build(self):
1389
- bg = KEY if self.rounded else BG
1390
- self.canvas = tk.Canvas(self.root, bg=bg, highlightthickness=0, bd=0)
1391
- self.canvas.pack(fill="both", expand=True)
1392
- self.canvas.bind("<Configure>", self._paint)
1393
-
1394
- # **没有 shell 了**:整窗只有 header 和 composer 两块不透明窗口部件,
1395
- # 中间的消息区直接画在 canvas 上 —— 这样毛玻璃底板才能透出来。
1396
- self._items = [] # Bubble / Meta,按时间顺序
1397
- self._scroll = 0 # 消息区滚动偏移(px,0 = 贴底)
1398
- self._total_h = 0
1399
- self._view_h = 1
1400
- self._grip_item = None
1401
-
1402
- self._build_header()
1403
- self._build_composer()
1404
-
1405
- self.canvas.bind("<Button-1>", self._drag_start)
1406
- self.canvas.bind("<B1-Motion>", self._drag_move)
1407
- # **必须有 Release**:`_paint` 里"正在拖动就不重绘"那个早退靠 `self._drag` 判断,
1408
- # 而它以前只在按下时被赋值、**没有任何地方清零** —— 于是点过窗口一次之后,
1409
- # 所有"尺寸没变"的重绘全部被静默跳过(用户看到的就是折叠再展开后
1410
- # 标题栏和输入栏一片空白,连 ✕ 都没了)。
1411
- self.canvas.bind("<ButtonRelease-1>", self._drag_end)
1412
- # 滚轮绑在整个窗口上:真机上鼠标多半停在气泡上,只绑画布就滚不动
1413
- self.root.bind_all("<MouseWheel>", self._on_wheel)
1414
-
1415
- def _min_h(self):
1416
- """窗口能被压到多矮 —— **由三块玻璃自己算出来,不拍脑袋写一个数**。
1417
-
1418
- 以前这里写死 `220 * s`(150% 缩放下 = 330)。但三段固定高度加起来就是
1419
- `out*2 + 46s(标题)+ 58s(输入栏)+ 缝 2×10s` ≈ **222**,
1420
- 剩下 108px 给消息区 —— 一条气泡都放不下,于是文字顶上输入栏、整窗看着"被压扁"。
1421
- 用户窗口存下来的正好是 700×329,刚好被那个下限放过去了。
1422
-
1423
- 主体给 `300s`(约两条气泡)。**190s 是不够的**:气泡行高同样是 `*s` 的,
1424
- 190 逻辑在 150% 下只有 285 物理像素 = 一条 100 字台词的 1.1 倍,滚动时
1425
- 完整可见才画的那条规则会让整个主体空成一片。
1426
- """
1427
- s = self.s
1428
- mid = int(10 * s)
1429
- top_h = int(46 * s)
1430
- bot_h = getattr(self, "_bot_slab_h", 0) or int(58 * s)
1431
- body_min = int(300 * s)
1432
- return self.out * 2 + top_h + bot_h + mid * 2 + body_min
1433
-
1434
- def _layout(self, w, h):
1435
- """算出三块玻璃的位置:**标题栏 / 主体 / 输入栏,各自独立、中间留缝**。
1436
-
1437
- iOS 26 那种分层就是这么来的 —— 不是"一块大玻璃里套两条",而是三块分开的
1438
- 玻璃,缝隙里能看见背后的桌面(窗口的抠色区域是透明的)。
1439
- 返回 (顶条, 主体, 底条),每个都是 (x1, y1, x2, y2)。
1440
- """
1441
- s = self.s
1442
- out = self.out
1443
- mid = int(10 * s) # 玻璃之间的缝(小了会粘成一坨,看不出"分开")
1444
- top_h = int(46 * s)
1445
- bot_h = self._bot_slab_h or int(58 * s)
1446
- x1, x2 = out, w - out
1447
- top = (x1, out, x2, out + top_h)
1448
- bot = (x1, h - out - bot_h, x2, h - out)
1449
- body = (x1, top[3] + mid, x2, bot[1] - mid)
1450
- return top, body, bot
1451
-
1452
- # ---- 玻璃 ----
1453
- def glass_ready(self):
1454
- return bool(HAVE_PIL and self.rounded and self._blurred is not None)
1455
-
1456
- def glass_ver(self):
1457
- return self._glass_v
1458
-
1459
- def chat_glass_ver(self):
1460
- """气泡用的版本号:**小幅拖动不失效**。
1461
-
1462
- 主体玻璃(面板/条)必须跟着新底板重烘;气泡只是几十像素的裁片,挪个一两百像素
1463
- 以后它背后还是一片糊过的色块,重烘 6 块 × 4ms 完全白花 —— 拖窗那一下的卡顿
1464
- 有一半在这儿。所以只有"缩放"或"挪得很远"才让气泡重烘。
1465
- """
1466
- return self._chat_v
1467
-
1468
- def plate_image(self, mode, rect, radius):
1469
- """按矩形裁一块玻璃(PIL 图,带缓存),rect 用画布坐标。
1470
-
1471
- **缓存键里只有尺寸、没有位置**:底板被糊成低频色块以后,同一块气泡在窗口里
1472
- 上下挪 40px,裁出来的图和原来几乎一样 —— 但每滚一格就重烘七八张 10ms 的图,
1473
- 手感会明显发涩。所以位置不进键,滚动时直接复用。
1474
-
1475
- 返回 PIL 图而不是 PhotoImage:入场动画要按进度改 alpha,拿原图才好逐步合成
1476
- (`ImageTk.PhotoImage` 是一次性快照,改不了)。
1477
- """
1478
- if not self.glass_ready():
1479
- return None
1480
- x1, y1, x2, y2 = (int(round(v)) for v in rect)
1481
- w, h = max(4, x2 - x1), max(4, y2 - y1)
1482
- key = (mode, w, h, int(round(radius)), self._glass_v)
1483
- hit = self._plate_imgs.get(key)
1484
- if hit is not None:
1485
- return hit
1486
- # 拖右下角缩放时,宽度每帧都在变 → 每帧都全量重烘。这里拿同 mode 的上一张
1487
- # 直接缩放到新尺寸顶着(玻璃是低频色块,缩放看不出),松手后再烘准的。
1488
- if getattr(self, "_resizing", False):
1489
- last = self._last_plate_imgs.get(mode)
1490
- if last is not None:
1491
- try:
1492
- img = last.resize((w, h), Image.BILINEAR)
1493
- self._plate_imgs[key] = img
1494
- return img
1495
- except Exception:
1496
- pass
1497
- try:
1498
- img, _pos = plate(self._blurred, (x1, y1, x1 + w, y1 + h),
1499
- radius, mode, self.s)
1500
- except Exception:
1501
- return None
1502
- if len(self._plate_imgs) > 300: # 尺寸变了会攒出一堆旧键,别让它长
1503
- self._plate_imgs.clear()
1504
- self._plate_imgs[key] = img
1505
- self._last_plate_imgs[mode] = img
1506
- return img
1507
-
1508
- def plate_photo(self, mode, rect, radius):
1509
- """`plate_image` 的 Tk 句柄版(缓存 PhotoImage)"""
1510
- img = self.plate_image(mode, rect, radius)
1511
- if img is None:
1512
- return None
1513
- key = (mode, int(round(rect[2] - rect[0])), int(round(rect[3] - rect[1])),
1514
- int(round(radius)), self._glass_v)
1515
- hit = self._plates.get(key)
1516
- if hit is not None:
1517
- return hit
1518
- try:
1519
- photo = ImageTk.PhotoImage(img)
1520
- except Exception:
1521
- return None
1522
- if len(self._plates) > 300:
1523
- self._plates.clear()
1524
- self._plates[key] = photo
1525
- return photo
1526
-
1527
- def _panel_photo(self, w, h, body):
1528
- """整块主体玻璃(含圆角透明)—— 只有它铺满窗口,其余都是"浮在上面的片"。
1529
-
1530
- **缩放过程中不重烘**:一次烘焙 50ms,拖右下角时每个 Configure 都烘一次就是
1531
- 肉眼可见的卡顿。这里拿上一张按新尺寸缩放顶上(玻璃本来就是一片低频色块,
1532
- 缩放看不出差别),松手 300ms 后再由 `_refresh_backdrop` 重烘一张准的。
1533
- """
1534
- key = ("__panel__", w, h, self._glass_v)
1535
- hit = self._plates.get(key)
1536
- if hit is not None:
1537
- return hit
1538
- if not self.glass_ready():
1539
- return None
1540
- if getattr(self, "_resizing", False) and self._last_panel is not None:
1541
- try:
1542
- img = self._last_panel.resize((w, h), Image.BILINEAR)
1543
- photo = ImageTk.PhotoImage(img)
1544
- self._plates[key] = photo
1545
- return photo
1546
- except Exception:
1547
- pass
1548
- try:
1549
- img = Image.new("RGBA", (w, h), (0, 0, 0, 0))
1550
- piece, pos = plate(self._blurred, body, self.radius, "panel", self.s)
1551
- img.paste(piece, pos)
1552
- self._last_panel = img
1553
- photo = ImageTk.PhotoImage(img)
1554
- except Exception:
1555
- return None
1556
- self._plates[key] = photo
1557
- return photo
1558
-
1559
- def _ensure_blurred(self, w, h):
1560
- """窗口尺寸和底板对不上时先拉伸对齐 —— 拖动/缩放后的那 400ms 里不至于空一块"""
1561
- if self._blurred is None or self._blurred.size == (w, h):
1562
- return
1563
- try:
1564
- self._blurred = self._blurred.resize((w, h), Image.BILINEAR)
1565
- self._glass_v += 1
1566
- self._plates.clear()
1567
- except Exception:
1568
- pass
1569
-
1570
- def _repaint_glass(self):
1571
- """**只换玻璃、不动内容。**
1572
-
1573
- 背景在变(对面在播视频)时每 1~2 秒来一发。`_paint()` 末尾会 `_reflow()`
1574
- 重排所有气泡(几十毫秒),为了换一层底色付这个代价不值得 —— 这里只
1575
- `delete("panel")` 再贴一张,气泡一个都不碰。
1576
- """
1577
- if self.acrylic or getattr(self, "_collapsed", False) or not self.glass_ready():
1578
- return
1579
- w, h = getattr(self, "_painted_size", None) or (self.canvas.winfo_width(),
1580
- self.canvas.winfo_height())
1581
- if w < 4 or h < 4:
1582
- return
1583
- top, body, bot = self._layout(w, h)
1584
- photo = self._panel_photo(w, h, body)
1585
- if photo is not None:
1586
- self._backdrop_photo = photo
1587
- # **复用同一个 canvas item,不要 delete + create**:
1588
- # 那样中间有一帧没有底板,7Hz 刷新时肉眼看到的就是"一下一下地闪"。
1589
- # `itemconfigure` 换图是原子的,不闪,成本也一样(实测 5.7ms)。
1590
- item = getattr(self, "_panel_item", None)
1591
- alive = item is not None and self.canvas.type(item) == "image"
1592
- if alive:
1593
- self.canvas.itemconfigure(item, image=photo)
1594
- else:
1595
- self._panel_item = self.canvas.create_image(
1596
- 0, 0, image=photo, anchor="nw", tags=("panel", "backdrop"))
1597
- self.canvas.tag_lower("panel")
1598
- self._slab_paint(top, bot)
1599
- else:
1600
- round_rect(self.canvas, body[0], body[1], body[2], body[3], self.radius,
1601
- fill=BG, outline="", tags=("panel", "backdrop"))
1602
-
1603
- def _slab_paint(self, top, bot):
1604
- """两块**悬浮**玻璃(标题栏 / 输入栏)。
1605
-
1606
- 它们不是主体的一部分:中间留着缝,缝里透出的是真桌面;而且它们要盖在消息
1607
- 上面 —— 消息是"滑到片底下",不是"从片里穿出来"。
1608
- """
1609
- cv = self.canvas
1610
- self._slab_photos = []
1611
- r = max(8, int(SLAB_R * self.s))
1612
- # **复用 item**:每帧 delete + create 中间有一帧没有玻璃,7Hz 下就是闪。
1613
- # 只有数量变了(折叠 / 展开)才重建。
1614
- items = getattr(self, "_slab_items", None)
1615
- if items is None or len(items) != 2:
1616
- cv.delete("slab")
1617
- items = [None, None]
1618
- for i, rect in enumerate((top, bot)):
1619
- photo = None if getattr(self, "acrylic", False) else self.plate_photo("slab", rect, r)
1620
- if photo is None:
1621
- items[i] = None
1622
- continue
1623
- self._slab_photos.append(photo) # 必须留引用,否则被 GC 变空白
1624
- item = items[i]
1625
- if item is not None and cv.type(item) == "image":
1626
- cv.itemconfigure(item, image=photo)
1627
- else:
1628
- items[i] = cv.create_image(int(rect[0]), int(rect[1]), image=photo,
1629
- anchor="nw", tags=("panel", "slab"))
1630
- self._slab_items = items
1631
-
1632
- def _paint_collapsed(self, w, h):
1633
- """折叠状态:**只剩标题栏那一块玻璃**,主体和输入栏一概不画。
1634
-
1635
- 以前折叠只是把内容"藏起来",但 `_layout` 仍然按窗口高度算出主体和底条两个矩形
1636
- (高度变成负数/互相穿过),玻璃照裁不误 —— 结果窗口底下多出一条横线,输入槽
1637
- 还被摆回标题栏上压着字。折叠就该是"换一种画法",不是"画完再藏"。
1638
- """
1639
- cv = self.canvas
1640
- self._painted_size = (w, h)
1641
- cv.delete("panel")
1642
- # 底板必须按**折叠后的窗口尺寸**重新裁一刀:`_blurred` 还是展开时那张
1643
- # (809 高),直接拿去裁会把整屏压进 105px 里 —— 标题栏那片玻璃会变成
1644
- # 一条把整个桌面压扁的怪东西。
1645
- try:
1646
- self._grab_backdrop((w, h))
1647
- except Exception:
1648
- pass
1649
- top = self._layout(w, h)[0]
1650
- photo = self.plate_photo("slab", top, max(8, int(SLAB_R * self.s)))
1651
- if photo is not None:
1652
- cv.create_image(int(top[0]), int(top[1]), image=photo,
1653
- anchor="nw", tags=("panel", "slab"))
1654
- else:
1655
- round_rect(cv, top[0], top[1], top[2], top[3],
1656
- max(8, int(SLAB_R * self.s)), fill=BG, outline="",
1657
- tags=("panel", "slab"))
1658
- cv.tag_lower("panel")
1659
- self._header_paint(top)
1660
- self._apply_collapsed()
1661
-
1662
- def _paint(self, event=None):
1663
- # **没 event 时以画布尺寸为准**:`root.winfo_height()` 在 `geometry()` 刚设完、
1664
- # 事件还没处理的那一帧返回的还是旧值 —— 拿它去重烘玻璃,裁出来就是一片 2px。
1665
- w = event.width if event else self.canvas.winfo_width()
1666
- h = event.height if event else self.canvas.winfo_height()
1667
- if w < 4 or h < 4:
1668
- return
1669
- if getattr(self, "_collapsed", False):
1670
- self._paint_collapsed(w, h)
1671
- return
1672
- # 拖动时窗口位置每变一次都会来一发 Configure,但尺寸没变 —— 这种纯粹"搬家"的
1673
- # 重绘没意义(内容一个像素都没动),玻璃交给 `_live_backdrop` 逐帧换。
1674
- if (getattr(self, "_drag", None) and self._painted_size == (w, h)
1675
- and not getattr(self, "_resizing", False)):
1676
- return
1677
- self._painted_size = (w, h)
1678
- self._apply_region()
1679
- self.canvas.delete("panel")
1680
- self._panel_item = None # 上面的 create_image 已经没了,下次重建
1681
- self._slab_items = None
1682
- self._ensure_blurred(w, h)
1683
- top, body, bot = self._layout(w, h)
1684
- if self.acrylic:
1685
- # 磨砂模式:**什么都不画**。canvas 的抠色被透明掉,露出 DWM 的 GPU 模糊层。
1686
- self._slab_paint(top, bot)
1687
- self._place_furniture(w, h)
1688
- self._reflow()
1689
- return
1690
- photo = self._panel_photo(w, h, body)
1691
- if photo is not None:
1692
- self._backdrop_photo = photo
1693
- self.canvas.create_image(0, 0, image=photo, anchor="nw",
1694
- tags=("panel", "backdrop"))
1695
- self._slab_paint(top, bot)
1696
- # **底板必须压在最下层**:它是一张整窗大小的图,晚一步创建就会盖住所有
1697
- # 已经画好的气泡("重排后只剩最新一条"这个 bug 就是这么来的)。
1698
- self.canvas.tag_lower("panel")
1699
- else:
1700
- # 兜底:没有 Pillow / 截不到屏时至少是一块圆角面板,不能整窗透明
1701
- round_rect(self.canvas, body[0], body[1], body[2], body[3], self.radius,
1702
- fill=BG, outline="", tags=("panel", "backdrop"))
1703
- self._place_furniture(w, h)
1704
- self._reflow()
1705
- # 折叠状态下重画出来的元素默认是 normal,得再藏一次
1706
- if getattr(self, "_collapsed", False):
1707
- self._apply_collapsed()
1708
-
1709
- def _place_furniture(self, w, h):
1710
- """摆标题栏和输入栏。**它们全部是画布上的元素**,没有一个 Frame/Label。
1711
-
1712
- 一版用 `tk.Frame` 装标题和按钮,而 Tk 的 Frame 必须填不透明底色 —— 于是
1713
- 三块玻璃里最上面那块永远是死黑,玻璃感从第一眼就塌了。现在文字、按钮、
1714
- 状态点全是 `create_text` / 画片,只有 `Entry` 留成真控件(它只能实心,
1715
- 正好塞进"内凹槽"里,看起来就是设计的一部分)。
1716
- """
1717
- s = self.s
1718
- cv = self.canvas
1719
- top, body, bot = self._layout(w, h)
1720
-
1721
- # ---- 标题栏 ----
1722
- self._header_paint(top)
1723
- # ---- 输入栏 ----
1724
- self._composer_paint(bot)
1725
-
1726
- self._view_top = body[1] + int(8 * s)
1727
- self._view_bot = body[3] - int(8 * s)
1728
- self._view_h = max(1, self._view_bot - self._view_top)
1729
-
1730
- def on_glass_fill(self, x, y, light=TEXT, dark="#0b0e13", thresh=148):
1731
- """**字压在这块玻璃上该用什么颜色**:取那个点的背景亮度,亮就翻成深色字。
1732
-
1733
- 取自 PR #15 的"逐字适配背后明暗",但**按整段取一次样**(#15 是每个字一个
1734
- canvas item,滚动长列表时 item 数翻倍)。玻璃上文字的明暗在几十像素内几乎
1735
- 不变,一个取样点就够 —— 成本 1 次 getpixel。
1736
-
1737
- 为什么要它:我们的 `plate()` 会把底板压暗(平均亮度压到 84 以下),所以白字
1738
- 大多数时候都读得清;**但标题条/输入条压在亮网页上时那片玻璃会被洗白**,
1739
- 白字就糊了。这一步只在这种时候把字翻成深色。
1740
- """
1741
- try:
1742
- blur = getattr(self, "_blurred", None)
1743
- if blur is None:
1744
- return light
1745
- w, h = blur.size
1746
- px = blur.getpixel((max(0, min(w - 1, int(x))), max(0, min(h - 1, int(y)))))
1747
- lum = 0.299 * px[0] + 0.587 * px[1] + 0.114 * px[2]
1748
- return dark if lum > thresh else light
1749
- except Exception:
1750
- return light
1751
-
1752
- # ---- 抓屏排除 ----
1753
- def _set_exclude(self, on):
1754
- """让本窗口**从屏幕捕获里消失**(`WDA_EXCLUDEFROMCAPTURE`)。
1755
-
1756
- 这样抓"自己背后"的时候不用把窗口 `-alpha` 设 0 再恢复 —— 那个来回会逼
1757
- DWM 把整个桌面重排两次,视频在播时最贵,肉眼就是"松手闪一下"。
1758
- 抓到的直接就是背后的桌面,不递归、不闪。
1759
-
1760
- 代价:**用户的截屏/录屏里看不到这个窗口**(录演示视频要关掉)。
1761
- `DSH_GLASS_WDA=0` 可关。取自 PR #15 的做法。
1762
- """
1763
- try:
1764
- import ctypes
1765
- import ctypes.wintypes as wt
1766
- fn = ctypes.windll.user32.SetWindowDisplayAffinity
1767
- fn.argtypes = [wt.HWND, wt.DWORD]
1768
- fn.restype = wt.BOOL
1769
- return bool(fn(self._hwnd(), 0x11 if on else 0))
1770
- except Exception:
1771
- return False
1772
-
1773
- # ---- 真毛玻璃底板 ----
1774
- def _hwnd(self):
1775
- """窗口句柄。**只能在窗口 map 之后拿** —— map 之前 `wm_frame()` 拿到的不是
1776
- 合成器正在用的那个窗口,挂上去的效果静默丢失(返回 True 但没反应)。"""
1777
- import ctypes.wintypes as wt
1778
- return wt.HWND(int(self.root.wm_frame(), 16))
1779
-
1780
- def _acrylic_late(self):
1781
- """窗口显示之后:挂磨砂 + 上圆角区域。两件事都必须在 map 之后做。"""
1782
- try:
1783
- self.root.update_idletasks()
1784
- except Exception:
1785
- pass
1786
- ok = self._apply_acrylic()
1787
- if os.environ.get("DSH_GLASS_DEBUG") == "1":
1788
- try:
1789
- print(f"[acrylic] frame={self.root.wm_frame()} ok={ok} "
1790
- f"mapped={self.root.winfo_ismapped()} "
1791
- f"size={self.root.winfo_width()}x{self.root.winfo_height()}",
1792
- file=sys.stderr, flush=True)
1793
- except Exception:
1794
- pass
1795
- if not ok:
1796
- self.acrylic = False # 挂不上就干净地退回抓屏模式,别留个半成品
1797
- return
1798
- self._apply_region()
1799
- # 磨砂层是矩形,canvas 的抠色抠不动它 → 圆角只能靠窗口区域
1800
- self._paint()
1801
-
1802
- def _apply_region(self):
1803
- """把窗口裁成**三块分离的圆角玻璃片**:顶栏 / 主体 / 输入栏。
1804
-
1805
- 这是整套实时透明的关键。`SetWindowRgn` 接受**不相连的多段区域**:
1806
- 只保留三块圆角矩形,它们之间的缝不在窗口区域内 → 窗口在那里"不存在"
1807
- → 缝里透出的是**未经任何处理的桌面**,而三块里是染过色的透明层。
1808
-
1809
- 几何直接取 `_layout(w, h)` —— 就是抓屏玻璃版一直在用的那三个矩形,
1810
- 所以"布局"和原来一模一样,只是透明层换成了 DWM 实时合成。
1811
-
1812
- ⚠️ 三个必须遵守的点(都踩过):
1813
- 1. **只能在窗口 map 之后调**(`__init__` 里 `winfo_width()` 返回 1 → 裁成 2×2 黑块)。
1814
- 2. **必须先把所有段合成完,最后只调一次 `SetWindowRgn`**:成功后句柄归系统所有,
1815
- 再拿它做 `CombineRgn` 会静默失败(表现就是"设了多段,出来还是一整块")。
1816
- 3. GDI 句柄是 64 位,`CreateRoundRectRgn` 的 `restype` 不声明成 `c_void_p`
1817
- 会被截断成 32 位 —— 同样返回 True、同样没效果。
1818
- """
1819
- if not self.acrylic:
1820
- return
1821
- try:
1822
- import ctypes
1823
- w = self.canvas.winfo_width()
1824
- h = self.canvas.winfo_height()
1825
- if w < 8 or h < 8:
1826
- return
1827
- collapsed = bool(getattr(self, "_collapsed", False))
1828
- top, body, bot = self._layout(w, h)
1829
- segs = [top] if collapsed else [top, body, bot]
1830
- key = (w, h, collapsed, tuple(int(v) for v in bot))
1831
- if getattr(self, "_region_size", None) == key:
1832
- return
1833
- self._region_size = key
1834
-
1835
- gdi, user = ctypes.windll.gdi32, ctypes.windll.user32
1836
- gdi.CreateRoundRectRgn.restype = ctypes.c_void_p
1837
- gdi.CreateRoundRectRgn.argtypes = [ctypes.c_int] * 6
1838
- gdi.CreateRectRgn.restype = ctypes.c_void_p
1839
- gdi.CreateRectRgn.argtypes = [ctypes.c_int] * 4
1840
- gdi.CombineRgn.argtypes = [ctypes.c_void_p, ctypes.c_void_p,
1841
- ctypes.c_void_p, ctypes.c_int]
1842
- gdi.DeleteObject.argtypes = [ctypes.c_void_p]
1843
- user.SetWindowRgn.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_bool]
1844
-
1845
- panel_r = max(8, 2 * self.radius) # 主体:外圈同心半径
1846
- slab_r = max(8, 2 * int(SLAB_R * self.s)) # 两条悬浮片小一档
1847
- out = gdi.CreateRectRgn(0, 0, 0, 0)
1848
- for i, (x1, y1, x2, y2) in enumerate(segs):
1849
- # 三条缝本来就是"没东西",别让区域外扩
1850
- x1, y1 = int(round(x1)), int(round(y1))
1851
- x2, y2 = int(round(x2)), int(round(y2))
1852
- if x2 - x1 < 4 or y2 - y1 < 4:
1853
- continue
1854
- d = slab_r if i != 1 else panel_r
1855
- part = gdi.CreateRoundRectRgn(x1, y1, x2, y2, d, d)
1856
- gdi.CombineRgn(out, out, part, 2) # RGN_OR
1857
- gdi.DeleteObject(part)
1858
- user.SetWindowRgn(self._hwnd(), out, True)
1859
- except Exception:
1860
- pass
1861
-
1862
- def _apply_acrylic(self):
1863
- """给窗口挂上 DWM 的**实时透明层**(`SetWindowCompositionAttribute`)。
1864
-
1865
- ## 为什么是 state 2,不是 3/4
1866
- | AccentState | 效果 | 能不能透出**清晰**背景 |
1867
- |---|---|---|
1868
- | 1 GRADIENT | 纯色 | ✗(完全实心,std 0.0) |
1869
- | **2 TRANSPARENTGRADIENT** | **只染色、不模糊** | ✓(实测 std 47.5,字边锐利) |
1870
- | 3 BLURBEHIND | 模糊 | ✗(std 1.8,糊成一片) |
1871
- | 4 ACRYLICBLURBEHIND | 磨砂 | ✗(std 1.8) |
1872
-
1873
- 用 2 的意义:背景**由 DWM 每帧合成**,我们一次屏都不截 —— 真正的零延迟半透明;
1874
- 而且背景是清晰的,不是糊的。抓屏那套 26.8Hz 的方案就是为了"透出背景",
1875
- 现在这条不要了(`DSH_GLASS_ACRYLIC=0` 仍可退回抓屏)。
1876
- `DSH_GLASS_ACCENT_STATE` 可改档(想磨砂就设 4)。
1877
- """
1878
- try:
1879
- import ctypes
1880
- import ctypes.wintypes as wt
1881
-
1882
- class ACCENT(ctypes.Structure):
1883
- _fields_ = [("AccentState", ctypes.c_int), ("AccentFlags", ctypes.c_int),
1884
- ("GradientColor", ctypes.c_uint), ("AnimationId", ctypes.c_int)]
1885
-
1886
- class WCAD(ctypes.Structure):
1887
- _fields_ = [("Attribute", ctypes.c_int),
1888
- ("Data", ctypes.POINTER(ACCENT)),
1889
- ("SizeOfData", ctypes.c_size_t)]
1890
-
1891
- # ABGR。**alpha 就是"这层颜色盖多厚"**:0xB4(180)=70% 几乎看不见背景,
1892
- # 0x8C(140)=55% 能在染色后仍分辨出背后的画面,同时白字读得清。
1893
- tint = int(os.environ.get("DSH_GLASS_ACRYLIC_TINT") or "0x8C121014", 0)
1894
- try:
1895
- state = int(os.environ.get("DSH_GLASS_ACCENT_STATE") or 2)
1896
- except Exception:
1897
- state = 2
1898
- policy = ACCENT(state, 2, tint & 0xFFFFFFFF, 0)
1899
- data = WCAD(19, ctypes.pointer(policy), ctypes.sizeof(policy))
1900
- hwnd = wt.HWND(int(self.root.wm_frame(), 16))
1901
- ok = bool(ctypes.windll.user32.SetWindowCompositionAttribute(hwnd, ctypes.byref(data)))
1902
- if ok:
1903
- # 这层自带透明,再叠整窗 alpha 会发灰
1904
- try:
1905
- self.root.attributes("-alpha", 1.0)
1906
- except Exception:
1907
- pass
1908
- # **圆角和"三块分离"都交给 `_apply_region()`**:这一层是整窗矩形的,
1909
- # canvas 的 `-transparentcolor` 抠不动 DWM 画上去的像素 —— 抠色只对
1910
- # "我们自己画的内容"有效。但**绝不能在 `__init__` 里设区域**
1911
- # (那次把窗口裁成 2×2 黑块、鼠标都点不进去)。
1912
- return ok
1913
- except Exception:
1914
- return False
1915
-
1916
- def _dpi_k(self):
1917
- """DPI 系数(首算后缓存):拖动的每一帧都要用,别每次去问 Windows"""
1918
- k = getattr(self, "_dpik", None)
1919
- if k is None:
1920
- k = self._dpi_scale()
1921
- self._dpik = k
1922
- return k
1923
-
1924
- def _dpi_scale(self):
1925
- """Tk 坐标 → 物理像素的倍数(`ImageGrab` 要的单位)。
1926
-
1927
- **运行期实测,不写死也不猜**:本机实测 `winfo_width()` = 701 = `GetWindowRect`
1928
- 宽度 = 701、`GetDpiForWindow` = 144,三者一致 —— 说明 Tk 在这个 DPI-aware 进程里
1929
- 报的**就是物理像素**,再乘 1.5 会把截图区域送到窗口外去(表现为"模糊图跟窗口对不上",
1930
- 但因为糊过又压暗过,肉眼很难发现,只会觉得"背景怪怪的")。
1931
- 不感知 DPI 的环境里 Tk 报逻辑像素,这时才需要乘 —— 比一次宽度就知道是哪种。
1932
- """
1933
- try:
1934
- import ctypes
1935
- import ctypes.wintypes as wt
1936
- hwnd = int(self.root.wm_frame(), 16)
1937
- rect = wt.RECT()
1938
- ctypes.windll.user32.GetWindowRect(hwnd, ctypes.byref(rect))
1939
- win_w = rect.right - rect.left
1940
- tk_w = self.root.winfo_width()
1941
- if win_w > 4 and tk_w > 4:
1942
- return max(0.5, min(4.0, win_w / float(tk_w)))
1943
- except Exception:
1944
- pass
1945
- return 1.0
1946
-
1947
- def _window_rect(self, size=None):
1948
- """窗口在屏幕上的矩形(`ImageGrab` 的单位)。
1949
-
1950
- `size` 显式传入时用它,**不读 `winfo_width()`** —— 窗口处于 `withdraw`
1951
- 状态时 `winfo_*` 全是 1,开窗第一次截图会截出一张 1×1 的图(缩放到全屏
1952
- 以后是一块纯色,看起来就像"毛玻璃没生效")。
1953
- """
1954
- try:
1955
- self.root.update_idletasks()
1956
- if size:
1957
- w, h = int(size[0]), int(size[1])
1958
- x, y = int(self.x), int(self.y)
1959
- else:
1960
- x, y = self.root.winfo_rootx(), self.root.winfo_rooty()
1961
- w, h = self.root.winfo_width(), self.root.winfo_height()
1962
- if w < 4 or h < 4:
1963
- return None
1964
- k = self._dpi_scale()
1965
- return int(x * k), int(y * k), int(w * k), int(h * k)
1966
- except Exception:
1967
- return None
1968
-
1969
- def _phys_screen(self):
1970
- """屏幕的**物理**像素尺寸。mss 给物理(2560×1600),ImageGrab 在 DPI-unaware
1971
- 进程里给逻辑(1707×1067)—— 两者不能混用,否则玻璃取的位置会整体偏掉。"""
1972
- cached = getattr(self, "_phys_screen_cache", None)
1973
- if cached is not None:
1974
- return cached
1975
- size = None
1976
- if HAVE_MSS:
1977
- try:
1978
- factory = getattr(_mss, "MSS", None) or getattr(_mss, "mss")
1979
- with factory() as g:
1980
- m = g.monitors[1]
1981
- size = (m["width"], m["height"])
1982
- except Exception:
1983
- size = None
1984
- if size is None:
1985
- size = (self.root.winfo_screenwidth(), self.root.winfo_screenheight())
1986
- self._phys_screen_cache = size
1987
- return size
1988
-
1989
- def _win_phys(self, pad=0):
1990
- """窗口在屏幕上的**物理**矩形,可选外扩 `pad`(夹在屏幕内)。"""
1991
- k = self._dpi_k()
1992
- sw, sh = self._phys_screen()
1993
- x, y = int(self.x * k), int(self.y * k)
1994
- w, h = int(self.w * k), int(self.h * k)
1995
- left = max(0, x - pad)
1996
- top = max(0, y - pad)
1997
- right = min(sw, x + w + pad)
1998
- bottom = min(sh, y + h + pad)
1999
- return left, top, max(1, right - left), max(1, bottom - top)
2000
-
2001
- def _stage(self, force=False):
2002
- """整块"已经糊好"的底板,**带留白**,1/4 分辨率。返回 (small, (sx,sy,sw,sh), at)。
2003
-
2004
- 为什么带留白:拖窗/缩放后每停一次手都要重算一次底板,而截屏 + 糊一次是
2005
- 70~90ms(还要先把窗口 `-alpha` 拉到 0 让 DWM 重排)。这里一次把"窗口 + 四周
2006
- 340px"一起处理掉,之后只要窗口还在这个范围里,取底板就是**裁一刀**(1~2ms)。
2007
- 留白 1.5 秒内有效 —— 背后可能是正在播放的视频,太久就真的不一样了。
2008
-
2009
- 为什么在 1/4 上把 blur/saturate/refract 全做完:这些都是低频处理,缩着做
2010
- 和放大做看不出差别,但成本差 16 倍;最后只把**窗口那一块**放大回去。
2011
- """
2012
- now = time.time()
2013
- cur = getattr(self, "_stage_cache", None)
2014
- if cur is not None and not force:
2015
- return cur
2016
- # **整屏一张**(不是"窗口 + 留白"):留白再大也有拖出去的时候,一出界就要
2017
- # 重新截屏 → 那一下就是"松手卡一下、闪一下"。整屏 1/4 分辨率只有 640×400,
2018
- # 一次截屏 + 缩 + 糊不到 200ms,而且**只在开窗时发生一次**(那时窗口是
2019
- # withdraw 的,看不见)—— 之后无论拖到哪儿都是裁一刀。
2020
- # **只抓"窗口 + 200px 留白"**,不抓整屏:本机实测整屏 41.6ms、
2021
- # 这块区域 11.8ms(2560×1600 屏幕 / 700×808 窗口),快 3.5 倍。
2022
- # 留白够遮住松手前的几像素漂移,真拖出去了 `_grab_backdrop` 会把缺的补黑。
2023
- PAD = 200
2024
- sx, sy, sw, sh = self._win_phys(PAD)
2025
- shot = None
2026
- if HAVE_MSS:
2027
- try:
2028
- factory = getattr(_mss, "MSS", None) or getattr(_mss, "mss")
2029
- with factory() as grabber:
2030
- raw = grabber.grab({"left": sx, "top": sy, "width": sw, "height": sh})
2031
- shot = Image.frombytes("RGB", raw.size, raw.bgra, "raw", "BGRX")
2032
- except Exception:
2033
- shot = None
2034
- if shot is None:
2035
- # 没有 mss:ImageGrab 在这个 DPI-unaware 进程里要**逻辑坐标**
2036
- k = self._dpi_k()
2037
- shot = ImageGrab.grab(bbox=(sx / k, sy / k, (sx + sw) / k, (sy + sh) / k),
2038
- all_screens=True)
2039
- small = build_stage(shot, sw, sh, self.s)
2040
- self._stage_cache = (small, (sx, sy, sw, sh), now)
2041
- return self._stage_cache
2042
-
2043
- def _grab_backdrop(self, size=None, force_stage=False):
2044
- """取窗口那一块底板:**从带留白的 stage 里裁 + 放大**,不做截屏本身。
2045
-
2046
- **调用前窗口必须不可见**(首次开窗是 withdraw,之后靠 `-alpha 0`),否则会把
2047
- 自己截进去。缓存命中时调用方根本不需要隐藏窗口(见 `_refresh_backdrop`)。
2048
-
2049
- **这里只负责"糊",不负责"压暗"**:压暗交给每块玻璃自己算(`plate()`),
2050
- 因为它要按**自己那块**的平均亮度来定 —— 标题栏可能压在白网页上、主体压在
2051
- 暗场景上,一个全窗统一的不透明度必然有一头是错的。
2052
- """
2053
- if not HAVE_PIL or not self.rounded:
2054
- return None
2055
- rect = self._window_rect(size)
2056
- if rect is None:
2057
- return None
2058
- x, y, w, h = rect
2059
- try:
2060
- if size:
2061
- lw, lh = int(size[0]), int(size[1])
2062
- else:
2063
- try:
2064
- lw, lh = self.root.winfo_width(), self.root.winfo_height()
2065
- except Exception:
2066
- lw, lh = w, h
2067
- lw, lh = max(4, int(lw)), max(4, int(lh))
2068
- staged = self._stage(force=force_stage)
2069
- if staged is None:
2070
- return None
2071
- small, (sx, sy, sw, sh), _at = staged
2072
- kx = small.size[0] / float(max(1, sw))
2073
- ky = small.size[1] / float(max(1, sh))
2074
- # 窗口可能有一截在屏幕外(贴边/半出界):stage 里没有那块画面,裁完贴回一张
2075
- # 同尺寸的图里,缺的部分留黑 —— 那截本来就不在屏幕上,用户看不见。
2076
- cx0 = int(round((x - sx) * kx))
2077
- cy0 = int(round((y - sy) * ky))
2078
- cx1 = cx0 + max(1, int(round(w * kx)))
2079
- cy1 = cy0 + max(1, int(round(h * ky)))
2080
- sw0, sh0 = small.size
2081
- box = (max(0, min(cx0, sw0 - 1)), max(0, min(cy0, sh0 - 1)),
2082
- max(1, min(cx1, sw0)), max(1, min(cy1, sh0)))
2083
- piece = small.crop(box)
2084
- full = Image.new("RGBA", (max(1, cx1 - cx0), max(1, cy1 - cy0)), (0, 0, 0, 255))
2085
- full.paste(piece, (box[0] - cx0, box[1] - cy0))
2086
- # 拖动时用 NEAREST:底板已经是 1/8 模糊图,最近邻放大和双线性肉眼分不出,
2087
- # 但 700×808 的缩放从 5.7ms 降到 1.9ms(拖动是 60Hz,这一项就是 34% 占用)。
2088
- interp = Image.NEAREST if getattr(self, "_drag", None) else Image.BILINEAR
2089
- img = full.resize((lw, lh), interp)
2090
- self._blurred = img.convert("RGBA")
2091
- self._glass_v += 1
2092
- # 只作废"吃底板"的那几片(面板/悬浮条):气泡的缓存键里带的是 `_chat_v`,
2093
- # 这里要是整张清掉,拖动时每帧都要把 6 条气泡重烘一遍(约 6ms/帧)。
2094
- for cache in (self._plates, self._plate_imgs):
2095
- for k in [k for k in cache if k[0] in ("panel", "slab", "__panel__")]:
2096
- cache.pop(k, None)
2097
- # 气泡玻璃只在"挪得很远"时才作废(见 `chat_glass_ver`)
2098
- ox, oy = getattr(self, "_last_origin", (None, None)) or (None, None)
2099
- if ox is None or abs(x - ox) + abs(y - oy) > 260:
2100
- self._chat_v += 1
2101
- self._last_origin = (x, y)
2102
- return self._blurred
2103
- except Exception:
2104
- return None
2105
-
2106
- def _shot_usable(self, x, y, w, h):
2107
- """缓存的 stage 还能不能盖住这个窗口矩形(1.5 秒内有效)"""
2108
- cur = getattr(self, "_stage_cache", None)
2109
- if cur is None:
2110
- return False
2111
- _img, (sx, sy, sw, sh), _at = cur
2112
- # **只要求"有重叠"**,不要求完全包含:窗口贴屏幕边时总有一截在外面,
2113
- # 以前这里判"必须整块在 stage 里",于是每次贴边松手都回退去重新截屏 —— 一闪。
2114
- return x + w > sx and y + h > sy and x < sx + sw and y < sy + sh
2115
-
2116
- def _refresh_backdrop(self, hide_first=False, force_stage=False):
2117
- """重截底板并重绘。`hide_first=True` 时先把自己透明掉(窗口已在显示状态)。"""
2118
- if not HAVE_PIL or not self.rounded:
2119
- return
2120
- prev_alpha = None
2121
- try:
2122
- # **能复用带留白的缓存截图时就不隐藏窗口**:`-alpha` 来回切会逼 DWM 把整个
2123
- # 桌面重排两次(视频在播时尤其贵),而缓存命中时根本不需要截自己。
2124
- rect = self._window_rect((self.w, self.h))
2125
- # `self._excluded`(WDA 生效)时**永远不用隐藏**:窗口本来就不在捕获结果里
2126
- if (hide_first and not getattr(self, "_excluded", False)
2127
- and (force_stage or not (rect and self._shot_usable(*rect)))):
2128
- prev_alpha = self.root.attributes("-alpha")
2129
- self.root.attributes("-alpha", 0.0)
2130
- self.root.update_idletasks()
2131
- self.root.update()
2132
- self.backdrop = self._grab_backdrop((self.w, self.h), force_stage=force_stage)
2133
- finally:
2134
- if prev_alpha is not None:
2135
- try:
2136
- self.root.attributes("-alpha", prev_alpha)
2137
- except Exception:
2138
- pass
2139
- self._paint()
2140
-
2141
- def _request_backdrop(self):
2142
- """拖动/缩放结束后延迟重截 —— 每动一下都截会卡,也没意义"""
2143
- if not HAVE_PIL or not self.rounded:
2144
- return
2145
- try:
2146
- if self._backdrop_job:
2147
- self.root.after_cancel(self._backdrop_job)
2148
- except Exception:
2149
- pass
2150
- self._backdrop_job = self.root.after(420, self._backdrop_settle)
2151
-
2152
- def _backdrop_settle(self):
2153
- self._backdrop_job = None
2154
- # 先试"不隐身"的写法:stage 还盖得住就只裁一次(几十毫秒内、无闪烁)。
2155
- # 只有真的拖出了留白范围,才值得为它把窗口藏一帧去截屏。
2156
- if self._live_backdrop():
2157
- # 拖动本身永远是即时的;只有"底板已经 8 秒没更新"才值得为它藏一帧重截,
2158
- # 否则一直用这一张。连续拖动时前面几帧都是新的,根本不会触发。
2159
- at = self._stage_cache[2] if self._stage_cache else 0
2160
- if time.time() - at > 8.0:
2161
- self._refresh_backdrop(hide_first=True, force_stage=True)
2162
- return
2163
- self._refresh_backdrop(hide_first=True, force_stage=True)
2164
-
2165
- def _build_header(self):
2166
- """标题栏:**全部画在画布上**,一个 Frame 都不用。
2167
-
2168
- 一版是 `tk.Frame(bg="#222836")` + 几个 Label。Frame 必须填不透明底色,于是
2169
- 最上面那块玻璃永远是一根死黑条 —— 玻璃感从第一眼就塌了。现在状态点、名字、
2170
- 条数、两个图标按钮都是画布元素,底下的玻璃该透还是透。
2171
-
2172
- 名字**可以改**(用户要把它改成自己的叫法):点标题就地变输入框,回车/失焦存进
2173
- `~/.dsh/watch-window.json` 的 `name`。
2174
- """
2175
- self._head_rect = (0, 0, 1, 1)
2176
- self._hint_text = ""
2177
- self._count = 0
2178
- self.dot_fg = ACCENT
2179
- self._title_item = None
2180
- self._editing = False
2181
-
2182
- # 改名用的 Entry:平时**不挂在画布上**(只在自己触发时 create_window)
2183
- self.title_entry = tk.Entry(self.canvas, bg="#1b1f27", fg=TEXT, relief="flat",
2184
- bd=0, insertbackground=TEXT,
2185
- font=self._f(10, "bold"), highlightthickness=0,
2186
- width=10)
2187
- self.title_entry.bind("<Return>", self._commit_title)
2188
- self.title_entry.bind("<Escape>", lambda _e: self._cancel_title())
2189
- self.title_entry.bind("<FocusOut>", lambda _e: self._commit_title(None))
2190
-
2191
- self.btn_close = GlassButton(self, "hd-close", "✕", kind="icon", fg=TEXT,
2192
- command=self.close, size=9, group="hdr")
2193
- self.btn_collapse = GlassButton(self, "hd-collapse", "▾", kind="icon", fg=TEXT,
2194
- command=self.toggle_collapse, size=9, group="hdr")
2195
- self.canvas.tag_bind("hd-title", "<Button-1>", self._edit_title)
2196
-
2197
- def _header_paint(self, top):
2198
- """重画标题栏(位置随窗口尺寸变,所以每次都整块重画,成本可忽略)"""
2199
- cv = self.canvas
2200
- cv.delete("header-art")
2201
- s = self.s
2202
- x1, y1, x2, y2 = top
2203
- self._head_rect = top
2204
- cy = (y1 + y2) / 2.0
2205
- cyi = int(round(cy))
2206
-
2207
- # ---- 右侧两个图标井(28×28 的圆,悬停才浮出玻璃)----
2208
- btn = int(28 * s)
2209
- pad = int(10 * s)
2210
- gap = int(4 * s)
2211
- rx2 = x2 - pad
2212
- self.btn_close.layout((rx2 - btn, cy - btn / 2, rx2, cy + btn / 2))
2213
- cx2 = rx2 - btn - gap
2214
- self.btn_collapse.layout((cx2 - btn, cy - btn / 2, cx2, cy + btn / 2))
2215
-
2216
- # ---- 状态点:一个实心点 + 一圈很淡的光环 ----
2217
- # 纯色圆点在玻璃上像贴纸;带光环才像"亮着的东西"。
2218
- dx = x1 + int(17 * s)
2219
- r = max(2.0, 3.2 * s)
2220
- cv.create_oval(dx - r * 2.1, cy - r * 2.1, dx + r * 2.1, cy + r * 2.1,
2221
- outline="", fill="", width=1,
2222
- tags=("hdr", "header-art"))
2223
- cv.create_oval(dx - r * 2.1, cy - r * 2.1, dx + r * 2.1, cy + r * 2.1,
2224
- outline=_mix(self.dot_fg, HEAD_BG, 0.62), width=max(1, int(s)),
2225
- tags=("hdr", "header-art"))
2226
- cv.create_oval(dx - r, cy - r, dx + r, cy + r, fill=self.dot_fg, outline="",
2227
- tags=("hdr", "header-art"))
2228
-
2229
- # ---- 名字 + 条数 + 状态 ----
2230
- tx = dx + r * 2.4 + int(7 * s)
2231
- t = text_on_glass(cv, tx, cyi, self.name, font=self._f(10, "bold"),
2232
- fill=self.on_glass_fill(tx, cyi), anchor="w",
2233
- tags=("hdr", "header-art", "hd-title"),
2234
- offset=max(1, int(s)))
2235
- box = cv.bbox(t) or (int(tx), cyi, int(tx) + int(40 * s), cyi)
2236
- nx = box[2] + int(7 * s)
2237
- if self._count > 0:
2238
- c = cv.create_text(nx, cyi + max(1, int(s)), text=f"{self._count} 条",
2239
- font=self._f(8.5), fill=DIM, anchor="w",
2240
- tags=("hdr", "header-art"))
2241
- box = cv.bbox(c) or box
2242
- nx = box[2] + int(7 * s)
2243
- if self._hint_text:
2244
- cv.create_text(nx, cyi + max(1, int(s)), text=self._hint_text,
2245
- font=self._f(8.5), fill=DANGER, anchor="w",
2246
- tags=("hdr", "header-art"))
2247
- # ---- 改名 ----
2248
- def _edit_title(self, _event=None):
2249
- """标题就地变输入框(不弹对话框 —— 那会把置顶窗口挡掉一半)"""
2250
- if getattr(self, "_editing", False):
2251
- return "break"
2252
- self._editing = True
2253
- s = self.s
2254
- top = self._head_rect
2255
- self.title_entry.delete(0, "end")
2256
- self.title_entry.insert(0, self.name)
2257
- if self._title_item is None:
2258
- self._title_item = self.canvas.create_window(
2259
- top[0] + int(26 * s), (top[1] + top[3]) / 2.0,
2260
- window=self.title_entry, anchor="w", width=int(120 * s))
2261
- self.title_entry.focus_set()
2262
- self.title_entry.select_range(0, "end")
2263
- return "break"
2264
-
2265
- def _commit_title(self, _event=None):
2266
- # **用显式标志,不用 `winfo_ismapped()`**:widget 刚挂上画布那一帧
2267
- # ismapped 还是 False,用户输入快一点回车就被这行吞掉(实测)。
2268
- if not getattr(self, "_editing", False):
2269
- return
2270
- self._editing = False
2271
- text = self.title_entry.get().strip()
2272
- if self._title_item is not None:
2273
- self.canvas.delete(self._title_item)
2274
- self._title_item = None
2275
- if text and text != self.name:
2276
- self.name = text[:24]
2277
- self.root.title(self.name)
2278
- write_config({"name": self.name})
2279
- self._header_paint(self._head_rect)
2280
- return "break"
2281
-
2282
- def _cancel_title(self):
2283
- self._editing = False
2284
- if self._title_item is not None:
2285
- self.canvas.delete(self._title_item)
2286
- self._title_item = None
2287
- self._header_paint(self._head_rect)
2288
- return "break"
2289
-
2290
- def _reflow(self):
2291
- """重排所有消息并重画(窗口尺寸变化 / 新消息 / 滚动都走这里)。
2292
-
2293
- 自绘列表的老问题:先要知道每条多高才能算位置,所以分两遍 ——
2294
- `measure()` 只测不画,`paint()` 才落 item。宽度没变就复用上次的测量结果,
2295
- 避免每次滚一下都把 60 条消息重新测一遍。
2296
- """
2297
- cv = self.canvas
2298
- w = cv.winfo_width()
2299
- if w < 4:
2300
- return
2301
- if getattr(self, "_collapsed", False) or self._view_h < 8:
2302
- # 折叠时视口高度是 0,以前每条都满足"比视口还高"那个分支 → 全部照画,
2303
- # 而且是拿折叠后那张 102px 高的底板去裁 → 每条气泡烘出一片 2px 的玻璃。
2304
- for it in self._items:
2305
- cv.delete(it.tag)
2306
- self._total_h = 0
2307
- return
2308
- avail = max(120, w - 2 * self.pad)
2309
- top, view_h = self._view_top, self._view_h
2310
-
2311
- # **每条都不能高过视口**:见 `Bubble.measure` 的 `max_h`。
2312
- # 视口还没量出来(首帧 `_view_h` 是 1)时不限制,否则会把所有气泡截成一行。
2313
- max_h = (view_h - 2) if view_h >= 80 else 0
2314
- total = 0
2315
- for it in self._items:
2316
- key = (avail, max_h)
2317
- if getattr(it, "_mkey", None) != key:
2318
- it.measure(cv, avail, max_h)
2319
- it._mkey = key
2320
- total += it.h
2321
- self._total_h = total
2322
-
2323
- # 贴底逻辑:内容比视口短就顶对齐;长了就滚到最底(新消息来了要看得到)
2324
- max_scroll = max(0, total - view_h)
2325
- self._scroll = max(0, min(self._scroll, max_scroll))
2326
- y = top - self._scroll
2327
-
2328
- x0 = self.pad
2329
- # **边框淡出带**:卡在视口边上的消息按"离边多远"给不透明度,滚进来是渐显、
2330
- # 滚出去是渐隐。以前是"完整可见才画、否则直接删",于是消息一跨过边界就
2331
- # 整块蹦出来/消失(用户说的"闪现")—— 画布没法裁剪,只能靠透明度接上。
2332
- band = max(12.0, 30.0 * self.s)
2333
- view_h_all = self._view_bot - top
2334
- # **到头的那一侧不要淡出**:滑到最底时最后一条正好贴着下沿,若还按"离边多远"
2335
- # 算,它就永远只剩一成不透明度 —— 最新的一条反而是最看不清的一条(真踩到了)。
2336
- at_top = self._scroll <= 0.5
2337
- at_bottom = self._scroll >= max_scroll - 0.5
2338
- for it in self._items:
2339
- y2 = y + it.h
2340
- if it.h > view_h_all:
2341
- # 比视口还高的一条(超长台词):不能按"完整可见"判,否则永远不画。
2342
- # **但它也不能从视口外面开始画** —— 玻璃是半透明的,从上面画起就会
2343
- # 盖住标题栏,用户看到的就是"字顶到标题栏里去了"。
2344
- # 画布裁不了,所以至少把起点夹进视口:顶部永远不越过 `top`。
2345
- it.paint(cv, x0, min(y, top), avail, 1.0)
2346
- elif y >= top - 1 and y2 <= self._view_bot + 1:
2347
- f_top = 1.0 if at_top else min(1.0, (y - top) / band)
2348
- f_bot = 1.0 if at_bottom else min(1.0, (self._view_bot - y2) / band)
2349
- it.paint(cv, x0, y, avail, max(0.0, min(f_top, f_bot)))
2350
- else:
2351
- cv.delete(it.tag)
2352
- y = y2
2353
- self._draw_scrollbar()
2354
- # **层级重排**:消息是后画的,会盖住玻璃片和标题栏。这里按"从下往上"的顺序
2355
- # 重新提一遍:片 → 标题栏 → 输入栏 → 滚动条。少提一层就会看到消息从标题栏
2356
- # 里穿出来。
2357
- # 顺序有讲究:填槽(field)必须在"片"之后、"控件"之前 ——
2358
- # 片先提上来会把输入槽整个盖掉(表现就是"输入框没有圆角",其实连底都没画上)。
2359
- for tag in ("slab", "field", "hdr", "cmp", "sbar"):
2360
- cv.tag_raise(tag)
2361
-
2362
- def _draw_scrollbar(self):
2363
- """细滚动条:只在真的滚得动时出现(原生 Scrollbar 太丑)"""
2364
- cv = self.canvas
2365
- cv.delete("sbar")
2366
- if self._total_h <= self._view_h:
2367
- return
2368
- s = self.s
2369
- # **放在主体玻璃外面的留白里**(不在消息区里):一进内容区就会和气泡抢地方,
2370
- # 也会挡住台词最后一个字。和输入栏一样,它是"浮在窗口上的一件东西",
2371
- # 不属于那块玻璃。
2372
- w = cv.winfo_width()
2373
- bw = max(3, int(3.4 * s))
2374
- x = w - self.out + int(6 * s)
2375
- frac = self._view_h / self._total_h
2376
- thumb_h = max(int(26 * s), self._view_h * frac)
2377
- t = self._scroll / max(1, self._total_h - self._view_h)
2378
- y0 = self._view_top + t * (self._view_h - thumb_h)
2379
- # Canvas 没有 alpha,只能挑一个"压在深色和浅色上都看得见"的中性灰
2380
- round_rect(cv, x, y0, x + bw, y0 + thumb_h, bw / 2.0,
2381
- fill="#8d95a4", outline="", tags="sbar")
2382
-
2383
- def _at_bottom(self):
2384
- return self._scroll >= max(0, self._total_h - self._view_h) - 2
2385
-
2386
- def _to_bottom(self):
2387
- self._scroll = max(0, self._total_h - self._view_h)
2388
- self._reflow()
2389
-
2390
- def _scroll_to(self, target, steps=5):
2391
- """滚动补间:5 帧 × 16ms 走完。
2392
-
2393
- **一格格硬跳就是"闪现"的另一半原因**:滚轮一次 60px,消息要么在、要么不在,
2394
- 边缘淡出根本没机会表现。补间以后每帧只挪十几像素,淡出带才真的"带"。
2395
- """
2396
- target = max(0, min(max(0, self._total_h - self._view_h), target))
2397
- start = self._scroll
2398
- if abs(target - start) < 1:
2399
- return
2400
- try:
2401
- if getattr(self, "_scroll_job", None):
2402
- self.root.after_cancel(self._scroll_job)
2403
- except Exception:
2404
- pass
2405
- self._scroll_job = None
2406
-
2407
- def step(i):
2408
- self._scroll_job = None
2409
- t = i / float(steps)
2410
- self._scroll = start + (target - start) * (1.0 - (1.0 - t) ** 2)
2411
- self._reflow()
2412
- if i < steps:
2413
- self._scroll_job = self.root.after(16, lambda: step(i + 1))
2414
-
2415
- step(1)
2416
-
2417
- def _on_wheel(self, event):
2418
- if self._total_h <= self._view_h:
2419
- return "break"
2420
- step = int(30 * self.s)
2421
- delta = -1 if event.delta > 0 else 1
2422
- self._scroll_to(self._scroll + delta * step)
2423
- return "break"
2424
-
2425
- def _clear_empty(self):
2426
- if self.empty is not None:
2427
- try:
2428
- self._items.remove(self.empty)
2429
- except ValueError:
2430
- pass
2431
- self.canvas.delete(self.empty.tag)
2432
- self.empty = None
2433
-
2434
- def _show_empty(self):
2435
- if self.empty is not None or self._items:
2436
- return
2437
- self.empty = Meta("在这里跟它说话 · 回车发送", self.opt, center=True)
2438
- self._items.append(self.empty)
2439
- self._reflow()
2440
-
2441
- def _add_bubble(self, role, text, stamp):
2442
- stick = self._at_bottom()
2443
- self._clear_empty()
2444
- bubble = Bubble(role, text, stamp, self.opt, self)
2445
- bubble._anim = 0.0 # 新来的从"没有"开始,历史回放不走这一套
2446
- self._items.append(bubble)
2447
- self._count = getattr(self, "_count", 0) + 1
2448
- if stick:
2449
- self._scroll = 10 ** 9 # 让 _reflow 夹到最底
2450
- self._reflow()
2451
- self._header_paint(self._head_rect)
2452
- self._animate_in(bubble)
2453
-
2454
- def _animate_in(self, bubble, steps=8, delay=24):
2455
- # 两个旋钮留出来是给"手感"调参用的(和 GLASS_* 一样);正常不用动
2456
- try:
2457
- steps = max(2, int(os.environ.get("DSH_WATCH_ANIM_STEPS") or steps))
2458
- delay = max(8, int(os.environ.get("DSH_WATCH_ANIM_DELAY") or delay))
2459
- except Exception:
2460
- pass
2461
- """新气泡入场:约 200ms,从"低 10px + 淡"浮到位。
2462
-
2463
- tkinter 没有补间动画,Canvas 的 item 也没有透明度可调 —— 只能每帧重新合成
2464
- 一张淡一点的玻璃图、再挪一下位置。8 帧 × 24ms 的节奏,眼睛能看清"渐变",
2465
- 又不至于让台词比声音晚太多(陪看是实时读的,动画一长就变成不同步)。
2466
- """
2467
- if not self.glass_ready():
2468
- bubble._anim = 1.0
2469
- return
2470
- prev = getattr(self, "_anim_bubble", None)
2471
- if prev is not None and prev is not bubble:
2472
- # 上一条还在飘就直接落地,别两条一起晃
2473
- prev._anim = 1.0
2474
- try:
2475
- prev.repaint(self.canvas)
2476
- except Exception:
2477
- pass
2478
- self._anim_bubble = bubble
2479
-
2480
- def step(i):
2481
- if bubble not in self._items:
2482
- return
2483
- t = i / float(steps)
2484
- bubble._anim = 1.0 - (1.0 - t) ** 3 # ease-out:起步快、收尾稳
2485
- try:
2486
- bubble.repaint(self.canvas)
2487
- except Exception:
2488
- return
2489
- if i < steps:
2490
- self.root.after(delay, lambda: step(i + 1))
2491
-
2492
- step(1)
2493
-
2494
- def _add_meta(self, text):
2495
- stick = self._at_bottom()
2496
- self._clear_empty()
2497
- self._items.append(Meta(text, self.opt))
2498
- if stick:
2499
- self._scroll = 10 ** 9
2500
- self._reflow()
2501
-
2502
- def _build_composer(self):
2503
- """输入栏:一个**内凹**胶囊 + 麦(玻璃方钮)+ 发送(强调胶囊)。
2504
-
2505
- 一版把三个控件 `pack` 进一个 `bg=SLAB_FILL` 的 Frame —— 那条不透明底色直接
2506
- 把底部玻璃盖成一根黑条,是"丑"的第二大来源。现在只有 `Entry` 是真空控件
2507
- (它只能不透明,正好当内凹槽),胶囊底和两个按钮全是画布元素。
2508
- """
2509
- # selectbackground 必须显式设成底色系:Tk 默认是白色,一有选区就在输入框里
2510
- # 显示一块白方块(截图里那个白块就是它)
2511
- # insertbackground 和底色一样:这个 Entry 只有 2×2,任何可见元素都是噪点
2512
- self.entry = tk.Entry(self.canvas, bg=FIELD_BG, fg=TEXT, insertbackground=FIELD_BG,
2513
- selectbackground="#2b4d73", selectforeground="#ffffff",
2514
- relief="flat", bd=0, font=self._f(10),
2515
- highlightthickness=0)
2516
- self.entry.bind("<Return>", self._send)
2517
- self.entry.bind("<FocusIn>", lambda _e: self._on_entry_focus(True))
2518
- self.entry.bind("<FocusOut>", lambda _e: self._on_entry_focus(False))
2519
- # 每次敲键都把画布上的字同步一遍(Entry 自己看不见)
2520
- self.entry.bind("<KeyRelease>", lambda _e: self._sync_field_text(), add="+")
2521
- self._field_text_id = None
2522
- self._field_caret_id = None
2523
- self._caret_on = True
2524
- self._entry_item = self.canvas.create_window(0, 0, window=self.entry,
2525
- anchor="w", tags=("cmp",))
2526
-
2527
- self.mic_btn = GlassButton(self, "cmp-mic", "麦", kind="ghost", fg=MUTED,
2528
- command=self.toggle_mic, size=9.5, group="cmp")
2529
- self.send_btn = GlassButton(self, "cmp-send", "发送", kind="accent", fg="#ffffff",
2530
- fill=ACCENT, command=self._send, size=9.5, group="cmp")
2531
- self._field_rect = None
2532
- self._field_geo = None
2533
- self._field_focus = False
2534
- self._field_ids = {}
2535
-
2536
- def _sync_field_text(self):
2537
- """把 Entry 里的字画到输入槽上(Entry 自己已经移出画布)。
2538
-
2539
- 只做"字 + 光标",不做背景 —— 背景就是脚下那块玻璃。
2540
- 空的时候显示一行灰提示,省得槽里空荡荡的。
2541
- """
2542
- cv = self.canvas
2543
- rect = getattr(self, "_field_rect", None)
2544
- if not rect:
2545
- return
2546
- x1, y1, x2, y2 = rect
2547
- padx = int((y2 - y1) / 2.0 + 3 * self.s)
2548
- try:
2549
- typed = self.entry.get()
2550
- except Exception:
2551
- typed = ""
2552
- show = typed if typed else "和 AI 说点什么…"
2553
- fill = TEXT if typed else "#5a6577"
2554
- cx, cy = x1 + padx, (y1 + y2) / 2.0
2555
- # **聚焦时字由 Entry 自己画**:它此刻贴在槽里,bg 和槽同色,看起来就是
2556
- # "字直接长在玻璃上";canvas 再画一遍会和它重影(两倍字重)。
2557
- try:
2558
- focused = bool(getattr(self, "_field_focus", False)) or \
2559
- (self.root.focus_get() is self.entry)
2560
- except Exception:
2561
- focused = bool(getattr(self, "_field_focus", False))
2562
- item = getattr(self, "_field_text_id", None)
2563
- try:
2564
- if item is not None and cv.type(item) == "text":
2565
- cv.itemconfigure(item, text=show, fill=fill)
2566
- cv.coords(item, cx, cy)
2567
- else:
2568
- self._field_text_id = text_on_glass(
2569
- cv, cx, cy, show, anchor="w", fill=fill, font=self._f(10),
2570
- tags="field", offset=max(1, int(self.s)))
2571
- except Exception:
2572
- self._field_text_id = None
2573
- # 光标:一条竖线,按 500ms 闪。**只在聚焦时画**,否则一直闪很吵。
2574
- caret = getattr(self, "_field_caret_id", None)
2575
- if not focused or not self._caret_on:
2576
- if caret is not None and cv.type(caret) == "line":
2577
- cv.itemconfigure(caret, state="hidden")
2578
- return
2579
- tx = cx
2580
- if typed:
2581
- try:
2582
- from tkinter import font as tkfont
2583
- tx = cx + tkfont.Font(family=self.family,
2584
- size=max(7, int(10 * self.s))).measure(typed)
2585
- except Exception:
2586
- tx = cx + len(typed) * 11 * self.s
2587
- hh = (y2 - y1) * 0.30
2588
- if caret is not None and cv.type(caret) == "line":
2589
- cv.coords(caret, tx, cy - hh, tx, cy + hh)
2590
- cv.itemconfigure(caret, state="normal")
2591
- else:
2592
- self._field_caret_id = cv.create_line(tx, cy - hh, tx, cy + hh,
2593
- fill=TEXT, width=max(1, int(self.s)), tags="field")
2594
-
2595
- def _caret_blink(self):
2596
- self._caret_on = not getattr(self, "_caret_on", True)
2597
- try:
2598
- self._sync_field_text()
2599
- self._caret_job = self.root.after(520, self._caret_blink)
2600
- except Exception:
2601
- self._caret_job = None
2602
-
2603
- def _text_w(self, text, size):
2604
- """量一段文字的像素宽(用来定按钮宽度 —— 估系数会把"发送"挤成 0 宽)"""
2605
- try:
2606
- from tkinter import font as tkfont
2607
- return tkfont.Font(family=self.family,
2608
- size=max(7, int(size * self.s))).measure(text)
2609
- except Exception:
2610
- return int(len(text) * 11 * self.s)
2611
-
2612
- def _composer_paint(self, bot):
2613
- """摆输入栏的三样东西,并把片的高度回填给 `_layout`。"""
2614
- cv = self.canvas
2615
- cv.delete("composer-art")
2616
- s = self.s
2617
- x1, y1, x2, y2 = bot
2618
- inset = int(11 * s)
2619
- h = int(36 * s)
2620
- self._bot_slab_h = h + 2 * inset
2621
- yc = (y1 + y2) / 2.0
2622
- ty = yc - h / 2.0
2623
-
2624
- # 麦:圆角方钮(半径 11 —— 苹果那种"圆角方"比正圆更轻)
2625
- mx1 = x1 + inset
2626
- self.mic_btn.layout((mx1, ty, mx1 + h, ty + h), radius=min(int(11 * s), h / 2))
2627
-
2628
- # 发送:强调胶囊,宽度按文字实测
2629
- sw = self._text_w("发送", 9.5) + int(26 * s)
2630
- sx2 = x2 - inset
2631
- self.send_btn.layout((sx2 - sw, ty, sx2, ty + h), radius=h / 2.0)
2632
-
2633
- # 输入槽
2634
- fx1 = mx1 + h + int(8 * s)
2635
- fx2 = sx2 - sw - int(8 * s)
2636
- if fx2 - fx1 < int(60 * s):
2637
- fx2 = fx1 + int(60 * s)
2638
- rect = (fx1, ty, fx2, ty + h)
2639
- if rect != self._field_rect:
2640
- self._field_rect = rect
2641
- self._field_geo = None
2642
- self._paint_field()
2643
-
2644
- cv.tag_raise("cmp")
2645
- cv.tag_raise("sbar")
2646
-
2647
- def _paint_field(self, event=None, accent=None):
2648
- """输入槽:**内凹**。上沿暗、下沿亮 —— 光从上面来,凹进去的东西上沿是背光的
2649
- 那道;反过来(上亮下暗)看着就变"凸起的按钮"。聚焦时整个槽换强调色描边。
2650
- """
2651
- cv = self.canvas
2652
- rect = getattr(self, "_field_rect", None)
2653
- if not rect:
2654
- return
2655
- if accent is not None:
2656
- self._field_focus = bool(accent)
2657
- if self._field_geo != rect or not self._field_ids:
2658
- cv.delete("field")
2659
- self._field_ids = {}
2660
- x1, y1, x2, y2 = rect
2661
- rr = (y2 - y1) / 2.0
2662
- w1 = max(1, int(self.s))
2663
- self._field_ids["body"] = round_rect(
2664
- cv, x1, y1, x2, y2, rr, fill=FIELD_BG, outline="", tags="field")
2665
- self._field_ids["rim"] = round_rect(
2666
- cv, x1 + 0.5, y1 + 0.5, x2 - 0.5, y2 - 0.5, rr,
2667
- fill="", outline="#232830", width=w1, tags="field")
2668
- self._field_ids["hi"] = cv.create_line(
2669
- x1 + rr * 0.8, y2 - 0.8, x2 - rr * 0.8, y2 - 0.8,
2670
- fill="#262b33", width=w1, tags="field")
2671
- self._field_geo = rect
2672
- cv.tag_raise("field")
2673
- cv.tag_raise("cmp")
2674
- cv.tag_raise("sbar")
2675
- rim = self._field_ids.get("rim")
2676
- if rim is not None:
2677
- cv.itemconfigure(rim, outline=ACCENT if self._field_focus else "#232830")
2678
- # Entry 贴在槽里。
2679
- # **宽度必须用画布窗口项的像素宽**(`itemconfigure(width=)`),不能靠
2680
- # `Entry.configure(width=字符数)` 反推:字宽是估的,中文一多就撑出去,
2681
- # 输入框会直接把胶囊和右边的"发送"一起盖掉(用户说的"输入框太长、捅破了"
2682
- # 就是这个 —— 那个 Entry 当时有 629px 宽,比槽宽了 160px)。
2683
- x1, y1, x2, y2 = rect
2684
- # 内缩量必须**大于胶囊的圆角半径**(= 高度一半):Entry 是方的,压进圆弧区
2685
- # 就会有一块直角露在胶囊外面,看着就是"输入框没有圆角"。
2686
- padx = int((y2 - y1) / 2.0 + 3 * self.s)
2687
- # **Entry 移到画布外**:它只负责收键盘和 IME,画面上一个字都不该由它显示。
2688
- # 原生 Entry 必须不透明,塞进玻璃里就是一块死黑方块(用户原话:
2689
- # "把输入框这个黑色矩形直接删掉,让字直接出现在液态玻璃上")。
2690
- # **Entry 平时在画布外,聚焦时才贴进槽里**。
2691
- # 以前它永远在 -4000,-4000:`offset` 在画布外的 canvas window 不会被 map,
2692
- # 而未 map 的控件**拿不到键盘焦点** —— `focus_set()` 直接空转,
2693
- # 于是"点输入框 → 聚焦 → 打字"这条链在第一步就断了(用户实报"点了都没反应")。
2694
- # 贴进来时它的 bg 和槽同色(FIELD_BG)、内缩量大于圆角半径,所以看不出是个原生控件。
2695
- self._place_entry(bool(getattr(self, "_field_focus", False)))
2696
- self._sync_field_text()
2697
-
2698
- def _place_entry(self, visible):
2699
- """把 `Entry` 放进输入槽里(或挪回画布外)。
2700
-
2701
- **必须是"贴进去再聚焦"的顺序**:没 map 的窗口控件不接受焦点。
2702
- """
2703
- cv = self.canvas
2704
- rect = getattr(self, "_field_rect", None)
2705
- if not rect:
2706
- return
2707
- x1, y1, x2, y2 = rect
2708
- padx = int((y2 - y1) / 2.0 + 3 * self.s)
2709
- try:
2710
- if visible:
2711
- # **缩成 2×2 贴在槽里**:`Entry` 是原生控件,做不出圆角
2712
- # (放大就是一个更宽的直角矩形,用户实报"蹦出一个直角矩形,太丑")。
2713
- # 但画布外的 `Entry` 不会被 map,未 map 就**拿不到键盘焦点** ——
2714
- # 所以它必须"在可视区域内极小且同色":只收键盘和 IME,
2715
- # 字和光标全部由画布画。
2716
- cv.coords(self._entry_item, x1 + padx, int((y1 + y2) / 2))
2717
- cv.itemconfigure(self._entry_item, width=2, height=2)
2718
- cv.tag_raise(self._entry_item)
2719
- else:
2720
- cv.coords(self._entry_item, -4000, -4000)
2721
- cv.itemconfigure(self._entry_item, width=2, height=2)
2722
- except Exception:
2723
- pass
2724
-
2725
- def _on_entry_focus(self, on):
2726
- """焦点进出:贴进/移出槽,并让 canvas 决定字由谁画。"""
2727
- self._field_focus = bool(on)
2728
- if not on:
2729
- self._place_entry(False)
2730
- self._paint_field(accent=on)
2731
- self._sync_field_text()
2732
-
2733
- def _focus_entry(self):
2734
- """把焦点交给输入框,但**不抢系统焦点**。
2735
-
2736
- 以前用 `focus_force()`:窗口一开就把焦点从浏览器抢走 —— 用户正看着片,
2737
- 敲空格想暂停,结果字打进了聊天框。`focus_set()` 只在本窗口内部指定焦点:
2738
- 点一下窗口就能直接打字,不点就完全不影响他在浏览器里的操作。
2739
- """
2740
- # **这里绝不能 focus_force**:开窗就把焦点从浏览器抢走,用户正看片、
2741
- # 敲空格想暂停,结果字打进了聊天框(踩过)。真正的聚焦发生在用户点窗口时
2742
- # (`_drag_start`),那时才 place + force。
2743
- try:
2744
- self.entry.focus_set()
2745
- except Exception:
2746
- pass
2747
-
2748
- # ---- 语音输入 ----
2749
- def toggle_mic(self):
2750
- if self.mic_proc and self.mic_proc.poll() is None:
2751
- self._stop_mic()
2752
- return
2753
- if not os.path.exists(MIC_SCRIPT):
2754
- self._add_meta(f"找不到 {MIC_SCRIPT}")
2755
- return
2756
- py = asr_python()
2757
- try:
2758
- self.mic_proc = subprocess.Popen(
2759
- [py, MIC_SCRIPT, "--engine", "local"],
2760
- stdout=subprocess.DEVNULL, # 识别结果走聊天流,这里不重复显示
2761
- stderr=subprocess.PIPE, # 状态/报错显示在窗口里
2762
- text=True, encoding="utf-8", errors="replace",
2763
- creationflags=0x08000000 if os.name == "nt" else 0, # 别弹控制台
2764
- )
2765
- except Exception as exc:
2766
- self._add_meta(f"起不来麦克风进程:{exc}")
2767
- return
2768
- self.mic_btn.set(text="●", bg="#7a2b2b", fg="#ffd9d9")
2769
- self.dot_fg = DANGER
2770
- self._hint_text = "录音中"
2771
- self._header_paint(self._head_rect)
2772
- threading.Thread(target=self._mic_log, args=(self.mic_proc,), daemon=True).start()
2773
-
2774
- def _stop_mic(self):
2775
- p = self.mic_proc
2776
- self.mic_proc = None
2777
- if p and p.poll() is None:
2778
- try:
2779
- p.terminate()
2780
- except Exception:
2781
- pass
2782
- self.mic_btn.set(text="麦", bg=None, fg=MUTED)
2783
- self.dot_fg = ACCENT
2784
- self._update_hint()
2785
-
2786
- def _mic_log(self, proc):
2787
- """把 mic.py 的状态/报错搬进窗口;它一退出就把按钮复位"""
2788
- try:
2789
- for line in proc.stderr:
2790
- line = (line or "").rstrip()
2791
- if line:
2792
- self.root.after(0, lambda l=line: self._add_meta(l))
2793
- except Exception:
2794
- pass
2795
- proc.wait()
2796
- self.root.after(0, self._mic_exited)
2797
-
2798
- def _mic_exited(self):
2799
- # 自己挂了(依赖缺失/设备被占)也要把按钮复位,别停在"录音中"
2800
- if self.mic_proc is not None:
2801
- self._stop_mic()
2802
-
2803
- # ---- 拖动 / 拉伸 ----
2804
- def _force_foreground(self):
2805
- """把窗口拉到前台。
2806
-
2807
- **override-redirect 窗口点一下不一定自己激活**(实测:点完
2808
- `GetForegroundWindow` 还是 Chrome),于是 `focus_set()` 空转、字打不进去。
2809
-
2810
- 这里**只用 `SetForegroundWindow`**,不碰 `AttachThreadInput`:
2811
- 后者要跨线程附加,参数类型一旦不对就是静默崩进程(实测过一次,日志里什么都没有)。
2812
- 调用发生在"用户点击"这一帧,属于用户输入触发,Windows 的前台锁一般会放行。
2813
- """
2814
- try:
2815
- import ctypes
2816
- u = ctypes.windll.user32
2817
- u.SetForegroundWindow.argtypes = [ctypes.c_void_p]
2818
- u.SetForegroundWindow.restype = ctypes.c_int
2819
- u.SetFocus.argtypes = [ctypes.c_void_p]
2820
- hwnd = ctypes.c_void_p(int(self._hwnd()))
2821
- if u.GetForegroundWindow() != hwnd.value:
2822
- u.SetForegroundWindow(hwnd)
2823
- u.SetFocus(hwnd)
2824
- except Exception:
2825
- pass
2826
-
2827
- def _drag_start(self, event):
2828
- # **点一下窗口就要能打字**。`Entry` 被挪到画布外(-4000,-4000)只收键盘和
2829
- # IME,画面上根本点不到它 —— 所以焦点必须在这里交过去。以前只在开窗 220ms
2830
- # 时 `focus_set()` 一次,之后焦点一旦被浏览器/别的窗口抢走,再点输入框就
2831
- # 只是"拖窗",一个字都打不进去(用户实报"点了都没反应")。
2832
- # 用 `focus_force`:用户主动点窗口,本来就该是"激活它"的语义。
2833
- try:
2834
- # **顺序不能反**:先把窗口拉到前台、再把 Entry 贴进槽(没 map 的控件
2835
- # 不接受焦点),最后才 focus
2836
- self._force_foreground()
2837
- self._place_entry(True)
2838
- self.root.focus_force()
2839
- self.entry.focus_set()
2840
- self._field_focus = True
2841
- self._sync_field_text()
2842
- except Exception:
2843
- pass
2844
- # 点在输入槽里就**只聚焦、不拖窗**:否则"想打字"和"想拖窗"抢同一个手势,
2845
- # 手一抖窗口就跟着跑。
2846
- fr = getattr(self, "_field_rect", None)
2847
- if fr and fr[0] <= event.x <= fr[2] and fr[1] <= event.y <= fr[3]:
2848
- self._drag = None
2849
- return
2850
- self._drag = (event.x_root - self.root.winfo_x(), event.y_root - self.root.winfo_y())
2851
-
2852
- def _drag_end(self, _event=None):
2853
- """松手:结束拖动状态,并把"搬家后的收尾重绘"补上。"""
2854
- if self._drag is None:
2855
- return
2856
- self._drag = None
2857
- try:
2858
- self._request_backdrop()
2859
- except Exception:
2860
- pass
2861
-
2862
- def _drag_move(self, event):
2863
- if not self._drag:
2864
- return
2865
- dx, dy = self._drag
2866
- self.x, self.y = event.x_root - dx, event.y_root - dy
2867
- self.root.geometry(f"+{self.x}+{self.y}")
2868
- # **拖动中就要刷新**:以前是"挪完停手 420ms 才重截",所以拖动全程背后是冻结的,
2869
- # 一松手还要卡一下、闪一下。现在只要窗口还在 stage(带留白的已糊底板)里,
2870
- # 就当场裁一张新的贴上去 —— 不截屏、不隐藏窗口,约 15ms 一帧。
2871
- # 事件比帧还密(鼠标 120Hz),按 30ms 节流,掉的那几帧由下一次 move 补上。
2872
- now = time.time()
2873
- if now - getattr(self, "_live_at", 0.0) >= 0.03 and self._live_backdrop():
2874
- self._live_at = now
2875
- else:
2876
- self._request_backdrop()
2877
-
2878
- def _paint_glass_only(self):
2879
- """**只换玻璃**:拖动时每帧走这里 —— 标题、气泡、输入栏原地不动。
2880
-
2881
- 整窗 `_paint` 会重画所有元素(标题文字、按钮、每条气泡),那些东西相对窗口
2882
- 根本没动,在拖动时重画纯属浪费(一帧多 20ms)。这里只换底板图和两块悬浮片。
2883
- """
2884
- cv = self.canvas
2885
- w, h = self.root.winfo_width(), self.root.winfo_height()
2886
- if w < 4 or h < 4:
2887
- return
2888
- if self.acrylic:
2889
- return # 磨砂模式不需要重画玻璃
2890
- self._ensure_blurred(w, h)
2891
- top, body, bot = self._layout(w, h)
2892
- photo = self._panel_photo(w, h, body)
2893
- if photo is None:
2894
- return
2895
- self._backdrop_photo = photo
2896
- # **复用同一个 item**:`delete("panel")` + `create_image` 每帧中间有一帧没底板,
2897
- # 拖动时 60Hz 就是"一路闪"。`itemconfigure(image=)` 是原子的,成本一样。
2898
- item = getattr(self, "_panel_item", None)
2899
- if item is not None and cv.type(item) == "image":
2900
- cv.itemconfigure(item, image=photo)
2901
- else:
2902
- self._panel_item = cv.create_image(0, 0, image=photo, anchor="nw",
2903
- tags=("panel", "backdrop"))
2904
- cv.tag_lower("panel")
2905
- # **拖动过程中不动两块悬浮片**:它们只占角落,位置每帧只挪几像素,肉眼看不出来,
2906
- # 但重烘两块 slab 要 6ms/帧 —— 60Hz 下就是 36% 的占用。
2907
- if not getattr(self, "_drag", None):
2908
- self._slab_paint(top, bot)
2909
- for tag in ("slab", "field", "hdr", "cmp", "sbar"):
2910
- cv.tag_raise(tag)
2911
-
2912
- def _live_backdrop(self):
2913
- """拖动/缩放过程中的"够快"刷新:stage 命中就不截屏、不隐身、不闪。"""
2914
- if not HAVE_PIL or not self.rounded:
2915
- return False
2916
- # **不能用 `_window_rect()`**:它内部 `update_idletasks()` 会顺手把一次
2917
- # Configure 处理掉,于是每帧在"换玻璃"之外又白跑一遍整窗重绘(实测 +17ms)。
2918
- k = self._dpi_k()
2919
- rect = (int(self.x * k), int(self.y * k), int(self.w * k), int(self.h * k))
2920
- if not self._shot_usable(*rect):
2921
- return False
2922
- try:
2923
- self._grab_backdrop() # 只是从 stage 里裁一块 + 放大
2924
- self._paint_glass_only()
2925
- except Exception:
2926
- return False
2927
- return True
2928
-
2929
- def _resize_start(self, event):
2930
- self._resize = (event.x_root, event.y_root, self.w, self.h)
2931
-
2932
- def _resize_move(self, event):
2933
- if not self._resize:
2934
- return
2935
- x0, y0, w0, h0 = self._resize
2936
- self.w = max(int(MIN_W * self.s), w0 + (event.x_root - x0))
2937
- # 拖拽也守同一个下限:以前允许拖到 220*s,比三块固定栏加起来还矮
2938
- self.h = max(self._min_h(), h0 + (event.y_root - y0))
2939
- self.root.geometry(f"{self.w}x{self.h}+{self.x}+{self.y}")
2940
- self._resizing = True # 期间走"缩放旧玻璃"的快路,不重烘
2941
- try:
2942
- if getattr(self, "_resize_job", None):
2943
- self.root.after_cancel(self._resize_job)
2944
- except Exception:
2945
- pass
2946
- self._resize_job = self.root.after(300, self._resize_done)
2947
- self._request_backdrop()
2948
-
2949
- def _resize_done(self):
2950
- self._resize_job = None
2951
- self._resizing = False
2952
- self._chat_v += 1 # 尺寸变了,气泡玻璃必须重烘
2953
- self._request_backdrop()
2954
-
2955
- # ---- 交互 ----
2956
- def toggle_collapse(self):
2957
- """折叠:只留标题栏那一条。消息和输入栏用 `itemconfigure(state)` 藏起来 ——
2958
- 它们现在是 canvas 上的 item / window,不能再用 pack_forget。"""
2959
- self._drag = None # 手势可能还没松手就换尺寸,别让早退条件卡住重绘
2960
- self._collapsed = not getattr(self, "_collapsed", False)
2961
- if self._collapsed:
2962
- self._saved_h = self.h
2963
- self.h = 2 * self.out + int(46 * self.s) # 正好只剩标题栏那片玻璃
2964
- else:
2965
- self.h = getattr(self, "_saved_h", None) or int(540 * self.s)
2966
- self.root.geometry(f"{self.w}x{self.h}+{self.x}+{self.y}")
2967
- self._apply_collapsed()
2968
- # 折叠/展开是"整窗换尺寸",任何一档缓存的尺寸都对不上 —— 全部作废重来,
2969
- # 否则会留下一张按旧高度裁出来的片(2px 高的气泡、消失的标题栏)。
2970
- self._blurred = None
2971
- self._plates.clear()
2972
- self._plate_imgs.clear()
2973
- self._last_plate_imgs.clear()
2974
- self._last_panel = None
2975
- self._chat_v += 1
2976
- try:
2977
- # 等窗口真的换成新尺寸(configure 一到就重画),再补一发保险
2978
- self.root.after(16, self._paint)
2979
- self.root.after(40, self._refresh_backdrop)
2980
- except Exception:
2981
- pass
2982
-
2983
- def _apply_collapsed(self):
2984
- """折叠 = 只留标题栏。消息和输入栏整组藏起来(它们都是画布元素,按 tag 藏)"""
2985
- state = "hidden" if getattr(self, "_collapsed", False) else "normal"
2986
- for tag in ("cmp", "field", "sbar"):
2987
- try:
2988
- self.canvas.itemconfigure(tag, state=state)
2989
- except Exception:
2990
- pass
2991
- for it in self._items:
2992
- try:
2993
- self.canvas.itemconfigure(it.tag, state=state)
2994
- except Exception:
2995
- pass
2996
-
2997
- def body_visible(self):
2998
- return not getattr(self, "_collapsed", False)
2999
-
3000
- def close(self):
3001
- self._glass_stop = True
3002
- try:
3003
- if getattr(self, "_glass_job", None):
3004
- self.root.after_cancel(self._glass_job)
3005
- self._glass_job = None
3006
- except Exception:
3007
- pass
3008
- self._stop_mic() # 窗口关了就别留个录音进程在后台
3009
- write_config({"geometry": f"{self.w}x{self.h}+{self.x}+{self.y}"})
3010
- self.root.destroy()
3011
-
3012
- def _send(self, _event=None):
3013
- text = self.entry.get().strip()
3014
- if not text:
3015
- return "break"
3016
- self.entry.delete(0, "end")
3017
- self._sync_field_text()
3018
- try:
3019
- append_user(text)
3020
- except Exception as exc:
3021
- self._add_meta(f"写不进去:{exc}")
3022
- return "break"
3023
- self.poll() # 立刻回显,不等下一拍
3024
- # 发完继续打字:点"发送"按钮进来的时候焦点不在 Entry 上
3025
- try:
3026
- self.entry.focus_set()
3027
- except Exception:
3028
- pass
3029
- return "break"
3030
-
3031
- def _render(self, entry):
3032
- """一条 jsonl → 一个玻璃片。**新消息和历史回放走同一条路**,样式才不会两套。
3033
-
3034
- `t`(播放位置)和 `at`(墙钟)都可能缺,缺了就留空 —— 不猜、不补 0
3035
- (`Number(null) === 0` 这个坑在 JS 那边踩过两次)。
3036
- """
3037
- role = entry.get("role")
3038
- text = str(entry.get("text") or "")
3039
- # **系统行(`meta`)走灰字,不做气泡**:它们是"叫醒失败""麦克风已开"这类诊断,
3040
- # 以前没分派,落到下面的 fallback 变成一块和正文一样大的气泡 —— 一屏全是
3041
- # `[一起看] 叫醒失败` 的方框,抢的就是台词的视线。
3042
- if role == "meta":
3043
- self._add_meta(text)
3044
- return
3045
- if role not in ROLE:
3046
- role = "assistant"
3047
- # **统一显示本机时间**(2026-11-01 用户要求):以前台词显示的是播放位置
3048
- # (`01:26.0`),别的显示墙钟,一条流里两种时间轴,读起来要先换算一次。
3049
- # 现在一律用 `at`(消息写进流的时刻);没有 `at` 就留空,不拿 `t` 顶替 ——
3050
- # 那会把"视频第几秒"冒充成"几点几分",比空着更误导。
3051
- stamp = clock(entry.get("at")) if entry.get("at") is not None else ""
3052
- self._add_bubble(role, text, stamp)
3053
-
3054
- # ---- 读盘(增量)----
3055
- def _reset_cursor(self):
3056
- """开场:回放最后 60 条(有上下文,又不会被几千条历史淹掉)"""
3057
- try:
3058
- size = os.path.getsize(CHAT_FILE)
3059
- except OSError:
3060
- size = 0
3061
- self._offset = size
3062
- self._carry = ""
3063
- self.seen = 0
3064
- if size == 0:
3065
- self._show_empty()
3066
- return
3067
- try:
3068
- with open(CHAT_FILE, "rb") as f:
3069
- f.seek(max(0, size - 96 * 1024))
3070
- chunk = f.read()
3071
- except OSError:
3072
- self._show_empty()
3073
- return
3074
- lines = [l for l in chunk.decode("utf-8", "replace").split("\n") if l.strip()]
3075
- if size > 96 * 1024 and lines:
3076
- lines = lines[1:] # 从文件中间开始读,第一行可能是半行
3077
- for line in lines[-60:]:
3078
- try:
3079
- self._render(json.loads(line))
3080
- except Exception:
3081
- continue
3082
- self.seen += 1
3083
- if self.seen == 0:
3084
- self._show_empty()
3085
-
3086
- def _drain(self):
3087
- """只读上次之后新追加的字节 —— 和 src/chat-store.js 的 watcher 同一套思路"""
3088
- try:
3089
- size = os.path.getsize(CHAT_FILE)
3090
- except OSError:
3091
- return []
3092
- if size < self._offset: # 文件被清空/重建
3093
- for row in self.rows:
3094
- try:
3095
- row.row.destroy()
3096
- except Exception:
3097
- pass
3098
- self.rows.clear()
3099
- self.empty = None
3100
- self._offset, self._carry, self.seen = 0, "", 0
3101
- self._show_empty()
3102
- if size == self._offset:
3103
- return []
3104
- try:
3105
- with open(CHAT_FILE, "rb") as f:
3106
- f.seek(self._offset)
3107
- chunk = f.read(size - self._offset)
3108
- except OSError:
3109
- return []
3110
- self._offset = size
3111
- text = self._carry + chunk.decode("utf-8", "replace")
3112
- parts = text.split("\n")
3113
- self._carry = parts.pop() # 末尾可能是半行,留到下一拍
3114
- out = []
3115
- for line in parts:
3116
- if not line.strip():
3117
- continue
3118
- try:
3119
- out.append(json.loads(line))
3120
- except Exception:
3121
- continue
3122
- return out
3123
-
3124
- def _update_hint(self):
3125
- """标题栏那点小字只留"录音中" —— 条数已经单独显示在名字右边了,
3126
- 以前一条是"5 条"、另一条是"已连上",两个位置各说一半,读起来像仪表盘。"""
3127
- hint = "录音中" if (self.mic_proc and self.mic_proc.poll() is None) else ""
3128
- if hint == getattr(self, "_hint_text", None):
3129
- return
3130
- self._hint_text = hint
3131
- try:
3132
- self._header_paint(self._head_rect)
3133
- except Exception:
3134
- pass
3135
-
3136
- def _sync_visible(self):
3137
- """跟随配置里的 `hidden`:插件写 true 就藏起来(进程还活着,照样收话、照样念),写 false 就回来。
3138
-
3139
- 为什么要"藏"而不是"关":关窗在陪看里等于"不看了"(会停表、落挂断记录)。
3140
- 用户想的是**这一次别挡着画面**,陪看继续 —— 那是两件事。
3141
- 用 withdraw 而不是 iconify:图标化的窗口还会占任务栏/出现在 Alt+Tab 里,
3142
- 而这是置顶悬浮窗,藏起来就该完全看不见。
3143
- """
3144
- want = bool(read_config().get("hidden"))
3145
- if want == self.hidden:
3146
- return
3147
- self.hidden = want
3148
- try:
3149
- if want:
3150
- # **藏起来的时候顺手重截底板**:此刻窗口本来就不可见,重截零成本,
3151
- # 等用户再放出来时玻璃就是新的。这样常驻时不闪也能保持新鲜。
3152
- try:
3153
- self.root.withdraw()
3154
- self.root.update_idletasks()
3155
- self._stage_cache = None
3156
- self._grab_backdrop((self.w, self.h), force_stage=True)
3157
- self._paint()
3158
- except Exception:
3159
- pass
3160
- self.root.withdraw()
3161
- else:
3162
- self.root.deiconify()
3163
- self.root.attributes("-topmost", True)
3164
- except Exception:
3165
- self.hidden = not want # 没成功就别记成已切换,下一拍再试
3166
-
3167
- def poll(self):
3168
- try:
3169
- self._sync_visible()
3170
- for e in self._drain():
3171
- self._render(e)
3172
- self.seen += 1
3173
- self._update_hint()
3174
- except Exception:
3175
- pass
3176
- # 200ms 而不是 400ms:台词是在**声音真的出来那一刻**才写盘的(见 src/chat-store.js),
3177
- # 轮询间隔就是"字比声音晚多少"的直接来源 —— 50~400ms 的滞后会被听成"不同步"。
3178
- self.root.after(200, self.poll)
3179
- # **只启一次**:`poll()` 每 200ms 自己再排一次,放在这里却不加锁的话,
3180
- # 每拍都会重启一条定时链 —— 实测 3.2 秒触发 16 次、截屏频率飙到 9Hz。
3181
- if not getattr(self, "_glass_started", False):
3182
- self._glass_started = True
3183
- self._glass_ttl_start()
3184
- if not getattr(self, "_caret_started", False):
3185
- self._caret_started = True
3186
- self.root.after(520, self._caret_blink)
3187
-
3188
- # ---- 玻璃底色跟着背景走 ----
3189
- #
3190
- # 以前整屏截图**只在开窗时发生一次**(`_stage` 的注释还写着"之后无论拖到哪儿都是裁一刀"),
3191
- # 于是对面视频换了场景、桌面换了壁纸,这块玻璃还是开窗那一刻的颜色 ——
3192
- # 用户原话:"背景换了,液态玻璃还没动,还没变颜色"。拖动结束后那 8 秒的判定也救不了静止的窗口。
3193
- #
3194
- # 现在按 TTL 定时重截:**截屏在子线程**(ImageGrab + 缩放 + 模糊,约 150~200ms),
3195
- # 主线程只做裁片 + 贴图(1~2ms)。Tk 的对象一个都不许在子线程碰 —— 屏幕尺寸、缩放系数
3196
- # 都在主线程读好再传进去。
3197
-
3198
- def _glass_ttl(self):
3199
- try:
3200
- return int(float(os.environ.get("DSH_WATCH_GLASS_TTL") or 60))
3201
- except Exception:
3202
- return 60
3203
-
3204
- def _glass_ttl_start(self):
3205
- self._glass_job = None
3206
- self._glass_busy = False
3207
- self._glass_q = queue.Queue(maxsize=1)
3208
- self._glass_stop = False
3209
- self._glass_rect = self._win_phys(200)
3210
- if self.acrylic:
3211
- return # 磨砂模式:完全交给 GPU,一次屏都不截
3212
- if self._glass_ttl() <= 0:
3213
- return # 0 = 关掉,回到"开窗截一次"的旧行为
3214
- try:
3215
- threading.Thread(target=self._glass_worker, daemon=True).start()
3216
- except Exception:
3217
- pass
3218
- try:
3219
- self._glass_job = self.root.after(self._glass_ttl(), self._glass_tick)
3220
- except Exception:
3221
- self._glass_job = None
3222
-
3223
- def _glass_tick(self):
3224
- """**主线程**:每 4ms 取一次最新帧。仿 PR #15 的架构 —— 后台不停地产,
3225
- 这里只负责"有就上",而不是"等够了 60ms 才去要一张"。
3226
-
3227
- 原来那套是定时器驱动的:`after(TTL)` → 起线程 → 回来 → 再排下一拍。
3228
- 一轮 32ms、TTL 60ms,等于每 92ms 才换一张脸(约 11Hz),而且有一半时间在空等。
3229
- 现在后台按目标帧率连续产出,主线程一有队列内容就贴,帧率由"一轮多久"决定。
3230
- """
3231
- self._glass_job = None
3232
- if self._glass_ttl() <= 0:
3233
- return
3234
- try:
3235
- self._glass_job = self.root.after(4, self._glass_tick)
3236
- except Exception:
3237
- self._glass_job = None
3238
- # 窗口可能刚被拖过:矩形在这里(主线程)刷新,子线程只读
3239
- try:
3240
- self._glass_rect = self._win_phys(200)
3241
- except Exception:
3242
- pass
3243
- q = getattr(self, "_glass_q", None)
3244
- if q is None:
3245
- return
3246
- staged = None
3247
- try:
3248
- staged = q.get_nowait()
3249
- except queue.Empty:
3250
- return
3251
- if staged is not None:
3252
- self._glass_apply(staged)
3253
-
3254
- def _glass_worker(self):
3255
- """**常驻子线程**:按目标帧率连续抓 + 算,结果丢进只有 1 个位置的队列。
3256
-
3257
- 队列 maxsize=1:算得比主线程贴得快时,**旧的直接扔掉**(观众只关心最新的一帧)。
3258
- """
3259
- target_fps = max(10, min(60, int(1000 / max(8, self._glass_ttl()) * 4)))
3260
- try:
3261
- target_fps = int(os.environ.get("DSH_WATCH_GLASS_FPS") or 30)
3262
- except Exception:
3263
- target_fps = 30
3264
- while not getattr(self, "_glass_stop", False):
3265
- t0 = time.time()
3266
- if getattr(self, "hidden", False) or getattr(self, "_collapsed", False):
3267
- time.sleep(0.1) # 看不见就别耗 CPU
3268
- continue
3269
- try:
3270
- rect = self._glass_rect # 主线程每拍更新
3271
- sx, sy, sw, sh = rect
3272
- staged = self._glass_capture(sx, sy, sw, sh, self.s)
3273
- except Exception:
3274
- staged = None
3275
- if staged is not None:
3276
- q = self._glass_q
3277
- try:
3278
- q.get_nowait() # 丢掉没被取走的旧帧
3279
- except queue.Empty:
3280
- pass
3281
- try:
3282
- q.put_nowait(staged)
3283
- except Exception:
3284
- pass
3285
- dt = time.time() - t0
3286
- time.sleep(max(0.0, 1.0 / target_fps - dt))
3287
-
3288
- def _glass_capture(self, sx, sy, sw, sh, s_scale):
3289
- """**子线程**:只做 PIL(截屏 → 1/8 → 模糊 → 色散 → 提饱和),**不碰 Tk**。"""
3290
- staged = None
3291
- try:
3292
- # **优先 mss**:同样是整屏,它 38ms、ImageGrab 71ms(本机实测),
3293
- # 而且它给的是物理分辨率(2560×1600),`_grab_backdrop` 用
3294
- # `small.size / (sw, sh)` 算比例,1.5 倍的 DPI 自动被吸收。
3295
- shot = None
3296
- if HAVE_MSS:
3297
- try:
3298
- # mss 10 起把 `mss.mss` 标成 deprecated,改叫 `MSS`;两个都认
3299
- factory = getattr(_mss, "MSS", None) or getattr(_mss, "mss")
3300
- with factory() as grabber:
3301
- raw = grabber.grab({"left": sx, "top": sy, "width": sw, "height": sh})
3302
- shot = Image.frombytes("RGB", raw.size, raw.bgra, "raw", "BGRX")
3303
- except Exception:
3304
- shot = None
3305
- if shot is None:
3306
- k = self._dpi_k()
3307
- shot = ImageGrab.grab(bbox=(sx / k, sy / k, (sx + sw) / k, (sy + sh) / k),
3308
- all_screens=True)
3309
- # ---- 静态跳帧(取自 PR #15 的策略,数字照抄)----
3310
- # 先用**没糊过的 raw** 判断有没有动:缩小到 48x30 比一次就够。
3311
- # 背景静止时整条管线(抓屏 17ms + 糊 + 色散 + 折射)全都不用跑;
3312
- # 阈值 mean>0.8/255 比"时间到了就重算"灵敏,慢速滚动不会先停一两帧。
3313
- now_s = time.time()
3314
- try:
3315
- sig = shot.resize((48, 30), Image.BILINEAR).convert("L")
3316
- prev = getattr(self, "_glass_sig", None)
3317
- same_box = getattr(self, "_glass_sig_box", None) == (sx, sy, sw, sh)
3318
- if prev is not None and same_box and prev.size == sig.size:
3319
- if ImageStat.Stat(ImageChops.difference(prev, sig)).mean[0] > 0.8:
3320
- self._glass_motion_at = now_s
3321
- elif now_s - getattr(self, "_glass_motion_at", 0.0) > 0.30:
3322
- self._glass_sig = sig
3323
- cached = getattr(self, "_glass_stage", None)
3324
- if cached is not None:
3325
- return cached # 没动:原样复用上一帧,一个像素都不算
3326
- else:
3327
- self._glass_motion_at = now_s
3328
- self._glass_sig = sig
3329
- self._glass_sig_box = (sx, sy, sw, sh)
3330
- except Exception:
3331
- pass
3332
- small = build_stage(shot, sw, sh, s_scale)
3333
- staged = (small, (sx, sy, sw, sh), time.time())
3334
- self._glass_stage = staged
3335
- except Exception:
3336
- staged = None
3337
- return staged
3338
-
3339
- # 相邻两帧底板的平均色差低于这个值就认为"背景没动",跳过重烘。
3340
- # 静止画面下每拍省掉主线程 26ms(重裁 6 + 烘焙 14 + 标题槽 6),也不闪。
3341
- GLASS_EPS = 0.6 # 0.25% 的平均色差就算"变了" —— 太保守会让慢摇镜头被跳过
3342
-
3343
- def _glass_apply(self, staged):
3344
- """**主线程**:换 stage → 重裁 → 只重画玻璃层。"""
3345
- self._glass_busy = False
3346
- if staged is None or not self.glass_ready():
3347
- return
3348
- prev = getattr(self, "_stage_cache", None)
3349
- if prev is not None:
3350
- try:
3351
- # 只比 1/4 分辨率的 stage(640×400),5ms 以内
3352
- a = ImageStat.Stat(staged[0]).mean
3353
- b = ImageStat.Stat(prev[0]).mean
3354
- if sum(abs(x - y) for x, y in zip(a, b)) < self.GLASS_EPS:
3355
- return # 背景没变:不换图、不重烘
3356
- except Exception:
3357
- pass
3358
- self._stage_cache = staged
3359
- self._blurred = None # 逼 _grab_backdrop 重新裁一刀
3360
- self._glass_v += 1 # 面板/悬浮条的缓存键里带它,作废
3361
- try:
3362
- size = getattr(self, "_painted_size", None) or (self.w, self.h)
3363
- self._grab_backdrop(size)
3364
- self._repaint_glass()
3365
- except Exception:
3366
- pass
3367
-
3368
-
3369
- if __name__ == "__main__":
3370
- if not os.path.exists(CHAT_FILE):
3371
- os.makedirs(os.path.dirname(CHAT_FILE), exist_ok=True)
3372
- FloatChat().root.mainloop()
1
+ #!/usr/bin/env python3
2
+ """真正悬浮窗:不铺全屏背景图,实时抓取窗口背后的桌面并模糊。
3
+
4
+ 关键点:
5
+ - Windows 10 2004+ 的 SetWindowDisplayAffinity(WDA_EXCLUDEFROMCAPTURE):
6
+ 让本窗口从屏幕捕获里消失,于是抓自己所在区域时抓到的是“背后的桌面”,
7
+ 不会抓到自己,不会递归,也不需要全屏置顶图片。
8
+ - 抓到的背景每 ~100ms 更新一次,所以是实时模糊,不是静态截图。
9
+ - 这不是 DWM Acrylic;Acrylic 需要系统“透明效果”开启。这里是软件实时模糊。
10
+ """
11
+ import ctypes
12
+ import json
13
+ import os
14
+ import queue
15
+ import subprocess
16
+ import sys
17
+ import threading
18
+ import time
19
+ from ctypes import wintypes
20
+ from pathlib import Path
21
+
22
+ # 必须在 import tkinter / 创建任何窗口之前声明 per-monitor v2 DPI 感知。
23
+ _u = ctypes.windll.user32
24
+ try:
25
+ _u.SetProcessDpiAwarenessContext.argtypes = [ctypes.c_void_p]
26
+ _u.SetProcessDpiAwarenessContext.restype = ctypes.c_bool
27
+ _u.SetProcessDpiAwarenessContext(ctypes.c_void_p(-4))
28
+ except Exception:
29
+ pass
30
+
31
+ try:
32
+ ctypes.windll.winmm.timeBeginPeriod(1)
33
+ except Exception:
34
+ pass
35
+
36
+ import tkinter as tk
37
+ import tkinter.font as tkfont
38
+ import mss
39
+ import numpy as np
40
+ from PIL import Image, ImageDraw, ImageEnhance, ImageFilter, ImageStat, ImageTk
41
+
42
+ # 悬浮窗接口:插件写 window-events.jsonl,窗口回 window-outbox.jsonl。
43
+ # 读不到就继续读 chat.jsonl,旧版插件不受影响。
44
+ try:
45
+ from window_protocol import WindowProtocol
46
+ except Exception:
47
+ WindowProtocol = None
48
+
49
+ W, H, R = 760, 560, 58
50
+ MIN_W, MIN_H = 480, 420
51
+ BAR_FRAC = 0.55
52
+ BAR_Y = 20
53
+ BAR_THICK = 4
54
+ KEY = "#010203"
55
+ FONT = "Microsoft YaHei UI"
56
+ INTERVAL_MS = 4
57
+ MAX_FPS = 120
58
+ PAD = 40
59
+ BAND = 64 # 全分辨率下的透镜带宽度
60
+ AMP = 30 # 全分辨率下的最大采样偏移
61
+ FORCE = os.environ.get("GLASS_FORCE") == "1"
62
+ # 仅用于文档截图/CI 视觉检查:暂停抓屏并把 WDA 关掉,窗口才会出现在截图里
63
+ PREVIEW = os.environ.get("DSH_GLASS_PREVIEW") == "1"
64
+ # 文档截图:正常抓屏 2.5 秒后暂停并取消 WDA,保留最后一帧玻璃
65
+ SNAPSHOT = os.environ.get("DSH_GLASS_SNAPSHOT") == "1"
66
+
67
+ # 和 window.py 用同一份聊天流 / 配置,两个窗口可以同时开,看到的是同一条时间线
68
+ HERE = Path(__file__).resolve().parent
69
+
70
+
71
+ def cache_dir():
72
+ d = os.environ.get("DSH_VIDEO_CACHE_DIR")
73
+ if d:
74
+ return Path(d)
75
+ local = os.environ.get("LOCALAPPDATA")
76
+ if os.name == "nt" and local:
77
+ return Path(local) / "dsh-video-storyboard" / "cache"
78
+ return Path(os.environ.get("XDG_CACHE_HOME") or "~/.cache").expanduser() / "dsh-video-storyboard"
79
+
80
+
81
+ CHAT_FILE = cache_dir() / "chat.jsonl"
82
+ CONFIG = Path(os.environ.get("DSH_HOME") or os.path.expanduser("~/.dsh")) / "watch-window.json"
83
+ MIC_SCRIPT = HERE / "mic.py"
84
+
85
+
86
+ def read_config():
87
+ try:
88
+ return json.loads(CONFIG.read_text(encoding="utf-8")) or {}
89
+ except Exception:
90
+ return {}
91
+
92
+
93
+ def write_config(patch):
94
+ cfg = read_config()
95
+ cfg.update(patch or {})
96
+ try:
97
+ CONFIG.parent.mkdir(parents=True, exist_ok=True)
98
+ tmp = CONFIG.with_suffix(".json.tmp")
99
+ tmp.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")
100
+ os.replace(tmp, CONFIG)
101
+ except Exception:
102
+ pass
103
+
104
+
105
+ def append_user(text):
106
+ CHAT_FILE.parent.mkdir(parents=True, exist_ok=True)
107
+ with open(CHAT_FILE, "a", encoding="utf-8") as f:
108
+ f.write(json.dumps({"role": "user", "text": text, "at": int(time.time() * 1000)},
109
+ ensure_ascii=False) + "\n")
110
+
111
+
112
+ def clock(ms):
113
+ try:
114
+ return time.strftime("%H:%M:%S", time.localtime(float(ms) / 1000.0))
115
+ except (TypeError, ValueError, OSError):
116
+ return ""
117
+
118
+
119
+ def asr_python():
120
+ """和 window.py 一样:麦克风用 ASR 的 Python,不是带 tkinter 的这个。"""
121
+ for key in ("DSH_ASR_PYTHON", "DSH_FLOAT_PYTHON"):
122
+ v = os.environ.get(key)
123
+ if v:
124
+ return v
125
+ if os.name == "nt":
126
+ return "python.exe"
127
+ return "python3"
128
+
129
+
130
+ def f(size, bold=False):
131
+ return (FONT, size, "bold") if bold else (FONT, size)
132
+
133
+
134
+ def display_hz():
135
+ """显示器刷新率;240Hz 屏也照实返回,但软件管线不会硬追 240。"""
136
+ try:
137
+ u = ctypes.windll.user32
138
+ g = ctypes.windll.gdi32
139
+ dc = u.GetDC(0)
140
+ hz = int(g.GetDeviceCaps(dc, 116))
141
+ u.ReleaseDC(0, dc)
142
+ return hz if hz > 0 else 60
143
+ except Exception:
144
+ return 60
145
+
146
+
147
+ def slabs_for(w, h):
148
+ """仓库那种三块玻璃:标题栏 / 主体 / 输入栏,中间留透明缝。"""
149
+ out, gap = 12, 10
150
+ top_h, bot_h = 54, 70
151
+ top = (out, out, w - out, out + top_h)
152
+ bot = (out, h - out - bot_h, w - out, h - out)
153
+ body = (out, top[3] + gap, w - out, bot[1] - gap)
154
+ return top, body, bot
155
+
156
+
157
+ def chat_layout(h):
158
+ """消息区在高度不足 560 时压缩行高;底部输入框始终贴底。"""
159
+ input_top = h - 80
160
+ if h >= 560:
161
+ ys, bh = [124, 214, 304, 404], 60
162
+ else:
163
+ # 顶部留 8px 空隙给最后一条和输入框,避免贴在一起
164
+ avail = max(0, input_top - 124 - 8)
165
+ bh = min(60, max(36, (avail - 24) // 4))
166
+ gap = max(8, (avail - 4 * bh) // 3)
167
+ ys = [124 + i * (bh + gap) for i in range(4)]
168
+ return ys, bh, input_top
169
+
170
+
171
+ def shapes_for(w, h):
172
+ """按窗口尺寸生成内部框位置;宽度横向伸展,底栏贴底。"""
173
+ ys, bh, input_top = chat_layout(h)
174
+ # 真实聊天流每条长度不可预测,四个气泡统一吃满内容宽度;输入/发送仍分开
175
+ return [
176
+ (38, ys[0], w - 38, ys[0] + bh, 30),
177
+ (38, ys[1], w - 38, ys[1] + bh, 30),
178
+ (38, ys[2], w - 38, ys[2] + bh, 30),
179
+ (38, ys[3], w - 38, ys[3] + bh, 30),
180
+ (36, input_top, w - 146, input_top + 54, 27),
181
+ (w - 134, input_top, w - 36, input_top + 54, 27),
182
+ ]
183
+
184
+
185
+ SHAPES = shapes_for(W, H)
186
+
187
+
188
+ def rounded_mask():
189
+ # 三块独立的玻璃;缝里保持透明,能透出桌面。
190
+ ss = 4
191
+ m = Image.new("L", (W * ss, H * ss), 0)
192
+ d = ImageDraw.Draw(m)
193
+ for x0, y0, x1, y1 in slabs_for(W, H):
194
+ d.rounded_rectangle((x0 * ss, y0 * ss, x1 * ss, y1 * ss),
195
+ radius=22 * ss, fill=255)
196
+ return m.resize((W, H), Image.Resampling.LANCZOS)
197
+
198
+
199
+ def build_overlay():
200
+ """只画气泡和输入控件;窗口本体不再加 tint / 高光 / 外圈。"""
201
+ layer = Image.new("RGBA", (W, H), (0, 0, 0, 0))
202
+ d = ImageDraw.Draw(layer)
203
+
204
+ # 只给内部框轻微染色,不做描边;窗口本体仍然完全透明
205
+ tints = [
206
+ (235, 242, 255, 5),
207
+ (110, 175, 255, 14),
208
+ (235, 242, 255, 4),
209
+ (235, 242, 255, 4),
210
+ (235, 242, 255, 5),
211
+ (110, 175, 255, 12),
212
+ ]
213
+ for (x0, y0, x1, y1, r), fill in zip(SHAPES, tints):
214
+ d.rounded_rectangle((x0, y0, x1, y1), radius=r, fill=fill)
215
+ return layer
216
+
217
+
218
+ def build_warp():
219
+ """半分辨率边缘位移图:真正采样“边界外”的背景,不是描边。
220
+
221
+ 半径方向向外取样本,越靠近边偏移越大;到 BAND 内归零。
222
+ 只在半分辨率算,成本约 1ms,放大后边缘会有真实的弯曲/压缩。
223
+ """
224
+ hw, hh = W // 4, H // 4
225
+ yy, xx = np.mgrid[0:hh, 0:hw].astype(np.float32)
226
+ r = R / 4.0
227
+ qx = np.abs(xx - hw / 2) - (hw / 2 - r)
228
+ qy = np.abs(yy - hh / 2) - (hh / 2 - r)
229
+ sdf = (np.hypot(np.maximum(qx, 0), np.maximum(qy, 0))
230
+ + np.minimum(np.maximum(qx, qy), 0) - r)
231
+ gy, gx = np.gradient(sdf)
232
+ n = np.maximum(np.hypot(gx, gy), 1e-6)
233
+ d = -sdf
234
+ t = np.clip(1.0 - d / (BAND / 4.0), 0.0, 1.0)
235
+ mag = (AMP / 4.0) * t * t
236
+ edge_mask = np.clip((BAND / 4.0 - d) / 1.5, 0.0, 1.0)
237
+ return xx + gx / n * mag, yy + gy / n * mag, edge_mask.astype(np.float32)
238
+
239
+
240
+ MASK = rounded_mask()
241
+ # color-key 透明不能用半透明边缘:半透明像素会和黑色 KEY 混合,形成四角黑边。
242
+ # 用二值遮罩硬切,边缘像素保留自身颜色,不再与 KEY 混合。
243
+ MASK_HARD = MASK.point(lambda v: 255 if v >= 128 else 0)
244
+ OVERLAY = build_overlay()
245
+ # 染色层在 1/4 分辨率合成,避免每帧对 760x560 做一次 alpha_composite
246
+ OVERLAY_2X = OVERLAY.resize((W // 2, H // 2), Image.Resampling.BILINEAR)
247
+
248
+ # 用你给的麦克风图:去背景得到 alpha,再分别做浅色/深色两版
249
+ MIC_POS = (53, H - 67)
250
+ MIC_MASK = Image.open(Path(__file__).with_name("mic-dsh.png")).convert("L")
251
+ MIC_MASK = MIC_MASK.resize((28, 28), Image.Resampling.LANCZOS)
252
+ MIC_LIGHT = Image.new("RGBA", MIC_MASK.size, (235, 244, 255, 0))
253
+ MIC_LIGHT.putalpha(MIC_MASK)
254
+ MIC_DARK = Image.new("RGBA", MIC_MASK.size, (24, 48, 72, 0))
255
+ MIC_DARK.putalpha(MIC_MASK)
256
+ WARP_X, WARP_Y, EDGE_MASK = build_warp()
257
+
258
+ # 内部框体:气泡 + 输入框 + 发送。透镜在 1/4 分辨率算,染色用全分辨率遮罩。
259
+ BOX_BAND = 7 # 1/4 分辨率下的折射带
260
+ BOX_AMP = 8 # 1/4 分辨率下的最大采样偏移
261
+
262
+
263
+
264
+ def build_box_maps():
265
+ out = []
266
+ for x0, y0, x1, y1, r in SHAPES:
267
+ qx0, qy0 = x0 // 4, y0 // 4
268
+ qw, qh = max(2, (x1 - x0) // 4), max(2, (y1 - y0) // 4)
269
+ xx, yy = np.meshgrid(np.arange(qw, dtype=np.float32),
270
+ np.arange(qh, dtype=np.float32))
271
+ rr = r / 4.0
272
+ cx, cy = qw / 2.0, qh / 2.0
273
+ qx = np.abs(xx - cx) - (cx - rr)
274
+ qy = np.abs(yy - cy) - (cy - rr)
275
+ sdf = (np.hypot(np.maximum(qx, 0), np.maximum(qy, 0))
276
+ + np.minimum(np.maximum(qx, qy), 0) - rr)
277
+ gy, gx = np.gradient(sdf)
278
+ n = np.maximum(np.hypot(gx, gy), 1e-6)
279
+ d = -sdf
280
+ inside = d >= 0
281
+ alpha = np.clip((d + 0.6) / 1.2, 0.0, 1.0).astype(np.float32)
282
+ edge = inside & (d <= BOX_BAND)
283
+ t = np.clip(1.0 - d / BOX_BAND, 0.0, 1.0)
284
+ mag = BOX_AMP * t * t
285
+ sx = np.rint(qx0 + xx + gx / n * mag).astype(np.int32)
286
+ sy = np.rint(qy0 + yy + gy / n * mag).astype(np.int32)
287
+ np.clip(sx, 0, W // 4 - 1, out=sx)
288
+ np.clip(sy, 0, H // 4 - 1, out=sy)
289
+ out.append((qx0, qy0, qw, qh, alpha, edge, sx, sy))
290
+ return out
291
+
292
+
293
+ BOX_MAPS = build_box_maps()
294
+
295
+
296
+ def build_box_union(ow, oh):
297
+ """目标分辨率下的圆角联合遮罩,4x 超采样后缩小,边界平滑。"""
298
+ ss = 4
299
+ fx, fy = ow / W, oh / H
300
+ m = Image.new("L", (ow * ss, oh * ss), 0)
301
+ d = ImageDraw.Draw(m)
302
+ for x0, y0, x1, y1, r in SHAPES:
303
+ d.rounded_rectangle((x0 * fx * ss, y0 * fy * ss,
304
+ x1 * fx * ss, y1 * fy * ss),
305
+ radius=r * min(fx, fy) * ss, fill=255)
306
+ return m.resize((ow, oh), Image.Resampling.LANCZOS)
307
+
308
+
309
+ HW, HH = W // 2, H // 2
310
+ BOX_UNION_2X = build_box_union(HW, HH)
311
+
312
+
313
+ def rebuild_geometry(w, h):
314
+ """窗口尺寸变化后重建所有和 W/H 绑定的贴图/遮罩。"""
315
+ global W, H, SHAPES, MASK, MASK_HARD, OVERLAY, OVERLAY_2X
316
+ global WARP_X, WARP_Y, EDGE_MASK, BOX_MAPS, HW, HH, BOX_UNION_2X, MIC_POS
317
+ W, H = w, h
318
+ SHAPES = shapes_for(w, h)
319
+ MASK = rounded_mask()
320
+ MASK_HARD = MASK.point(lambda v: 255 if v >= 128 else 0)
321
+ OVERLAY = build_overlay()
322
+ OVERLAY_2X = OVERLAY.resize((W // 2, H // 2), Image.Resampling.BILINEAR)
323
+ MIC_POS = (53, H - 67)
324
+ WARP_X, WARP_Y, EDGE_MASK = build_warp()
325
+ BOX_MAPS = build_box_maps()
326
+ HW, HH = W // 2, H // 2
327
+ BOX_UNION_2X = build_box_union(HW, HH)
328
+
329
+
330
+ def finish(panel):
331
+ """只做圆角遮罩;染色已经在 1/4 分辨率合成过。"""
332
+ out = Image.new("RGB", (W, H), KEY)
333
+ out.paste(panel.convert("RGB"), (0, 0), MASK_HARD)
334
+ return out
335
+
336
+
337
+ class RECT(ctypes.Structure):
338
+ _fields_ = [("left", ctypes.c_long), ("top", ctypes.c_long),
339
+ ("right", ctypes.c_long), ("bottom", ctypes.c_long)]
340
+
341
+
342
+ class LiveGlass:
343
+ def __init__(self):
344
+ global W, H
345
+ cfg = read_config()
346
+ raw_name = cfg.get("name")
347
+ self.name = (raw_name.strip()[:24] if isinstance(raw_name, str) and raw_name.strip()
348
+ else "陪看")
349
+ self.messages = []
350
+ self._msg_offset = 0
351
+ self._file_pos = 0
352
+ self._file_size = -1
353
+ self._chat_after = None
354
+ self._mic_proc = None
355
+ self._status = ""
356
+ self._cfg_key = None
357
+ self._hidden = False
358
+ self._protocol = WindowProtocol() if WindowProtocol is not None else None
359
+ self._seen = set()
360
+ self._collapsed = False
361
+ self._saved_h = H
362
+ # 只在双击标题时创建,平时不占画布
363
+ self._title_entry = None
364
+ self._title_item = None
365
+ self._editing = False
366
+
367
+ self.root = tk.Tk()
368
+ self.root.withdraw()
369
+ self.root.overrideredirect(True)
370
+ self.root.title(self.name)
371
+ self.root.attributes("-topmost", True)
372
+ self.root.configure(bg=KEY)
373
+ self.root.attributes("-transparentcolor", KEY)
374
+
375
+ sw, sh = self.root.winfo_screenwidth(), self.root.winfo_screenheight()
376
+ self._sw, self._sh = sw, sh
377
+ # 默认比旧窗宽一点;有 geometry 就恢复,但尺寸仍在玻璃引擎的可用范围内
378
+ self._parse_geometry(cfg.get("geometry") if isinstance(cfg.get("geometry"), str) else "")
379
+ # 入场:从下方 22px 滑上来(不碰 -alpha,避免和抠色冲突)。
380
+ self._intro_target_y = self._y
381
+ self._intro_y = self._y + 22
382
+ self.root.geometry(f"{W}x{H}+{self._x}+{self._intro_y}")
383
+ rebuild_geometry(W, H)
384
+
385
+ self.canvas = tk.Canvas(self.root, width=W, height=H, bg=KEY,
386
+ highlightthickness=0, bd=0)
387
+ self.canvas.pack(fill="both", expand=True)
388
+
389
+ self._img = None
390
+ self._last_frame = None
391
+ self._bg = None
392
+ self._hwnd = None
393
+ self._excluded = False
394
+ self._drag = None
395
+ self._resize = None
396
+ self._preview_at = 0.0
397
+ self._geo_lock = threading.Lock()
398
+ self._q = queue.Queue(maxsize=1)
399
+ self._stop = threading.Event()
400
+ self._pause = threading.Event()
401
+ self._worker = threading.Thread(target=self._work, daemon=True)
402
+ self._hz = display_hz()
403
+ self._target_fps = min(MAX_FPS, self._hz)
404
+ self._sig = None
405
+ self._sig_bbox = None
406
+ self._ema = 1.0 / max(1, self._target_fps)
407
+ self._frames = 0
408
+ self._text_items = []
409
+ self._text_colors = {}
410
+ self._text_shadows = {}
411
+ self._color_at = 0.0
412
+ self._aux_at = 0.0
413
+ self._load_initial()
414
+ self._build_ui()
415
+ self._add_text_shadows()
416
+
417
+ self.root.deiconify()
418
+ self.root.update_idletasks()
419
+ shadow_ids = {sid for ids in self._text_shadows.values() for sid in ids}
420
+ self._text_items = [i for i in self.canvas.find_all()
421
+ if self.canvas.type(i) == "text"
422
+ and i not in shadow_ids]
423
+ self._set_exclude(os.environ.get("DSH_GLASS_WDA") != "0")
424
+ self._worker.start()
425
+ self.root.lift()
426
+ self.root.after(80, self.root.lift)
427
+ self.root.after(120, self.root.focus_set)
428
+ self.root.after(60, self._tick)
429
+ self.root.after(30, lambda: self._intro_step(0))
430
+ self.root.after(250, self._poll_chat)
431
+ if SNAPSHOT:
432
+ self.root.after(2600, self._snapshot_mode)
433
+
434
+ def _intro_step(self, n):
435
+ """窗口入场:6 步滑到保存的位置,之后完全交给用户拖动。"""
436
+ try:
437
+ if n >= 6:
438
+ self._y = self._intro_target_y
439
+ else:
440
+ self._y = self._intro_target_y + int(22 * (1 - (n + 1) / 6.0))
441
+ self.root.geometry(f"{W}x{H}+{self._x}+{self._y}")
442
+ except Exception:
443
+ pass
444
+ if n < 6:
445
+ self.root.after(26, lambda: self._intro_step(n + 1))
446
+
447
+ # ---- 真实聊天流 ----
448
+
449
+ def _parse_geometry(self, geo):
450
+ global W, H
451
+ sw, sh = self._sw, self._sh
452
+ w, h, x, y = W, H, max(40, sw - W - 80), max(40, (sh - H) // 2 - 40)
453
+ try:
454
+ size, rest = geo.split("+", 1)
455
+ pw, ph = (int(v) for v in size.split("x"))
456
+ px, py = (int(v) for v in rest.split("+")[:2])
457
+ w = max(MIN_W, min(sw - 40, pw))
458
+ h = max(MIN_H, min(sh - 40, ph))
459
+ x = max(0, min(sw - w, px))
460
+ y = max(0, min(sh - h, py))
461
+ except Exception:
462
+ pass
463
+ W, H = w, h
464
+ self._x, self._y = x, y
465
+
466
+ def _load_initial(self):
467
+ self.messages = []
468
+ self._seen.clear()
469
+ self._file_pos = 0
470
+ try:
471
+ lines = CHAT_FILE.read_text(encoding="utf-8").splitlines()[-80:]
472
+ for line in lines:
473
+ self._append_message(self._parse_message(line))
474
+ self._file_pos = CHAT_FILE.stat().st_size
475
+ except Exception:
476
+ self._file_pos = 0
477
+ self._file_size = self._file_pos
478
+ self._msg_offset = 0
479
+ self._replay_protocol()
480
+
481
+ @staticmethod
482
+ def _parse_message(line):
483
+ line = (line or "").strip()
484
+ if not line:
485
+ return None
486
+ try:
487
+ raw = json.loads(line)
488
+ except Exception:
489
+ return None
490
+ text = raw.get("text")
491
+ role = raw.get("role") or ("meta" if raw.get("type") == "meta" else "assistant")
492
+ # meta 行是宿主/麦克风状态(叫醒失败、录音状态),不是聊天内容:不进气泡,
493
+ # 放到标题栏下面那行状态里,别把四条消息挤掉。
494
+ if role == "meta":
495
+ return {"role": "meta", "text": str(text or ""),
496
+ "stamp": "", "at": raw.get("at")}
497
+ if not isinstance(text, str) or not text:
498
+ return None
499
+ return {"role": role,
500
+ "text": text,
501
+ "stamp": clock(raw.get("at")) if raw.get("at") is not None else "",
502
+ "at": raw.get("at")}
503
+
504
+ def _append_message(self, msg):
505
+ if not msg:
506
+ return False
507
+ key = (msg.get("role"), msg.get("text"), msg.get("at"))
508
+ if key in self._seen:
509
+ return False
510
+ self._seen.add(key)
511
+ if len(self._seen) > 2000:
512
+ self._seen = set(list(self._seen)[-1200:])
513
+ if msg.get("role") == "meta":
514
+ self._status = str(msg.get("text") or "")[:80]
515
+ return True
516
+ self.messages.append(msg)
517
+ self.messages = self.messages[-200:]
518
+ return True
519
+
520
+ # ---- 窗口接口 ----
521
+
522
+ def _render_event(self, event):
523
+ if not isinstance(event, dict):
524
+ return
525
+ kind = event.get("type")
526
+ if kind in ("message", "meta"):
527
+ self._append_message(self._parse_message(json.dumps(event, ensure_ascii=False)))
528
+ self._refresh_feed()
529
+ elif kind == "control":
530
+ self._apply_control(event)
531
+
532
+ def _apply_control(self, event):
533
+ action = str(event.get("action") or "")
534
+ value = event.get("value")
535
+ try:
536
+ if action == "rename" and str(value or "").strip():
537
+ self.name = str(value).strip()[:24]
538
+ self.root.title(self.name)
539
+ write_config({"name": self.name})
540
+ self._refresh_feed()
541
+ elif action == "collapse" and not self._collapsed:
542
+ self.toggle_collapse()
543
+ elif action == "expand" and self._collapsed:
544
+ self.toggle_collapse()
545
+ elif action == "hide":
546
+ self._hidden = True
547
+ write_config({"hidden": True})
548
+ self.root.withdraw()
549
+ elif action == "show":
550
+ self._hidden = False
551
+ write_config({"hidden": False})
552
+ self.root.deiconify()
553
+ self.root.attributes("-topmost", True)
554
+ except Exception:
555
+ pass
556
+
557
+ def _replay_protocol(self):
558
+ if self._protocol is None:
559
+ return
560
+ try:
561
+ for event in self._protocol.reset_events(60):
562
+ self._render_event(event)
563
+ except Exception:
564
+ pass
565
+
566
+ def _drain_protocol(self):
567
+ if self._protocol is None:
568
+ return []
569
+ try:
570
+ return self._protocol.read_events()
571
+ except Exception:
572
+ return []
573
+
574
+ def _poll_chat(self):
575
+ try:
576
+ self._sync_visible()
577
+ # 新接口优先;chat.jsonl 仍然读,兼容旧版插件/浏览器页。
578
+ for event in self._drain_protocol():
579
+ self._render_event(event)
580
+ if self._mic_proc is not None and self._mic_proc.poll() is not None:
581
+ self._mic_proc = None
582
+ self._status = ""
583
+ self._refresh_feed()
584
+ try:
585
+ size = CHAT_FILE.stat().st_size
586
+ except OSError:
587
+ size = 0
588
+ if size < self._file_pos:
589
+ self._load_initial()
590
+ self._refresh_feed()
591
+ elif size > self._file_pos:
592
+ new = []
593
+ with open(CHAT_FILE, "r", encoding="utf-8") as f:
594
+ f.seek(self._file_pos)
595
+ data = f.read()
596
+ self._file_pos = f.tell()
597
+ for line in data.splitlines():
598
+ msg = self._parse_message(line)
599
+ if msg:
600
+ new.append(msg)
601
+ changed = False
602
+ for msg in new:
603
+ if self._append_message(msg):
604
+ changed = True
605
+ if changed:
606
+ if self._msg_offset > 0:
607
+ self._msg_offset += len(new)
608
+ self._msg_offset = max(0, min(self._msg_offset, max(0, len(self.messages) - 1)))
609
+ self._refresh_feed()
610
+ self._file_size = size
611
+ except Exception as exc:
612
+ print("chat poll error", exc, flush=True)
613
+ if not self._stop.is_set():
614
+ self._chat_after = self.root.after(250, self._poll_chat)
615
+
616
+ def _sync_visible(self):
617
+ try:
618
+ st = CONFIG.stat()
619
+ key = (st.st_mtime_ns, st.st_size)
620
+ except OSError:
621
+ key = None
622
+ if key == self._cfg_key:
623
+ return
624
+ self._cfg_key = key
625
+ want = bool(read_config().get("hidden"))
626
+ if want == self._hidden:
627
+ return
628
+ self._hidden = want
629
+ try:
630
+ if want:
631
+ self.root.withdraw()
632
+ else:
633
+ self.root.deiconify()
634
+ self.root.attributes("-topmost", True)
635
+ self.root.lift()
636
+ except Exception:
637
+ self._hidden = not want
638
+
639
+ def _visible_messages(self):
640
+ end = max(0, len(self.messages) - self._msg_offset)
641
+ start = max(0, end - 4)
642
+ return self.messages[start:end]
643
+
644
+ def _refresh_feed(self):
645
+ """聊天流变了就重画文字;Entry 的草稿和焦点要保住。"""
646
+ if not hasattr(self, "canvas"):
647
+ return
648
+ self._build_ui()
649
+ self._text_items = [i for i in self.canvas.find_all()
650
+ if self.canvas.type(i) == "text"]
651
+ if self._last_frame is not None:
652
+ try:
653
+ self._img = ImageTk.PhotoImage(self._last_frame, master=self.canvas)
654
+ self.canvas.itemconfigure(self._bg, image=self._img)
655
+ self.canvas.tag_lower(self._bg)
656
+ self._color_at = 0.0
657
+ self._aux_at = 0.0
658
+ self._adapt_text(self._last_frame)
659
+ self._adapt_aux(self._last_frame)
660
+ except Exception:
661
+ pass
662
+ def _send(self, _event=None):
663
+ try:
664
+ text = self.entry.get().strip()
665
+ except Exception:
666
+ return "break"
667
+ if not text:
668
+ return "break"
669
+ try:
670
+ append_user(text)
671
+ except Exception as exc:
672
+ self._status = f"写不进去:{exc}"
673
+ self._refresh_feed()
674
+ return "break"
675
+ try:
676
+ self.entry.delete(0, "end")
677
+ except Exception:
678
+ pass
679
+ try:
680
+ if self._protocol is not None:
681
+ self._protocol.action("say", text=text)
682
+ except Exception:
683
+ pass
684
+ self._render_input()
685
+ self.root.after(40, self._poll_chat)
686
+ return "break"
687
+
688
+ def _wheel(self, e):
689
+ if not self.messages:
690
+ return
691
+ step = 1 if e.delta > 0 else -1
692
+ self._msg_offset = max(0, min(len(self.messages) - 1, self._msg_offset + step))
693
+ self._refresh_feed()
694
+
695
+ def _toggle_mic(self):
696
+ if self._mic_proc is not None and self._mic_proc.poll() is None:
697
+ self._stop_mic()
698
+ return
699
+ if not MIC_SCRIPT.exists():
700
+ self._status = "找不到 mic.py"
701
+ self._refresh_feed()
702
+ return
703
+ try:
704
+ self._mic_proc = subprocess.Popen(
705
+ [asr_python(), str(MIC_SCRIPT), "--engine", "local"],
706
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
707
+ creationflags=0x08000000 if os.name == "nt" else 0,
708
+ )
709
+ self._status = "录音中"
710
+ except Exception as exc:
711
+ self._status = f"麦起不来:{exc}"
712
+ self._refresh_feed()
713
+
714
+ def _stop_mic(self):
715
+ p = self._mic_proc
716
+ self._mic_proc = None
717
+ self._status = ""
718
+ if p is not None and p.poll() is None:
719
+ try:
720
+ p.terminate()
721
+ except Exception:
722
+ pass
723
+ self._refresh_feed()
724
+
725
+ def _save_geometry(self):
726
+ write_config({"geometry": f"{self.root.winfo_width()}x{self.root.winfo_height()}"
727
+ f"+{self.root.winfo_x()}+{self.root.winfo_y()}"})
728
+
729
+ def _hwnd_root(self):
730
+ if self._hwnd is None:
731
+ self._hwnd = ctypes.windll.user32.GetAncestor(self.root.winfo_id(), 2)
732
+ return self._hwnd
733
+
734
+ def _set_exclude(self, on):
735
+ hwnd = self._hwnd_root()
736
+ fn = ctypes.windll.user32.SetWindowDisplayAffinity
737
+ fn.argtypes = [wintypes.HWND, wintypes.DWORD]
738
+ fn.restype = wintypes.BOOL
739
+ ok = bool(fn(hwnd, 0x11 if on else 0))
740
+ self._excluded = ok and on
741
+ if not ok:
742
+ print("WDA failed", ctypes.GetLastError(), flush=True)
743
+
744
+ def _bbox(self):
745
+ hwnd = self._hwnd_root()
746
+ rc = RECT()
747
+ ctypes.windll.user32.GetWindowRect(hwnd, ctypes.byref(rc))
748
+ return (rc.left, rc.top, rc.right, rc.bottom)
749
+
750
+ def _capture(self, sct):
751
+ l, t, r, b = self._bbox()
752
+ if r <= l or b <= t:
753
+ return None
754
+ # 多抓一圈,边缘透镜才能取到“框外”的背景
755
+ gl = max(0, l - PAD)
756
+ gt = max(0, t - PAD)
757
+ gr = min(self._sw, r + PAD)
758
+ gb = min(self._sh, b + PAD)
759
+ shot = sct.grab({"left": gl, "top": gt,
760
+ "width": gr - gl, "height": gb - gt})
761
+ im = Image.frombytes("RGB", shot.size, shot.rgb)
762
+ sw4, sh4 = max(2, (gr - gl) // 4), max(2, (gb - gt) // 4)
763
+ # 60fps 路径:只在 1/4 分辨率做一次模糊和折射,再放大
764
+ small_raw = im.resize((sw4, sh4), Image.Resampling.BILINEAR)
765
+ arr_raw = np.asarray(small_raw)
766
+ # 静态跳帧:先用未模糊的 raw 判断,静止时连模糊都不用做。
767
+ # 采样 4px、均值 0.01 + 最大差 0.5、运动后保持 0.3s;比原来的
768
+ # 8px / 0.18 更早触发,慢速滚动不会先停一两帧再动。
769
+ sig = arr_raw[::4, ::4].astype(np.int16).mean(axis=2)
770
+ box = (gl, gt, gr, gb)
771
+ now = time.perf_counter()
772
+ moved = False
773
+ if self._sig is not None and box == self._sig_bbox and sig.shape == self._sig.shape:
774
+ d = np.abs(sig - self._sig)
775
+ moved = bool(float(d.mean()) > 0.01 or float(d.max()) > 0.5)
776
+ if moved:
777
+ self._last_motion = now
778
+ if (not FORCE and not moved and box == self._sig_bbox
779
+ and now - getattr(self, "_last_motion", 0.0) > 0.30):
780
+ self._sig = sig
781
+ return None
782
+ self._sig = sig
783
+ self._sig_bbox = box
784
+ small = small_raw.filter(ImageFilter.GaussianBlur(1.45))
785
+ strong = small.filter(ImageFilter.GaussianBlur(2.6))
786
+ arr = np.asarray(small)
787
+ arr_strong = np.asarray(strong)
788
+ px = int(round((l - gl) / 4.0))
789
+ py = int(round((t - gt) / 4.0))
790
+ sx = np.rint(WARP_X + px).astype(np.int32)
791
+ sy = np.rint(WARP_Y + py).astype(np.int32)
792
+ np.clip(sx, 0, arr.shape[1] - 1, out=sx)
793
+ np.clip(sy, 0, arr.shape[0] - 1, out=sy)
794
+ warped = arr[sy, sx]
795
+ # 内部框:边缘折射 + 中心强模糊仍在 1/4 分辨率完成
796
+ strong_panel = arr_strong[sy, sx]
797
+ out_panel = warped.copy()
798
+ for qx0, qy0, qw, qh, alpha, edge, bsx, bsy in BOX_MAPS:
799
+ base_patch = warped[qy0:qy0 + qh, qx0:qx0 + qw]
800
+ edge_patch = arr_raw[np.clip(bsy + py, 0, arr_raw.shape[0] - 1),
801
+ np.clip(bsx + px, 0, arr_raw.shape[1] - 1)]
802
+ strong_patch = strong_panel[qy0:qy0 + qh, qx0:qx0 + qw]
803
+ patch = np.where(edge[..., None], edge_patch, strong_patch)
804
+ a = alpha[..., None]
805
+ out_panel[qy0:qy0 + qh, qx0:qx0 + qw] = (
806
+ base_patch * (1.0 - a) + patch * a)
807
+ # 1/4 透镜结果放大后,用全分辨率联合圆角遮罩贴回;
808
+ # 边界是 PIL 4x 超采样遮罩,不再有 1/4 放大的像素台阶。
809
+ # 2x 合成:比全分辨率轻,比 1/4 明显平滑,兼顾帧率和圆角
810
+ base_2x = Image.fromarray(warped).resize(
811
+ (HW, HH), Image.Resampling.BILINEAR)
812
+ lens_2x = Image.fromarray(out_panel).resize(
813
+ (HW, HH), Image.Resampling.BILINEAR)
814
+ panel = Image.composite(lens_2x, base_2x, BOX_UNION_2X)
815
+ panel = Image.alpha_composite(
816
+ panel.convert("RGBA"), OVERLAY_2X).convert("RGB")
817
+ # 麦克风图标:先回到全分辨率再贴,避免坐标落在 2x 画布外
818
+ out = panel.convert("RGB").resize((W, H), Image.Resampling.BILINEAR)
819
+ mic_box = out.crop((MIC_POS[0], MIC_POS[1],
820
+ MIC_POS[0] + 28, MIC_POS[1] + 28)).convert("L")
821
+ mic_bg = float(np.median(np.asarray(mic_box))) / 255.0
822
+ out = out.convert("RGBA")
823
+ icon = MIC_LIGHT if mic_bg < 0.48 else MIC_DARK
824
+ out.paste(icon, MIC_POS, icon)
825
+ return finish(out.convert("RGB"))
826
+
827
+ def _work(self):
828
+ """抓取 + 模糊 + 合成全在后台,主线程只负责显示最新一帧。"""
829
+ idle = 0
830
+ with mss.MSS() as sct:
831
+ while not self._stop.is_set():
832
+ if self._pause.is_set():
833
+ time.sleep(0.03)
834
+ continue
835
+ t0 = time.perf_counter()
836
+ try:
837
+ with self._geo_lock:
838
+ out = self._capture(sct)
839
+ if out is not None:
840
+ idle = 0
841
+ try:
842
+ self._q.get_nowait()
843
+ except queue.Empty:
844
+ pass
845
+ self._q.put(out)
846
+ else:
847
+ idle += 1
848
+ except Exception as exc:
849
+ print("capture error", exc, flush=True)
850
+ dt = time.perf_counter() - t0
851
+ self._ema = self._ema * 0.9 + dt * 0.1
852
+ if FORCE:
853
+ self._target_fps = MAX_FPS
854
+ elif self._ema > 0.026:
855
+ self._target_fps = 45
856
+ elif self._ema > 0.016:
857
+ self._target_fps = 60
858
+ elif self._ema > 0.011:
859
+ self._target_fps = 90
860
+ else:
861
+ self._target_fps = min(MAX_FPS, self._hz)
862
+ # 静态画面:跳过合成,但保留 60fps 探针,变化后 ~16ms 内响应
863
+ if idle > 20:
864
+ time.sleep(max(0.016, 1 / max(1, self._target_fps) - dt))
865
+ else:
866
+ time.sleep(max(0.0, 1 / max(1, self._target_fps) - dt))
867
+
868
+ def _text(self, x, y, text, anchor="center", fill="#f2f8ff",
869
+ font=None, max_width=None, tags=()):
870
+ """按字符拆成 Canvas 文本;每个字单独适配背后的明暗。"""
871
+ fobj = tkfont.Font(root=self.root, font=font)
872
+ measure = fobj.measure
873
+ linespace = fobj.metrics("linespace")
874
+ if max_width is not None:
875
+ lines, cur = [], ""
876
+ for ch in text:
877
+ if not cur or measure(cur + ch) <= max_width:
878
+ cur += ch
879
+ else:
880
+ lines.append(cur)
881
+ cur = ch
882
+ lines.append(cur)
883
+ else:
884
+ lines = [text]
885
+ top_anchor = anchor in ("n", "nw", "ne")
886
+ right_anchor = anchor in ("e", "ne", "se")
887
+ center_anchor = anchor in ("center", "n", "s")
888
+ height = fobj.metrics("ascent") + fobj.metrics("descent")
889
+ for i, line in enumerate(lines):
890
+ lw = measure(line)
891
+ if right_anchor:
892
+ lx = x - lw
893
+ elif center_anchor:
894
+ lx = x - lw / 2
895
+ else:
896
+ lx = x
897
+ if top_anchor:
898
+ ly = y + i * linespace + height / 2
899
+ else:
900
+ ly = y + (i - (len(lines) - 1) / 2) * linespace
901
+ for i, ch in enumerate(line):
902
+ cx = lx + measure(line[:i])
903
+ self.canvas.create_text(cx, ly, text=ch, anchor="w",
904
+ fill=fill, font=font, tags=tags)
905
+
906
+ def _render_input(self):
907
+ """输入文字画在 Canvas 上;隐藏 Entry 只负责 IME/键盘。"""
908
+ if not hasattr(self, "entry") or self.entry is None:
909
+ return
910
+ c = self.canvas
911
+ c.delete("inputtext", "inputcursor")
912
+ try:
913
+ text = self.entry.get()
914
+ focused = self.root.focus_get() is self.entry
915
+ except Exception:
916
+ text, focused = "", False
917
+ x0, y0, x1, y1, _r = SHAPES[4]
918
+ x, y = x0 + 84, y0 + 27
919
+ maxw = max(60, x1 - x0 - 100)
920
+ if not text and not focused:
921
+ self._text(x, y, "在这里跟它说话…", anchor="w",
922
+ fill="#8e9db2", font=f(11),
923
+ tags=("inputtext", "inputzone"))
924
+ elif text:
925
+ fobj = tkfont.Font(root=self.root, font=f(11))
926
+ while text and fobj.measure(text) > maxw:
927
+ text = text[1:]
928
+ self._text(x, y, text, anchor="w", fill="#eef6ff",
929
+ font=f(11), tags=("inputtext", "inputzone"))
930
+ if focused:
931
+ cx = x + fobj.measure(text)
932
+ c.create_line(cx + 1, y - 9, cx + 1, y + 9,
933
+ fill="#b9d7ff", width=1, tags=("inputcursor",))
934
+ elif focused:
935
+ c.create_line(x + 1, y - 9, x + 1, y + 9,
936
+ fill="#b9d7ff", width=1, tags=("inputcursor",))
937
+ self._text_items = [i for i in c.find_all() if c.type(i) == "text"]
938
+
939
+ def _on_input_key(self, _e=None):
940
+ self._render_input()
941
+ return None
942
+
943
+ def _focus_input(self, _e=None):
944
+ try:
945
+ # 用户已经点了输入区,这里可以抢焦点;启动时仍然不抢系统焦点
946
+ self.entry.focus_force()
947
+ self.entry.icursor("end")
948
+ except Exception:
949
+ pass
950
+ self._render_input()
951
+
952
+ # ---- 改名 ----
953
+
954
+ def _edit_title(self, _event=None):
955
+ """双击标题:就地变输入框(PR #15 底稿没有改名,补上)。"""
956
+ if getattr(self, "_editing", False):
957
+ return "break"
958
+ self._editing = True
959
+ if self._title_entry is None:
960
+ self._title_entry = tk.Entry(self.root, font=f(18), relief="flat", bd=0,
961
+ bg="#1b2330", fg="#f7fbff", insertbackground="#f7fbff")
962
+ self._title_entry.bind("<Return>", self._commit_title)
963
+ self._title_entry.bind("<Escape>", self._cancel_title)
964
+ self._title_entry.bind("<FocusOut>", self._commit_title)
965
+ self._title_entry.delete(0, "end")
966
+ self._title_entry.insert(0, self.name)
967
+ if self._title_item is not None:
968
+ self.canvas.delete(self._title_item)
969
+ self._title_item = self.canvas.create_window(72, 54, anchor="w",
970
+ window=self._title_entry, width=180)
971
+ self._title_entry.focus_set()
972
+ self._title_entry.select_range(0, "end")
973
+ return "break"
974
+
975
+ def _commit_title(self, _event=None):
976
+ if not getattr(self, "_editing", False):
977
+ return
978
+ self._editing = False
979
+ text = self._title_entry.get().strip()
980
+ if self._title_item is not None:
981
+ self.canvas.delete(self._title_item)
982
+ self._title_item = None
983
+ if text and text != self.name:
984
+ self.name = text[:24]
985
+ self.root.title(self.name)
986
+ write_config({"name": self.name})
987
+ try:
988
+ if self._protocol is not None:
989
+ self._protocol.action("rename", value=self.name)
990
+ except Exception:
991
+ pass
992
+ self._refresh_feed()
993
+ return "break"
994
+
995
+ def _cancel_title(self):
996
+ self._editing = False
997
+ if self._title_item is not None:
998
+ self.canvas.delete(self._title_item)
999
+ self._title_item = None
1000
+ self._refresh_feed()
1001
+ return "break"
1002
+
1003
+ # ---- 折叠 ----
1004
+
1005
+ def toggle_collapse(self, _event=None):
1006
+ global H
1007
+ self._collapsed = not getattr(self, "_collapsed", False)
1008
+ if self._collapsed:
1009
+ self._saved_h = H
1010
+ H = 2 * 12 + 54
1011
+ else:
1012
+ H = getattr(self, "_saved_h", H)
1013
+ rebuild_geometry(W, H)
1014
+ self.root.geometry(f"{W}x{H}+{self._x}+{self._y}")
1015
+ self._rebuild(W, H)
1016
+ try:
1017
+ if self._protocol is not None:
1018
+ self._protocol.action("collapse" if self._collapsed else "expand")
1019
+ except Exception:
1020
+ pass
1021
+
1022
+ def _build_ui(self):
1023
+ c = self.canvas
1024
+ old_text, old_focus, old_cursor = "", False, 0
1025
+ try:
1026
+ if getattr(self, "entry", None) is not None:
1027
+ old_text = self.entry.get()
1028
+ old_cursor = self.entry.index("insert")
1029
+ old_focus = self.root.focus_get() is self.entry
1030
+ self.entry.destroy()
1031
+ except Exception:
1032
+ pass
1033
+ self.entry = None
1034
+ # 重排时必须先清掉上一轮的文字和底图:只 create 不 delete 会在每一条
1035
+ # 新消息到达时把旧文字留在 Canvas 上,形成重影(而且旧的左对齐用户消息
1036
+ # 会和新的右对齐版本叠在一起,看起来像“左右没分开”)。
1037
+ c.delete("all")
1038
+ # 背景图 item 先建,后续文字都在它上面
1039
+ self._bg = c.create_image(0, 0, anchor="nw")
1040
+ if self._last_frame is not None:
1041
+ try:
1042
+ self._img = ImageTk.PhotoImage(self._last_frame, master=self.canvas)
1043
+ c.itemconfigure(self._bg, image=self._img)
1044
+ except Exception:
1045
+ pass
1046
+ if PREVIEW:
1047
+ c.create_rectangle(0, 0, W, H, fill="#0d131d", outline="",
1048
+ tags=("preview-bg",))
1049
+ c.tag_lower("preview-bg")
1050
+
1051
+ w, h = W, H
1052
+ name = self.name[:10]
1053
+ self._text(76, 54, name, anchor="w", fill="#f7fbff",
1054
+ font=f(21, True), tags=("title",))
1055
+ count = self._status or f"{len(self.messages)} 条"
1056
+ self._text(176, 54, count, anchor="w", fill="#dbe6f5",
1057
+ font=f(11))
1058
+ # 右上角按钮跟随窗口宽度内收
1059
+ self._text(w - 94, 38, "▾", anchor="w",
1060
+ fill="#7f8da3", font=f(12), tags=("collapse",))
1061
+ self._text(w - 58, 38, "✕", anchor="w", fill="#9fb0c8",
1062
+ font=f(13), tags=("close",))
1063
+
1064
+ ys = [s[1] for s in SHAPES[:4]]
1065
+ bh = SHAPES[0][3] - SHAPES[0][1]
1066
+ shown = self._visible_messages()
1067
+ # 小窗口不放时间戳,避免和压缩后的气泡文字重叠
1068
+ if h >= 560:
1069
+ for i, msg in enumerate(shown):
1070
+ if msg.get("stamp"):
1071
+ if str(msg.get("role") or "").lower() in ("user", "me", "human"):
1072
+ self._text(SHAPES[i][2] - 26, ys[i] - 20, msg["stamp"], anchor="ne",
1073
+ fill="#a8b7c9", font=f(9), tags=("feed",))
1074
+ else:
1075
+ self._text(72, ys[i] - 20, msg["stamp"], anchor="nw",
1076
+ fill="#a8b7c9", font=f(9), tags=("feed",))
1077
+
1078
+ # 可见的最近 4 条;滚轮往前翻时整体换页
1079
+ for i, msg in enumerate(shown):
1080
+ x0, y0, x1, _y1, _r = SHAPES[i]
1081
+ is_user = str(msg.get("role") or "").lower() in ("user", "me", "human")
1082
+ tx = (x1 - 26) if is_user else (x0 + 26)
1083
+ ta = "e" if is_user else "w"
1084
+ self._text(tx, y0 + bh // 2, msg["text"], anchor=ta,
1085
+ max_width=max(120, x1 - x0 - 52),
1086
+ fill="#edf6ff", font=f(14), tags=("feed",))
1087
+ if not shown:
1088
+ self._text(w // 2, SHAPES[0][1] + bh // 2,
1089
+ "在这里跟它说话 · 滚轮翻历史", anchor="center",
1090
+ fill="#8e9db2", font=f(12), tags=("feed",))
1091
+
1092
+ # 输入:Entry 只做 IME/键盘的背面接收器,放到 2x2 且底色是键色,
1093
+ # 真正显示的文字画在 Canvas 上 —— 否则玻璃里会出现一个突兀的黑条。
1094
+ x0, y0, x1, y1, _r = SHAPES[4]
1095
+ self.entry = tk.Entry(self.root, bg=KEY, fg=KEY, insertbackground=KEY,
1096
+ relief="flat", bd=0, font=f(11), insertwidth=0,
1097
+ highlightthickness=0)
1098
+ self._entry_item = c.create_window(
1099
+ x0 + 84, y0 + 27, window=self.entry, anchor="w",
1100
+ width=2, height=2, tags=("feed",))
1101
+ self.entry.bind("<KeyRelease>", self._on_input_key)
1102
+ self.entry.bind("<Return>", self._send)
1103
+ self.entry.bind("<FocusIn>", lambda _e: self._render_input())
1104
+ self.entry.bind("<FocusOut>", lambda _e: self._render_input())
1105
+ if old_text:
1106
+ self.entry.insert(0, old_text)
1107
+ self.entry.icursor(min(old_cursor, len(old_text)))
1108
+ if old_focus:
1109
+ self.entry.focus_set()
1110
+ self._render_input()
1111
+
1112
+ x0, y0, x1, y1, _r = SHAPES[5]
1113
+ self._text((x0 + x1) // 2, y0 + 27, "发送", tags=("send", "feed"),
1114
+ fill="#ffffff", font=f(12, True))
1115
+
1116
+ # 最上面正中的细条,长度随窗口宽度走
1117
+ self._bar_len = max(72, int(w * BAR_FRAC))
1118
+ self._bar = c.create_line(w // 2 - self._bar_len // 2, BAR_Y,
1119
+ w // 2 + self._bar_len // 2, BAR_Y,
1120
+ width=BAR_THICK, fill="#b8cbe0",
1121
+ capstyle="round")
1122
+
1123
+ c.tag_bind("close", "<Button-1>", self._close)
1124
+ c.tag_bind("send", "<Button-1>", self._send)
1125
+ c.tag_bind("collapse", "<Button-1>", self.toggle_collapse)
1126
+ c.tag_bind("title", "<Double-Button-1>", self._edit_title)
1127
+ c.tag_bind("inputzone", "<Button-1>", self._focus_input)
1128
+ c.tag_raise("close")
1129
+ c.tag_raise("send")
1130
+ self._draw_scrollbar()
1131
+ if getattr(self, "_collapsed", False):
1132
+ c.itemconfigure("feed", state="hidden")
1133
+
1134
+ def _draw_scrollbar(self):
1135
+ """仓库布局:滚动条放在主体玻璃右侧外面,不占消息区。"""
1136
+ c = self.canvas
1137
+ c.delete("sbar")
1138
+ total = len(self.messages)
1139
+ visible = 4
1140
+ if total <= visible:
1141
+ return
1142
+ _top, body, _bot = slabs_for(W, H)
1143
+ x = W - 6
1144
+ top = body[1] + 8
1145
+ view_h = max(1, body[3] - body[1] - 16)
1146
+ frac = visible / float(total)
1147
+ thumb = max(24, int(view_h * frac))
1148
+ max_off = max(1, total - visible)
1149
+ t = 1.0 - max(0, min(max_off, self._msg_offset)) / float(max_off)
1150
+ y0 = top + t * max(0, view_h - thumb)
1151
+ c.create_line(x, y0, x, y0 + thumb, width=3, fill="#8d95a4",
1152
+ capstyle="round", tags=("sbar",))
1153
+ c.tag_raise("sbar")
1154
+
1155
+ def _preview_resize(self, w, h):
1156
+ """拖拽时先缩放上一帧并重排文字,松手后再重建玻璃贴图。"""
1157
+ global W, H, SHAPES, MIC_POS
1158
+ W, H = w, h
1159
+ SHAPES = shapes_for(w, h)
1160
+ MIC_POS = (53, h - 67)
1161
+ self.canvas.config(width=w, height=h)
1162
+ self.canvas.delete("all")
1163
+ self._img = None
1164
+ self._bg = None
1165
+ self._text_items = []
1166
+ self._text_colors = {}
1167
+ self._text_shadows = {}
1168
+ self._build_ui()
1169
+ self._add_text_shadows()
1170
+ shadow_ids = {sid for ids in self._text_shadows.values() for sid in ids}
1171
+ self._text_items = [i for i in self.canvas.find_all()
1172
+ if self.canvas.type(i) == "text"
1173
+ and i not in shadow_ids]
1174
+ if self._last_frame is not None:
1175
+ preview = self._last_frame.resize(
1176
+ (w, h), Image.Resampling.BILINEAR)
1177
+ self._img = ImageTk.PhotoImage(preview, master=self.canvas)
1178
+ self.canvas.itemconfigure(self._bg, image=self._img)
1179
+ self.canvas.tag_lower(self._bg)
1180
+ # 预览期间也立刻按新背景选字色,不等松手
1181
+ self._color_at = 0.0
1182
+ self._aux_at = 0.0
1183
+ self._adapt_text(preview)
1184
+ self._adapt_aux(preview)
1185
+
1186
+ def _rebuild(self, w, h):
1187
+ """按新窗口尺寸重建玻璃贴图和全部 Canvas 控件。"""
1188
+ self._pause.set()
1189
+ with self._geo_lock:
1190
+ rebuild_geometry(w, h)
1191
+ self.canvas.config(width=w, height=h)
1192
+ self.canvas.delete("all")
1193
+ self._img = None
1194
+ self._bg = None
1195
+ self._text_items = []
1196
+ self._text_colors = {}
1197
+ self._text_shadows = {}
1198
+ self._color_at = 0.0
1199
+ self._aux_at = 0.0
1200
+ self._sig = None
1201
+ self._sig_bbox = None
1202
+ self._build_ui()
1203
+ self._add_text_shadows()
1204
+ shadow_ids = {sid for ids in self._text_shadows.values() for sid in ids}
1205
+ self._text_items = [i for i in self.canvas.find_all()
1206
+ if self.canvas.type(i) == "text"
1207
+ and i not in shadow_ids]
1208
+ while True:
1209
+ try:
1210
+ self._q.get_nowait()
1211
+ except queue.Empty:
1212
+ break
1213
+ if self._last_frame is not None:
1214
+ seed = self._last_frame.resize(
1215
+ (w, h), Image.Resampling.BILINEAR)
1216
+ self._img = ImageTk.PhotoImage(seed, master=self.canvas)
1217
+ self.canvas.itemconfigure(self._bg, image=self._img)
1218
+ self.canvas.tag_lower(self._bg)
1219
+ self._color_at = 0.0
1220
+ self._aux_at = 0.0
1221
+ self._adapt_text(seed)
1222
+ self._adapt_aux(seed)
1223
+ self._pause.clear()
1224
+
1225
+ def _add_text_shadows(self):
1226
+ """不再叠偏移描边;之前四向黑影会看起来像重影。"""
1227
+ self._text_shadows = {}
1228
+
1229
+ def _adapt_text(self, out):
1230
+ """按文字背后的暗部/亮部比例选色,并同步描边颜色。"""
1231
+ now = time.time()
1232
+ if now - self._color_at < 0.12:
1233
+ return
1234
+ self._color_at = now
1235
+ for item in self._text_items:
1236
+ box = self.canvas.bbox(item)
1237
+ if not box:
1238
+ continue
1239
+ x0, y0, x1, y1 = box
1240
+ x0, y0 = max(0, x0 - 2), max(0, y0 - 2)
1241
+ x1, y1 = min(W, x1 + 2), min(H, y1 + 2)
1242
+ if x1 <= x0 or y1 <= y0:
1243
+ continue
1244
+ gray = np.asarray(out.crop((x0, y0, x1, y1)).convert("L"))
1245
+ p50 = float(np.percentile(gray, 50)) / 255.0
1246
+ dark = float(np.mean(gray < 107))
1247
+ light = float(np.mean(gray > 158))
1248
+ # 先看这块背景是偏暗还是偏亮,混合区域再退回中位亮度
1249
+ if dark > light + 0.08:
1250
+ color = "#f2f8ff"
1251
+ elif light > dark + 0.08:
1252
+ color = "#07111d"
1253
+ elif p50 < 0.50:
1254
+ color = "#f2f8ff"
1255
+ else:
1256
+ color = "#07111d"
1257
+ if color != self._text_colors.get(item):
1258
+ self.canvas.itemconfigure(item, fill=color)
1259
+ self._text_colors[item] = color
1260
+
1261
+ def _adapt_aux(self, out):
1262
+ """最上面细条随背景切换深浅。"""
1263
+ now = time.time()
1264
+ if now - self._aux_at < 0.25:
1265
+ return
1266
+ self._aux_at = now
1267
+ mid = W // 2
1268
+ half = max(50, self._bar_len // 2)
1269
+ bar = np.asarray(out.crop(
1270
+ (mid - half, BAR_Y - 6, mid + half, BAR_Y + 12)).convert("L"))
1271
+ p50 = float(np.median(bar)) / 255.0
1272
+ bar_fill = "#b8cbe0" if p50 < 0.48 else "#4e6278"
1273
+ self.canvas.itemconfigure(self._bar, fill=bar_fill)
1274
+
1275
+
1276
+
1277
+ def _snapshot_mode(self):
1278
+ """只给文档截图:停抓取、关 WDA,保留最后一帧(不改变正常路径)。"""
1279
+ self._pause.set()
1280
+ if self._excluded:
1281
+ self._set_exclude(False)
1282
+
1283
+ def _tick(self):
1284
+ if PREVIEW:
1285
+ self._pause.set()
1286
+ if self._excluded:
1287
+ self._set_exclude(False)
1288
+ self.root.after(100, self._tick)
1289
+ return
1290
+ # 缩放拖拽期间由 _preview_resize 负责画面,避免旧帧覆盖预览
1291
+ if self._resize:
1292
+ self.root.after(INTERVAL_MS, self._tick)
1293
+ return
1294
+ if not self._excluded:
1295
+ self._set_exclude(True)
1296
+ self._pause.clear()
1297
+
1298
+ try:
1299
+ out = self._q.get_nowait()
1300
+ except queue.Empty:
1301
+ out = None
1302
+ if out is not None:
1303
+ try:
1304
+ self._last_frame = out
1305
+ self._img = ImageTk.PhotoImage(out, master=self.canvas)
1306
+ self.canvas.itemconfigure(self._bg, image=self._img)
1307
+ self.canvas.tag_lower(self._bg)
1308
+ self._adapt_text(out)
1309
+ self._adapt_aux(out)
1310
+ except Exception as exc:
1311
+ print("draw error", exc, flush=True)
1312
+
1313
+ self.root.after(INTERVAL_MS, self._tick)
1314
+
1315
+ def _close(self, _e=None):
1316
+ try:
1317
+ self._save_geometry()
1318
+ if self._chat_after is not None:
1319
+ try:
1320
+ self.root.after_cancel(self._chat_after)
1321
+ except Exception:
1322
+ pass
1323
+ self._stop_mic()
1324
+ self._stop.set()
1325
+ self._pause.set()
1326
+ self._set_exclude(False)
1327
+ self._worker.join(timeout=0.3)
1328
+ ctypes.windll.winmm.timeEndPeriod(1)
1329
+ finally:
1330
+ self.root.destroy()
1331
+ return "break"
1332
+
1333
+ def _hide_window(self, _e=None):
1334
+ """藏起来但继续收消息;插件写 hidden=false 后会重新出现。"""
1335
+ write_config({"hidden": True})
1336
+ self._hidden = True
1337
+ self.root.withdraw()
1338
+ return "break"
1339
+
1340
+ # 边缘缩放 / 窗口拖动
1341
+ def _edge_at(self, x, y):
1342
+ w, h = self.root.winfo_width(), self.root.winfo_height()
1343
+ edge, corner = 10, 26
1344
+ # 圆角区域是透明的,命中区要往内收够,才能点到可见的角
1345
+ if x <= corner and y <= corner:
1346
+ return "nw"
1347
+ if x >= w - corner and y <= corner:
1348
+ return "ne"
1349
+ if x <= corner and y >= h - corner:
1350
+ return "sw"
1351
+ if x >= w - corner and y >= h - corner:
1352
+ return "se"
1353
+ # 顶部中间只拖动,不缩放;四角仍然可同时调宽高
1354
+ if y <= edge:
1355
+ return None
1356
+ if x <= edge:
1357
+ return "w"
1358
+ if x >= w - edge:
1359
+ return "e"
1360
+ if y >= h - edge:
1361
+ return "s"
1362
+ return None
1363
+
1364
+ def _cursor_for(self, mode):
1365
+ return {
1366
+ "nw": "size_nw_se", "se": "size_nw_se",
1367
+ "ne": "size_ne_sw", "sw": "size_ne_sw",
1368
+ "w": "size_we", "e": "size_we",
1369
+ "n": "size_ns", "s": "size_ns",
1370
+ }.get(mode, "")
1371
+
1372
+ def _hover(self, e):
1373
+ if self._resize:
1374
+ return
1375
+ try:
1376
+ self.canvas.config(cursor=self._cursor_for(self._edge_at(e.x, e.y)))
1377
+ except Exception:
1378
+ pass
1379
+
1380
+ def _leave(self, _e):
1381
+ if not self._resize:
1382
+ self.canvas.config(cursor="")
1383
+
1384
+ def _press(self, e):
1385
+ # 麦克风图标是画在玻璃里的,不在 Canvas 上单独建控件;点它不能当拖窗
1386
+ if abs(e.x - (MIC_POS[0] + 14)) <= 22 and abs(e.y - (MIC_POS[1] + 14)) <= 22:
1387
+ self._toggle_mic()
1388
+ return
1389
+ x0, y0, x1, y1, _r = SHAPES[4]
1390
+ if x0 <= e.x <= x1 and y0 <= e.y <= y1:
1391
+ self._focus_input()
1392
+ return
1393
+ mode = self._edge_at(e.x, e.y)
1394
+ if mode:
1395
+ self._resize = (mode, e.x_root, e.y_root,
1396
+ self.root.winfo_x(), self.root.winfo_y(),
1397
+ self.root.winfo_width(), self.root.winfo_height())
1398
+ self._drag = None
1399
+ self._pause.set()
1400
+ return
1401
+ self._drag = (e.x_root - self.root.winfo_x(),
1402
+ e.y_root - self.root.winfo_y())
1403
+
1404
+ def _motion(self, e):
1405
+ if self._resize:
1406
+ mode, sx, sy, x0, y0, w0, h0 = self._resize
1407
+ dx, dy = e.x_root - sx, e.y_root - sy
1408
+ nw, nh, nx, ny = w0, h0, x0, y0
1409
+ if "e" in mode:
1410
+ nw = max(MIN_W, min(max(MIN_W, self._sw - x0), w0 + dx))
1411
+ if "w" in mode:
1412
+ nw = max(MIN_W, min(max(MIN_W, x0 + w0), w0 - dx))
1413
+ nx = x0 + w0 - nw
1414
+ if "s" in mode:
1415
+ nh = max(MIN_H, min(max(MIN_H, self._sh - y0), h0 + dy))
1416
+ if "n" in mode:
1417
+ nh = max(MIN_H, min(max(MIN_H, y0 + h0), h0 - dy))
1418
+ ny = y0 + h0 - nh
1419
+ nx = max(0, min(nx, max(0, self._sw - nw)))
1420
+ ny = max(0, min(ny, max(0, self._sh - nh)))
1421
+ self.root.geometry(f"{nw}x{nh}+{nx}+{ny}")
1422
+ now = time.time()
1423
+ if now - self._preview_at >= 0.04:
1424
+ self._preview_at = now
1425
+ self._preview_resize(nw, nh)
1426
+ return
1427
+ if self._drag:
1428
+ self.root.geometry(f"+{e.x_root - self._drag[0]}+{e.y_root - self._drag[1]}")
1429
+
1430
+ def _release(self, e):
1431
+ if self._resize:
1432
+ self._resize = None
1433
+ self._preview_at = 0.0
1434
+ self.root.update_idletasks()
1435
+ w = max(MIN_W, self.root.winfo_width())
1436
+ h = max(MIN_H, self.root.winfo_height())
1437
+ self._rebuild(w, h)
1438
+ self._hover(e)
1439
+ return
1440
+ self._drag = None
1441
+
1442
+ def run(self):
1443
+ self.root.bind("<Escape>", self._close)
1444
+ self.root.bind("<MouseWheel>", self._wheel)
1445
+ self.root.bind("<Motion>", self._hover, add="+")
1446
+ self.root.bind("<Leave>", self._leave, add="+")
1447
+ self.root.bind("<ButtonPress-1>", self._press, add="+")
1448
+ self.root.bind("<B1-Motion>", self._motion, add="+")
1449
+ self.root.bind("<ButtonRelease-1>", self._release, add="+")
1450
+ self.root.mainloop()
1451
+
1452
+
1453
+ if __name__ == "__main__":
1454
+ LiveGlass().run()