dsh-watch-together 0.2.2 → 0.2.4

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.
@@ -39,6 +39,11 @@ import mss
39
39
  import numpy as np
40
40
  from PIL import Image, ImageDraw, ImageEnhance, ImageFilter, ImageStat, ImageTk
41
41
 
42
+ try:
43
+ import cv2 as _cv2
44
+ except Exception: # OpenCV 只是加速,缺了仍走 PIL
45
+ _cv2 = None
46
+
42
47
  # 悬浮窗接口:插件写 window-events.jsonl,窗口回 window-outbox.jsonl。
43
48
  # 读不到就继续读 chat.jsonl,旧版插件不受影响。
44
49
  try:
@@ -158,7 +163,9 @@ def chat_layout(h):
158
163
  """消息区在高度不足 560 时压缩行高;底部输入框始终贴底。"""
159
164
  input_top = h - 80
160
165
  if h >= 560:
161
- ys, bh = [124, 214, 304, 404], 60
166
+ # 四条消息每条都能放下"时间头 + 两行正文";f12 在 150% DPI 下
167
+ # 行高约 28px,82px 的框刚好装 2 行,不再为了塞下文字把字号压到 9。
168
+ ys, bh = [104, 198, 292, 386], 88
162
169
  else:
163
170
  # 顶部留 8px 空隙给最后一条和输入框,避免贴在一起
164
171
  avail = max(0, input_top - 124 - 8)
@@ -169,9 +176,9 @@ def chat_layout(h):
169
176
 
170
177
 
171
178
  def shapes_for(w, h):
172
- """按窗口尺寸生成内部框位置;宽度横向伸展,底栏贴底。"""
179
+ """按窗口尺寸生成内部框位置;消息气泡的最终宽度由文字测量决定。"""
173
180
  ys, bh, input_top = chat_layout(h)
174
- # 真实聊天流每条长度不可预测,四个气泡统一吃满内容宽度;输入/发送仍分开
181
+ # 这里只给消息区四个纵向槽位;_message_shapes() 会按文字收窄宽度和高度。
175
182
  return [
176
183
  (38, ys[0], w - 38, ys[0] + bh, 30),
177
184
  (38, ys[1], w - 38, ys[1] + bh, 30),
@@ -183,6 +190,7 @@ def shapes_for(w, h):
183
190
 
184
191
 
185
192
  SHAPES = shapes_for(W, H)
193
+ SHAPES_VERSION = 0
186
194
 
187
195
 
188
196
  def rounded_mask():
@@ -264,6 +272,8 @@ BOX_AMP = 8 # 1/4 分辨率下的最大采样偏移
264
272
  def build_box_maps():
265
273
  out = []
266
274
  for x0, y0, x1, y1, r in SHAPES:
275
+ if x1 <= x0 or y1 <= y0:
276
+ continue
267
277
  qx0, qy0 = x0 // 4, y0 // 4
268
278
  qw, qh = max(2, (x1 - x0) // 4), max(2, (y1 - y0) // 4)
269
279
  xx, yy = np.meshgrid(np.arange(qw, dtype=np.float32),
@@ -277,16 +287,18 @@ def build_box_maps():
277
287
  gy, gx = np.gradient(sdf)
278
288
  n = np.maximum(np.hypot(gx, gy), 1e-6)
279
289
  d = -sdf
280
- inside = d >= 0
281
290
  alpha = np.clip((d + 0.6) / 1.2, 0.0, 1.0).astype(np.float32)
282
- edge = inside & (d <= BOX_BAND)
283
291
  t = np.clip(1.0 - d / BOX_BAND, 0.0, 1.0)
284
292
  mag = BOX_AMP * t * t
285
293
  sx = np.rint(qx0 + xx + gx / n * mag).astype(np.int32)
286
294
  sy = np.rint(qy0 + yy + gy / n * mag).astype(np.int32)
287
295
  np.clip(sx, 0, W // 4 - 1, out=sx)
288
296
  np.clip(sy, 0, H // 4 - 1, out=sy)
289
- out.append((qx0, qy0, qw, qh, alpha, edge, sx, sy))
297
+ # 边缘到中心用平滑权重过渡,不再用二值 edge 在“原始帧”和
298
+ # “强模糊帧”之间硬切;系数不一致会看到一圈割裂。
299
+ w = np.clip(d / BOX_BAND, 0.0, 1.0).astype(np.float32)
300
+ w = (w * w * (3.0 - 2.0 * w)).astype(np.float32)
301
+ out.append((qx0, qy0, qw, qh, alpha, w, sx, sy))
290
302
  return out
291
303
 
292
304
 
@@ -314,6 +326,7 @@ def rebuild_geometry(w, h):
314
326
  """窗口尺寸变化后重建所有和 W/H 绑定的贴图/遮罩。"""
315
327
  global W, H, SHAPES, MASK, MASK_HARD, OVERLAY, OVERLAY_2X
316
328
  global WARP_X, WARP_Y, EDGE_MASK, BOX_MAPS, HW, HH, BOX_UNION_2X, MIC_POS
329
+ _CHROMA_CACHE.clear() # 旧尺寸的索引图不再用,避免每次缩放都攒一份
317
330
  W, H = w, h
318
331
  SHAPES = shapes_for(w, h)
319
332
  MASK = rounded_mask()
@@ -327,6 +340,21 @@ def rebuild_geometry(w, h):
327
340
  BOX_UNION_2X = build_box_union(HW, HH)
328
341
 
329
342
 
343
+ def apply_shapes(shapes):
344
+ """消息气泡宽度/高度变化后,只重建和内部框有关的贴图。
345
+
346
+ 窗口尺寸不变,所以不用碰 WARP/MASK;只更新染色层、四分之一透镜
347
+ 坐标和 2x 联合遮罩。调用方负责持有 _geo_lock。
348
+ """
349
+ global SHAPES, OVERLAY, OVERLAY_2X, BOX_MAPS, BOX_UNION_2X, SHAPES_VERSION
350
+ SHAPES = list(shapes)
351
+ OVERLAY = build_overlay()
352
+ OVERLAY_2X = OVERLAY.resize((W // 2, H // 2), Image.Resampling.BILINEAR)
353
+ BOX_MAPS = build_box_maps()
354
+ BOX_UNION_2X = build_box_union(HW, HH)
355
+ SHAPES_VERSION += 1
356
+
357
+
330
358
  def finish(panel):
331
359
  """只做圆角遮罩;染色已经在 1/4 分辨率合成过。"""
332
360
  out = Image.new("RGB", (W, H), KEY)
@@ -334,6 +362,60 @@ def finish(panel):
334
362
  return out
335
363
 
336
364
 
365
+ def _smoothstep(a, b, x):
366
+ t = np.clip((x - a) / (b - a), 0.0, 1.0)
367
+ return t * t * (3.0 - 2.0 * t)
368
+
369
+
370
+ _CHROMA_CACHE = {}
371
+
372
+
373
+ def _chroma_maps(w, h, strength):
374
+ """2x 色散索引图只跟尺寸/强度走,缓存后每帧只做 gather。"""
375
+ key = (w, h, round(float(strength), 2))
376
+ hit = _CHROMA_CACHE.get(key)
377
+ if hit is not None:
378
+ return hit
379
+ yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)
380
+ dx = (xx + 0.5) / w - 0.5
381
+ dy = (yy + 0.5) / h - 0.5
382
+ r = np.hypot(dx, dy) + 1e-6
383
+ edge = _smoothstep(0.38, 0.48, r) * (1.0 - _smoothstep(0.52, 0.585, r))
384
+ k = strength * edge
385
+ ox = np.rint(dx / r * k).astype(np.int32)
386
+ oy = np.rint(dy / r * k).astype(np.int32)
387
+ xi = xx.astype(np.int32)
388
+ yi = yy.astype(np.int32)
389
+ hit = (
390
+ edge.astype(np.float32),
391
+ np.clip(xi + ox, 0, w - 1),
392
+ np.clip(yi + oy, 0, h - 1),
393
+ np.clip(xi - ox, 0, w - 1),
394
+ np.clip(yi - oy, 0, h - 1),
395
+ )
396
+ _CHROMA_CACHE[key] = hit
397
+ return hit
398
+
399
+
400
+ def apply_chroma(im, strength=1.7):
401
+ """外框径向色散:R 向外、B 向内错一位,和 GPU 后处理同一思路。
402
+
403
+ 只在圆角外缘的窄带里做,且按 edge 权重混回原图;否则整张图会变成
404
+ 红蓝重影。CPU 版在 2x 合成图上做,成本远低于全分辨率逐像素采样。
405
+ """
406
+ arr = np.asarray(im.convert("RGB"), dtype=np.float32)
407
+ h, w = arr.shape[:2]
408
+ edge, xr, yr, xb, yb = _chroma_maps(w, h, strength)
409
+ if not np.any(edge > 0.001):
410
+ return im
411
+ rr = arr[yr, xr, 0]
412
+ bb = arr[yb, xb, 2]
413
+ out = arr.copy()
414
+ out[:, :, 0] = arr[:, :, 0] * (1.0 - edge) + rr * edge
415
+ out[:, :, 2] = arr[:, :, 2] * (1.0 - edge) + bb * edge
416
+ return Image.fromarray(np.clip(out, 0, 255).astype(np.uint8))
417
+
418
+
337
419
  class RECT(ctypes.Structure):
338
420
  _fields_ = [("left", ctypes.c_long), ("top", ctypes.c_long),
339
421
  ("right", ctypes.c_long), ("bottom", ctypes.c_long)]
@@ -359,6 +441,7 @@ class LiveGlass:
359
441
  self._seen = set()
360
442
  self._collapsed = False
361
443
  self._saved_h = H
444
+ self._snapshot_done = False
362
445
  # 只在双击标题时创建,平时不占画布
363
446
  self._title_entry = None
364
447
  self._title_item = None
@@ -388,6 +471,9 @@ class LiveGlass:
388
471
 
389
472
  self._img = None
390
473
  self._last_frame = None
474
+ self._prev_out = None
475
+ self._motion_blur = 0.0
476
+ self._collapsed_frame = None
391
477
  self._bg = None
392
478
  self._hwnd = None
393
479
  self._excluded = False
@@ -407,9 +493,11 @@ class LiveGlass:
407
493
  self._frames = 0
408
494
  self._text_items = []
409
495
  self._text_colors = {}
496
+ self._text_pending = {}
410
497
  self._text_shadows = {}
411
498
  self._color_at = 0.0
412
499
  self._aux_at = 0.0
500
+ self._bar_color = "#b8cbe0"
413
501
  self._load_initial()
414
502
  self._build_ui()
415
503
  self._add_text_shadows()
@@ -428,6 +516,7 @@ class LiveGlass:
428
516
  self.root.after(60, self._tick)
429
517
  self.root.after(30, lambda: self._intro_step(0))
430
518
  self.root.after(250, self._poll_chat)
519
+ self.root.after(1200, self._keep_on_top)
431
520
  if SNAPSHOT:
432
521
  self.root.after(2600, self._snapshot_mode)
433
522
 
@@ -444,6 +533,19 @@ class LiveGlass:
444
533
  if n < 6:
445
534
  self.root.after(26, lambda: self._intro_step(n + 1))
446
535
 
536
+ def _keep_on_top(self):
537
+ """DSH 等置顶窗口被激活后会把悬浮窗压下去;定时重新抬到最上层。"""
538
+ try:
539
+ if not getattr(self, "_hidden", False):
540
+ self.root.attributes("-topmost", True)
541
+ self.root.lift()
542
+ except Exception:
543
+ pass
544
+ try:
545
+ self.root.after(1800, self._keep_on_top)
546
+ except Exception:
547
+ pass
548
+
447
549
  # ---- 真实聊天流 ----
448
550
 
449
551
  def _parse_geometry(self, geo):
@@ -605,7 +707,7 @@ class LiveGlass:
605
707
  if changed:
606
708
  if self._msg_offset > 0:
607
709
  self._msg_offset += len(new)
608
- self._msg_offset = max(0, min(self._msg_offset, max(0, len(self.messages) - 1)))
710
+ self._msg_offset = max(0, min(self._msg_offset, max(0, len(self.messages) - 4)))
609
711
  self._refresh_feed()
610
712
  self._file_size = size
611
713
  except Exception as exc:
@@ -637,9 +739,10 @@ class LiveGlass:
637
739
  self._hidden = not want
638
740
 
639
741
  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]
742
+ total = len(self.messages)
743
+ visible = min(4, total)
744
+ start = max(0, total - visible - self._msg_offset)
745
+ return self.messages[start:start + visible]
643
746
 
644
747
  def _refresh_feed(self):
645
748
  """聊天流变了就重画文字;Entry 的草稿和焦点要保住。"""
@@ -689,7 +792,8 @@ class LiveGlass:
689
792
  if not self.messages:
690
793
  return
691
794
  step = 1 if e.delta > 0 else -1
692
- self._msg_offset = max(0, min(len(self.messages) - 1, self._msg_offset + step))
795
+ max_off = max(0, len(self.messages) - 4)
796
+ self._msg_offset = max(0, min(max_off, self._msg_offset + step))
693
797
  self._refresh_feed()
694
798
 
695
799
  def _toggle_mic(self):
@@ -722,8 +826,42 @@ class LiveGlass:
722
826
  pass
723
827
  self._refresh_feed()
724
828
 
829
+ def _make_collapsed_frame(self):
830
+ """折叠时只保留标题栏那一块玻璃,并补上圆角。
831
+
832
+ 直接裁 _last_frame 会让底部变成一条硬切边(遮罩还是 560px 高),
833
+ 看起来像渲染坏了;这里按 78px 重新贴一次圆角遮罩。
834
+ """
835
+ if self._last_frame is None:
836
+ return None
837
+ try:
838
+ w, h = W, H
839
+ crop = self._last_frame.convert("RGB").crop((0, 0, w, h))
840
+ mask = Image.new("L", (w, h), 0)
841
+ d = ImageDraw.Draw(mask)
842
+ d.rounded_rectangle((12, 12, w - 12, 66), radius=22, fill=255)
843
+ out = Image.new("RGB", (w, h), KEY)
844
+ out.paste(crop, (0, 0), mask)
845
+ return out
846
+ except Exception:
847
+ return None
848
+
849
+ def _sync_pos(self):
850
+ """把 Tk 当前左上角同步回 _x/_y。
851
+
852
+ 拖动/缩放只改了 root.geometry,没有改这两个缓存;折叠时如果继续用
853
+ 旧坐标,窗口会被拉回拖动前的位置(用户看到的就是"点收起位置跳回")。
854
+ """
855
+ try:
856
+ self._x = int(self.root.winfo_x())
857
+ self._y = int(self.root.winfo_y())
858
+ except Exception:
859
+ pass
860
+
725
861
  def _save_geometry(self):
726
- write_config({"geometry": f"{self.root.winfo_width()}x{self.root.winfo_height()}"
862
+ # 折叠态存回展开高度,否则下次启动会按 78px 的高度恢复。
863
+ h = getattr(self, "_saved_h", H) if getattr(self, "_collapsed", False) else self.root.winfo_height()
864
+ write_config({"geometry": f"{self.root.winfo_width()}x{h}"
727
865
  f"+{self.root.winfo_x()}+{self.root.winfo_y()}"})
728
866
 
729
867
  def _hwnd_root(self):
@@ -756,13 +894,24 @@ class LiveGlass:
756
894
  gt = max(0, t - PAD)
757
895
  gr = min(self._sw, r + PAD)
758
896
  gb = min(self._sh, b + PAD)
897
+ # 防御:多显示器 / DPI 变化 / 被其他程序挪动时,窗口仍可能越界,
898
+ # 钳位后宽高会变成 0 或负数,mss 会抛 "Region has zero or negative size";
899
+ # 那个异常在 _work() 里被吞掉只打一行日志,于是每帧刷一条、背景永远画不出来。
900
+ if gr - gl <= 0 or gb - gt <= 0:
901
+ return None
759
902
  shot = sct.grab({"left": gl, "top": gt,
760
903
  "width": gr - gl, "height": gb - gt})
761
904
  im = Image.frombytes("RGB", shot.size, shot.rgb)
762
905
  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)
906
+ # 60fps 路径:只在 1/4 分辨率做一次模糊和折射,再放大。
907
+ # cv2 的 resize 比 PIL 快一个数量级;没有 OpenCV 时无感回退。
908
+ if _cv2 is not None:
909
+ arr_raw = _cv2.resize(np.asarray(im), (sw4, sh4),
910
+ interpolation=_cv2.INTER_LINEAR)
911
+ small_raw = Image.fromarray(arr_raw)
912
+ else:
913
+ small_raw = im.resize((sw4, sh4), Image.Resampling.BILINEAR)
914
+ arr_raw = np.asarray(small_raw)
766
915
  # 静态跳帧:先用未模糊的 raw 判断,静止时连模糊都不用做。
767
916
  # 采样 4px、均值 0.01 + 最大差 0.5、运动后保持 0.3s;比原来的
768
917
  # 8px / 0.18 更早触发,慢速滚动不会先停一两帧再动。
@@ -775,9 +924,15 @@ class LiveGlass:
775
924
  moved = bool(float(d.mean()) > 0.01 or float(d.max()) > 0.5)
776
925
  if moved:
777
926
  self._last_motion = now
927
+ self._motion_blur = min(1.0, getattr(self, "_motion_blur", 0.0) * 0.50 + 0.50)
928
+ else:
929
+ self._motion_blur = getattr(self, "_motion_blur", 0.0) * 0.55
778
930
  if (not FORCE and not moved and box == self._sig_bbox
779
931
  and now - getattr(self, "_last_motion", 0.0) > 0.30):
780
932
  self._sig = sig
933
+ # 静态跳帧期间不更新画面;上一帧若带着运动模糊,绝不能在
934
+ # 很久以后重新移动时再被混进来,否则就是“淡淡的旧画面”。
935
+ self._prev_out = None
781
936
  return None
782
937
  self._sig = sig
783
938
  self._sig_bbox = box
@@ -795,27 +950,57 @@ class LiveGlass:
795
950
  # 内部框:边缘折射 + 中心强模糊仍在 1/4 分辨率完成
796
951
  strong_panel = arr_strong[sy, sx]
797
952
  out_panel = warped.copy()
798
- for qx0, qy0, qw, qh, alpha, edge, bsx, bsy in BOX_MAPS:
953
+ for qx0, qy0, qw, qh, alpha, edge_w, bsx, bsy in BOX_MAPS:
799
954
  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)]
955
+ # 边缘也用和主玻璃相同的 1.45 模糊,不再直接拿未模糊的
956
+ # arr_raw;中心再平滑过渡到 2.6 的强模糊。
957
+ edge_patch = arr[np.clip(bsy + py, 0, arr.shape[0] - 1),
958
+ np.clip(bsx + px, 0, arr.shape[1] - 1)]
802
959
  strong_patch = strong_panel[qy0:qy0 + qh, qx0:qx0 + qw]
803
- patch = np.where(edge[..., None], edge_patch, strong_patch)
960
+ we = edge_w[..., None]
961
+ patch = edge_patch * (1.0 - we) + strong_patch * we
804
962
  a = alpha[..., None]
805
963
  out_panel[qy0:qy0 + qh, qx0:qx0 + qw] = (
806
964
  base_patch * (1.0 - a) + patch * a)
807
965
  # 1/4 透镜结果放大后,用全分辨率联合圆角遮罩贴回;
808
966
  # 边界是 PIL 4x 超采样遮罩,不再有 1/4 放大的像素台阶。
809
967
  # 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)
968
+ if _cv2 is not None:
969
+ base_2x = Image.fromarray(_cv2.resize(
970
+ warped, (HW, HH), interpolation=_cv2.INTER_LINEAR))
971
+ lens_2x = Image.fromarray(_cv2.resize(
972
+ out_panel, (HW, HH), interpolation=_cv2.INTER_LINEAR))
973
+ else:
974
+ base_2x = Image.fromarray(warped).resize(
975
+ (HW, HH), Image.Resampling.BILINEAR)
976
+ lens_2x = Image.fromarray(out_panel).resize(
977
+ (HW, HH), Image.Resampling.BILINEAR)
814
978
  panel = Image.composite(lens_2x, base_2x, BOX_UNION_2X)
815
979
  panel = Image.alpha_composite(
816
980
  panel.convert("RGBA"), OVERLAY_2X).convert("RGB")
817
- # 麦克风图标:先回到全分辨率再贴,避免坐标落在 2x 画布外
818
- out = panel.convert("RGB").resize((W, H), Image.Resampling.BILINEAR)
981
+ # 2x 上做一次显式 R/B 错位;全分辨率逐像素做会把这个 60fps 管线拖慢。
982
+ # 移动中跳过色散(约 3.5ms/帧),优先保证拖动/滚动响应;停下后
983
+ # 的静止帧再补上,最终观感不变。
984
+ if not moved:
985
+ panel = apply_chroma(panel, 1.7)
986
+ if _cv2 is not None:
987
+ out = Image.fromarray(_cv2.resize(
988
+ np.asarray(panel.convert("RGB")), (W, H),
989
+ interpolation=_cv2.INTER_LINEAR))
990
+ else:
991
+ out = panel.convert("RGB").resize((W, H), Image.Resampling.BILINEAR)
992
+ # CPU 也做上一帧混合,但比 GPU 的 0.55 轻、且只在检测到移动时混:
993
+ # 拖动停下后立刻恢复清晰,不会留下淡淡的旧画面。
994
+ # 先混再贴麦克风,避免把上一帧的麦克风位置糊到这一帧。
995
+ if moved and self._prev_out is not None and self._prev_out.size == out.size:
996
+ # 只在“这一帧确实检测到移动”时混上一帧;停下后下一帧
997
+ # 立刻干净,不会留下越拖越淡的残影。
998
+ blend = 0.35 * max(0.0, min(1.0, getattr(self, "_motion_blur", 0.0)))
999
+ if blend > 0.01:
1000
+ out = Image.blend(self._prev_out, out, blend)
1001
+ self._prev_out = out.copy()
1002
+ # 麦克风图标回到仓库的做法:贴进玻璃帧,按背后亮度选浅/深两版。
1003
+ # 位置用 MIC_POS(左上角),不是 Canvas 坐标,缩放时一起重建。
819
1004
  mic_box = out.crop((MIC_POS[0], MIC_POS[1],
820
1005
  MIC_POS[0] + 28, MIC_POS[1] + 28)).convert("L")
821
1006
  mic_bg = float(np.median(np.asarray(mic_box))) / 255.0
@@ -832,6 +1017,11 @@ class LiveGlass:
832
1017
  if self._pause.is_set():
833
1018
  time.sleep(0.03)
834
1019
  continue
1020
+ if getattr(self, "_collapsed", False):
1021
+ # 折叠态只剩一条标题栏,玻璃遮罩仍是展开时的尺寸;继续抓会在
1022
+ # 合成时抛 images do not match(每帧一条,能把日志刷到几十 MB)。
1023
+ time.sleep(0.05)
1024
+ continue
835
1025
  t0 = time.perf_counter()
836
1026
  try:
837
1027
  with self._geo_lock:
@@ -865,6 +1055,33 @@ class LiveGlass:
865
1055
  else:
866
1056
  time.sleep(max(0.0, 1 / max(1, self._target_fps) - dt))
867
1057
 
1058
+ def _fit_lines(self, text, font, max_width, max_height):
1059
+ """按框宽/框高折行并截断,避免文字溢出气泡。"""
1060
+ fobj = tkfont.Font(root=self.root, font=font)
1061
+ ls = max(1, fobj.metrics("linespace"))
1062
+ max_lines = max(1, int(max_height // ls))
1063
+ lines = []
1064
+ no_start = ",。、;:!?)》」』…,.;:!?)]}"
1065
+ for para in str(text).splitlines() or [""]:
1066
+ cur = ""
1067
+ for ch in para:
1068
+ if not cur or fobj.measure(cur + ch) <= max_width:
1069
+ cur += ch
1070
+ elif ch in no_start:
1071
+ # 标点不能单独掉到下一行(会变成孤零零一个句号)
1072
+ cur += ch
1073
+ else:
1074
+ lines.append(cur)
1075
+ cur = ch
1076
+ lines.append(cur)
1077
+ if len(lines) > max_lines:
1078
+ lines = lines[:max_lines]
1079
+ last = lines[-1]
1080
+ while last and fobj.measure(last + "…") > max_width:
1081
+ last = last[:-1]
1082
+ lines[-1] = (last + "…") if last else "…"
1083
+ return lines or [""]
1084
+
868
1085
  def _text(self, x, y, text, anchor="center", fill="#f2f8ff",
869
1086
  font=None, max_width=None, tags=()):
870
1087
  """按字符拆成 Canvas 文本;每个字单独适配背后的明暗。"""
@@ -957,7 +1174,7 @@ class LiveGlass:
957
1174
  return "break"
958
1175
  self._editing = True
959
1176
  if self._title_entry is None:
960
- self._title_entry = tk.Entry(self.root, font=f(18), relief="flat", bd=0,
1177
+ self._title_entry = tk.Entry(self.root, font=f(15), relief="flat", bd=0,
961
1178
  bg="#1b2330", fg="#f7fbff", insertbackground="#f7fbff")
962
1179
  self._title_entry.bind("<Return>", self._commit_title)
963
1180
  self._title_entry.bind("<Escape>", self._cancel_title)
@@ -966,7 +1183,7 @@ class LiveGlass:
966
1183
  self._title_entry.insert(0, self.name)
967
1184
  if self._title_item is not None:
968
1185
  self.canvas.delete(self._title_item)
969
- self._title_item = self.canvas.create_window(72, 54, anchor="w",
1186
+ self._title_item = self.canvas.create_window(68, 38, anchor="w",
970
1187
  window=self._title_entry, width=180)
971
1188
  self._title_entry.focus_set()
972
1189
  self._title_entry.select_range(0, "end")
@@ -1004,21 +1221,86 @@ class LiveGlass:
1004
1221
 
1005
1222
  def toggle_collapse(self, _event=None):
1006
1223
  global H
1224
+ # 先读真实坐标再切高度:_x/_y 只是启动时的缓存,拖动/缩放后已过期。
1225
+ self._sync_pos()
1007
1226
  self._collapsed = not getattr(self, "_collapsed", False)
1008
1227
  if self._collapsed:
1009
1228
  self._saved_h = H
1010
1229
  H = 2 * 12 + 54
1230
+ self._collapsed_frame = self._make_collapsed_frame()
1231
+ # 折叠态只需要标题栏:不重建整窗几何,直接缩窗口 + 只画头。
1232
+ # 这样不会在小高度下生成负尺寸的输入框/主体玻璃。
1233
+ self.root.geometry(f"{W}x{H}+{self._x}+{self._y}")
1234
+ self._build_ui()
1011
1235
  else:
1012
1236
  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)
1237
+ self._collapsed_frame = None
1238
+ rebuild_geometry(W, H)
1239
+ self.root.geometry(f"{W}x{H}+{self._x}+{self._y}")
1240
+ self._rebuild(W, H)
1016
1241
  try:
1017
1242
  if self._protocol is not None:
1018
1243
  self._protocol.action("collapse" if self._collapsed else "expand")
1019
1244
  except Exception:
1020
1245
  pass
1021
1246
 
1247
+ def _message_shapes(self, shown):
1248
+ """把四个固定大框换成按正文文字测量的聊天气泡。
1249
+
1250
+ 时间戳不再算进气泡:它贴在气泡上方,气泡只包正文。先按最大
1251
+ 可用宽度折行,再取实际最长行的宽度;短消息不会撑满整行。
1252
+ """
1253
+ w, h = W, H
1254
+ base = shapes_for(w, h)
1255
+ left, right = base[0][0], base[0][2]
1256
+ max_bubble = min(right - left, max(240, int((right - left) * 0.72)))
1257
+ min_bubble = min(110, max_bubble)
1258
+ pad = 14
1259
+ body_font = f(11)
1260
+ stamp_font = f(9)
1261
+ fbody = tkfont.Font(root=self.root, font=body_font)
1262
+ fstamp = tkfont.Font(root=self.root, font=stamp_font)
1263
+ ls = max(1, fbody.metrics("linespace"))
1264
+ shapes, infos = [], []
1265
+ for i in range(4):
1266
+ if i >= len(shown):
1267
+ # 没有第 5 条消息时留空,不要把固定大框继续画出来。
1268
+ shapes.append((0, 0, 0, 0, 0))
1269
+ continue
1270
+ msg = shown[i]
1271
+ x0, y0, x1, y1, _r = base[i]
1272
+ slot_h = y1 - y0
1273
+ is_user = str(msg.get("role") or "").lower() in ("user", "me", "human")
1274
+ stamp = str(msg.get("stamp") or "")
1275
+ stamp_h = fstamp.metrics("linespace") if stamp else 0
1276
+ body_avail = max(12, slot_h - stamp_h)
1277
+ content_max = max(80, max_bubble - 2 * pad)
1278
+ lines = self._fit_lines(msg.get("text") or "", body_font,
1279
+ content_max, body_avail)
1280
+ inner = max([0] + [fbody.measure(line) for line in lines])
1281
+ bw = min(max_bubble, max(min_bubble, inner + 2 * pad))
1282
+ bh = min(body_avail, max(ls + 4, len(lines) * ls + 4))
1283
+ by0 = y0 + stamp_h
1284
+ by1 = min(y1, by0 + bh)
1285
+ if is_user:
1286
+ bx1 = right
1287
+ bx0 = bx1 - bw
1288
+ tx, ta = bx1 - pad, "ne"
1289
+ else:
1290
+ bx0 = left
1291
+ bx1 = bx0 + bw
1292
+ tx, ta = bx0 + pad, "nw"
1293
+ shape = (bx0, by0, bx1, by1, min(26, max(16, bh // 3)))
1294
+ shapes.append(shape)
1295
+ infos.append({
1296
+ "shape": shape, "is_user": is_user, "stamp": stamp,
1297
+ "tx": tx, "ta": ta, "lines": lines,
1298
+ "body_font": body_font, "ty": by0 + 2,
1299
+ "stamp_y": y0, "ls": ls,
1300
+ })
1301
+ shapes.extend(base[4:])
1302
+ return shapes, infos
1303
+
1022
1304
  def _build_ui(self):
1023
1305
  c = self.canvas
1024
1306
  old_text, old_focus, old_cursor = "", False, 0
@@ -1037,9 +1319,10 @@ class LiveGlass:
1037
1319
  c.delete("all")
1038
1320
  # 背景图 item 先建,后续文字都在它上面
1039
1321
  self._bg = c.create_image(0, 0, anchor="nw")
1040
- if self._last_frame is not None:
1322
+ frame = self._collapsed_frame if getattr(self, "_collapsed", False) else self._last_frame
1323
+ if frame is not None:
1041
1324
  try:
1042
- self._img = ImageTk.PhotoImage(self._last_frame, master=self.canvas)
1325
+ self._img = ImageTk.PhotoImage(frame, master=self.canvas)
1043
1326
  c.itemconfigure(self._bg, image=self._img)
1044
1327
  except Exception:
1045
1328
  pass
@@ -1049,11 +1332,29 @@ class LiveGlass:
1049
1332
  c.tag_lower("preview-bg")
1050
1333
 
1051
1334
  w, h = W, H
1335
+ # 状态点:仓库实现里的"亮着的蓝点 + 很淡的光环"。纯色圆点像贴纸,
1336
+ # 带一圈环才像状态灯;录音时变红。
1337
+ dot = "#e05a5a" if (self._mic_proc is not None and self._mic_proc.poll() is None) else "#0a84ff"
1338
+ # 标题栏玻璃是 y=12..66,中心 39;右边 ▾/✕ 也在 38。点、名字、
1339
+ # 状态必须同一条水平中线,且字号要能完整落在条内,不能压到气泡区。
1340
+ cy = 38
1341
+ dot_x = 54
1342
+ title_x = 68
1343
+ # 点放大但保留光环;之前半径 3/7 在 54px 的标题条里太小。
1344
+ c.create_oval(dot_x - 9, cy - 9, dot_x + 9, cy + 9,
1345
+ outline="#2b4d73" if dot == "#0a84ff" else "#6b3030", width=1)
1346
+ c.create_oval(dot_x - 4, cy - 4, dot_x + 4, cy + 4, fill=dot, outline="")
1052
1347
  name = self.name[:10]
1053
- self._text(76, 54, name, anchor="w", fill="#f7fbff",
1054
- font=f(21, True), tags=("title",))
1348
+ title_font = f(16, True)
1349
+ self._text(title_x, cy, name, anchor="w", fill="#f7fbff",
1350
+ font=title_font, tags=("title",))
1055
1351
  count = self._status or f"{len(self.messages)} 条"
1056
- self._text(176, 54, count, anchor="w", fill="#dbe6f5",
1352
+ try:
1353
+ nx = title_x + tkfont.Font(root=self.root, font=title_font).measure(name) + 10
1354
+ except Exception:
1355
+ nx = title_x + 72
1356
+ self._text(nx, cy, count, anchor="w",
1357
+ fill="#ffb4b4" if self._status else "#dbe6f5",
1057
1358
  font=f(11))
1058
1359
  # 右上角按钮跟随窗口宽度内收
1059
1360
  self._text(w - 94, 38, "▾", anchor="w",
@@ -1061,31 +1362,41 @@ class LiveGlass:
1061
1362
  self._text(w - 58, 38, "✕", anchor="w", fill="#9fb0c8",
1062
1363
  font=f(13), tags=("close",))
1063
1364
 
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",))
1365
+ if getattr(self, "_collapsed", False):
1366
+ self.canvas.config(width=w, height=h)
1367
+ c.tag_bind("close", "<Button-1>", self._close)
1368
+ c.tag_bind("collapse", "<Button-1>", self.toggle_collapse)
1369
+ # 双击改名:单击要留给"按住标题拖动窗口",两者不能抢同一个事件
1370
+ c.tag_bind("title", "<Double-Button-1>", self._edit_title)
1371
+ self._bar_len = max(72, int(w * BAR_FRAC))
1372
+ self._bar = c.create_line(w // 2 - self._bar_len // 2, BAR_Y,
1373
+ w // 2 + self._bar_len // 2, BAR_Y,
1374
+ width=BAR_THICK, fill="#b8cbe0",
1375
+ capstyle="round")
1376
+ return
1077
1377
 
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",))
1378
+ shown = self._visible_messages()
1379
+ if shown:
1380
+ shapes, infos = self._message_shapes(shown)
1381
+ else:
1382
+ shapes, infos = shapes_for(w, h), []
1383
+ if shapes != SHAPES:
1384
+ with self._geo_lock:
1385
+ apply_shapes(shapes)
1386
+ # 每条消息只按正文占一块;时间戳贴在气泡上方,不进框。
1387
+ for info in infos:
1388
+ bx0, by0, bx1, by1, _r = info["shape"]
1389
+ if info["stamp"]:
1390
+ self._text(info["tx"], info["stamp_y"], info["stamp"],
1391
+ anchor=info["ta"], fill="#a8b7c9",
1392
+ font=f(9), tags=("feed",))
1393
+ for li, line in enumerate(info["lines"]):
1394
+ self._text(info["tx"], info["ty"] + li * info["ls"], line,
1395
+ anchor=info["ta"], fill="#edf6ff",
1396
+ font=info["body_font"], tags=("feed",))
1087
1397
  if not shown:
1088
- self._text(w // 2, SHAPES[0][1] + bh // 2,
1398
+ # 空态:`bh` 是旧代码的局部变量,这里只能从 SHAPES 反推第一格高度
1399
+ self._text(w // 2, SHAPES[0][1] + (SHAPES[0][3] - SHAPES[0][1]) // 2,
1089
1400
  "在这里跟它说话 · 滚轮翻历史", anchor="center",
1090
1401
  fill="#8e9db2", font=f(12), tags=("feed",))
1091
1402
 
@@ -1113,16 +1424,22 @@ class LiveGlass:
1113
1424
  self._text((x0 + x1) // 2, y0 + 27, "发送", tags=("send", "feed"),
1114
1425
  fill="#ffffff", font=f(12, True))
1115
1426
 
1427
+ # 麦克风图标和仓库一样贴进玻璃帧(_capture 里按 MIC_POS 合成),
1428
+ # 不在 Canvas 上单独建图;点击仍由 _press 在 MIC_POS 附近识别。
1116
1429
  # 最上面正中的细条,长度随窗口宽度走
1117
1430
  self._bar_len = max(72, int(w * BAR_FRAC))
1118
1431
  self._bar = c.create_line(w // 2 - self._bar_len // 2, BAR_Y,
1119
1432
  w // 2 + self._bar_len // 2, BAR_Y,
1120
1433
  width=BAR_THICK, fill="#b8cbe0",
1121
1434
  capstyle="round")
1435
+ # 新建的条是浅色,缓存也要跟着归位;否则折叠重建后旧色值还在,
1436
+ # `bar_fill == cur` 会把这次同步直接跳过去,条和缓存就对不上了。
1437
+ self._bar_color = "#b8cbe0"
1122
1438
 
1123
1439
  c.tag_bind("close", "<Button-1>", self._close)
1124
1440
  c.tag_bind("send", "<Button-1>", self._send)
1125
1441
  c.tag_bind("collapse", "<Button-1>", self.toggle_collapse)
1442
+ # 同上:单击留给拖动,改名走双击
1126
1443
  c.tag_bind("title", "<Double-Button-1>", self._edit_title)
1127
1444
  c.tag_bind("inputzone", "<Button-1>", self._focus_input)
1128
1445
  c.tag_raise("close")
@@ -1162,8 +1479,10 @@ class LiveGlass:
1162
1479
  self.canvas.delete("all")
1163
1480
  self._img = None
1164
1481
  self._bg = None
1482
+ self._prev_out = None
1165
1483
  self._text_items = []
1166
1484
  self._text_colors = {}
1485
+ self._text_pending = {}
1167
1486
  self._text_shadows = {}
1168
1487
  self._build_ui()
1169
1488
  self._add_text_shadows()
@@ -1192,8 +1511,12 @@ class LiveGlass:
1192
1511
  self.canvas.delete("all")
1193
1512
  self._img = None
1194
1513
  self._bg = None
1514
+ self._prev_out = None
1515
+ self._motion_blur = 0.0
1516
+ self._collapsed_frame = None
1195
1517
  self._text_items = []
1196
1518
  self._text_colors = {}
1519
+ self._text_pending = {}
1197
1520
  self._text_shadows = {}
1198
1521
  self._color_at = 0.0
1199
1522
  self._aux_at = 0.0
@@ -1227,7 +1550,17 @@ class LiveGlass:
1227
1550
  self._text_shadows = {}
1228
1551
 
1229
1552
  def _adapt_text(self, out):
1230
- """按文字背后的暗部/亮部比例选色,并同步描边颜色。"""
1553
+ """按文字背后的暗部/亮部比例选色。
1554
+
1555
+ **必须带滞回**:气泡是透明的,背后就是桌面/视频/网页。画面一动,
1556
+ 这块背景的中位亮度就在 0.5 附近来回穿越,而原来这里是 `p50 < 0.50`
1557
+ 硬切、每 0.12 秒判一次 —— 结果字一秒能翻七八次黑白,肉眼就是"一直闪"。
1558
+
1559
+ 现在两道闸:
1560
+ 1. **滞回**:白的要暗到 0.38 才翻深,深的要亮到 0.62 才翻白;
1561
+ 中间的 0.38~0.62 一律保持现状,不给抖动留门。
1562
+ 2. **连续两次同向才切**:单帧跳变忽略,最坏 0.24 秒才换一次色。
1563
+ """
1231
1564
  now = time.time()
1232
1565
  if now - self._color_at < 0.12:
1233
1566
  return
@@ -1245,21 +1578,29 @@ class LiveGlass:
1245
1578
  p50 = float(np.percentile(gray, 50)) / 255.0
1246
1579
  dark = float(np.mean(gray < 107))
1247
1580
  light = float(np.mean(gray > 158))
1248
- # 先看这块背景是偏暗还是偏亮,混合区域再退回中位亮度
1581
+ cur = self._text_colors.get(item)
1582
+ # 先看这块背景是偏暗还是偏亮(这两支自带 0.08 余量,本身不抖)
1249
1583
  if dark > light + 0.08:
1250
- color = "#f2f8ff"
1584
+ want = "#f2f8ff"
1251
1585
  elif light > dark + 0.08:
1252
- color = "#07111d"
1253
- elif p50 < 0.50:
1254
- color = "#f2f8ff"
1586
+ want = "#07111d"
1587
+ elif cur == "#07111d":
1588
+ want = "#f2f8ff" if p50 < 0.38 else cur
1255
1589
  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
1590
+ # 还没定色时先给白字;之后要亮过 0.62 才敢翻深
1591
+ want = "#07111d" if (cur is not None and p50 > 0.62) else (cur or "#f2f8ff")
1592
+ if want == cur:
1593
+ self._text_pending.pop(item, None)
1594
+ continue
1595
+ if self._text_pending.get(item) != want:
1596
+ self._text_pending[item] = want # 第一次:只记下,不换
1597
+ continue
1598
+ self._text_pending.pop(item, None)
1599
+ self.canvas.itemconfigure(item, fill=want)
1600
+ self._text_colors[item] = want
1260
1601
 
1261
1602
  def _adapt_aux(self, out):
1262
- """最上面细条随背景切换深浅。"""
1603
+ """最上面细条随背景切换深浅(同样要滞回,理由见 `_adapt_text`)。"""
1263
1604
  now = time.time()
1264
1605
  if now - self._aux_at < 0.25:
1265
1606
  return
@@ -1269,18 +1610,34 @@ class LiveGlass:
1269
1610
  bar = np.asarray(out.crop(
1270
1611
  (mid - half, BAR_Y - 6, mid + half, BAR_Y + 12)).convert("L"))
1271
1612
  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)
1613
+ cur = self._bar_color
1614
+ if cur == "#4e6278":
1615
+ # 已经很深了:要暗到 0.36 才翻浅,避免在阈值附近来回跳
1616
+ bar_fill = "#b8cbe0" if p50 < 0.36 else cur
1617
+ else:
1618
+ bar_fill = "#4e6278" if p50 > 0.60 else cur
1619
+ if bar_fill != cur:
1620
+ self._bar_color = bar_fill
1621
+ self.canvas.itemconfigure(self._bar, fill=bar_fill)
1274
1622
 
1275
1623
 
1276
1624
 
1277
1625
  def _snapshot_mode(self):
1278
1626
  """只给文档截图:停抓取、关 WDA,保留最后一帧(不改变正常路径)。"""
1627
+ self._snapshot_done = True
1279
1628
  self._pause.set()
1280
1629
  if self._excluded:
1281
1630
  self._set_exclude(False)
1282
1631
 
1283
1632
  def _tick(self):
1633
+ # 截图模式:worker 已暂停,保持 WDA 关闭;否则下一拍会重新开 WDA,
1634
+ # 窗口再次从截图/录屏里消失,_snapshot_mode 等于没做。
1635
+ if SNAPSHOT and getattr(self, "_snapshot_done", False):
1636
+ self._pause.set()
1637
+ if self._excluded:
1638
+ self._set_exclude(False)
1639
+ self.root.after(100, self._tick)
1640
+ return
1284
1641
  if PREVIEW:
1285
1642
  self._pause.set()
1286
1643
  if self._excluded:
@@ -1291,7 +1648,13 @@ class LiveGlass:
1291
1648
  if self._resize:
1292
1649
  self.root.after(INTERVAL_MS, self._tick)
1293
1650
  return
1294
- if not self._excluded:
1651
+ if getattr(self, "_collapsed", False):
1652
+ # 折叠态用 _make_collapsed_frame 的静态背景;_work 也停抓取。
1653
+ # 若还让这里消费旧队列,会把 560px 的帧贴回 78px 的 Canvas,
1654
+ # 底部圆角/暗边会闪一下,看起来像渲染错位。
1655
+ self.root.after(INTERVAL_MS, self._tick)
1656
+ return
1657
+ if not self._excluded and os.environ.get("DSH_GLASS_WDA") != "0":
1295
1658
  self._set_exclude(True)
1296
1659
  self._pause.clear()
1297
1660
 
@@ -1340,7 +1703,9 @@ class LiveGlass:
1340
1703
  # 边缘缩放 / 窗口拖动
1341
1704
  def _edge_at(self, x, y):
1342
1705
  w, h = self.root.winfo_width(), self.root.winfo_height()
1343
- edge, corner = 10, 26
1706
+ # 圆角是透明的,鼠标落在最外侧时命中的是 DWM 非客户区;
1707
+ # 命中带放宽到 20px,用户不必精确到 1px 也能拖边缘/四角。
1708
+ edge, corner = 20, 32
1344
1709
  # 圆角区域是透明的,命中区要往内收够,才能点到可见的角
1345
1710
  if x <= corner and y <= corner:
1346
1711
  return "nw"
@@ -1425,7 +1790,13 @@ class LiveGlass:
1425
1790
  self._preview_resize(nw, nh)
1426
1791
  return
1427
1792
  if self._drag:
1428
- self.root.geometry(f"+{e.x_root - self._drag[0]}+{e.y_root - self._drag[1]}")
1793
+ # 和缩放分支一样必须钳位:拖到屏幕外时窗口坐标会变负,
1794
+ # 抓屏区域随之越界(高度算出负数),背景永远画不出来 —— 表现为花屏。
1795
+ nx = e.x_root - self._drag[0]
1796
+ ny = e.y_root - self._drag[1]
1797
+ nx = max(0, min(max(0, self._sw - self.root.winfo_width()), nx))
1798
+ ny = max(0, min(max(0, self._sh - self.root.winfo_height()), ny))
1799
+ self.root.geometry(f"+{nx}+{ny}")
1429
1800
 
1430
1801
  def _release(self, e):
1431
1802
  if self._resize:
@@ -1435,9 +1806,11 @@ class LiveGlass:
1435
1806
  w = max(MIN_W, self.root.winfo_width())
1436
1807
  h = max(MIN_H, self.root.winfo_height())
1437
1808
  self._rebuild(w, h)
1809
+ self._sync_pos()
1438
1810
  self._hover(e)
1439
1811
  return
1440
1812
  self._drag = None
1813
+ self._sync_pos()
1441
1814
 
1442
1815
  def run(self):
1443
1816
  self.root.bind("<Escape>", self._close)