papersearch 0.5.6 → 0.5.8

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 (90) hide show
  1. package/README.en.md +25 -23
  2. package/README.md +25 -23
  3. package/assets/ask-with-skill.png +0 -0
  4. package/carsi/paper_search_carsi/assets/api_keys.json +6 -4
  5. package/carsi/paper_search_carsi/assets/capsule.html +173 -21
  6. package/carsi/paper_search_carsi/assets/capsule_en.json +68 -5
  7. package/carsi/paper_search_carsi/browser/watchdog.py +6 -1
  8. package/carsi/paper_search_carsi/capsule_placement.py +8 -5
  9. package/carsi/paper_search_carsi/capsule_window.py +495 -0
  10. package/carsi/paper_search_carsi/cli.py +2 -2
  11. package/carsi/paper_search_carsi/engine/batch_capture.py +11 -3
  12. package/carsi/paper_search_carsi/engine/batch_login.py +3 -2
  13. package/carsi/paper_search_carsi/engine/batch_waits.py +28 -7
  14. package/carsi/paper_search_carsi/i18n.py +5 -0
  15. package/carsi/paper_search_carsi/progress_capsule.py +177 -426
  16. package/carsi/paper_search_carsi/progress_macos.py +53 -6
  17. package/carsi/paper_search_carsi/progress_reporter.py +132 -20
  18. package/carsi/paper_search_carsi/progress_view.py +95 -14
  19. package/carsi/paper_search_carsi/server.py +25 -3
  20. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js +1 -1
  21. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js.map +1 -1
  22. package/dist/capabilities/pdf-discovery/batch.d.ts +4 -3
  23. package/dist/capabilities/pdf-discovery/batch.d.ts.map +1 -1
  24. package/dist/capabilities/pdf-discovery/batch.js +217 -85
  25. package/dist/capabilities/pdf-discovery/batch.js.map +1 -1
  26. package/dist/capabilities/pdf-discovery/batchPapers.d.ts +19 -0
  27. package/dist/capabilities/pdf-discovery/batchPapers.d.ts.map +1 -0
  28. package/dist/capabilities/pdf-discovery/batchPapers.js +44 -0
  29. package/dist/capabilities/pdf-discovery/batchPapers.js.map +1 -0
  30. package/dist/capabilities/pdf-discovery/batchSummary.d.ts +6 -1
  31. package/dist/capabilities/pdf-discovery/batchSummary.d.ts.map +1 -1
  32. package/dist/capabilities/pdf-discovery/batchSummary.js +33 -8
  33. package/dist/capabilities/pdf-discovery/batchSummary.js.map +1 -1
  34. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js +1 -1
  35. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js.map +1 -1
  36. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts +13 -1
  37. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts.map +1 -1
  38. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +77 -25
  39. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js.map +1 -1
  40. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts +4 -0
  41. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts.map +1 -1
  42. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js +5 -0
  43. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js.map +1 -1
  44. package/dist/capabilities/pdf-discovery/carsi/CarsiResultNormalizer.d.ts.map +1 -1
  45. package/dist/capabilities/pdf-discovery/carsi/CarsiResultNormalizer.js +4 -3
  46. package/dist/capabilities/pdf-discovery/carsi/CarsiResultNormalizer.js.map +1 -1
  47. package/dist/capabilities/pdf-discovery/carsi/index.d.ts +1 -1
  48. package/dist/capabilities/pdf-discovery/carsi/index.d.ts.map +1 -1
  49. package/dist/capabilities/pdf-discovery/carsi/types.d.ts +51 -2
  50. package/dist/capabilities/pdf-discovery/carsi/types.d.ts.map +1 -1
  51. package/dist/capabilities/pdf-discovery/handler.d.ts.map +1 -1
  52. package/dist/capabilities/pdf-discovery/handler.js +2 -1
  53. package/dist/capabilities/pdf-discovery/handler.js.map +1 -1
  54. package/dist/capabilities/pdf-discovery/outputLayout.d.ts +27 -2
  55. package/dist/capabilities/pdf-discovery/outputLayout.d.ts.map +1 -1
  56. package/dist/capabilities/pdf-discovery/outputLayout.js +133 -29
  57. package/dist/capabilities/pdf-discovery/outputLayout.js.map +1 -1
  58. package/dist/capabilities/pdf-discovery/types.d.ts +5 -0
  59. package/dist/capabilities/pdf-discovery/types.d.ts.map +1 -1
  60. package/dist/cli.js +1 -31
  61. package/dist/cli.js.map +1 -1
  62. package/dist/infrastructure/runlog/RunLedger.d.ts +4 -0
  63. package/dist/infrastructure/runlog/RunLedger.d.ts.map +1 -1
  64. package/dist/infrastructure/runlog/RunLedger.js +11 -3
  65. package/dist/infrastructure/runlog/RunLedger.js.map +1 -1
  66. package/dist/management/carsi/autoUpdate.d.ts +2 -2
  67. package/dist/management/carsi/autoUpdate.d.ts.map +1 -1
  68. package/dist/management/carsi/autoUpdate.js +8 -2
  69. package/dist/management/carsi/autoUpdate.js.map +1 -1
  70. package/dist/management/carsi/cliProgress.d.ts +8 -0
  71. package/dist/management/carsi/cliProgress.d.ts.map +1 -0
  72. package/dist/management/carsi/cliProgress.js +38 -0
  73. package/dist/management/carsi/cliProgress.js.map +1 -0
  74. package/dist/management/carsi/installer.d.ts.map +1 -1
  75. package/dist/management/carsi/installer.js +3 -6
  76. package/dist/management/carsi/installer.js.map +1 -1
  77. package/dist/management/skills/nextSteps.js +1 -1
  78. package/dist/management/skills/nextSteps.js.map +1 -1
  79. package/dist/skills/SkillInstaller.d.ts +4 -0
  80. package/dist/skills/SkillInstaller.d.ts.map +1 -1
  81. package/dist/skills/SkillInstaller.js +20 -2
  82. package/dist/skills/SkillInstaller.js.map +1 -1
  83. package/package.json +2 -2
  84. package/skills/paper-search/SKILL.md +13 -9
  85. package/skills/paper-search/references/browser-download.md +4 -4
  86. package/skills/paper-search/references/cli-contract.md +2 -2
  87. package/skills/paper-search/references/management-layer.md +20 -10
  88. package/skills/paper-search/references/setup.md +3 -3
  89. package/skills/paper-search/references/troubleshooting.md +2 -1
  90. package/carsi/paper_search_carsi/progress_bar.py +0 -684
@@ -1,14 +1,13 @@
1
1
  """The download progress capsule: a small always-on-top floating pill.
2
2
 
3
3
  Collapsed it shows how far the task is ("12/40 正文 · Wiley"). Hovering opens
4
- a card with the paper, the counts and every action of the classic window
5
- (skip, no access, stop, problem report, settings, output folder). A step that
6
- needs the user (school login, verification) turns amber with a breathing glow
7
- and raises one system notification. Clicking the reminder activates the task's
8
- browser. The page is HTML (``assets/capsule.html``)
9
- drawn by pywebview with the system web engine: WebKit on macOS, WebView2 on
10
- Windows. Without pywebview or a usable engine the classic window
11
- (``progress_bar``) opens instead.
4
+ a card with the paper, the counts and every action (skip, no access, stop,
5
+ problem report, settings, output folder). A step that needs the user (school
6
+ login, verification) turns amber with a breathing glow and raises one system
7
+ notification. Clicking the reminder activates the task's browser. The page is
8
+ HTML (``assets/capsule.html``) drawn by pywebview with the system web engine:
9
+ WebKit on macOS, WebView2 on Windows. It is the only progress window: without
10
+ pywebview or a usable engine there is none, and the download goes on.
12
11
 
13
12
  Usage: ``paper-search-carsi progress`` (or ``python -m paper_search_carsi.progress_capsule``).
14
13
  Spawned automatically by ``progress_reporter.ensure_progress_bar`` when a download starts.
@@ -27,8 +26,12 @@ from pathlib import Path
27
26
  from typing import Any
28
27
 
29
28
  from . import api_keys, download_directory, i18n, progress_view, user_settings
30
- from .capsule_placement import Placement, Rect, ScreenArea
31
- from .progress_reporter import progress_path, read_state, take_settings_request
29
+ from .capsule_placement import Placement, Rect
30
+ from .capsule_window import (_MacDrag, _cocoa_call, _enable_inactive_hover, _mac_button_held, _mac_pointer,
31
+ _prepare_nonactivating_start, _round_windows_corners, _screen_areas, _set_window_frame,
32
+ _window_geometry, _window_scale, _windows_button_held, _windows_pointer,
33
+ _windows_taskbar_icon)
34
+ from .progress_reporter import papers_path, progress_path, read_papers, read_state, take_settings_request
32
35
 
33
36
  ASSETS = Path(__file__).with_name("assets")
34
37
  PAGE = ASSETS / "capsule.html"
@@ -37,8 +40,8 @@ PAGE = ASSETS / "capsule.html"
37
40
  def page_html() -> str:
38
41
  """The page with its English table in it (the window loads it as one string)."""
39
42
  return PAGE.read_text(encoding="utf-8").replace("/*CAPSULE_EN*/null", i18n.TABLE.read_text(encoding="utf-8"))
40
- # PaperSearch's icon (assets/icon.svg) for the Dock and the Windows taskbar.
41
- ICON, TASKBAR_ICON = ASSETS / "icon-512.png", ASSETS / "icon-64.png"
43
+ # PaperSearch's icon (assets/icon.svg) for the Dock.
44
+ ICON = ASSETS / "icon-512.png"
42
45
  # The first, collapsed frame; the page then reports the size it needs.
43
46
  START_SIZE = (260, 56)
44
47
  MIN_SIZE = (60, 30)
@@ -48,6 +51,31 @@ def _corner() -> str:
48
51
  return "top" if sys.platform == "darwin" else "bottom"
49
52
 
50
53
 
54
+ # Windows toasts go out under PowerShell's registered app id: Settings names them "Windows PowerShell".
55
+ _TOAST_MANAGER = ("[Windows.UI.Notifications.ToastNotificationManager,Windows.UI.Notifications,ContentType=WindowsRuntime]>$null;"
56
+ "$n=[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier("
57
+ "'{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe');")
58
+
59
+
60
+ def _powershell(script: str, **env: str) -> str:
61
+ done = subprocess.run(["powershell", "-NoProfile", "-NonInteractive", "-Command", script],
62
+ env={**os.environ, **env}, capture_output=True, text=True, timeout=10, check=True,
63
+ creationflags=0x08000000)
64
+ return done.stdout.strip()
65
+
66
+
67
+ def _windows_toast(title: str, body: str) -> None:
68
+ # The texts go in by environment so no quoting is needed.
69
+ _powershell(_TOAST_MANAGER
70
+ + "$x=[Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent("
71
+ "[Windows.UI.Notifications.ToastTemplateType]::ToastText02);"
72
+ "$t=$x.GetElementsByTagName('text');"
73
+ "$t.Item(0).AppendChild($x.CreateTextNode($env:PSC_TITLE))>$null;"
74
+ "$t.Item(1).AppendChild($x.CreateTextNode($env:PSC_BODY))>$null;"
75
+ "$n.Show([Windows.UI.Notifications.ToastNotification]::new($x))",
76
+ PSC_TITLE=title, PSC_BODY=body)
77
+
78
+
51
79
  def notify(title: str, body: str, state: dict[str, Any] | None = None) -> None:
52
80
  """One system notification, bound to the current task on macOS."""
53
81
  if not user_settings.notify_enabled():
@@ -58,28 +86,29 @@ def notify(title: str, body: str, state: dict[str, Any] | None = None) -> None:
58
86
 
59
87
  native_notify(title, body, state or {})
60
88
  elif os.name == "nt":
61
- # Windows toast through PowerShell's registered app id; the texts go in by
62
- # environment so no quoting is needed.
63
- script = (
64
- "[Windows.UI.Notifications.ToastNotificationManager,Windows.UI.Notifications,ContentType=WindowsRuntime]>$null;"
65
- "$x=[Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent("
66
- "[Windows.UI.Notifications.ToastTemplateType]::ToastText02);"
67
- "$t=$x.GetElementsByTagName('text');"
68
- "$t.Item(0).AppendChild($x.CreateTextNode($env:PSC_TITLE))>$null;"
69
- "$t.Item(1).AppendChild($x.CreateTextNode($env:PSC_BODY))>$null;"
70
- "[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier("
71
- "'{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe'"
72
- ").Show([Windows.UI.Notifications.ToastNotification]::new($x))"
73
- )
74
- subprocess.run(["powershell", "-NoProfile", "-NonInteractive", "-Command", script],
75
- env={**os.environ, "PSC_TITLE": title, "PSC_BODY": body},
76
- capture_output=True, timeout=10, check=True, creationflags=0x08000000)
89
+ _windows_toast(title, body)
77
90
  except Exception as exc:
78
91
  import logging
79
92
 
80
93
  logging.getLogger(__name__).warning("progress notification failed: %s", type(exc).__name__)
81
94
 
82
95
 
96
+ def notifications_allowed() -> str:
97
+ """Whether the system lets PaperSearch's notifications show: "ok", "off" or "unknown"."""
98
+ if sys.platform == "darwin":
99
+ from .progress_macos import notifications_allowed as mac_allowed
100
+
101
+ return mac_allowed()
102
+ if os.name == "nt":
103
+ # Enabled, or DisabledForUser / DisabledForApplication / DisabledByGroupPolicy / DisabledByManifest.
104
+ setting = _powershell(_TOAST_MANAGER + "$n.Setting")
105
+ return "ok" if setting == "Enabled" else "off" if setting.startswith("Disabled") else "unknown"
106
+ return "unknown"
107
+
108
+
109
+ TEST_NOTIFICATION = "测试通知:需要你登录或验证时,会这样提醒你"
110
+
111
+
83
112
  class Notifier:
84
113
  """A system notification when a step starts to need the user, once per prompt."""
85
114
 
@@ -128,6 +157,9 @@ class Api:
128
157
  self._native_geometry = False
129
158
  self._drag_origin: tuple[float, float, float, float] | None = None
130
159
  self._drag_pointer: tuple[float, float] | None = None
160
+ self._mac_drag: _MacDrag | None = None # macOS: presses tracked natively (main)
161
+ self._native_drag = False # this drag follows the mouse natively, not the page
162
+ self._papers_seen: tuple[int, str] = (0, "") # papers.json: when read, its batch
131
163
  self._hovering = False
132
164
  self._layout: tuple[int, bool, Rect, Rect] | None = None
133
165
  self._closed = False
@@ -145,7 +177,11 @@ class Api:
145
177
  """The capsule's view of the progress file; ``hovering`` keeps a finished window open."""
146
178
  self._hovering = bool(hovering) or self._dragging
147
179
  try:
148
- shown = progress_view.view(read_state(), time.time())
180
+ snapshot = read_state()
181
+ shown = progress_view.view(snapshot, time.time())
182
+ # 成功, 失败 and 剩余 open their lists once the caller has sent this batch's papers.
183
+ if snapshot and snapshot.get("batch_id") and self._papers_batch() == snapshot["batch_id"]:
184
+ shown["lists"] = True
149
185
  except Exception:
150
186
  shown = {"mode": "idle"}
151
187
  shown["lang"] = self._lang
@@ -252,6 +288,40 @@ class Api:
252
288
  def open_folder(self) -> bool:
253
289
  return progress_view.open_folder(str((read_state() or {}).get("output_dir") or ""))
254
290
 
291
+ # --- the lists behind 成功, 失败 and 剩余 ---------------------------------
292
+ def _papers_batch(self) -> str:
293
+ """The batch of the papers file, read again only when the file changed."""
294
+ try:
295
+ changed = papers_path().stat().st_mtime_ns
296
+ except OSError:
297
+ return ""
298
+ if changed != self._papers_seen[0]:
299
+ self._papers_seen = (changed, str((read_papers() or {}).get("batch_id") or ""))
300
+ return self._papers_seen[1]
301
+
302
+ def paper_lists(self) -> dict[str, Any]:
303
+ return progress_view.paper_lists(read_papers(), read_state())
304
+
305
+ def show_paper(self, index: int) -> str:
306
+ """A saved PDF of the running or finished batch, shown in its folder; only inside the batch's folder."""
307
+ listed, state = read_papers() or {}, read_state() or {}
308
+ key = str(index) if isinstance(index, int) and not isinstance(index, bool) else ""
309
+ paper = (listed.get("papers") or {}).get(key) if listed.get("batch_id") == state.get("batch_id") else None
310
+ path = str((paper or {}).get("path") or "") if (paper or {}).get("state") == "ok" else ""
311
+ folder = str(listed.get("folder") or "")
312
+ if not path or not folder:
313
+ return "打开失败:没有这篇的 PDF"
314
+ real, base = os.path.realpath(path), os.path.realpath(folder)
315
+ try:
316
+ inside = os.path.commonpath([real, base]) == base
317
+ except ValueError: # another drive (Windows)
318
+ inside = False
319
+ if not inside or not real.lower().endswith(".pdf"):
320
+ return "打开失败:PDF 不在这批的下载文件夹里"
321
+ if not progress_view.reveal_file(real):
322
+ return "打开失败:文件已被移走或删除"
323
+ return "已打开所在文件夹"
324
+
255
325
  # --- settings ---------------------------------------------------------
256
326
  def settings(self) -> dict[str, Any]:
257
327
  values = user_settings.current()
@@ -285,6 +355,51 @@ class Api:
285
355
  return {"ok": False, "error": f"保存失败:{type(exc).__name__}"}
286
356
  return {"ok": True, "notify": enabled}
287
357
 
358
+ # The settings' check of system notifications (user, 2026-11-10): a switch turned on,
359
+ # or a test notification, says when the system keeps them from showing.
360
+ def check_notifications(self) -> dict[str, str]:
361
+ """"ok", "off" (the system keeps PaperSearch's notifications from showing) or "unknown"."""
362
+ try:
363
+ return {"state": notifications_allowed()}
364
+ except Exception as exc:
365
+ import logging
366
+
367
+ logging.getLogger(__name__).warning("notification check failed: %s", type(exc).__name__)
368
+ return {"state": "unknown"}
369
+
370
+ def test_notification(self) -> dict[str, str]:
371
+ """A test notification, unless the system keeps it from showing: "sent", "off" or "failed"."""
372
+ if self.check_notifications()["state"] == "off":
373
+ return {"state": "off"}
374
+ title = "PaperSearch"
375
+ body = i18n.translate(TEST_NOTIFICATION, user_settings.language())
376
+ try:
377
+ if sys.platform == "darwin":
378
+ from .progress_macos import send_test
379
+
380
+ send_test(title, body)
381
+ elif os.name == "nt":
382
+ _windows_toast(title, body)
383
+ else:
384
+ return {"state": "failed", "message": "测试通知没有发出:这台电脑不发系统通知"}
385
+ except Exception as exc:
386
+ return {"state": "failed", "message": f"测试通知没有发出:{type(exc).__name__}"}
387
+ return {"state": "sent"}
388
+
389
+ def open_notification_settings(self) -> bool:
390
+ try:
391
+ if sys.platform == "darwin":
392
+ from .progress_macos import open_settings
393
+
394
+ open_settings()
395
+ elif os.name == "nt":
396
+ os.startfile("ms-settings:notifications") # type: ignore[attr-defined]
397
+ else:
398
+ return False
399
+ except Exception:
400
+ return False
401
+ return True
402
+
288
403
  def save_settings(self, values: dict[str, Any], download_dir: str | None = None) -> dict[str, Any]:
289
404
  """Check the fields of one settings page, then save them all; nothing is
290
405
  saved when one is wrong. The notification switch saves on its own."""
@@ -392,25 +507,44 @@ class Api:
392
507
  return _windows_pointer()
393
508
  return x, y
394
509
 
510
+ def _mac_press(self) -> tuple[float, float, float, float] | None:
511
+ """The press a macOS drag began with, followed natively from now on (_MacDrag)."""
512
+ if self._mac_drag is None or not (sys.platform == "darwin" and self._native_geometry):
513
+ return None
514
+ try:
515
+ return _cocoa_call(self._mac_drag.start)
516
+ except TimeoutError as exc:
517
+ import logging
518
+
519
+ logging.getLogger(__name__).warning("capsule drag follows the page: %s", exc)
520
+ return None
521
+
395
522
  def set_dragging(self, active: bool, screen_x: float | None = None,
396
523
  screen_y: float | None = None) -> None:
397
524
  """Freeze resizing while held, then place the window on its drop screen."""
398
525
  with self._geometry_lock:
399
526
  if active:
400
- x, y, _, _ = _window_geometry(self._window, self._native_geometry)
401
527
  scale = _window_scale(self._window)
402
- point = self._drag_point(screen_x or 0, screen_y or 0)
403
- self._drag_origin = (*point, x * scale, y * scale)
404
- self._drag_pointer = point
528
+ press = self._mac_press()
529
+ self._native_drag = press is not None
530
+ if press is None:
531
+ x, y, _, _ = _window_geometry(self._window, self._native_geometry)
532
+ point = self._drag_point(screen_x or 0, screen_y or 0)
533
+ press = (*point, x * scale, y * scale)
534
+ self._drag_origin = press
535
+ self._drag_pointer = press[:2]
405
536
  self._dragging = self._hovering = True
406
537
  self._placement.rescale(scale)
407
538
  self._layout = None
408
539
  elif self._dragging:
409
540
  try:
410
- if screen_x is not None and screen_y is not None:
541
+ if not self._native_drag and screen_x is not None and screen_y is not None:
411
542
  self.move_drag(screen_x, screen_y)
412
543
  finally:
413
544
  self._dragging = False
545
+ if self._native_drag:
546
+ self._native_drag = False
547
+ self._drag_pointer = _cocoa_call(self._mac_drag.stop) or self._drag_pointer
414
548
  origin, point = self._drag_origin, self._drag_pointer
415
549
  self._drag_origin = None
416
550
  self._drag_pointer = None
@@ -427,8 +561,8 @@ class Api:
427
561
  def move_drag(self, screen_x: float, screen_y: float) -> None:
428
562
  """Use pointer deltas, independent of the web engine's screen origin."""
429
563
  with self._geometry_lock:
430
- if not self._dragging or self._drag_origin is None:
431
- return
564
+ if not self._dragging or self._drag_origin is None or self._native_drag:
565
+ return # on macOS the window follows the mouse itself (_MacDrag)
432
566
  sx, sy, x, y = self._drag_origin
433
567
  if not self._button_held():
434
568
  # The page reports the release late, and the pointer may have
@@ -517,396 +651,11 @@ class Api:
517
651
  pass
518
652
 
519
653
 
520
- def _enable_inactive_hover(window: Any) -> None:
521
- """WKWebView's normal tracking is key-window-only; track our own window always."""
522
- if sys.platform != "darwin":
523
- return
524
- import AppKit
525
- from PyObjCTools import AppHelper
526
-
527
- class CapsuleTrackingOwner(AppKit.NSObject):
528
- def mouseEntered_(self, event):
529
- self.send_(True)
530
-
531
- def mouseExited_(self, event):
532
- self.send_(False)
533
-
534
- def send_(self, inside):
535
- # evaluate_js waits for WebKit: never block Cocoa's event thread.
536
- def send():
537
- try:
538
- window.evaluate_js("observeHover()")
539
- except Exception:
540
- pass # The window can close while a tracking event is queued.
541
- threading.Thread(target=send, daemon=True).start()
542
-
543
- def install():
544
- native = window.native
545
- native.setAcceptsMouseMovedEvents_(True)
546
- owner = CapsuleTrackingOwner.alloc().init()
547
- view = native.contentView()
548
- options = (AppKit.NSTrackingMouseEnteredAndExited | AppKit.NSTrackingActiveAlways
549
- | AppKit.NSTrackingInVisibleRect)
550
- area = AppKit.NSTrackingArea.alloc().initWithRect_options_owner_userInfo_(
551
- view.bounds(), options, owner, None)
552
- view.addTrackingArea_(area)
553
- window._capsule_tracking = (owner, area) # Retain both while the window lives.
554
- AppHelper.callAfter(install)
555
-
556
-
557
- def _cocoa_call(action):
558
- """Wait for the one native geometry operation instead of queuing frames."""
559
- from PyObjCTools import AppHelper
560
-
561
- complete, cancelled = threading.Event(), threading.Event()
562
- result, errors = [], []
563
-
564
- def apply():
565
- try:
566
- if not cancelled.is_set():
567
- result.append(action())
568
- except Exception as exc:
569
- errors.append(exc)
570
- finally:
571
- complete.set()
572
-
573
- AppHelper.callAfter(apply)
574
- if not complete.wait(2):
575
- cancelled.set()
576
- raise TimeoutError("capsule native geometry did not complete")
577
- if errors:
578
- raise errors[0]
579
- return result[0]
580
-
581
-
582
- def _window_geometry(window: Any, native: bool = False) -> tuple[float, float, float, float]:
583
- if sys.platform == "darwin" and native:
584
- import AppKit
585
-
586
- def read():
587
- frame = window.native.frame()
588
- top = AppKit.NSScreen.screens()[0].frame().size.height
589
- return frame.origin.x, top - frame.origin.y - frame.size.height, frame.size.width, frame.size.height
590
- return _cocoa_call(read)
591
- if sys.platform == "win32":
592
- n = window.native
593
- scale = _window_scale(window)
594
- return n.Location.X / scale, n.Location.Y / scale, n.Width / scale, n.Height / scale
595
- return window.x, window.y, window.width, window.height
596
-
597
-
598
- def _mac_pointer() -> tuple[float, float]:
599
- import AppKit
600
-
601
- def read():
602
- point = AppKit.NSEvent.mouseLocation()
603
- top = AppKit.NSScreen.screens()[0].frame().size.height
604
- return point.x, top - point.y
605
- return _cocoa_call(read)
606
-
607
-
608
- def _mac_button_held() -> bool:
609
- import AppKit
610
-
611
- return bool(_cocoa_call(lambda: AppKit.NSEvent.pressedMouseButtons() & 1))
612
-
613
-
614
- def _windows_button_held() -> bool:
615
- import ctypes
616
-
617
- user32 = ctypes.windll.user32
618
- # The physical button state: the primary one is the right button when the
619
- # user swapped them (SM_SWAPBUTTON).
620
- button = 0x02 if user32.GetSystemMetrics(23) else 0x01
621
- return bool(user32.GetAsyncKeyState(button) & 0x8000)
622
-
623
-
624
- def _windows_pointer() -> tuple[float, float]:
625
- import ctypes
626
- from ctypes import wintypes
627
-
628
- point = wintypes.POINT()
629
- if not ctypes.windll.user32.GetCursorPos(ctypes.byref(point)):
630
- raise OSError("Cannot read capsule pointer position")
631
- return point.x, point.y
632
-
633
-
634
- def _window_scale(window: Any = None) -> float:
635
- if sys.platform != "win32":
636
- return 1.0
637
- if window is not None:
638
- return float(window.native._scale)
639
- import ctypes
640
-
641
- return ctypes.windll.user32.GetDpiForSystem() / 96
642
-
643
-
644
- def _screen_areas(window: Any = None) -> list[ScreenArea]:
645
- """Use native work areas in the same logical coordinate space as the window."""
646
- if sys.platform == "darwin":
647
- import AppKit
648
-
649
- def read():
650
- screens = AppKit.NSScreen.screens()
651
- top = screens[0].frame().origin.y + screens[0].frame().size.height
652
-
653
- def rect(frame):
654
- return Rect(frame.origin.x, top - frame.origin.y - frame.size.height,
655
- frame.size.width, frame.size.height)
656
-
657
- return [ScreenArea(str(s.deviceDescription()["NSScreenNumber"]),
658
- rect(s.frame()), rect(s.visibleFrame())) for s in screens]
659
- return _cocoa_call(read) if window is not None else read()
660
- if sys.platform == "win32":
661
- return _windows_screen_areas(window)
662
- import webview
663
-
664
- return [ScreenArea(str(i), Rect(s.x, s.y, s.width, s.height), Rect(s.x, s.y, s.width, s.height))
665
- for i, s in enumerate(webview.screens)]
666
-
667
-
668
- def _windows_screen_areas(window: Any = None) -> list[ScreenArea]:
669
- import ctypes
670
- from ctypes import wintypes
671
-
672
- class MonitorInfo(ctypes.Structure):
673
- _fields_ = [("cbSize", wintypes.DWORD), ("rcMonitor", wintypes.RECT),
674
- ("rcWork", wintypes.RECT), ("dwFlags", wintypes.DWORD),
675
- ("szDevice", wintypes.WCHAR * 32)]
676
-
677
- user = ctypes.windll.user32
678
- user.GetMonitorInfoW.argtypes = [wintypes.HANDLE, ctypes.POINTER(MonitorInfo)]
679
- user.GetMonitorInfoW.restype = wintypes.BOOL
680
- user.MonitorFromWindow.argtypes = [wintypes.HWND, wintypes.DWORD]
681
- user.MonitorFromWindow.restype = wintypes.HANDLE
682
- scale = _window_scale(window)
683
- if scale <= 0:
684
- raise RuntimeError("Invalid capsule monitor DPI")
685
- current = user.MonitorFromWindow(window.native.Handle.ToInt64(), 2) if window is not None else None
686
- areas = []
687
- failures = []
688
-
689
- def collect(handle, _dc, _rect, _data):
690
- info = MonitorInfo()
691
- info.cbSize = ctypes.sizeof(info)
692
- if not user.GetMonitorInfoW(handle, ctypes.byref(info)):
693
- failures.append(handle)
694
- return False
695
-
696
- def rect(r):
697
- return Rect(r.left / scale, r.top / scale, (r.right - r.left) / scale,
698
- (r.bottom - r.top) / scale)
699
-
700
- areas.append((handle == current if current is not None else bool(info.dwFlags & 1),
701
- ScreenArea(info.szDevice, rect(info.rcMonitor), rect(info.rcWork))))
702
- return True
703
-
704
- callback_type = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HANDLE, wintypes.HDC,
705
- ctypes.POINTER(wintypes.RECT), wintypes.LPARAM)
706
- user.EnumDisplayMonitors.argtypes = [wintypes.HDC, ctypes.POINTER(wintypes.RECT), callback_type, wintypes.LPARAM]
707
- user.EnumDisplayMonitors.restype = wintypes.BOOL
708
- if not user.EnumDisplayMonitors(None, None, callback_type(collect), 0) or failures or not areas:
709
- raise OSError("Cannot read capsule monitor work areas")
710
- return [s for _, s in sorted(areas, key=lambda item: not item[0])]
711
-
712
-
713
- def _cocoa_rect(frame: Rect) -> Any:
714
- """``frame`` (top-left coordinates from the primary screen's top) as a Cocoa rect."""
715
- import AppKit
716
-
717
- top = AppKit.NSScreen.screens()[0].frame().size.height
718
- return AppKit.NSMakeRect(frame.x, top - frame.y - frame.height, frame.width, frame.height)
719
-
720
-
721
- def _moved_origin(ns_window: Any) -> tuple[float, float]:
722
- """pywebview's moved-event origin, also for a window not yet on any screen: it read
723
- that window's screen, found none, and the capsule remembered on a second display
724
- never opened (2026-11-07). The primary screen stands in."""
725
- import AppKit
726
-
727
- frame = ns_window.frame()
728
- screen = (ns_window.screen() or AppKit.NSScreen.screens()[0]).frame()
729
- return frame.origin.x, screen.size.height - frame.size.height - frame.origin.y
730
-
731
-
732
- def _set_window_frame(window: Any, frame: Rect) -> None:
733
- """Move and resize in one native operation, without activating the window."""
734
- if sys.platform == "darwin":
735
- _cocoa_call(lambda: window.native.setFrame_display_(_cocoa_rect(frame), True))
736
- elif sys.platform == "win32":
737
- window._capsule_set_frame(frame)
738
- else:
739
- from webview.window import FixPoint
740
-
741
- window.resize(frame.width, frame.height, fix_point=FixPoint.NORTH | FixPoint.WEST)
742
- window.move(frame.x, frame.y)
743
-
744
-
745
- def _windows_taskbar_icon(window: Any) -> None:
746
- """PaperSearch's icon on the window's taskbar button (WinForms through pythonnet)."""
747
- try:
748
- from System.Drawing import Bitmap, Icon
749
-
750
- window.native.Icon = Icon.FromHandle(Bitmap(str(TASKBAR_ICON)).GetHicon())
751
- except Exception:
752
- pass
753
-
754
-
755
- def _round_windows_corners(window: Any) -> None:
756
- """Windows 11 rounds a frameless window only when asked (DWM corner preference)."""
757
- try:
758
- import ctypes
759
-
760
- from ctypes import wintypes
761
-
762
- hwnd = int(window.native.Handle.ToInt64())
763
- set_attribute = ctypes.WinDLL("dwmapi").DwmSetWindowAttribute
764
- set_attribute.argtypes = [wintypes.HWND, wintypes.DWORD, ctypes.c_void_p, wintypes.DWORD]
765
- set_attribute.restype = ctypes.c_long
766
- value = ctypes.c_int(2) # DWMWCP_ROUND
767
- set_attribute(hwnd, 33, ctypes.byref(value), ctypes.sizeof(value))
768
- except Exception:
769
- pass
770
-
771
-
772
- def _classic(separate: bool = False) -> None:
773
- """The classic window. ``separate``: in a process of its own, where pywebview has
774
- already set up Cocoa in this one; Tk's own setup then crashed (2026-11-07)."""
775
- if separate:
776
- import subprocess
777
-
778
- subprocess.run([sys.executable, "-m", "paper_search_carsi.progress_bar"], check=False)
779
- return
780
- from .progress_bar import main as classic_window
781
-
782
- classic_window()
783
-
784
-
785
- def _prepare_nonactivating_start(window: Any) -> None:
786
- """Show the capsule without taking keyboard focus; clicks can still activate it.
787
-
788
- pywebview's focus=False also disables keyboard entry in Settings, so only
789
- suppress initial activation, not the window's ability to become active.
790
- """
791
- if sys.platform == "darwin":
792
- from webview.platforms import cocoa
793
-
794
- import objc
795
-
796
- def acceptsFirstMouse_(self, event):
797
- # Accept the first grab instead of consuming it just for activation.
798
- return self.pywebview_window is window
799
-
800
- objc.classAddMethods(cocoa.BrowserView.WebKitHost, [acceptsFirstMouse_])
801
-
802
- def windowDidMove_(self, notification):
803
- i = cocoa.BrowserView.get_instance('window', notification.object())
804
- if i:
805
- i.pywebview_window.events.moved.set(*_moved_origin(i.window))
806
-
807
- objc.classAddMethods(cocoa.BrowserView.WindowDelegate, [windowDidMove_])
808
- original = cocoa.BrowserView.first_show
809
-
810
- def first_show(view):
811
- if view.pywebview_window is not window:
812
- return original(view)
813
- home = getattr(window, "_capsule_home", None)
814
- if home is not None:
815
- # The remembered place, from the primary screen's top like every
816
- # other capsule move: pywebview's own x/y count from the screen
817
- # with the active window, another display when one is in use.
818
- view.window.setFrame_display_(_cocoa_rect(home), False)
819
- if not view.hidden:
820
- view.window.orderFrontRegardless()
821
- view.shown.set()
822
- if not cocoa.BrowserView.app.isRunning():
823
- menu = view._recreate_menus(view.menu)
824
- cocoa.BrowserView.app.setMainMenu_(menu)
825
- cocoa.AppHelper.installMachInterrupt()
826
- cocoa.BrowserView.app.run()
827
-
828
- cocoa.BrowserView.first_show = first_show
829
- elif os.name == "nt":
830
- import ctypes
831
- from ctypes import wintypes
832
-
833
- user32 = ctypes.windll.user32
834
- get_style = user32.GetWindowLongPtrW
835
- set_style = user32.SetWindowLongPtrW
836
- get_style.argtypes = [wintypes.HWND, ctypes.c_int]
837
- get_style.restype = ctypes.c_ssize_t
838
- set_style.argtypes = [wintypes.HWND, ctypes.c_int, ctypes.c_ssize_t]
839
- set_style.restype = ctypes.c_ssize_t
840
- user32.SetWindowPos.argtypes = [wintypes.HWND, wintypes.HWND, ctypes.c_int, ctypes.c_int,
841
- ctypes.c_int, ctypes.c_int, wintypes.UINT]
842
- user32.SetForegroundWindow.argtypes = [wintypes.HWND]
843
- initial = []
844
-
845
- def before_show():
846
- from webview.window import FixPoint
847
-
848
- native = window.native
849
- hwnd = native.Handle.ToInt64()
850
- initial.append((hwnd, get_style(hwnd, -20)))
851
- set_style(hwnd, -20, initial[-1][1] | 0x08000000) # WS_EX_NOACTIVATE
852
- # WinForms' geometry methods omit SWP_NOACTIVATE: even an animated
853
- # resize can steal focus after the nonactivating initial show.
854
- # Preserve their logical-pixel geometry, only for this capsule.
855
- def resize(width, height, fix_point):
856
- width, height = int(width * native._scale), int(height * native._scale)
857
- x, y = native.Location.X, native.Location.Y
858
- if fix_point & FixPoint.EAST:
859
- x += native.Width - width
860
- if fix_point & FixPoint.SOUTH:
861
- y += native.Height - height
862
- user32.SetWindowPos(hwnd, None, x, y, width, height, 0x0054)
863
-
864
- def move(x, y):
865
- user32.SetWindowPos(hwnd, None, int(x * native._scale), int(y * native._scale),
866
- 0, 0, 0x0055) # NOSIZE | NOZORDER | NOACTIVATE | SHOWWINDOW
867
-
868
- native.resize, native.move = resize, move
869
-
870
- def set_frame(frame):
871
- scale = native._scale
872
- # NOZORDER | NOACTIVATE; preserve hidden/minimized state as well.
873
- if not user32.SetWindowPos(hwnd, None, round(frame.x * scale), round(frame.y * scale),
874
- round(frame.width * scale), round(frame.height * scale), 0x0014):
875
- raise OSError("Cannot update capsule window frame")
876
-
877
- window._capsule_set_frame = set_frame
878
- # pywebview's Shown handler calls WebView2.Focus() after raising
879
- # events.shown. That explicit focus defeats the initial native
880
- # style, even if we restore the style later. Suppress just this
881
- # first Focus call; later user-initiated restores keep normal input.
882
- original = native.on_shown
883
-
884
- def first_shown(*_):
885
- native.Shown -= first_shown
886
- native.Shown += original
887
- window.events.shown.set()
888
-
889
- native.Shown -= original
890
- native.Shown += first_shown
891
-
892
- def activate_on_input():
893
- if initial:
894
- hwnd, style = initial.pop()
895
- set_style(hwnd, -20, style)
896
- user32.SetForegroundWindow(hwnd)
897
-
898
- window.events.before_show += before_show
899
- # Keep the style through the native startup sequence. Restoring it on
900
- # shown allows Application.Run/WebView2 to focus the just-shown form.
901
- window._capsule_activate_on_input = activate_on_input
902
-
903
-
904
654
  def main() -> None:
905
655
  try:
906
656
  import webview
907
- except Exception: # pywebview missing: the classic window
908
- _classic()
909
- return
657
+ except ImportError as exc:
658
+ raise SystemExit(f"进度胶囊需要 pywebview,当前环境里没有({exc});请运行 paper-search carsi update")
910
659
  try:
911
660
  page = page_html()
912
661
  screens = _screen_areas()
@@ -936,6 +685,9 @@ def main() -> None:
936
685
  logging.getLogger(__name__).warning("notification host unavailable: %s", type(exc).__name__)
937
686
  api._native_geometry = sys.platform == "darwin"
938
687
  _prepare_nonactivating_start(window)
688
+ if sys.platform == "darwin":
689
+ api._mac_drag = _MacDrag(window)
690
+ window.events.loaded += lambda: api._mac_drag.install_soon()
939
691
  # Do not persist native moved events: animated resizing emits them too.
940
692
  # Only the user's completed drag updates the collapsed home.
941
693
  window.events.loaded += lambda: _enable_inactive_hover(window)
@@ -951,14 +703,13 @@ def main() -> None:
951
703
  progress_view.write_window_lock()
952
704
  # icon: the Dock icon on macOS, instead of a blank one; watch: notifications and closing.
953
705
  webview.start(func=api.watch, icon=str(ICON) if sys.platform == "darwin" else None)
954
- except Exception: # no usable web engine (e.g. WebView2 missing): the classic window
706
+ except Exception: # no usable web engine (e.g. WebView2 missing): no window this time
955
707
  if sys.platform == "darwin":
956
708
  from .progress_macos import close
957
709
 
958
710
  close()
959
711
  progress_view.release_window_lock()
960
- _classic(separate=sys.platform == "darwin")
961
- return
712
+ raise
962
713
  progress_view.release_window_lock()
963
714
  if sys.platform == "darwin":
964
715
  from .progress_macos import close