papersearch 0.5.5 → 0.5.7

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.
Files changed (84) hide show
  1. package/README.en.md +11 -9
  2. package/README.md +11 -9
  3. package/assets/ask-with-skill.png +0 -0
  4. package/carsi/paper_search_carsi/assets/capsule.html +173 -21
  5. package/carsi/paper_search_carsi/assets/capsule_en.json +64 -1
  6. package/carsi/paper_search_carsi/browser/watchdog.py +6 -1
  7. package/carsi/paper_search_carsi/capsule_placement.py +8 -5
  8. package/carsi/paper_search_carsi/capsule_window.py +495 -0
  9. package/carsi/paper_search_carsi/cli.py +2 -2
  10. package/carsi/paper_search_carsi/engine/batch_capture.py +11 -3
  11. package/carsi/paper_search_carsi/engine/batch_login.py +3 -2
  12. package/carsi/paper_search_carsi/engine/batch_waits.py +28 -7
  13. package/carsi/paper_search_carsi/i18n.py +5 -0
  14. package/carsi/paper_search_carsi/progress_capsule.py +177 -426
  15. package/carsi/paper_search_carsi/progress_macos.py +53 -6
  16. package/carsi/paper_search_carsi/progress_reporter.py +132 -20
  17. package/carsi/paper_search_carsi/progress_view.py +95 -14
  18. package/carsi/paper_search_carsi/server.py +25 -3
  19. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js +1 -1
  20. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js.map +1 -1
  21. package/dist/capabilities/pdf-discovery/batch.d.ts +4 -3
  22. package/dist/capabilities/pdf-discovery/batch.d.ts.map +1 -1
  23. package/dist/capabilities/pdf-discovery/batch.js +217 -85
  24. package/dist/capabilities/pdf-discovery/batch.js.map +1 -1
  25. package/dist/capabilities/pdf-discovery/batchPapers.d.ts +19 -0
  26. package/dist/capabilities/pdf-discovery/batchPapers.d.ts.map +1 -0
  27. package/dist/capabilities/pdf-discovery/batchPapers.js +44 -0
  28. package/dist/capabilities/pdf-discovery/batchPapers.js.map +1 -0
  29. package/dist/capabilities/pdf-discovery/batchSummary.d.ts +6 -1
  30. package/dist/capabilities/pdf-discovery/batchSummary.d.ts.map +1 -1
  31. package/dist/capabilities/pdf-discovery/batchSummary.js +33 -8
  32. package/dist/capabilities/pdf-discovery/batchSummary.js.map +1 -1
  33. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js +1 -1
  34. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js.map +1 -1
  35. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts +13 -1
  36. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts.map +1 -1
  37. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +77 -25
  38. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js.map +1 -1
  39. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts +4 -0
  40. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts.map +1 -1
  41. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js +5 -0
  42. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js.map +1 -1
  43. package/dist/capabilities/pdf-discovery/carsi/CarsiResultNormalizer.d.ts.map +1 -1
  44. package/dist/capabilities/pdf-discovery/carsi/CarsiResultNormalizer.js +4 -3
  45. package/dist/capabilities/pdf-discovery/carsi/CarsiResultNormalizer.js.map +1 -1
  46. package/dist/capabilities/pdf-discovery/carsi/index.d.ts +1 -1
  47. package/dist/capabilities/pdf-discovery/carsi/index.d.ts.map +1 -1
  48. package/dist/capabilities/pdf-discovery/carsi/types.d.ts +51 -2
  49. package/dist/capabilities/pdf-discovery/carsi/types.d.ts.map +1 -1
  50. package/dist/capabilities/pdf-discovery/handler.d.ts.map +1 -1
  51. package/dist/capabilities/pdf-discovery/handler.js +2 -1
  52. package/dist/capabilities/pdf-discovery/handler.js.map +1 -1
  53. package/dist/capabilities/pdf-discovery/outputLayout.d.ts +27 -2
  54. package/dist/capabilities/pdf-discovery/outputLayout.d.ts.map +1 -1
  55. package/dist/capabilities/pdf-discovery/outputLayout.js +133 -29
  56. package/dist/capabilities/pdf-discovery/outputLayout.js.map +1 -1
  57. package/dist/capabilities/pdf-discovery/types.d.ts +5 -0
  58. package/dist/capabilities/pdf-discovery/types.d.ts.map +1 -1
  59. package/dist/cli.js +1 -31
  60. package/dist/cli.js.map +1 -1
  61. package/dist/infrastructure/runlog/RunLedger.d.ts +4 -0
  62. package/dist/infrastructure/runlog/RunLedger.d.ts.map +1 -1
  63. package/dist/infrastructure/runlog/RunLedger.js +11 -3
  64. package/dist/infrastructure/runlog/RunLedger.js.map +1 -1
  65. package/dist/management/carsi/autoUpdate.d.ts +2 -2
  66. package/dist/management/carsi/autoUpdate.d.ts.map +1 -1
  67. package/dist/management/carsi/autoUpdate.js +8 -2
  68. package/dist/management/carsi/autoUpdate.js.map +1 -1
  69. package/dist/management/carsi/cliProgress.d.ts +8 -0
  70. package/dist/management/carsi/cliProgress.d.ts.map +1 -0
  71. package/dist/management/carsi/cliProgress.js +38 -0
  72. package/dist/management/carsi/cliProgress.js.map +1 -0
  73. package/dist/management/carsi/installer.d.ts.map +1 -1
  74. package/dist/management/carsi/installer.js +3 -6
  75. package/dist/management/carsi/installer.js.map +1 -1
  76. package/package.json +1 -1
  77. package/skills/paper-search/SKILL.md +4 -5
  78. package/skills/paper-search/references/browser-download.md +6 -6
  79. package/skills/paper-search/references/carsi-setup.md +2 -3
  80. package/skills/paper-search/references/cli-contract.md +4 -4
  81. package/skills/paper-search/references/management-layer.md +2 -2
  82. package/skills/paper-search/references/setup.md +3 -3
  83. package/skills/paper-search/references/troubleshooting.md +2 -2
  84. package/carsi/paper_search_carsi/progress_bar.py +0 -684
@@ -1,684 +0,0 @@
1
- """Floating download progress window.
2
-
3
- A small always-on-top window that watches the task progress file
4
- (``progress_reporter``) and shows: status and done/total, the current phase
5
- and elapsed time, the paper being worked on, a slim progress bar, success /
6
- failure / remaining counters and a link to the output folder. Drag the client
7
- area to move; the native title bar provides minimize and close.
8
-
9
- Usage: ``paper-search-carsi progress`` (or ``python -m paper_search_carsi.progress_bar``).
10
- Spawned automatically by ``progress_reporter.ensure_progress_bar`` when a download starts.
11
-
12
- Visual stack (no third-party GUI deps):
13
- - Light and dark palettes follow the OS appearance (macOS / Windows).
14
- - Platform fonts: the macOS system font (SF + PingFang), Microsoft YaHei UI
15
- on Windows, Noto Sans CJK on Linux; DOIs use the platform monospace.
16
- - Windows: per-monitor DPI aware, rounded DWM frame with a matching title bar.
17
- - All text is laid out with measured widths (CJK-safe).
18
- """
19
-
20
- from __future__ import annotations
21
-
22
- import os
23
- import time
24
- import tkinter as tk
25
- import tkinter.font as tkfont
26
- from pathlib import Path
27
- from typing import Any
28
-
29
- import sys as _sys
30
-
31
- from . import user_settings
32
- from . import progress_view
33
- from .progress_reporter import read_state
34
- # Kept importable from here for tests and older callers.
35
- from .progress_view import ( # noqa: F401
36
- CONTENT_LABELS, DEFAULT_LINGER_SECONDS, STAGE_TEXT, TERMINAL_STATUSES, AutoClose,
37
- )
38
-
39
- # --- Win32 / DWM constants -------------------------------------------------
40
- DWMWA_USE_IMMERSIVE_DARK_MODE = 20
41
- DWMWA_BORDER_COLOR = 34
42
- DWMWA_CAPTION_COLOR = 35
43
- DWMWA_TEXT_COLOR = 36
44
- DWMWA_WINDOW_CORNER_PREFERENCE = 33
45
- DWMWA_SYSTEMBACKDROP_TYPE = 38
46
- DWMWCP_ROUND = 2
47
- DWMSBT_MAINWINDOW = 2 # light Mica
48
-
49
- # Palettes: (light, dark). Picked once at start from the OS appearance.
50
- PALETTES = {
51
- "light": {
52
- "bg": "#ffffff", "text": "#111827", "dim": "#6b7280", "faint": "#9ca3af",
53
- "track": "#e5e7eb", "accent": "#2563eb", "ok": "#16a34a", "bad": "#dc2626",
54
- "warn": "#b45309", "warn_bg": "#fef3c7", "link": "#2563eb", "btn": "#374151",
55
- },
56
- "dark": {
57
- "bg": "#1f2023", "text": "#f3f4f6", "dim": "#a1a1aa", "faint": "#71717a",
58
- "track": "#3f3f46", "accent": "#60a5fa", "ok": "#4ade80", "bad": "#f87171",
59
- "warn": "#fbbf24", "warn_bg": "#3b2f12", "link": "#60a5fa", "btn": "#d4d4d8",
60
- },
61
- }
62
-
63
- # Window, macOS Dock and Windows taskbar icon, rendered from assets/icon.svg.
64
- ICON_FILES = ("icon-512.png", "icon-64.png", "icon-32.png")
65
-
66
- # Logical layout (scaled by the real DPI factor at runtime)
67
- W, H, PAD = 420, 172, 18
68
-
69
-
70
- _dark_mode = progress_view.dark_mode
71
-
72
-
73
- def _pick_family(candidates: list[str], fallback: str) -> str:
74
- try:
75
- available = {f.lower(): f for f in tkfont.families()}
76
- except Exception:
77
- return fallback
78
- for name in candidates:
79
- if name.lower() in available:
80
- return available[name.lower()]
81
- return fallback
82
-
83
-
84
- _fmt_elapsed = progress_view.fmt_elapsed
85
-
86
-
87
- def _enable_dpi_awareness() -> None:
88
- try:
89
- import ctypes
90
- ctypes.windll.shcore.SetProcessDpiAwareness(2) # per-monitor aware
91
- except Exception:
92
- try:
93
- import ctypes
94
- ctypes.windll.user32.SetProcessDPIAware()
95
- except Exception:
96
- pass
97
-
98
-
99
- def _dwm(hwnd: int, attr: int, value: int) -> bool:
100
- try:
101
- import ctypes
102
- import ctypes.wintypes as wt
103
- dwm = ctypes.windll.dwmapi
104
- dwm.DwmSetWindowAttribute.argtypes = [
105
- wt.HWND, wt.DWORD, ctypes.c_void_p, wt.DWORD,
106
- ]
107
- dwm.DwmSetWindowAttribute.restype = ctypes.c_long
108
- v = ctypes.c_int(value)
109
- r = dwm.DwmSetWindowAttribute(
110
- hwnd, attr, ctypes.byref(v), ctypes.sizeof(v),
111
- )
112
- return r == 0
113
- except Exception:
114
- return False
115
-
116
-
117
- def _dwm_color(hwnd: int, attr: int, color: int) -> bool:
118
- """Set a DWM COLORREF attribute when the current Windows build supports it."""
119
- try:
120
- import ctypes
121
- import ctypes.wintypes as wt
122
- dwm = ctypes.windll.dwmapi
123
- dwm.DwmSetWindowAttribute.argtypes = [
124
- wt.HWND, wt.DWORD, ctypes.c_void_p, wt.DWORD,
125
- ]
126
- dwm.DwmSetWindowAttribute.restype = ctypes.c_long
127
- value = ctypes.c_uint(color)
128
- return dwm.DwmSetWindowAttribute(
129
- hwnd, attr, ctypes.byref(value), ctypes.sizeof(value),
130
- ) == 0
131
- except Exception:
132
- return False
133
-
134
-
135
- def _elide(font: tkfont.Font, text: str, width_px: int) -> str:
136
- if font.measure(text) <= width_px:
137
- return text
138
- while text and font.measure(text + "…") > width_px:
139
- text = text[:-1]
140
- return text + "…"
141
-
142
-
143
- class ProgressWindow:
144
- def __init__(self) -> None:
145
- _enable_dpi_awareness()
146
- self._auto_close = AutoClose.from_env()
147
- self.root = tk.Tk()
148
- self._set_icon()
149
- self.c = PALETTES["dark" if _dark_mode() else "light"]
150
- # Tk on macOS already renders in points on Retina; Windows needs the
151
- # explicit per-monitor factor.
152
- self.s = 1.0 if _sys.platform == "darwin" else max(1.0, self.root.winfo_fpixels("1i") / 96.0)
153
- self.W, self.H, self.P = int(W * self.s), int(H * self.s), int(PAD * self.s)
154
- self.root.title("PaperSearch · 下载进度")
155
- self.root.geometry(f"{self.W}x{self.H}+{self._anchor_x()}{self._anchor_y()}")
156
- self.root.minsize(self.W, self.H)
157
- self.root.resizable(True, False)
158
- self.root.attributes("-topmost", True)
159
- self.root.configure(bg=self.c["bg"])
160
-
161
- self.canvas = tk.Canvas(self.root, width=self.W, height=self.H,
162
- bg=self.c["bg"], highlightthickness=0, bd=0)
163
- self.canvas.pack(fill="both", expand=True)
164
-
165
- # Map the Tk window before asking Win32 for its top-level handle.
166
- self.root.update_idletasks()
167
- self.root.update()
168
- self._apply_backdrop()
169
- self._fonts()
170
- self._bind_mouse()
171
- self._draw_bindings: list[tuple[str, str, str]] = []
172
- self._finished_elapsed: float | None = None
173
- self._finished_run: object = None
174
- self._flash: tuple[str, float, str] | None = None # (text, until, doi)
175
- self._chosen: tuple[str, str] | None = None # (doi, action) pressed for the current paper
176
- self._hover = "" # the button under the mouse; kept across redraws
177
- self._settings: tk.Toplevel | None = None # the settings dialog, when open
178
- self._last_current = "" # the paper shown, for a message after the dialog closes
179
- self.root.after(400, self._tick)
180
-
181
- # --- window plumbing ---------------------------------------------------
182
- def _set_icon(self) -> None:
183
- """PaperSearch's icon for this window, the macOS Dock and the Windows
184
- taskbar; a plain Python process shows a blank one."""
185
- folder = Path(__file__).with_name("assets")
186
- try:
187
- # Kept on self: Tk drops an image once Python frees the PhotoImage.
188
- self._icons = [tk.PhotoImage(master=self.root, file=str(folder / name)) for name in ICON_FILES]
189
- self.root.iconphoto(True, *self._icons)
190
- except tk.TclError:
191
- pass # a missing icon file must not keep the progress window from opening
192
-
193
- def _hwnd(self) -> int:
194
- if os.name != "nt":
195
- return 0
196
- try:
197
- import ctypes
198
- import ctypes.wintypes as wt
199
- self.root.update_idletasks()
200
- user32 = ctypes.windll.user32
201
- # GetParent on Tk's root returns 0; GetAncestor(GA_ROOT) is the frame.
202
- user32.GetAncestor.argtypes = [wt.HWND, wt.UINT]
203
- user32.GetAncestor.restype = wt.HWND
204
- hwnd = user32.GetAncestor(self.root.winfo_id(), 2)
205
- return int(hwnd or self.root.winfo_id())
206
- except Exception:
207
- return 0
208
-
209
- def _apply_backdrop(self) -> None:
210
- """Windows 11: rounded frame and a title bar in the window's palette."""
211
- hwnd = self._hwnd()
212
- if not hwnd:
213
- return
214
- dark = self.c is PALETTES["dark"]
215
- _dwm(hwnd, DWMWA_USE_IMMERSIVE_DARK_MODE, 1 if dark else 0)
216
- _dwm(hwnd, DWMWA_WINDOW_CORNER_PREFERENCE, DWMWCP_ROUND)
217
-
218
- def colorref(hex_color: str) -> int: # "#rrggbb" -> 0x00BBGGRR
219
- r, g, b = int(hex_color[1:3], 16), int(hex_color[3:5], 16), int(hex_color[5:7], 16)
220
- return (b << 16) | (g << 8) | r
221
-
222
- _dwm_color(hwnd, DWMWA_CAPTION_COLOR, colorref(self.c["bg"]))
223
- _dwm_color(hwnd, DWMWA_BORDER_COLOR, colorref(self.c["track"]))
224
- _dwm_color(hwnd, DWMWA_TEXT_COLOR, colorref(self.c["text"]))
225
-
226
- def _fonts(self) -> None:
227
- if _sys.platform == "darwin":
228
- ui = tkfont.nametofont("TkDefaultFont").actual("family") # SF + PingFang fallback
229
- mono = _pick_family(["SF Mono", "Menlo"], "Courier")
230
- elif os.name == "nt":
231
- ui = _pick_family(["Microsoft YaHei UI", "Segoe UI"], "TkDefaultFont")
232
- mono = _pick_family(["Cascadia Mono", "Consolas"], "Courier New")
233
- else:
234
- ui = _pick_family(["Noto Sans CJK SC", "Noto Sans SC", "WenQuanYi Micro Hei", "DejaVu Sans"], "TkDefaultFont")
235
- mono = _pick_family(["DejaVu Sans Mono", "Noto Sans Mono", "Liberation Mono"], "Courier")
236
- px = lambda n: -int(round(n * self.s)) # negative size = pixels
237
- self.f_title = tkfont.Font(family=ui, size=px(14), weight="bold")
238
- self.f_count = tkfont.Font(family=ui, size=px(14), weight="bold")
239
- self.f_body = tkfont.Font(family=ui, size=px(12))
240
- self.f_small = tkfont.Font(family=ui, size=px(11))
241
- self.f_mono = tkfont.Font(family=mono, size=px(11))
242
-
243
- def _anchor_x(self) -> int:
244
- return max(0, self.root.winfo_screenwidth() - self.W - int(20 * self.s))
245
-
246
- def _anchor_y(self) -> str:
247
- # macOS: top-right under the menu bar (the Dock owns the bottom edge).
248
- # Windows/Linux: bottom-right above the taskbar.
249
- if _sys.platform == "darwin":
250
- return "+44"
251
- return f"-{int(56 * self.s)}"
252
-
253
- def _bind_mouse(self) -> None:
254
- self._drag_dx = self._drag_dy = 0
255
- c = self.canvas
256
- c.bind("<Button-1>", self._press)
257
- c.bind("<B1-Motion>", self._move)
258
- # A finished window stays while the pointer is on it (AutoClose).
259
- self._pointer_in = False
260
- c.bind("<Enter>", lambda e: setattr(self, "_pointer_in", True))
261
- c.bind("<Leave>", lambda e: setattr(self, "_pointer_in", False))
262
-
263
- def _press(self, event: Any) -> None:
264
- self._drag_dx, self._drag_dy = event.x, event.y
265
-
266
- def _move(self, event: Any) -> None:
267
- x = self.root.winfo_x() + event.x - self._drag_dx
268
- y = self.root.winfo_y() + event.y - self._drag_dy
269
- self.root.geometry(f"+{x}+{y}")
270
-
271
- # --- drawing ------------------------------------------------------------
272
- def _pill(self, x0: int, y0: int, x1: int, y1: int, fill: str, tags: Any = ()) -> None:
273
- """Crisp rounded rectangle: two discs plus a rectangle (no polygon smoothing)."""
274
- r = (y1 - y0) / 2
275
- c = self.canvas
276
- if x1 - x0 <= 2 * r:
277
- c.create_oval(x0, y0, x0 + 2 * r, y1, fill=fill, outline=fill, tags=tags)
278
- return
279
- c.create_oval(x0, y0, x0 + 2 * r, y1, fill=fill, outline=fill, tags=tags)
280
- c.create_oval(x1 - 2 * r, y0, x1, y1, fill=fill, outline=fill, tags=tags)
281
- c.create_rectangle(x0 + r, y0, x1 - r, y1, fill=fill, outline=fill, tags=tags)
282
-
283
- def _elapsed(self, state: dict[str, Any], finished: bool) -> str:
284
- from datetime import datetime
285
-
286
- try:
287
- started = datetime.fromisoformat(str(state.get("started_at")))
288
- except (TypeError, ValueError):
289
- return ""
290
- if finished:
291
- try:
292
- end = datetime.fromisoformat(str(state.get("finished_at")))
293
- except (TypeError, ValueError):
294
- run = state.get("run_id")
295
- if self._finished_run != run or self._finished_elapsed is None:
296
- self._finished_run = run
297
- self._finished_elapsed = (datetime.now() - started).total_seconds()
298
- return _fmt_elapsed(self._finished_elapsed)
299
- return _fmt_elapsed((end - started).total_seconds())
300
- return _fmt_elapsed((datetime.now() - started).total_seconds())
301
-
302
- _status_text = staticmethod(progress_view.status_text)
303
- _attention_items = staticmethod(progress_view.attention_items)
304
-
305
- def _bind_draw(self, tag: str, event: str, callback: Any) -> None:
306
- """A binding owned by this frame, released before its items are deleted."""
307
- command = self.canvas.tag_bind(tag, event, callback)
308
- self._draw_bindings.append((tag, event, command))
309
-
310
- def _draw(self, state: dict[str, Any] | None) -> None:
311
- c, col, s = self.canvas, self.c, self.s
312
- # Canvas.delete removes items, not tag_bind's registered Tcl/Python
313
- # commands. Keep neither old state nor callbacks across the 500 ms redraws.
314
- for tag, event, command in self._draw_bindings:
315
- c.tag_unbind(tag, event, command)
316
- self._draw_bindings.clear()
317
- c.delete("all")
318
- P = self.P
319
- Wl = max(self.W, c.winfo_width())
320
- Hl = max(self.H, c.winfo_height())
321
- u = lambda n: int(round(n * s))
322
-
323
- gear_left = self._draw_gear(Wl - P, P + u(9))
324
- if not state:
325
- self._last_current = ""
326
- c.create_text(Wl // 2, Hl // 2 - u(8), text="PaperSearch", fill=col["text"], font=self.f_title)
327
- c.create_text(Wl // 2, Hl // 2 + u(14), text="暂无下载任务", fill=col["dim"], font=self.f_small)
328
- return
329
-
330
- status = str(state.get("status") or "")
331
- running = status == "running"
332
- total = max(0, int(state.get("total", 0) or 0))
333
- done = int(state.get("done", 0) or 0)
334
- done = min(total, done) if total else done
335
- ok = int(state.get("success", 0) or 0)
336
- bad = int(state.get("failed", 0) or 0)
337
- pct = (done / total) if total else 0.0
338
- attention = self._attention_items(state) if running else []
339
-
340
- if attention:
341
- tone, headline = col["warn"], "需要你操作"
342
- elif running:
343
- tone, headline = col["accent"], str(state.get("task") or "下载中")
344
- elif ok == 0 and bad > 0:
345
- tone, headline = col["bad"], "下载未成功"
346
- elif bad > 0:
347
- tone, headline = col["warn"], "下载结束,部分失败"
348
- else:
349
- tone, headline = col["ok"], "下载完成"
350
-
351
- # Row 1: status dot + headline ......... done / total
352
- y1 = P + u(9)
353
- dot = u(8)
354
- c.create_oval(P, y1 - dot // 2, P + dot, y1 + dot // 2, fill=tone, outline=tone)
355
- count = f"{done} / {total}" if total else f"{done}"
356
- c.create_text(gear_left - u(8), y1, text=count, fill=col["text"], font=self.f_count, anchor="e")
357
- count_w = self.f_count.measure(count) + (Wl - P - gear_left) + u(8)
358
- # What this download fetches, as a small label left of the count.
359
- content = CONTENT_LABELS.get(str(state.get("content") or "main"), CONTENT_LABELS["main"])
360
- chip_h = u(18)
361
- chip_x1 = Wl - P - count_w - u(8)
362
- chip_x0 = chip_x1 - self.f_small.measure(content) - u(14)
363
- self._pill(chip_x0, y1 - chip_h // 2, chip_x1, y1 + chip_h // 2, col["track"])
364
- c.create_text((chip_x0 + chip_x1) / 2, y1, text=content, fill=col["dim"], font=self.f_small)
365
- title_x = P + dot + u(8)
366
- c.create_text(title_x, y1, anchor="w", fill=col["text"], font=self.f_title,
367
- text=_elide(self.f_title, headline, chip_x0 - u(8) - title_x))
368
-
369
- # Row 2: phase (or the verification request) ........ elapsed
370
- y2 = y1 + u(25)
371
- elapsed = self._elapsed(state, finished=not running)
372
- elapsed_text = (f"已用 {elapsed}" if running else f"用时 {elapsed}") if elapsed else ""
373
- if elapsed_text:
374
- c.create_text(Wl - P, y2, text=elapsed_text, fill=col["faint"], font=self.f_small, anchor="e")
375
- phase_room = Wl - 2 * P - (self.f_small.measure(elapsed_text) + u(12) if elapsed_text else 0)
376
- flash = self._flash if self._flash and time.time() < self._flash[1] else None
377
- # What the download did about a click (batch_user.py), once it is newer than the click.
378
- notice = state.get("notice") if isinstance(state.get("notice"), dict) else {}
379
- notice_at = float(notice.get("at") or 0) if notice else 0.0
380
- if (notice and time.time() - notice_at < 10 and str(notice.get("current") or "") == str(state.get("current") or "")
381
- and (not flash or notice_at >= flash[1] - 6)):
382
- flash = (str(notice.get("text") or ""), notice_at + 10, str(notice.get("current") or ""))
383
- if flash and flash[2] == str(state.get("current") or ""):
384
- c.create_text(P, y2, anchor="w", fill=col["accent"], font=self.f_body,
385
- text=_elide(self.f_body, flash[0], phase_room))
386
- elif attention:
387
- item = attention[-1]
388
- notice = str(item.get("message") or "请在浏览器窗口完成安全验证")
389
- if len(attention) > 1:
390
- notice += f"(另有 {len(attention) - 1} 项)"
391
- text = _elide(self.f_body, notice, phase_room - u(16))
392
- self._pill(P - u(2), y2 - u(11), P + self.f_body.measure(text) + u(14), y2 + u(11), col["warn_bg"])
393
- c.create_text(P + u(6), y2, text=text, fill=col["warn"], font=self.f_body, anchor="w")
394
- else:
395
- phase = self._status_text(state, running)
396
- c.create_text(P, y2, anchor="w", fill=col["dim"], font=self.f_body,
397
- text=_elide(self.f_body, phase, phase_room))
398
-
399
- # Row 3: the paper being worked on
400
- y3 = y2 + u(22)
401
- current = str((attention[-1].get("current") if attention else "") or state.get("current") or "")
402
- self._last_current = current
403
- if current:
404
- c.create_text(P, y3, anchor="w", fill=col["text"] if running else col["dim"], font=self.f_mono,
405
- text=_elide(self.f_mono, current, Wl - 2 * P))
406
- where = " · ".join(v for v in (str(state.get("journal") or ""), str(state.get("publisher") or "")) if v)
407
- if where:
408
- doi_w = self.f_mono.measure(current) + u(10)
409
- if doi_w < Wl - 2 * P - u(60):
410
- c.create_text(P + doi_w, y3, anchor="w", fill=col["faint"], font=self.f_small,
411
- text=_elide(self.f_small, where, Wl - 2 * P - doi_w))
412
-
413
- # Row 4: slim progress bar
414
- y4 = y3 + u(20)
415
- bar_h = u(6)
416
- self._pill(P, y4, Wl - P, y4 + bar_h, col["track"])
417
- fill_w = int((Wl - 2 * P) * pct)
418
- if fill_w > 0:
419
- self._pill(P, y4, P + max(bar_h, fill_w), y4 + bar_h, tone)
420
-
421
- # Row 5: counters ........ open folder
422
- y5 = y4 + bar_h + u(17)
423
- x = P
424
- for label, value, color in (("成功", ok, col["ok"]), ("失败", bad, col["bad"]),
425
- ("剩余", max(0, total - done), col["faint"])):
426
- if label == "剩余" and (not total or not running):
427
- continue
428
- d = u(6)
429
- c.create_oval(x, y5 - d // 2, x + d, y5 + d // 2, fill=color, outline=color)
430
- text = f"{label} {value}"
431
- c.create_text(x + d + u(5), y5, text=text, fill=col["dim"], font=self.f_small, anchor="w")
432
- x += d + u(5) + self.f_small.measure(text) + u(14)
433
- # Row 6: buttons for the current paper. Neutral until pressed; a pressed one
434
- # turns amber (the "no access" ones are remembered for later runs).
435
- y6 = y5 + u(26)
436
- if running and current and not state.get("awaiting_next"):
437
- x = P
438
- chosen = self._chosen[1] if self._chosen and self._chosen[0] == current else ""
439
- for key, label in (("skip_item", "跳过本篇"), ("skip_journal", "本刊无权限"),
440
- ("skip_publisher", "出版社无权限"), ("stop_batch", "终止任务")):
441
- pressed = key == chosen
442
- text = ("✓ " + label) if pressed else label
443
- w = self.f_small.measure(text) + u(18)
444
- tag = f"btn-{key}"
445
- self._pill(x, y6 - u(11), x + w, y6 + u(11), col["warn"] if pressed else col["track"], tags=(tag,))
446
- fill = col["bg"] if pressed else (col["text"] if self._hover == key else col["btn"])
447
- label_id = c.create_text(x + w / 2, y6, text=text, fill=fill, font=self.f_small, tags=(tag,))
448
- self._bind_draw(tag, "<Button-1>", lambda e, k=key, d=current, s=state: (
449
- self._stop(d, s) if k == "stop_batch" else self._decide(k, d, s)))
450
- if not pressed:
451
- self._bind_draw(tag, "<Enter>", lambda e, k=key, i=label_id: self._hover_button(k, i))
452
- self._bind_draw(tag, "<Leave>", lambda e, i=label_id: self._hover_button("", i))
453
- x += w + u(8)
454
- # Problem report for the agent to review: a small flag icon, right-aligned.
455
- c.create_text(Wl - P, y6, text="\u2691", fill=col["faint"], font=self.f_body,
456
- anchor="e", tags=("report",))
457
- self._bind_draw("report", "<Button-1>", lambda e, d=current, s=state: self._report_menu(e, d, s))
458
-
459
- output_dir = str(state.get("output_dir") or "")
460
- if output_dir:
461
- link = c.create_text(Wl - P, y5, text="打开文件夹", fill=col["link"], font=self.f_small,
462
- anchor="e", tags=("outdir",))
463
- self._bind_draw("outdir", "<Button-1>", lambda e: self._open_output_dir(state))
464
- self._bind_draw("outdir", "<Enter>", lambda e: c.itemconfigure(link, font=self._underlined()))
465
- self._bind_draw("outdir", "<Leave>", lambda e: c.itemconfigure(link, font=self.f_small))
466
-
467
- def _decide(self, action: str, doi: str, state: dict[str, Any]) -> None:
468
- """Ask the running download to apply the user's entitlement decision."""
469
- try:
470
- from .entitlements import request_action
471
-
472
- request_action(doi, action, str(state.get("run_id") or ""))
473
- text = progress_view.ACTION_FEEDBACK[action]
474
- except Exception as exc:
475
- text = f"记录失败:{type(exc).__name__}"
476
- self._flash = (text, time.time() + 6, doi)
477
- self._chosen = (doi, action)
478
- self._draw(state)
479
-
480
- def _stop(self, doi: str, state: dict[str, Any]) -> None:
481
- """Stop the whole task, after asking: this paper ends, the rest are not downloaded."""
482
- from tkinter import messagebox
483
-
484
- left = max(0, int(state.get("total", 0) or 0) - int(state.get("done", 0) or 0) - 1)
485
- question = "终止整个下载任务?这一篇立即结束" + (f",剩下的 {left} 篇不再下载。" if left else "。")
486
- if messagebox.askyesno("终止任务", question, parent=self.root):
487
- self._decide("stop_batch", doi, state)
488
-
489
- def _draw_gear(self, right: int, y: int) -> int:
490
- """Round settings button with a small, font-independent gear."""
491
- import math
492
-
493
- c, col, s = self.canvas, self.c, self.s
494
- d = 17.6 * s
495
- x0, cx = right - d, right - d / 2
496
- c.create_oval(x0, y - d / 2, right, y + d / 2,
497
- fill=col["track"], outline=col["track"], tags=("settings",))
498
- # 11.2 px = 70% of the previous 16 px icon. Angular teeth keep the
499
- # original gear appearance without platform-specific font rendering.
500
- points = []
501
- for tooth in range(8):
502
- for offset, radius in ((-0.5, 4.1), (-0.28, 5.6), (0.28, 5.6), (0.5, 4.1)):
503
- angle = (tooth + offset) * math.pi / 4
504
- points.extend((cx + radius * s * math.cos(angle), y + radius * s * math.sin(angle)))
505
- gear = c.create_polygon(*points, fill=col["btn"], outline="", tags=("settings",))
506
- r = 2.1 * s
507
- c.create_oval(cx - r, y - r, cx + r, y + r, fill=col["track"], outline="", tags=("settings",))
508
- self._bind_draw("settings", "<Button-1>", lambda e: self._open_settings())
509
- self._bind_draw("settings", "<Enter>", lambda e: c.itemconfigure(gear, fill=col["text"]))
510
- self._bind_draw("settings", "<Leave>", lambda e: c.itemconfigure(gear, fill=col["btn"]))
511
- return x0
512
-
513
- def _open_settings(self) -> None:
514
- """The settings dialog: each value typed in and checked; saved values
515
- apply from the next paper."""
516
- if self._settings is not None and self._settings.winfo_exists():
517
- self._settings.lift()
518
- return
519
- col, pad = self.c, int(round(14 * self.s))
520
- top = self._settings = tk.Toplevel(self.root, bg=col["bg"])
521
- top.title("设置")
522
- top.resizable(False, False)
523
- top.attributes("-topmost", True)
524
- top.transient(self.root)
525
- frame = tk.Frame(top, bg=col["bg"], padx=pad, pady=pad)
526
- frame.pack(fill="both", expand=True)
527
- tk.Label(frame, text="设置", bg=col["bg"], fg=col["text"], font=self.f_title).grid(
528
- row=0, column=0, columnspan=3, sticky="w", pady=(0, pad // 2))
529
- values = user_settings.current()
530
- entries: dict[str, tk.Entry] = {}
531
- errors: dict[str, tk.Label] = {}
532
- for i, field in enumerate(user_settings.FIELDS):
533
- row = 1 + 2 * i
534
- tk.Label(frame, text=field.label, bg=col["bg"], fg=col["text"], font=self.f_body).grid(
535
- row=row, column=0, sticky="w", padx=(0, pad))
536
- entry = tk.Entry(frame, width=6, justify="right", font=self.f_body)
537
- entry.insert(0, str(values[field.name]))
538
- entry.grid(row=row, column=1, pady=3)
539
- tk.Label(frame, text=field.unit, bg=col["bg"], fg=col["dim"], font=self.f_body).grid(
540
- row=row, column=2, sticky="w", padx=(6, 0))
541
- error = tk.Label(frame, text="", bg=col["bg"], fg=col["bad"], font=self.f_small)
542
- error.grid(row=row + 1, column=0, columnspan=3, sticky="w")
543
- error.grid_remove()
544
- entries[field.name], errors[field.name] = entry, error
545
-
546
- def reset() -> None:
547
- for field in user_settings.FIELDS:
548
- entries[field.name].delete(0, "end")
549
- entries[field.name].insert(0, str(field.default))
550
- errors[field.name].grid_remove()
551
-
552
- def save() -> None:
553
- chosen: dict[str, int] = {}
554
- for field in user_settings.FIELDS:
555
- value, problem = user_settings.check(field, entries[field.name].get())
556
- if problem:
557
- errors[field.name].configure(text=problem)
558
- errors[field.name].grid()
559
- else:
560
- errors[field.name].grid_remove()
561
- chosen[field.name] = int(value)
562
- if len(chosen) < len(user_settings.FIELDS):
563
- return
564
- try:
565
- user_settings.save(chosen)
566
- text = "设置已保存,从下一篇起生效"
567
- except Exception as exc:
568
- text = f"保存失败:{type(exc).__name__}"
569
- top.destroy()
570
- self._flash = (text, time.time() + 6, self._last_current)
571
-
572
- buttons = tk.Frame(frame, bg=col["bg"])
573
- buttons.grid(row=1 + 2 * len(user_settings.FIELDS), column=0, columnspan=3, sticky="e", pady=(pad // 2, 0))
574
- for text, command in (("恢复默认", reset), ("取消", top.destroy), ("保存", save)):
575
- tk.Button(buttons, text=text, command=command, font=self.f_small).pack(side="left", padx=(6, 0))
576
- top.bind("<Return>", lambda e: save())
577
- top.bind("<Escape>", lambda e: top.destroy())
578
- top.update_idletasks()
579
- x = self.root.winfo_rootx()
580
- y = max(0, self.root.winfo_rooty() - top.winfo_height() - 8)
581
- top.geometry(f"+{x}+{y}")
582
-
583
- def _hover_button(self, key: str, label_id: int) -> None:
584
- self._hover = key
585
- self.canvas.itemconfigure(label_id, fill=self.c["text"] if key else self.c["btn"])
586
-
587
- def _report_menu(self, event: Any, doi: str, state: dict[str, Any]) -> None:
588
- """Pick the problem seen in the browser; the running download acts on it at once."""
589
- from .issues import ISSUE_KINDS
590
-
591
- menu = tk.Menu(self.root, tearoff=0)
592
- for kind, label in ISSUE_KINDS.items():
593
- menu.add_command(label=label, command=lambda k=kind: self._report(k, doi, state))
594
- try:
595
- menu.tk_popup(event.x_root, event.y_root)
596
- finally:
597
- menu.grab_release()
598
-
599
- def _report(self, kind: str, doi: str, state: dict[str, Any]) -> None:
600
- try:
601
- from .issues import ISSUE_KINDS, report
602
-
603
- report(doi, kind, state)
604
- text = f"已收到:{ISSUE_KINDS[kind]},正在处理"
605
- except Exception as exc:
606
- text = f"记录失败:{type(exc).__name__}"
607
- self._flash = (text, time.time() + 6, doi)
608
- self._draw(state)
609
-
610
- def _underlined(self) -> tkfont.Font:
611
- if not hasattr(self, "_f_link_hover"):
612
- self._f_link_hover = self.f_small.copy()
613
- self._f_link_hover.configure(underline=True)
614
- return self._f_link_hover
615
-
616
- # --- polling ------------------------------------------------------------
617
- def _open_output_dir(self, state: dict) -> None:
618
- progress_view.open_folder(str(state.get("output_dir") or ""))
619
-
620
- def _tick(self) -> None:
621
- state = None
622
- try:
623
- state = read_state()
624
- self._draw(state)
625
- except Exception:
626
- pass
627
- try:
628
- import time as _time
629
-
630
- if self._auto_close.should_close(state, _time.monotonic(), hovering=self._pointer_in):
631
- self._close()
632
- return
633
- except Exception:
634
- pass
635
- self.root.after(500, self._tick)
636
-
637
- def _report_geom(self) -> None:
638
- try:
639
- print(
640
- f"GEOM {self.root.winfo_x()} {self.root.winfo_y()} "
641
- f"{self.root.winfo_width()} {self.root.winfo_height()}",
642
- flush=True,
643
- )
644
- except Exception:
645
- pass
646
-
647
- def _write_lock(self) -> None:
648
- progress_view.write_window_lock()
649
-
650
- def _release_lock(self) -> None:
651
- progress_view.release_window_lock()
652
-
653
- def run(self) -> None:
654
- self._write_lock()
655
- self.root.protocol("WM_DELETE_WINDOW", self._close)
656
- self.root.after(400, self._report_geom)
657
- self.root.mainloop()
658
-
659
- def _close(self) -> None:
660
- self._release_lock()
661
- self.root.destroy()
662
-
663
-
664
- def main() -> None:
665
- try:
666
- ProgressWindow().run()
667
- except Exception as exc: # headless / non-Windows fallback: console tail
668
- print(f"progress bar unavailable ({exc}); watching file…")
669
- import time as _t
670
- last = None
671
- while True:
672
- s = read_state()
673
- line = None
674
- if s:
675
- line = (f"{s.get('task')} {s.get('done')}/{s.get('total')} "
676
- f"ok={s.get('success')} fail={s.get('failed')} {s.get('current')}")
677
- if line != last:
678
- print(line or "(idle)", flush=True)
679
- last = line
680
- _t.sleep(1)
681
-
682
-
683
- if __name__ == "__main__":
684
- main()