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
@@ -187,16 +187,18 @@
187
187
  "预印本": "Preprint",
188
188
  "出版社 API": "Publisher API",
189
189
  "开放获取": "Open access",
190
+ "开放下载": "Open download",
191
+ "机构下载": "School download",
190
192
  "学校登录页最多等": "Wait for school login",
191
193
  "其他页面最多等": "Wait for other pages",
192
194
  "验证提醒前最多等": "Wait before check alert",
193
195
  "每家出版社每小时最多": "Per publisher per hour",
194
196
  "秒": "s",
195
197
  "篇": "papers",
196
- "查期刊、搜正文": "Journals & snippets",
197
- "出版社接口": "Publisher APIs",
198
- "增加检索来源": "More sources",
199
- "提高限额": "Higher limits",
198
+ "查期刊、搜正文(推荐配置)": "Journals & snippets (recommended)",
199
+ "出版社接口(非必须)": "Publisher APIs (optional)",
200
+ "增加检索来源(非必须)": "More sources (optional)",
201
+ "提高限额(非必须)": "Higher limits (optional)",
200
202
  "查影响因子和分区": "Impact factor & rank",
201
203
  "搜正文片段": "Full-text snippets",
202
204
  "下载全文,检索 ScienceDirect、Scopus": "Full text; search ScienceDirect, Scopus",
@@ -239,7 +241,36 @@
239
241
  "已中断": "Interrupted",
240
242
  "被拒绝:key 不对,或已失效": "Rejected: wrong or expired key",
241
243
  "服务器限流,稍后再试;key 本身可能没问题": "Rate-limited; try later",
242
- "没连上服务器,没法判断;检查网络或代理后再试": "Couldn't reach the server"
244
+ "没连上服务器,没法判断;检查网络或代理后再试": "Couldn't reach the server",
245
+ "正在下载": "Downloading now",
246
+ "排队等机构下载": "Queued for school",
247
+ "开放下载还没查": "Open not checked yet",
248
+ "没有论文": "No papers",
249
+ "正在读取…": "Loading…",
250
+ "打开失败:没有这篇的 PDF": "Couldn't open: no PDF saved",
251
+ "打开失败:PDF 不在这批的下载文件夹里": "Couldn't open: PDF outside the batch folder",
252
+ "打开失败:文件已被移走或删除": "Couldn't open: file moved or deleted",
253
+ "打开所在文件夹": "Show in folder",
254
+ "已打开所在文件夹": "Shown in its folder",
255
+ "没看到?": "Didn't see it?",
256
+ "看看要改哪里": "What to change",
257
+ "测试通知没有发出": "Test not sent",
258
+ "macOS 没有允许 PaperSearch 发通知": "macOS blocks PaperSearch's notifications",
259
+ "Windows 关掉了 PaperSearch 的通知": "Windows turned PaperSearch's notifications off",
260
+ "打开系统通知设置": "Notification settings",
261
+ "打开通知设置": "Notification settings",
262
+ "在“系统设置 › 通知 › PaperSearch”里打开“允许通知”,提醒样式选“横幅”或“提醒”。": "In System Settings › Notifications › PaperSearch, allow notifications, style Banners or Alerts.",
263
+ "通知以“Windows PowerShell”的名义发出:在“设置 › 系统 › 通知”里打开通知,并允许 Windows PowerShell。": "They come as \"Windows PowerShell\": in Settings › System › Notifications, turn them on and allow it.",
264
+ "没看到通知时,检查这几处": "No notification? Check these",
265
+ "系统设置 › 通知 › PaperSearch:允许通知,样式选“横幅”": "System Settings › Notifications › PaperSearch: allow, Banners",
266
+ "勿扰或专注模式开着时,通知不会弹出": "Do Not Disturb or a Focus hides them",
267
+ "设置 › 系统 › 通知:打开通知,并允许 Windows PowerShell": "Settings › System › Notifications: on, allow PowerShell",
268
+ "勿扰模式开着时,通知不会弹出": "Do Not Disturb hides them",
269
+ "测试通知:需要你登录或验证时,会这样提醒你": "Test: this is how you'll be asked to sign in",
270
+ "测试通知没有发出:这台电脑不发系统通知": "Test not sent: no system notifications here",
271
+ "✓ 已发出,右上角应弹出一条通知": "✓ Sent; see the top right",
272
+ "✓ 已发出,右下角应弹出一条通知": "✓ Sent; see the bottom right",
273
+ "改好后再点一次“测试”": "Then press Test again"
243
274
  },
244
275
  "patterns": [
245
276
  [
@@ -354,6 +385,14 @@
354
385
  "^开放获取 (\\d+)$",
355
386
  "Open access $1"
356
387
  ],
388
+ [
389
+ "^开放下载 (\\d+)(?: 篇)?$",
390
+ "Open download $1"
391
+ ],
392
+ [
393
+ "^机构下载 (\\d+)(?: 篇)?$",
394
+ "School download $1"
395
+ ],
357
396
  [
358
397
  "^附录 (\\d+) 个已保存$",
359
398
  "$1 supp. saved"
@@ -437,6 +476,30 @@
437
476
  [
438
477
  "^找不到 paper-search 命令,没法测试;也可以在终端运行 (.+)$",
439
478
  "paper-search not found; run $1 in a terminal"
479
+ ],
480
+ [
481
+ "^成功 (\\d+) 篇$",
482
+ "Saved $1"
483
+ ],
484
+ [
485
+ "^失败 (\\d+) 篇$",
486
+ "Failed $1"
487
+ ],
488
+ [
489
+ "^剩余 (\\d+) 篇$",
490
+ "Left $1"
491
+ ],
492
+ [
493
+ "^第 (\\d+) 篇$",
494
+ "Paper $1"
495
+ ],
496
+ [
497
+ "^(\\d+) 篇$",
498
+ "$1"
499
+ ],
500
+ [
501
+ "^测试通知没有发出:(.+)$",
502
+ "Test not sent: $1"
440
503
  ]
441
504
  ]
442
505
  }
@@ -32,6 +32,11 @@ log = logging.getLogger(__name__)
32
32
  # The longest legitimate call is a page load (60 s, the engine's longest
33
33
  # timeout); waits for the user are made of short calls.
34
34
  LIMIT_SEC = 90
35
+ # A call already sent when its step's budget ran out may finish within this; the
36
+ # next call then is not sent (BrowserBudgetExhausted) and the browser goes on. A
37
+ # 0 s title read or wait cut at the deadline was taken for a stalled browser and
38
+ # lost the PDF in hand (Science, 2026-11-09).
39
+ OPERATION_GRACE_SEC = 5
35
40
 
36
41
  _inflight: dict[int, tuple[float, str, list[str], Any, Any, Any]] = {}
37
42
  _call_deadlines: dict[int, tuple[float, str]] = {}
@@ -269,7 +274,7 @@ def check(limit_sec: float) -> bool:
269
274
  deadlines = dict(_call_deadlines)
270
275
  overdue = [(key, entry) for key, entry in list(_inflight.items())
271
276
  if now - entry[0] > limit_sec
272
- or (key in deadlines and now >= deadlines[key][0])]
277
+ or (key in deadlines and now >= deadlines[key][0] + OPERATION_GRACE_SEC)]
273
278
  if not overdue:
274
279
  return False
275
280
  key, entry = min(overdue, key=lambda pair: pair[1][0])
@@ -260,14 +260,17 @@ class Placement:
260
260
  self.home = after
261
261
  self.direction = self._direction(pill_anchor(after, work))
262
262
  else:
263
- # The pill goes to the card's top corner on the side nearer the
264
- # screen edge (bottom corner when docked there), so opening it
265
- # again puts the card back where it was dropped.
263
+ # The pill goes to the card's corner on the side nearer the screen
264
+ # edge, so opening it again puts the card back where it was
265
+ # dropped: the bottom corner when docked there or when the card
266
+ # sits so low that it would open up from there (it no longer jumps
267
+ # up to the card's top, 2026-11-10), otherwise the top corner.
268
+ w, h = self.home.width, self.home.height
269
+ from_bottom = direction_for(Rect(after.x, after.bottom - h, w, h), work, after.height)[0]
266
270
  self._dragged_card = after
267
- self.direction = self._direction(("down", pill_anchor(after, work)[1]))
271
+ self.direction = self._direction((from_bottom, pill_anchor(after, work)[1]))
268
272
  self._direction_fixed = True
269
273
  vertical, horizontal = self.direction
270
- w, h = self.home.width, self.home.height
271
274
  self.home = Rect(after.right - w if horizontal == "left" else after.x,
272
275
  after.bottom - h if vertical == "up" else after.y, w, h)
273
276
  self.home = self._fit(self.home)
@@ -0,0 +1,495 @@
1
+ """The capsule's native window on macOS and Windows, for ``progress_capsule``.
2
+
3
+ Where it is and on which screens (in one top-left, logical coordinate space on
4
+ both systems), moving and sizing it in one native step, the pointer and its
5
+ button while dragging (macOS follows the mouse itself, ``_MacDrag``), and the
6
+ first show that takes no focus. Cocoa calls run on the main thread
7
+ (``_cocoa_call``); nothing here knows the page or the download.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import sys
14
+ import threading
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from .capsule_placement import Rect, ScreenArea
19
+
20
+ # PaperSearch's icon for the Windows taskbar (assets/icon.svg).
21
+ TASKBAR_ICON = Path(__file__).with_name("assets") / "icon-64.png"
22
+
23
+
24
+ def _enable_inactive_hover(window: Any) -> None:
25
+ """WKWebView's normal tracking is key-window-only; track our own window always."""
26
+ if sys.platform != "darwin":
27
+ return
28
+ import AppKit
29
+ from PyObjCTools import AppHelper
30
+
31
+ class CapsuleTrackingOwner(AppKit.NSObject):
32
+ def mouseEntered_(self, event):
33
+ self.send_(True)
34
+
35
+ def mouseExited_(self, event):
36
+ self.send_(False)
37
+
38
+ def send_(self, inside):
39
+ # evaluate_js waits for WebKit: never block Cocoa's event thread.
40
+ def send():
41
+ try:
42
+ window.evaluate_js("observeHover()")
43
+ except Exception:
44
+ pass # The window can close while a tracking event is queued.
45
+ threading.Thread(target=send, daemon=True).start()
46
+
47
+ def install():
48
+ native = window.native
49
+ native.setAcceptsMouseMovedEvents_(True)
50
+ owner = CapsuleTrackingOwner.alloc().init()
51
+ view = native.contentView()
52
+ options = (AppKit.NSTrackingMouseEnteredAndExited | AppKit.NSTrackingActiveAlways
53
+ | AppKit.NSTrackingInVisibleRect)
54
+ area = AppKit.NSTrackingArea.alloc().initWithRect_options_owner_userInfo_(
55
+ view.bounds(), options, owner, None)
56
+ view.addTrackingArea_(area)
57
+ window._capsule_tracking = (owner, area) # Retain both while the window lives.
58
+ AppHelper.callAfter(install)
59
+
60
+
61
+ def _cocoa_call(action):
62
+ """Wait for the one native geometry operation instead of queuing frames."""
63
+ from PyObjCTools import AppHelper
64
+
65
+ complete, cancelled = threading.Event(), threading.Event()
66
+ result, errors = [], []
67
+
68
+ def apply():
69
+ try:
70
+ if not cancelled.is_set():
71
+ result.append(action())
72
+ except Exception as exc:
73
+ errors.append(exc)
74
+ finally:
75
+ complete.set()
76
+
77
+ AppHelper.callAfter(apply)
78
+ if not complete.wait(2):
79
+ cancelled.set()
80
+ raise TimeoutError("capsule native geometry did not complete")
81
+ if errors:
82
+ raise errors[0]
83
+ return result[0]
84
+
85
+
86
+ def _window_geometry(window: Any, native: bool = False) -> tuple[float, float, float, float]:
87
+ if sys.platform == "darwin" and native:
88
+ import AppKit
89
+
90
+ def read():
91
+ frame = window.native.frame()
92
+ top = AppKit.NSScreen.screens()[0].frame().size.height
93
+ return frame.origin.x, top - frame.origin.y - frame.size.height, frame.size.width, frame.size.height
94
+ return _cocoa_call(read)
95
+ if sys.platform == "win32":
96
+ n = window.native
97
+ scale = _window_scale(window)
98
+ return n.Location.X / scale, n.Location.Y / scale, n.Width / scale, n.Height / scale
99
+ return window.x, window.y, window.width, window.height
100
+
101
+
102
+ def _mac_pointer() -> tuple[float, float]:
103
+ import AppKit
104
+
105
+ def read():
106
+ point = AppKit.NSEvent.mouseLocation()
107
+ top = AppKit.NSScreen.screens()[0].frame().size.height
108
+ return point.x, top - point.y
109
+ return _cocoa_call(read)
110
+
111
+
112
+ class _MacDrag:
113
+ """The capsule follows the mouse by itself while it is dragged (macOS).
114
+
115
+ A local event monitor sees each press in the window from its mouse-down.
116
+ Once the page says the press is a drag, the window moves on the main
117
+ thread with each drag event, keeping the point grabbed under the mouse,
118
+ and stops where the button came up. Moved from the page over the bridge,
119
+ the window fell behind a busy Mac, and the moves still queued at the
120
+ release were dropped (they had made it jump after the release, 2026-11-08):
121
+ it stopped short of where it was let go (the user's recording, 2026-11-10).
122
+ The page's drag start comes over the same bridge, late as well, possibly
123
+ after the release: measured from the press itself, the window catches up.
124
+ """
125
+
126
+ def __init__(self, window: Any) -> None:
127
+ self._window = window
128
+ self._monitor: Any = None
129
+ self._press: tuple[float, float, float, float] | None = None # pointer x, y; window x, y (top-left, global)
130
+ self._held = self._started = self._following = False
131
+ self._ended: tuple[float, float] | None = None
132
+ self.last: tuple[float, float] | None = None
133
+
134
+ def install_soon(self) -> None:
135
+ from PyObjCTools import AppHelper
136
+
137
+ AppHelper.callAfter(self.install)
138
+
139
+ def install(self) -> None:
140
+ """Watch the window's presses (main thread); without this, drags follow the page."""
141
+ import AppKit
142
+
143
+ if self._monitor is not None:
144
+ return
145
+
146
+ def handle(event: Any) -> Any:
147
+ try:
148
+ self._event(event)
149
+ except Exception as exc:
150
+ import logging
151
+
152
+ logging.getLogger(__name__).warning("capsule drag event: %s", exc)
153
+ return event # the page still gets its pointer events
154
+
155
+ try:
156
+ self._monitor = AppKit.NSEvent.addLocalMonitorForEventsMatchingMask_handler_(
157
+ AppKit.NSEventMaskLeftMouseDown | AppKit.NSEventMaskLeftMouseDragged
158
+ | AppKit.NSEventMaskLeftMouseUp, handle)
159
+ except Exception as exc:
160
+ import logging
161
+
162
+ logging.getLogger(__name__).warning("capsule drag follows the page: %s", exc)
163
+
164
+ def _event(self, event: Any) -> None:
165
+ import AppKit
166
+ import Quartz
167
+
168
+ kind = event.type()
169
+ if kind == AppKit.NSEventTypeLeftMouseDown and event.windowNumber() != self._window.native.windowNumber():
170
+ return # a dialog's press
171
+ # Global and from the top: events queued on a busy Mac are relative to
172
+ # where the window was when they came, not where it has moved since.
173
+ location = Quartz.CGEventGetLocation(event.CGEvent())
174
+ point = (location.x, location.y)
175
+ if kind == AppKit.NSEventTypeLeftMouseDown:
176
+ if self._following: # the page has not ended the last drag yet
177
+ self._ended, self._following = self.last, False
178
+ frame = self._window.native.frame()
179
+ top = AppKit.NSScreen.screens()[0].frame().size.height
180
+ self._press = (*point, frame.origin.x, top - frame.origin.y - frame.size.height)
181
+ self.last, self._held, self._started = point, True, False
182
+ return
183
+ if not self._held:
184
+ return # the mouse moves on after the release: the window stays
185
+ self.last = point
186
+ self._held = kind != AppKit.NSEventTypeLeftMouseUp
187
+ if self._following:
188
+ self._move()
189
+
190
+ def _move(self) -> None:
191
+ import AppKit
192
+
193
+ sx, sy, x, y = self._press
194
+ top = AppKit.NSScreen.screens()[0].frame().size.height
195
+ self._window.native.setFrameTopLeftPoint_(
196
+ AppKit.NSPoint(round(x + self.last[0] - sx), top - round(y + self.last[1] - sy)))
197
+
198
+ def start(self) -> tuple[float, float, float, float] | None:
199
+ """The page's drag start (main thread): its press, the window caught up; None without one."""
200
+ if self._press is None or self._started:
201
+ return None
202
+ self._started = self._following = True
203
+ self._ended = None
204
+ if self.last != self._press[:2]:
205
+ self._move()
206
+ return self._press
207
+
208
+ def stop(self) -> tuple[float, float] | None:
209
+ """The page's drag end (main thread): where the drag ended."""
210
+ self._following = False
211
+ point, self._ended = self._ended or self.last, None
212
+ return point
213
+
214
+
215
+ def _mac_button_held() -> bool:
216
+ import AppKit
217
+
218
+ return bool(_cocoa_call(lambda: AppKit.NSEvent.pressedMouseButtons() & 1))
219
+
220
+
221
+ def _windows_button_held() -> bool:
222
+ import ctypes
223
+
224
+ user32 = ctypes.windll.user32
225
+ # The physical button state: the primary one is the right button when the
226
+ # user swapped them (SM_SWAPBUTTON).
227
+ button = 0x02 if user32.GetSystemMetrics(23) else 0x01
228
+ return bool(user32.GetAsyncKeyState(button) & 0x8000)
229
+
230
+
231
+ def _windows_pointer() -> tuple[float, float]:
232
+ import ctypes
233
+ from ctypes import wintypes
234
+
235
+ point = wintypes.POINT()
236
+ if not ctypes.windll.user32.GetCursorPos(ctypes.byref(point)):
237
+ raise OSError("Cannot read capsule pointer position")
238
+ return point.x, point.y
239
+
240
+
241
+ def _window_scale(window: Any = None) -> float:
242
+ if sys.platform != "win32":
243
+ return 1.0
244
+ if window is not None:
245
+ return float(window.native._scale)
246
+ import ctypes
247
+
248
+ return ctypes.windll.user32.GetDpiForSystem() / 96
249
+
250
+
251
+ def _screen_areas(window: Any = None) -> list[ScreenArea]:
252
+ """Use native work areas in the same logical coordinate space as the window."""
253
+ if sys.platform == "darwin":
254
+ import AppKit
255
+
256
+ def read():
257
+ screens = AppKit.NSScreen.screens()
258
+ top = screens[0].frame().origin.y + screens[0].frame().size.height
259
+
260
+ def rect(frame):
261
+ return Rect(frame.origin.x, top - frame.origin.y - frame.size.height,
262
+ frame.size.width, frame.size.height)
263
+
264
+ return [ScreenArea(str(s.deviceDescription()["NSScreenNumber"]),
265
+ rect(s.frame()), rect(s.visibleFrame())) for s in screens]
266
+ return _cocoa_call(read) if window is not None else read()
267
+ if sys.platform == "win32":
268
+ return _windows_screen_areas(window)
269
+ import webview
270
+
271
+ return [ScreenArea(str(i), Rect(s.x, s.y, s.width, s.height), Rect(s.x, s.y, s.width, s.height))
272
+ for i, s in enumerate(webview.screens)]
273
+
274
+
275
+ def _windows_screen_areas(window: Any = None) -> list[ScreenArea]:
276
+ import ctypes
277
+ from ctypes import wintypes
278
+
279
+ class MonitorInfo(ctypes.Structure):
280
+ _fields_ = [("cbSize", wintypes.DWORD), ("rcMonitor", wintypes.RECT),
281
+ ("rcWork", wintypes.RECT), ("dwFlags", wintypes.DWORD),
282
+ ("szDevice", wintypes.WCHAR * 32)]
283
+
284
+ user = ctypes.windll.user32
285
+ user.GetMonitorInfoW.argtypes = [wintypes.HANDLE, ctypes.POINTER(MonitorInfo)]
286
+ user.GetMonitorInfoW.restype = wintypes.BOOL
287
+ user.MonitorFromWindow.argtypes = [wintypes.HWND, wintypes.DWORD]
288
+ user.MonitorFromWindow.restype = wintypes.HANDLE
289
+ scale = _window_scale(window)
290
+ if scale <= 0:
291
+ raise RuntimeError("Invalid capsule monitor DPI")
292
+ current = user.MonitorFromWindow(window.native.Handle.ToInt64(), 2) if window is not None else None
293
+ areas = []
294
+ failures = []
295
+
296
+ def collect(handle, _dc, _rect, _data):
297
+ info = MonitorInfo()
298
+ info.cbSize = ctypes.sizeof(info)
299
+ if not user.GetMonitorInfoW(handle, ctypes.byref(info)):
300
+ failures.append(handle)
301
+ return False
302
+
303
+ def rect(r):
304
+ return Rect(r.left / scale, r.top / scale, (r.right - r.left) / scale,
305
+ (r.bottom - r.top) / scale)
306
+
307
+ areas.append((handle == current if current is not None else bool(info.dwFlags & 1),
308
+ ScreenArea(info.szDevice, rect(info.rcMonitor), rect(info.rcWork))))
309
+ return True
310
+
311
+ callback_type = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HANDLE, wintypes.HDC,
312
+ ctypes.POINTER(wintypes.RECT), wintypes.LPARAM)
313
+ user.EnumDisplayMonitors.argtypes = [wintypes.HDC, ctypes.POINTER(wintypes.RECT), callback_type, wintypes.LPARAM]
314
+ user.EnumDisplayMonitors.restype = wintypes.BOOL
315
+ if not user.EnumDisplayMonitors(None, None, callback_type(collect), 0) or failures or not areas:
316
+ raise OSError("Cannot read capsule monitor work areas")
317
+ return [s for _, s in sorted(areas, key=lambda item: not item[0])]
318
+
319
+
320
+ def _cocoa_rect(frame: Rect) -> Any:
321
+ """``frame`` (top-left coordinates from the primary screen's top) as a Cocoa rect."""
322
+ import AppKit
323
+
324
+ top = AppKit.NSScreen.screens()[0].frame().size.height
325
+ return AppKit.NSMakeRect(frame.x, top - frame.y - frame.height, frame.width, frame.height)
326
+
327
+
328
+ def _moved_origin(ns_window: Any) -> tuple[float, float]:
329
+ """pywebview's moved-event origin, also for a window not yet on any screen: it read
330
+ that window's screen, found none, and the capsule remembered on a second display
331
+ never opened (2026-11-07). The primary screen stands in."""
332
+ import AppKit
333
+
334
+ frame = ns_window.frame()
335
+ screen = (ns_window.screen() or AppKit.NSScreen.screens()[0]).frame()
336
+ return frame.origin.x, screen.size.height - frame.size.height - frame.origin.y
337
+
338
+
339
+ def _set_window_frame(window: Any, frame: Rect) -> None:
340
+ """Move and resize in one native operation, without activating the window."""
341
+ if sys.platform == "darwin":
342
+ _cocoa_call(lambda: window.native.setFrame_display_(_cocoa_rect(frame), True))
343
+ elif sys.platform == "win32":
344
+ window._capsule_set_frame(frame)
345
+ else:
346
+ from webview.window import FixPoint
347
+
348
+ window.resize(frame.width, frame.height, fix_point=FixPoint.NORTH | FixPoint.WEST)
349
+ window.move(frame.x, frame.y)
350
+
351
+
352
+ def _windows_taskbar_icon(window: Any) -> None:
353
+ """PaperSearch's icon on the window's taskbar button (WinForms through pythonnet)."""
354
+ try:
355
+ from System.Drawing import Bitmap, Icon
356
+
357
+ window.native.Icon = Icon.FromHandle(Bitmap(str(TASKBAR_ICON)).GetHicon())
358
+ except Exception:
359
+ pass
360
+
361
+
362
+ def _round_windows_corners(window: Any) -> None:
363
+ """Windows 11 rounds a frameless window only when asked (DWM corner preference)."""
364
+ try:
365
+ import ctypes
366
+
367
+ from ctypes import wintypes
368
+
369
+ hwnd = int(window.native.Handle.ToInt64())
370
+ set_attribute = ctypes.WinDLL("dwmapi").DwmSetWindowAttribute
371
+ set_attribute.argtypes = [wintypes.HWND, wintypes.DWORD, ctypes.c_void_p, wintypes.DWORD]
372
+ set_attribute.restype = ctypes.c_long
373
+ value = ctypes.c_int(2) # DWMWCP_ROUND
374
+ set_attribute(hwnd, 33, ctypes.byref(value), ctypes.sizeof(value))
375
+ except Exception:
376
+ pass
377
+
378
+
379
+ def _prepare_nonactivating_start(window: Any) -> None:
380
+ """Show the capsule without taking keyboard focus; clicks can still activate it.
381
+
382
+ pywebview's focus=False also disables keyboard entry in Settings, so only
383
+ suppress initial activation, not the window's ability to become active.
384
+ """
385
+ if sys.platform == "darwin":
386
+ from webview.platforms import cocoa
387
+
388
+ import objc
389
+
390
+ def acceptsFirstMouse_(self, event):
391
+ # Accept the first grab instead of consuming it just for activation.
392
+ return self.pywebview_window is window
393
+
394
+ objc.classAddMethods(cocoa.BrowserView.WebKitHost, [acceptsFirstMouse_])
395
+
396
+ def windowDidMove_(self, notification):
397
+ i = cocoa.BrowserView.get_instance('window', notification.object())
398
+ if i:
399
+ i.pywebview_window.events.moved.set(*_moved_origin(i.window))
400
+
401
+ objc.classAddMethods(cocoa.BrowserView.WindowDelegate, [windowDidMove_])
402
+ original = cocoa.BrowserView.first_show
403
+
404
+ def first_show(view):
405
+ if view.pywebview_window is not window:
406
+ return original(view)
407
+ home = getattr(window, "_capsule_home", None)
408
+ if home is not None:
409
+ # The remembered place, from the primary screen's top like every
410
+ # other capsule move: pywebview's own x/y count from the screen
411
+ # with the active window, another display when one is in use.
412
+ view.window.setFrame_display_(_cocoa_rect(home), False)
413
+ if not view.hidden:
414
+ view.window.orderFrontRegardless()
415
+ view.shown.set()
416
+ if not cocoa.BrowserView.app.isRunning():
417
+ menu = view._recreate_menus(view.menu)
418
+ cocoa.BrowserView.app.setMainMenu_(menu)
419
+ cocoa.AppHelper.installMachInterrupt()
420
+ cocoa.BrowserView.app.run()
421
+
422
+ cocoa.BrowserView.first_show = first_show
423
+ elif os.name == "nt":
424
+ import ctypes
425
+ from ctypes import wintypes
426
+
427
+ user32 = ctypes.windll.user32
428
+ get_style = user32.GetWindowLongPtrW
429
+ set_style = user32.SetWindowLongPtrW
430
+ get_style.argtypes = [wintypes.HWND, ctypes.c_int]
431
+ get_style.restype = ctypes.c_ssize_t
432
+ set_style.argtypes = [wintypes.HWND, ctypes.c_int, ctypes.c_ssize_t]
433
+ set_style.restype = ctypes.c_ssize_t
434
+ user32.SetWindowPos.argtypes = [wintypes.HWND, wintypes.HWND, ctypes.c_int, ctypes.c_int,
435
+ ctypes.c_int, ctypes.c_int, wintypes.UINT]
436
+ user32.SetForegroundWindow.argtypes = [wintypes.HWND]
437
+ initial = []
438
+
439
+ def before_show():
440
+ from webview.window import FixPoint
441
+
442
+ native = window.native
443
+ hwnd = native.Handle.ToInt64()
444
+ initial.append((hwnd, get_style(hwnd, -20)))
445
+ set_style(hwnd, -20, initial[-1][1] | 0x08000000) # WS_EX_NOACTIVATE
446
+ # WinForms' geometry methods omit SWP_NOACTIVATE: even an animated
447
+ # resize can steal focus after the nonactivating initial show.
448
+ # Preserve their logical-pixel geometry, only for this capsule.
449
+ def resize(width, height, fix_point):
450
+ width, height = int(width * native._scale), int(height * native._scale)
451
+ x, y = native.Location.X, native.Location.Y
452
+ if fix_point & FixPoint.EAST:
453
+ x += native.Width - width
454
+ if fix_point & FixPoint.SOUTH:
455
+ y += native.Height - height
456
+ user32.SetWindowPos(hwnd, None, x, y, width, height, 0x0054)
457
+
458
+ def move(x, y):
459
+ user32.SetWindowPos(hwnd, None, int(x * native._scale), int(y * native._scale),
460
+ 0, 0, 0x0055) # NOSIZE | NOZORDER | NOACTIVATE | SHOWWINDOW
461
+
462
+ native.resize, native.move = resize, move
463
+
464
+ def set_frame(frame):
465
+ scale = native._scale
466
+ # NOZORDER | NOACTIVATE; preserve hidden/minimized state as well.
467
+ if not user32.SetWindowPos(hwnd, None, round(frame.x * scale), round(frame.y * scale),
468
+ round(frame.width * scale), round(frame.height * scale), 0x0014):
469
+ raise OSError("Cannot update capsule window frame")
470
+
471
+ window._capsule_set_frame = set_frame
472
+ # pywebview's Shown handler calls WebView2.Focus() after raising
473
+ # events.shown. That explicit focus defeats the initial native
474
+ # style, even if we restore the style later. Suppress just this
475
+ # first Focus call; later user-initiated restores keep normal input.
476
+ original = native.on_shown
477
+
478
+ def first_shown(*_):
479
+ native.Shown -= first_shown
480
+ native.Shown += original
481
+ window.events.shown.set()
482
+
483
+ native.Shown -= original
484
+ native.Shown += first_shown
485
+
486
+ def activate_on_input():
487
+ if initial:
488
+ hwnd, style = initial.pop()
489
+ set_style(hwnd, -20, style)
490
+ user32.SetForegroundWindow(hwnd)
491
+
492
+ window.events.before_show += before_show
493
+ # Keep the style through the native startup sequence. Restoring it on
494
+ # shown allows Application.Run/WebView2 to focus the just-shown form.
495
+ window._capsule_activate_on_input = activate_on_input
@@ -203,7 +203,7 @@ _LOGIN_MESSAGES = {
203
203
  "institution_pdf_entitlement_missing": "已登录学校,但学校没有这篇文章的全文权限;换一篇学校订阅的文章再试",
204
204
  "login_credentials_rejected": "学校登录页没有接受账号或密码",
205
205
  "institution_not_registered": "出版社的机构列表里没有找到你的学校",
206
- "login_not_reached": "程序没能进入学校登录页(一直停在出版社页面);详情见诊断文件",
206
+ "login_not_reached": "程序没能进入学校登录页的输入步骤(停在出版社页面或跳转途中);详情见诊断文件",
207
207
  }
208
208
 
209
209
 
@@ -482,7 +482,7 @@ def _cmd_settings(args: argparse.Namespace) -> int:
482
482
  ensure_ascii=False))
483
483
  return 1
484
484
  try:
485
- import webview # noqa: F401 (the settings need the capsule's web view, not the classic window)
485
+ import webview # noqa: F401 (the settings are a page of the capsule's web view)
486
486
  except Exception:
487
487
  print(json.dumps({"ok": False, "error": f"设置窗口需要 pywebview,当前环境里没有;请运行 paper-search carsi update,或在终端运行 {terminal}"},
488
488
  ensure_ascii=False))