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
@@ -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))
@@ -716,16 +716,24 @@ class CaptureMixin:
716
716
  # article page shows "Download PDF", 2026-11-02).
717
717
  before_click = self._pdf_candidates(page, doi) if bound_pdf_urls is None else []
718
718
  click_started = time.time()
719
+ fallback = getattr(self, "_fallback_pdf", None)
719
720
  if self._click_pdf_entry(page, result, doi=doi, bound=bound_pdf_urls):
720
721
  begin("click", self._clicked_pdf_control(result), click_started)
721
722
  # Until the PDF (or a block) arrives, or Firefox shows one it may
722
723
  # read in its viewer. OUP's watermarked PDF URL names no article,
723
724
  # so its response is what counts (BJS, 2026-11-01).
724
- pump_until(page, lambda: bool(captured["bytes"] or captured["block_reason"]) or (
725
+ pump_until(page, lambda: bool(captured["bytes"] or captured["block_reason"]
726
+ or getattr(self, "_fallback_pdf", None) is not fallback) or (
725
727
  not self._is_chromium(page) and self._pdf_viewer_present(page)
726
728
  and self._native_viewer_pdf_allowed(str(getattr(page, "url", "") or ""), **fallback_options)), 5_000)
727
729
  if captured["bytes"] or captured["block_reason"]:
728
730
  return captured["bytes"], str(captured["url"]), captured["block_reason"]
731
+ if getattr(self, "_fallback_pdf", None) is not fallback:
732
+ # The article's own PDF link gave a PDF naming neither DOI nor title.
733
+ # The page's other addresses give the same file (Science's reader and
734
+ # PDF addresses took the rest of the minute every time, 2026-11-09):
735
+ # it is saved now, unconfirmed, for PaperSearch to check.
736
+ return None, "", None
729
737
  self._wait_past_redirect_page(page, result) # e.g. a sign-in round trip first
730
738
  if not self._resolve_suspect_block(page, result, captured):
731
739
  return None, "", captured["block_reason"]
@@ -767,8 +775,8 @@ class CaptureMixin:
767
775
  # document; try each URL once.
768
776
  candidates = list(dict.fromkeys(str(url).split("#", 1)[0] for url in candidates if url))
769
777
  for pdf_url in candidates:
770
- if captured["bytes"] or captured["block_reason"]:
771
- break
778
+ if captured["bytes"] or captured["block_reason"] or getattr(self, "_fallback_pdf", None) is not None:
779
+ break # a PDF naming neither DOI nor title is in hand: saved unconfirmed, as after the click
772
780
  if pdf_url in rejected_pdf_urls:
773
781
  continue
774
782
  if entitlement_denied():
@@ -332,8 +332,8 @@ class LoginMixin:
332
332
  settle(page, 2_000)
333
333
  self._select_institution(page, result)
334
334
 
335
- deadline = self._user_wait_deadline(result)
336
- with self._login_wait_budget(result, "_user_wait_deadline", deadline, time.time) as wait:
335
+ deadline = self._school_login_deadline(result)
336
+ with self._login_wait_budget(result, "_school_login_deadline", deadline, time.time) as wait:
337
337
  last_state = ""
338
338
  last_auto_action = ""
339
339
  last_auto_action_at = 0.0
@@ -1408,6 +1408,7 @@ class LoginMixin:
1408
1408
  - ``school_login``: the school's own login page, the user's step;
1409
1409
  - ``school_choice``: a school chooser with no school configured, also the user's;
1410
1410
  - ``institution_chooser``: a chooser where the configured school was to be chosen;
1411
+ - ``authentication_redirect``: the school's site, its login not shown (yet);
1411
1412
  - ``publisher``: the publisher's own pages: the login was never reached;
1412
1413
  - ``other`` or ``closed``.
1413
1414
  """
@@ -78,7 +78,8 @@ class UserWaitMixin:
78
78
  request with a human-verification page. Every open tab is checked; the
79
79
  verification tab is brought to the front, the user is asked to
80
80
  complete it, and the loop waits until the PDF is captured (success),
81
- no verification/suspect page is left (the capture loop continues), or
81
+ no verification/suspect page is left (the capture loop continues), a
82
+ PDF naming neither DOI nor title came through (saved unconfirmed), or
82
83
  the bounded wait ends (only then ``ip_blocked``). Returns False when
83
84
  the route must stop.
84
85
  """
@@ -108,7 +109,8 @@ class UserWaitMixin:
108
109
  return self._wait_out_suspect_block(page, result, captured, suspect, suspect_host, started)
109
110
  finally:
110
111
  self._note_wait(result, f"the PDF step's {suspect[:120]}", started,
111
- "pdf" if captured.get("bytes") else captured.get("block_reason") or "page changed")
112
+ "pdf" if captured.get("bytes") or captured.get("unconfirmed_pdf")
113
+ else captured.get("block_reason") or "page changed")
112
114
 
113
115
  def _wait_out_suspect_block(self, page: Any, result: DownloadResult, captured: dict[str, Any], suspect: str,
114
116
  suspect_host: str, started: float) -> bool:
@@ -126,6 +128,7 @@ class UserWaitMixin:
126
128
  reporter = None
127
129
  shown = "" # "verification" | "login" | "unknown"
128
130
  verification_tab = None
131
+ fallback = getattr(self, "_fallback_pdf", None)
129
132
  try:
130
133
  while time.time() < deadline:
131
134
  self._check_user_decision(result, page)
@@ -133,6 +136,15 @@ class UserWaitMixin:
133
136
  self._event(result, "challenge_resolved", "pdf captured while waiting")
134
137
  captured["suspect_block"] = None
135
138
  return True
139
+ if getattr(self, "_fallback_pdf", None) is not fallback:
140
+ # The verification let the PDF through as a download, and the tab
141
+ # stays on "Verification successful. Waiting for ..." (Science, a
142
+ # fresh profile, 2026-11-09). It names neither DOI nor title on its
143
+ # first pages: the capture ends here and saves it unconfirmed.
144
+ self._event(result, "challenge_resolved", "pdf arrived while waiting, unconfirmed")
145
+ captured["suspect_block"] = None
146
+ captured["unconfirmed_pdf"] = True
147
+ return False
136
148
  try:
137
149
  pages = [p for p in list(page.context.pages) if not p.is_closed()]
138
150
  except Exception:
@@ -351,16 +363,25 @@ class UserWaitMixin:
351
363
  return (getattr(self, "config", None) or {}).get("user_wait") == "short"
352
364
 
353
365
  def _user_wait_deadline(self, result: DownloadResult) -> float:
354
- """One deadline for all waits on the user in this article (verification,
355
- school login, the PDF step): ``login_timeout_sec`` from the first of them."""
356
- wait = getattr(result, "_login_wait", None)
357
- if wait is not None and wait.attribute == "_user_wait_deadline":
358
- return wait.deadline
366
+ """One deadline for the verification waits in this article (at the article,
367
+ the PDF step): ``login_timeout_sec`` from the first of them. The school
368
+ login has its own (``_school_login_deadline``)."""
359
369
  deadline = getattr(result, "_user_wait_deadline", None)
360
370
  if deadline is None:
361
371
  deadline = result._user_wait_deadline = time.time() + self.login_timeout_sec
362
372
  return deadline
363
373
 
374
+ def _school_login_deadline(self, result: DownloadResult) -> float:
375
+ """The school login's own time: ``login_timeout_sec`` from when this article
376
+ first reaches it, however often it is entered. A verification and the
377
+ program's own steps before it never shorten it (Elsevier: a 22 s
378
+ verification and choosing the school left 1 s of 30 on the school's login
379
+ page, 2026-11-09; OUP's login has had its own since 2026-11-02)."""
380
+ deadline = getattr(result, "_school_login_deadline", None)
381
+ if deadline is None:
382
+ deadline = result._school_login_deadline = time.time() + self.login_timeout_sec
383
+ return deadline
384
+
364
385
  def _wait_deadline(self, result: DownloadResult, deadline: float | None = None) -> float:
365
386
  """End of a wait on the user that starts now, off the school's login page
366
387
  (verification pages): the caller's bound, the article's total, the page
@@ -13,6 +13,7 @@ from pathlib import Path
13
13
  TABLE = Path(__file__).resolve().parent / "assets" / "capsule_en.json"
14
14
  LANGUAGES = ("zh", "en")
15
15
  _HAN = re.compile(r"[\u4e00-\u9fff]")
16
+ _BRACKETS = re.compile(r"^(.+?)((.+))$")
16
17
 
17
18
 
18
19
  @lru_cache(maxsize=1)
@@ -36,6 +37,10 @@ def _one(text: str) -> str:
36
37
  if pattern.search(core):
37
38
  exact = pattern.sub(target, core)
38
39
  break
40
+ parts = _BRACKETS.match(core) if exact is None else None
41
+ if parts:
42
+ # "开放下载 18(出版社 API 3、预印本 1)": the text and what its brackets list, each on its own.
43
+ exact = f"{_one(parts[1])} ({', '.join(_one(item) for item in parts[2].split('、'))})"
39
44
  return text if exact is None else text.replace(core, exact)
40
45
 
41
46