papersearch 0.4.8 → 0.4.10
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.
- package/README.en.md +50 -62
- package/README.md +50 -62
- package/assets/overview.en.png +0 -0
- package/assets/overview.png +0 -0
- package/assets/progress-capsule.en.png +0 -0
- package/assets/progress-capsule.png +0 -0
- package/carsi/README.md +5 -6
- package/carsi/paper_search_carsi/adapters/elsevier/__init__.py +1 -1
- package/carsi/paper_search_carsi/adapters/ieee/__init__.py +1 -1
- package/carsi/paper_search_carsi/adapters/jama/__init__.py +3 -1
- package/carsi/paper_search_carsi/adapters/karger/__init__.py +2 -1
- package/carsi/paper_search_carsi/adapters/lww/ovid.py +2 -2
- package/carsi/paper_search_carsi/adapters/oup/__init__.py +3 -4
- package/carsi/paper_search_carsi/adapters/world_scientific/__init__.py +5 -4
- package/carsi/paper_search_carsi/assets/capsule.html +199 -24
- package/carsi/paper_search_carsi/browser/backend.py +270 -227
- package/carsi/paper_search_carsi/browser/batch_session.py +42 -0
- package/carsi/paper_search_carsi/browser/challenge_interaction.py +79 -43
- package/carsi/paper_search_carsi/browser/cookies.py +8 -8
- package/carsi/paper_search_carsi/browser/driver.py +29 -0
- package/carsi/paper_search_carsi/browser/engine.py +17 -23
- package/carsi/paper_search_carsi/browser/foreground.py +21 -15
- package/carsi/paper_search_carsi/browser/login.py +12 -18
- package/carsi/paper_search_carsi/browser/preview.py +31 -12
- package/carsi/paper_search_carsi/browser/profiles.py +16 -23
- package/carsi/paper_search_carsi/browser/watchdog.py +61 -55
- package/carsi/paper_search_carsi/capsule_placement.py +266 -0
- package/carsi/paper_search_carsi/cli.py +22 -7
- package/carsi/paper_search_carsi/cold_start.py +65 -51
- package/carsi/paper_search_carsi/config.py +6 -4
- package/carsi/paper_search_carsi/engine/batch.py +9 -5
- package/carsi/paper_search_carsi/engine/batch_access.py +2 -4
- package/carsi/paper_search_carsi/engine/batch_capture.py +56 -20
- package/carsi/paper_search_carsi/engine/batch_common.py +56 -16
- package/carsi/paper_search_carsi/engine/batch_diagnostics.py +4 -2
- package/carsi/paper_search_carsi/engine/batch_institution.py +146 -17
- package/carsi/paper_search_carsi/engine/batch_login.py +79 -26
- package/carsi/paper_search_carsi/engine/batch_user.py +1 -1
- package/carsi/paper_search_carsi/engine/batch_waits.py +92 -37
- package/carsi/paper_search_carsi/engine/bridge.py +23 -13
- package/carsi/paper_search_carsi/engine/login_wait.py +1 -1
- package/carsi/paper_search_carsi/engine/page_activity.py +15 -15
- package/carsi/paper_search_carsi/mcp_progress.py +13 -5
- package/carsi/paper_search_carsi/network.py +1 -1
- package/carsi/paper_search_carsi/progress_capsule.py +233 -93
- package/carsi/paper_search_carsi/progress_reporter.py +88 -7
- package/carsi/paper_search_carsi/progress_view.py +61 -0
- package/carsi/paper_search_carsi/server.py +47 -10
- package/carsi/paper_search_carsi/session_broker.py +1 -1
- package/carsi/paper_search_carsi/user_settings.py +1 -1
- package/carsi/pyproject.toml +7 -7
- package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js +6 -0
- package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js.map +1 -1
- package/dist/capabilities/pdf-discovery/batch.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/batch.js +15 -5
- package/dist/capabilities/pdf-discovery/batch.js.map +1 -1
- package/dist/capabilities/pdf-discovery/batchSummary.d.ts +22 -0
- package/dist/capabilities/pdf-discovery/batchSummary.d.ts.map +1 -0
- package/dist/capabilities/pdf-discovery/batchSummary.js +131 -0
- package/dist/capabilities/pdf-discovery/batchSummary.js.map +1 -0
- package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts +1 -0
- package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js +52 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts +8 -4
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +89 -30
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts +4 -0
- package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js +10 -0
- package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/index.d.ts +2 -2
- package/dist/capabilities/pdf-discovery/carsi/index.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/index.js +1 -1
- package/dist/capabilities/pdf-discovery/carsi/index.js.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/types.d.ts +36 -0
- package/dist/capabilities/pdf-discovery/carsi/types.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/handler.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/handler.js +11 -6
- package/dist/capabilities/pdf-discovery/handler.js.map +1 -1
- package/dist/capabilities/pdf-discovery/types.d.ts +3 -0
- package/dist/capabilities/pdf-discovery/types.d.ts.map +1 -1
- package/dist/cli.js +13 -9
- package/dist/cli.js.map +1 -1
- package/dist/management/carsi/installer.d.ts +26 -14
- package/dist/management/carsi/installer.d.ts.map +1 -1
- package/dist/management/carsi/installer.js +113 -69
- package/dist/management/carsi/installer.js.map +1 -1
- package/dist/management/carsi/runtime.d.ts +12 -1
- package/dist/management/carsi/runtime.d.ts.map +1 -1
- package/dist/management/carsi/runtime.js +30 -1
- package/dist/management/carsi/runtime.js.map +1 -1
- package/package.json +1 -1
- package/skills/paper-search/SKILL.md +4 -4
- package/skills/paper-search/references/browser-download.md +3 -3
- package/skills/paper-search/references/carsi-setup.md +7 -6
- package/skills/paper-search/references/cli-contract.md +4 -4
- package/skills/paper-search/references/management-layer.md +2 -2
- package/carsi/paper_search_carsi/assets/quiet-browser/api.js +0 -142
- package/carsi/paper_search_carsi/assets/quiet-browser/manifest.json +0 -24
- package/carsi/paper_search_carsi/assets/quiet-browser/schema.json +0 -1
- package/carsi/paper_search_carsi/browser/background.py +0 -68
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""The download progress capsule: a small always-on-top pill
|
|
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
4
|
a card with the paper, the counts and every action of the classic window
|
|
@@ -16,7 +16,6 @@ Spawned automatically by ``progress_reporter.ensure_progress_bar`` when a downlo
|
|
|
16
16
|
|
|
17
17
|
from __future__ import annotations
|
|
18
18
|
|
|
19
|
-
import json
|
|
20
19
|
import os
|
|
21
20
|
import subprocess
|
|
22
21
|
import sys
|
|
@@ -26,6 +25,7 @@ from pathlib import Path
|
|
|
26
25
|
from typing import Any
|
|
27
26
|
|
|
28
27
|
from . import download_directory, progress_view, user_settings
|
|
28
|
+
from .capsule_placement import Placement, Rect, ScreenArea
|
|
29
29
|
from .progress_reporter import progress_path, read_state
|
|
30
30
|
|
|
31
31
|
ASSETS = Path(__file__).with_name("assets")
|
|
@@ -35,56 +35,12 @@ ICON, TASKBAR_ICON = ASSETS / "icon-512.png", ASSETS / "icon-64.png"
|
|
|
35
35
|
# The first, collapsed frame; the page then reports the size it needs.
|
|
36
36
|
START_SIZE = (260, 56)
|
|
37
37
|
MIN_SIZE = (60, 30)
|
|
38
|
-
EDGE = 20 # distance from the screen's right edge
|
|
39
|
-
# macOS: top-right under the menu bar (the Dock owns the bottom edge).
|
|
40
|
-
# Windows/Linux: bottom-right above the taskbar, clear of the browser's window buttons.
|
|
41
|
-
TOP_GAP, BOTTOM_GAP = 44, 56
|
|
42
38
|
|
|
43
39
|
|
|
44
40
|
def _corner() -> str:
|
|
45
41
|
return "top" if sys.platform == "darwin" else "bottom"
|
|
46
42
|
|
|
47
43
|
|
|
48
|
-
class Placement:
|
|
49
|
-
"""Where the capsule sits: its right edge and its top (macOS) or bottom
|
|
50
|
-
edge stay put while it grows and shrinks; dragging it moves them, and the
|
|
51
|
-
spot is remembered for the next window."""
|
|
52
|
-
|
|
53
|
-
def __init__(self, path: Path, corner: str) -> None:
|
|
54
|
-
self.path = path
|
|
55
|
-
self.corner = corner
|
|
56
|
-
self.right: float | None = None
|
|
57
|
-
self.edge: float | None = None
|
|
58
|
-
try:
|
|
59
|
-
data = json.loads(path.read_text(encoding="utf-8"))
|
|
60
|
-
if data.get("corner") == corner:
|
|
61
|
-
self.right, self.edge = float(data["right"]), float(data["edge"])
|
|
62
|
-
except Exception:
|
|
63
|
-
pass
|
|
64
|
-
|
|
65
|
-
def start(self, screen_w: float, screen_h: float, size: tuple[int, int]) -> tuple[int, int]:
|
|
66
|
-
"""Top-left corner for the first frame; the default spot when none is
|
|
67
|
-
remembered or the remembered one is off this screen."""
|
|
68
|
-
w, h = size
|
|
69
|
-
right, edge = self.right, self.edge
|
|
70
|
-
if right is None or edge is None or not (w <= right <= screen_w + 1) or not (0 <= edge <= screen_h + 1):
|
|
71
|
-
right = screen_w - EDGE
|
|
72
|
-
edge = TOP_GAP if self.corner == "top" else screen_h - BOTTOM_GAP
|
|
73
|
-
self.right, self.edge = right, edge
|
|
74
|
-
return int(right - w), int(edge if self.corner == "top" else edge - h)
|
|
75
|
-
|
|
76
|
-
def moved(self, x: float, y: float, w: float, h: float, *, persist: bool = True) -> None:
|
|
77
|
-
self.right = x + w
|
|
78
|
-
self.edge = y if self.corner == "top" else y + h
|
|
79
|
-
if not persist:
|
|
80
|
-
return
|
|
81
|
-
try:
|
|
82
|
-
self.path.write_text(json.dumps({"corner": self.corner, "right": self.right, "edge": self.edge}),
|
|
83
|
-
encoding="utf-8")
|
|
84
|
-
except Exception:
|
|
85
|
-
pass
|
|
86
|
-
|
|
87
|
-
|
|
88
44
|
def notify(title: str, body: str, state: dict[str, Any] | None = None) -> None:
|
|
89
45
|
"""One system notification, bound to the current task on macOS."""
|
|
90
46
|
if not user_settings.notify_enabled():
|
|
@@ -159,12 +115,13 @@ class Api:
|
|
|
159
115
|
self._placement = placement
|
|
160
116
|
self._notifier = notifier
|
|
161
117
|
self._auto_close = auto_close
|
|
162
|
-
self._size = START_SIZE
|
|
163
118
|
self._geometry_lock = threading.RLock()
|
|
164
119
|
self._dragging = False
|
|
165
120
|
self._native_geometry = False
|
|
166
121
|
self._drag_origin: tuple[float, float, float, float] | None = None
|
|
122
|
+
self._drag_pointer: tuple[float, float] | None = None
|
|
167
123
|
self._hovering = False
|
|
124
|
+
self._layout: tuple[int, bool, Rect, Rect] | None = None
|
|
168
125
|
self._closed = False
|
|
169
126
|
self._close_requested: float | None = None
|
|
170
127
|
|
|
@@ -316,17 +273,44 @@ class Api:
|
|
|
316
273
|
return str(selected[0]) if selected else None
|
|
317
274
|
|
|
318
275
|
# --- the window -------------------------------------------------------
|
|
319
|
-
def
|
|
320
|
-
|
|
276
|
+
def _drag_point(self, x: float, y: float) -> tuple[float, float]:
|
|
277
|
+
if sys.platform == "darwin" and self._native_geometry:
|
|
278
|
+
return _mac_pointer()
|
|
279
|
+
if sys.platform == "win32":
|
|
280
|
+
return _windows_pointer()
|
|
281
|
+
return x, y
|
|
282
|
+
|
|
283
|
+
def set_dragging(self, active: bool, screen_x: float | None = None,
|
|
284
|
+
screen_y: float | None = None) -> None:
|
|
285
|
+
"""Freeze resizing while held, then place the window on its drop screen."""
|
|
321
286
|
with self._geometry_lock:
|
|
322
|
-
|
|
323
|
-
if self._dragging:
|
|
324
|
-
self._hovering = True
|
|
287
|
+
if active:
|
|
325
288
|
x, y, _, _ = _window_geometry(self._window, self._native_geometry)
|
|
326
|
-
|
|
327
|
-
|
|
289
|
+
scale = _window_scale(self._window)
|
|
290
|
+
point = self._drag_point(screen_x or 0, screen_y or 0)
|
|
291
|
+
self._drag_origin = (*point, x * scale, y * scale)
|
|
292
|
+
self._drag_pointer = point
|
|
293
|
+
self._dragging = self._hovering = True
|
|
294
|
+
self._placement.rescale(scale)
|
|
295
|
+
self._layout = None
|
|
296
|
+
elif self._dragging:
|
|
297
|
+
try:
|
|
298
|
+
if screen_x is not None and screen_y is not None:
|
|
299
|
+
self.move_drag(screen_x, screen_y)
|
|
300
|
+
finally:
|
|
301
|
+
self._dragging = False
|
|
302
|
+
origin, point = self._drag_origin, self._drag_pointer
|
|
328
303
|
self._drag_origin = None
|
|
329
|
-
self.
|
|
304
|
+
self._drag_pointer = None
|
|
305
|
+
if self._window is None or origin is None or point is None or point == origin[:2]:
|
|
306
|
+
return
|
|
307
|
+
actual = Rect(*_window_geometry(self._window, self._native_geometry))
|
|
308
|
+
scale = _window_scale(self._window)
|
|
309
|
+
self._placement.rescale(scale)
|
|
310
|
+
target = self._placement.dragged(actual, _screen_areas(self._window),
|
|
311
|
+
(point[0] / scale, point[1] / scale))
|
|
312
|
+
if target != actual:
|
|
313
|
+
_set_window_frame(self._window, target)
|
|
330
314
|
|
|
331
315
|
def move_drag(self, screen_x: float, screen_y: float) -> None:
|
|
332
316
|
"""Use pointer deltas, independent of the web engine's screen origin."""
|
|
@@ -334,6 +318,12 @@ class Api:
|
|
|
334
318
|
if not self._dragging or self._drag_origin is None:
|
|
335
319
|
return
|
|
336
320
|
sx, sy, x, y = self._drag_origin
|
|
321
|
+
# WebView coordinates can rebase across monitors. Native pointer
|
|
322
|
+
# deltas stay global; on Windows they are physical until the move.
|
|
323
|
+
screen_x, screen_y = self._drag_point(screen_x, screen_y)
|
|
324
|
+
if self._drag_pointer == (screen_x, screen_y):
|
|
325
|
+
return
|
|
326
|
+
self._drag_pointer = (screen_x, screen_y)
|
|
337
327
|
x, y = round(x + screen_x - sx), round(y + screen_y - sy)
|
|
338
328
|
if sys.platform == "darwin" and self._native_geometry:
|
|
339
329
|
import AppKit
|
|
@@ -343,27 +333,58 @@ class Api:
|
|
|
343
333
|
self._window.native.setFrameTopLeftPoint_(AppKit.NSPoint(x, top - y))
|
|
344
334
|
_cocoa_call(move)
|
|
345
335
|
else:
|
|
346
|
-
self._window
|
|
336
|
+
scale = _window_scale(self._window)
|
|
337
|
+
self._window.move(round(x / scale), round(y / scale))
|
|
347
338
|
|
|
348
|
-
def
|
|
349
|
-
"""
|
|
350
|
-
|
|
351
|
-
with self._geometry_lock:
|
|
352
|
-
if self._dragging or size == self._size or self._window is None:
|
|
353
|
-
return
|
|
354
|
-
try:
|
|
355
|
-
from webview.window import FixPoint
|
|
339
|
+
def hover_state(self) -> dict[str, Any]:
|
|
340
|
+
"""Read the real pointer/frame together; native enter/exit events may be stale."""
|
|
341
|
+
import AppKit
|
|
356
342
|
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
343
|
+
def read():
|
|
344
|
+
point = AppKit.NSEvent.mouseLocation()
|
|
345
|
+
frame = self._window.native.frame()
|
|
346
|
+
return {"x": point.x, "y": point.y,
|
|
347
|
+
"inside": frame.origin.x + 10 <= point.x < frame.origin.x + frame.size.width - 10
|
|
348
|
+
and frame.origin.y + 10 <= point.y < frame.origin.y + frame.size.height - 10}
|
|
349
|
+
return _cocoa_call(read)
|
|
362
350
|
|
|
363
|
-
def
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
351
|
+
def begin_layout(self, expanded: bool, width: float, height: float, generation: int) -> dict[str, Any]:
|
|
352
|
+
"""Choose a corner once per expansion and plan one atomic frame animation."""
|
|
353
|
+
with self._geometry_lock:
|
|
354
|
+
if self._dragging or self._window is None:
|
|
355
|
+
return {}
|
|
356
|
+
actual = Rect(*_window_geometry(self._window, self._native_geometry))
|
|
357
|
+
self._placement.rescale(_window_scale(self._window))
|
|
358
|
+
self._placement.begin(expanded, actual, _screen_areas(self._window))
|
|
359
|
+
target = self._placement.target(max(MIN_SIZE[0], int(width)), max(MIN_SIZE[1], int(height)), expanded)
|
|
360
|
+
self._layout = (generation, expanded, actual, target)
|
|
361
|
+
vertical, horizontal = self._placement.direction
|
|
362
|
+
return {"vertical": vertical, "horizontal": horizontal,
|
|
363
|
+
"width": target.width, "height": target.height,
|
|
364
|
+
"from_width": actual.width, "from_height": actual.height}
|
|
365
|
+
|
|
366
|
+
def resize(self, width: float, height: float, fraction: float = 1, generation: int = 0) -> None:
|
|
367
|
+
"""Position and size change together; obsolete animation frames are ignored."""
|
|
368
|
+
with self._geometry_lock:
|
|
369
|
+
if self._dragging or self._window is None or self._layout is None:
|
|
370
|
+
return
|
|
371
|
+
current, _, start, target = self._layout
|
|
372
|
+
if generation != current:
|
|
373
|
+
return
|
|
374
|
+
t = max(0, min(1, fraction))
|
|
375
|
+
frame = Rect(round(start.x + (target.x - start.x) * t),
|
|
376
|
+
round(start.y + (target.y - start.y) * t),
|
|
377
|
+
round(start.width + (target.width - start.width) * t),
|
|
378
|
+
round(start.height + (target.height - start.height) * t))
|
|
379
|
+
_set_window_frame(self._window, frame)
|
|
380
|
+
|
|
381
|
+
def finish_layout(self, generation: int) -> None:
|
|
382
|
+
with self._geometry_lock:
|
|
383
|
+
if self._layout is None or self._layout[0] != generation or self._dragging:
|
|
384
|
+
return
|
|
385
|
+
_, expanded, _, target = self._layout
|
|
386
|
+
self._placement.finish(expanded, target)
|
|
387
|
+
self._layout = None
|
|
367
388
|
|
|
368
389
|
def request_close(self) -> None:
|
|
369
390
|
# Let the JS bridge deliver this call's reply before disposing WebView2.
|
|
@@ -398,7 +419,7 @@ def _enable_inactive_hover(window: Any) -> None:
|
|
|
398
419
|
# evaluate_js waits for WebKit: never block Cocoa's event thread.
|
|
399
420
|
def send():
|
|
400
421
|
try:
|
|
401
|
-
window.evaluate_js("
|
|
422
|
+
window.evaluate_js("observeHover()")
|
|
402
423
|
except Exception:
|
|
403
424
|
pass # The window can close while a tracking event is queued.
|
|
404
425
|
threading.Thread(target=send, daemon=True).start()
|
|
@@ -451,27 +472,129 @@ def _window_geometry(window: Any, native: bool = False) -> tuple[float, float, f
|
|
|
451
472
|
top = AppKit.NSScreen.screens()[0].frame().size.height
|
|
452
473
|
return frame.origin.x, top - frame.origin.y - frame.size.height, frame.size.width, frame.size.height
|
|
453
474
|
return _cocoa_call(read)
|
|
475
|
+
if sys.platform == "win32":
|
|
476
|
+
n = window.native
|
|
477
|
+
scale = _window_scale(window)
|
|
478
|
+
return n.Location.X / scale, n.Location.Y / scale, n.Width / scale, n.Height / scale
|
|
454
479
|
return window.x, window.y, window.width, window.height
|
|
455
480
|
|
|
456
481
|
|
|
457
|
-
def
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
482
|
+
def _mac_pointer() -> tuple[float, float]:
|
|
483
|
+
import AppKit
|
|
484
|
+
|
|
485
|
+
def read():
|
|
486
|
+
point = AppKit.NSEvent.mouseLocation()
|
|
487
|
+
top = AppKit.NSScreen.screens()[0].frame().size.height
|
|
488
|
+
return point.x, top - point.y
|
|
489
|
+
return _cocoa_call(read)
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def _windows_pointer() -> tuple[float, float]:
|
|
493
|
+
import ctypes
|
|
494
|
+
from ctypes import wintypes
|
|
495
|
+
|
|
496
|
+
point = wintypes.POINT()
|
|
497
|
+
if not ctypes.windll.user32.GetCursorPos(ctypes.byref(point)):
|
|
498
|
+
raise OSError("Cannot read capsule pointer position")
|
|
499
|
+
return point.x, point.y
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def _window_scale(window: Any = None) -> float:
|
|
503
|
+
if sys.platform != "win32":
|
|
504
|
+
return 1.0
|
|
505
|
+
if window is not None:
|
|
506
|
+
return float(window.native._scale)
|
|
507
|
+
import ctypes
|
|
508
|
+
|
|
509
|
+
return ctypes.windll.user32.GetDpiForSystem() / 96
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def _screen_areas(window: Any = None) -> list[ScreenArea]:
|
|
513
|
+
"""Use native work areas in the same logical coordinate space as the window."""
|
|
514
|
+
if sys.platform == "darwin":
|
|
515
|
+
import AppKit
|
|
516
|
+
|
|
517
|
+
def read():
|
|
518
|
+
screens = AppKit.NSScreen.screens()
|
|
519
|
+
top = screens[0].frame().origin.y + screens[0].frame().size.height
|
|
520
|
+
|
|
521
|
+
def rect(frame):
|
|
522
|
+
return Rect(frame.origin.x, top - frame.origin.y - frame.size.height,
|
|
523
|
+
frame.size.width, frame.size.height)
|
|
524
|
+
|
|
525
|
+
return [ScreenArea(str(s.deviceDescription()["NSScreenNumber"]),
|
|
526
|
+
rect(s.frame()), rect(s.visibleFrame())) for s in screens]
|
|
527
|
+
return _cocoa_call(read) if window is not None else read()
|
|
528
|
+
if sys.platform == "win32":
|
|
529
|
+
return _windows_screen_areas(window)
|
|
530
|
+
import webview
|
|
531
|
+
|
|
532
|
+
return [ScreenArea(str(i), Rect(s.x, s.y, s.width, s.height), Rect(s.x, s.y, s.width, s.height))
|
|
533
|
+
for i, s in enumerate(webview.screens)]
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
def _windows_screen_areas(window: Any = None) -> list[ScreenArea]:
|
|
537
|
+
import ctypes
|
|
538
|
+
from ctypes import wintypes
|
|
539
|
+
|
|
540
|
+
class MonitorInfo(ctypes.Structure):
|
|
541
|
+
_fields_ = [("cbSize", wintypes.DWORD), ("rcMonitor", wintypes.RECT),
|
|
542
|
+
("rcWork", wintypes.RECT), ("dwFlags", wintypes.DWORD),
|
|
543
|
+
("szDevice", wintypes.WCHAR * 32)]
|
|
544
|
+
|
|
545
|
+
user = ctypes.windll.user32
|
|
546
|
+
user.GetMonitorInfoW.argtypes = [wintypes.HANDLE, ctypes.POINTER(MonitorInfo)]
|
|
547
|
+
user.GetMonitorInfoW.restype = wintypes.BOOL
|
|
548
|
+
user.MonitorFromWindow.argtypes = [wintypes.HWND, wintypes.DWORD]
|
|
549
|
+
user.MonitorFromWindow.restype = wintypes.HANDLE
|
|
550
|
+
scale = _window_scale(window)
|
|
551
|
+
if scale <= 0:
|
|
552
|
+
raise RuntimeError("Invalid capsule monitor DPI")
|
|
553
|
+
current = user.MonitorFromWindow(window.native.Handle.ToInt64(), 2) if window is not None else None
|
|
554
|
+
areas = []
|
|
555
|
+
failures = []
|
|
556
|
+
|
|
557
|
+
def collect(handle, _dc, _rect, _data):
|
|
558
|
+
info = MonitorInfo()
|
|
559
|
+
info.cbSize = ctypes.sizeof(info)
|
|
560
|
+
if not user.GetMonitorInfoW(handle, ctypes.byref(info)):
|
|
561
|
+
failures.append(handle)
|
|
562
|
+
return False
|
|
563
|
+
|
|
564
|
+
def rect(r):
|
|
565
|
+
return Rect(r.left / scale, r.top / scale, (r.right - r.left) / scale,
|
|
566
|
+
(r.bottom - r.top) / scale)
|
|
567
|
+
|
|
568
|
+
areas.append((handle == current if current is not None else bool(info.dwFlags & 1),
|
|
569
|
+
ScreenArea(info.szDevice, rect(info.rcMonitor), rect(info.rcWork))))
|
|
570
|
+
return True
|
|
571
|
+
|
|
572
|
+
callback_type = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HANDLE, wintypes.HDC,
|
|
573
|
+
ctypes.POINTER(wintypes.RECT), wintypes.LPARAM)
|
|
574
|
+
user.EnumDisplayMonitors.argtypes = [wintypes.HDC, ctypes.POINTER(wintypes.RECT), callback_type, wintypes.LPARAM]
|
|
575
|
+
user.EnumDisplayMonitors.restype = wintypes.BOOL
|
|
576
|
+
if not user.EnumDisplayMonitors(None, None, callback_type(collect), 0) or failures or not areas:
|
|
577
|
+
raise OSError("Cannot read capsule monitor work areas")
|
|
578
|
+
return [s for _, s in sorted(areas, key=lambda item: not item[0])]
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def _set_window_frame(window: Any, frame: Rect) -> None:
|
|
582
|
+
"""Move and resize in one native operation, without activating the window."""
|
|
583
|
+
if sys.platform == "darwin":
|
|
584
|
+
import AppKit
|
|
462
585
|
|
|
463
|
-
def resize(width, height, fix_point=None):
|
|
464
586
|
def apply():
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
frame.
|
|
468
|
-
if fix_point and fix_point & FixPoint.NORTH:
|
|
469
|
-
frame.origin.y += frame.size.height - height
|
|
470
|
-
frame.size.width, frame.size.height = width, height
|
|
471
|
-
window.native.setFrame_display_(frame, True)
|
|
587
|
+
top = AppKit.NSScreen.screens()[0].frame().size.height
|
|
588
|
+
window.native.setFrame_display_(AppKit.NSMakeRect(
|
|
589
|
+
frame.x, top - frame.y - frame.height, frame.width, frame.height), True)
|
|
472
590
|
_cocoa_call(apply)
|
|
591
|
+
elif sys.platform == "win32":
|
|
592
|
+
window._capsule_set_frame(frame)
|
|
593
|
+
else:
|
|
594
|
+
from webview.window import FixPoint
|
|
473
595
|
|
|
474
|
-
|
|
596
|
+
window.resize(frame.width, frame.height, fix_point=FixPoint.NORTH | FixPoint.WEST)
|
|
597
|
+
window.move(frame.x, frame.y)
|
|
475
598
|
|
|
476
599
|
|
|
477
600
|
def _windows_taskbar_icon(window: Any) -> None:
|
|
@@ -578,6 +701,15 @@ def _prepare_nonactivating_start(window: Any) -> None:
|
|
|
578
701
|
0, 0, 0x0055) # NOSIZE | NOZORDER | NOACTIVATE | SHOWWINDOW
|
|
579
702
|
|
|
580
703
|
native.resize, native.move = resize, move
|
|
704
|
+
|
|
705
|
+
def set_frame(frame):
|
|
706
|
+
scale = native._scale
|
|
707
|
+
# NOZORDER | NOACTIVATE; preserve hidden/minimized state as well.
|
|
708
|
+
if not user32.SetWindowPos(hwnd, None, round(frame.x * scale), round(frame.y * scale),
|
|
709
|
+
round(frame.width * scale), round(frame.height * scale), 0x0014):
|
|
710
|
+
raise OSError("Cannot update capsule window frame")
|
|
711
|
+
|
|
712
|
+
window._capsule_set_frame = set_frame
|
|
581
713
|
# pywebview's Shown handler calls WebView2.Focus() after raising
|
|
582
714
|
# events.shown. That explicit focus defeats the initial native
|
|
583
715
|
# style, even if we restore the style later. Suppress just this
|
|
@@ -612,13 +744,14 @@ def main() -> None:
|
|
|
612
744
|
return
|
|
613
745
|
try:
|
|
614
746
|
page = PAGE.read_text(encoding="utf-8")
|
|
615
|
-
|
|
747
|
+
screens = _screen_areas()
|
|
616
748
|
placement = Placement(progress_path().parent / "capsule.json", _corner())
|
|
617
|
-
x, y = placement.start(
|
|
749
|
+
x, y = placement.start(screens, START_SIZE, _window_scale())
|
|
750
|
+
size = (round(placement.home.width), round(placement.home.height))
|
|
618
751
|
api = Api(placement, Notifier(), progress_view.AutoClose.from_env())
|
|
619
752
|
dark = progress_view.dark_mode()
|
|
620
753
|
window = webview.create_window(
|
|
621
|
-
"PaperSearch", html=page, js_api=api, width=
|
|
754
|
+
"PaperSearch", html=page, js_api=api, width=size[0], height=size[1], x=x, y=y,
|
|
622
755
|
min_size=MIN_SIZE, resizable=False, frameless=True, easy_drag=False, on_top=True, focus=True,
|
|
623
756
|
transparent=sys.platform == "darwin", shadow=True,
|
|
624
757
|
background_color="#202124" if dark else "#FFFFFF",
|
|
@@ -634,11 +767,18 @@ def main() -> None:
|
|
|
634
767
|
|
|
635
768
|
logging.getLogger(__name__).warning("notification host unavailable: %s", type(exc).__name__)
|
|
636
769
|
api._native_geometry = sys.platform == "darwin"
|
|
637
|
-
_serialize_native_resize(window)
|
|
638
770
|
_prepare_nonactivating_start(window)
|
|
639
|
-
|
|
771
|
+
# Do not persist native moved events: animated resizing emits them too.
|
|
772
|
+
# Only the user's completed drag updates the collapsed home.
|
|
640
773
|
window.events.loaded += lambda: _enable_inactive_hover(window)
|
|
641
774
|
if os.name == "nt":
|
|
775
|
+
def restore_after_dpi_setup():
|
|
776
|
+
# pywebview enables DPI awareness while creating the native form.
|
|
777
|
+
# Re-read work areas before showing it, in that form's actual scale.
|
|
778
|
+
placement.start(_screen_areas(window), START_SIZE, _window_scale(window))
|
|
779
|
+
_set_window_frame(window, placement.home)
|
|
780
|
+
|
|
781
|
+
window.events.before_show += restore_after_dpi_setup
|
|
642
782
|
window.events.shown += lambda: (_round_windows_corners(window), _windows_taskbar_icon(window))
|
|
643
783
|
progress_view.write_window_lock()
|
|
644
784
|
# icon: the Dock icon on macOS, instead of a blank one; watch: notifications and closing.
|
|
@@ -11,8 +11,10 @@ on every update, so readers never see a torn write.
|
|
|
11
11
|
|
|
12
12
|
from __future__ import annotations
|
|
13
13
|
|
|
14
|
+
import html
|
|
14
15
|
import json
|
|
15
16
|
import os
|
|
17
|
+
import re
|
|
16
18
|
import tempfile
|
|
17
19
|
import threading
|
|
18
20
|
import time
|
|
@@ -188,12 +190,16 @@ class BatchContext:
|
|
|
188
190
|
|
|
189
191
|
|
|
190
192
|
def _batch_state(batch_id: str) -> dict[str, Any] | None:
|
|
191
|
-
"""
|
|
193
|
+
"""This batch's report, if an earlier item or stretch left one.
|
|
194
|
+
|
|
195
|
+
A finished stretch counts too: the institutional stretch of a batch ends
|
|
196
|
+
before its supplementary files and the caller's final summary, and the
|
|
197
|
+
batch keeps its start time (and run) across them."""
|
|
192
198
|
try:
|
|
193
199
|
state = json.loads(progress_path().read_text(encoding="utf-8"))
|
|
194
200
|
except Exception:
|
|
195
201
|
return None
|
|
196
|
-
if isinstance(state, dict) and state.get("batch_id") == batch_id and state.get("status")
|
|
202
|
+
if isinstance(state, dict) and state.get("batch_id") == batch_id and state.get("status") in ("running", "done"):
|
|
197
203
|
return state
|
|
198
204
|
return None
|
|
199
205
|
|
|
@@ -216,7 +222,8 @@ def _adopt_batch(batch_id: str, total: int, counts: tuple[int | None, int | None
|
|
|
216
222
|
_STARTED_MONO = time.monotonic()
|
|
217
223
|
if previous is None:
|
|
218
224
|
previous = {
|
|
219
|
-
|
|
225
|
+
# A lone download comes as a batch of one (its finished card gets the reason).
|
|
226
|
+
"task": "机构 PDF 批量下载" if total > 1 else "机构 PDF 下载",
|
|
220
227
|
"done": 0, "success": 0, "failed": 0,
|
|
221
228
|
"started_at": datetime.now().isoformat(timespec="seconds"),
|
|
222
229
|
"schema_version": 1,
|
|
@@ -238,17 +245,23 @@ def _adopt_batch(batch_id: str, total: int, counts: tuple[int | None, int | None
|
|
|
238
245
|
**fields,
|
|
239
246
|
}
|
|
240
247
|
_STATE.pop("finished_at", None)
|
|
248
|
+
_STATE.pop("results", None)
|
|
241
249
|
_write_state()
|
|
242
250
|
|
|
243
251
|
|
|
244
252
|
def sync_batch(batch_id: str, total: int, done: int, succeeded: int, failed: int, *,
|
|
245
|
-
current: str = "", finished: bool = False) -> bool:
|
|
246
|
-
"""Record batch totals for items finished without the backend, or the batch end.
|
|
253
|
+
current: str = "", finished: bool = False, results: Any = None) -> bool:
|
|
254
|
+
"""Record batch totals for items finished without the backend, or the batch end.
|
|
255
|
+
|
|
256
|
+
``results`` (the batch end only) is the caller's summary of every item,
|
|
257
|
+
for the finished window: see ``_batch_results``. It updates an existing
|
|
258
|
+
report and never opens a window for a batch the backend did not show."""
|
|
247
259
|
ctx = BatchContext.from_args(batch_id, max(1, min(done, total)), total, done, succeeded, failed)
|
|
248
260
|
if ctx is None or done > total:
|
|
249
261
|
return False
|
|
262
|
+
summary = _batch_results(results) if finished and results is not None else None
|
|
250
263
|
previous = _batch_state(ctx.batch_id)
|
|
251
|
-
if finished and previous is None and done == 0:
|
|
264
|
+
if finished and previous is None and (done == 0 or summary is not None):
|
|
252
265
|
return False
|
|
253
266
|
_adopt_batch(ctx.batch_id, total, (done, succeeded, failed),
|
|
254
267
|
**({"current": current} if current else {}),
|
|
@@ -259,12 +272,80 @@ def sync_batch(batch_id: str, total: int, done: int, succeeded: int, failed: int
|
|
|
259
272
|
if finished:
|
|
260
273
|
_STATE.update(status="done", awaiting_next=False,
|
|
261
274
|
finished_at=datetime.now().isoformat(timespec="seconds"))
|
|
275
|
+
if summary is not None:
|
|
276
|
+
started = summary.pop("started", None)
|
|
277
|
+
if started is not None and started < str(_STATE.get("started_at") or "~"):
|
|
278
|
+
_STATE["started_at"] = started # the caller's open stages ran before the window
|
|
279
|
+
if summary.pop("stopped", False):
|
|
280
|
+
_STATE["status"] = "cancelled"
|
|
281
|
+
folder = summary.pop("folder", None)
|
|
282
|
+
if folder:
|
|
283
|
+
_STATE["output_dir"] = folder # the whole batch, not the last paper's folder
|
|
284
|
+
_STATE["results"] = summary
|
|
262
285
|
else:
|
|
263
286
|
_STATE.update(awaiting_next=True)
|
|
264
287
|
_write_state()
|
|
265
288
|
return True
|
|
266
289
|
|
|
267
290
|
|
|
291
|
+
FAILURE_CLASSES = ("no_access", "user_or_external", "unsupported", "unexplained")
|
|
292
|
+
_RESULT_CONTENTS = ("main", "supplements", "both")
|
|
293
|
+
_MAX_RESULT_FAILURES = 1000 # the caller's batch limit
|
|
294
|
+
_MAX_RESULT_TEXT = 300
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _batch_results(raw: Any) -> dict[str, Any] | None:
|
|
298
|
+
"""The caller's end-of-batch summary, checked and bounded for the window.
|
|
299
|
+
|
|
300
|
+
Wire shape (PaperSearch writes it, the window only lays it out):
|
|
301
|
+
``content``; ``folder`` (the batch's download folder, absolute);
|
|
302
|
+
``started`` (epoch seconds the batch began); ``stopped``;
|
|
303
|
+
``main`` (main texts saved), ``supplements`` (attachment files saved),
|
|
304
|
+
``no_supplements`` (pages that listed none); ``sources`` ([label, count]);
|
|
305
|
+
``failures`` ([{cls, reason, title, journal, doi, note}]) with ``cls`` one
|
|
306
|
+
of FAILURE_CLASSES and a short ``reason`` text. Anything else is dropped.
|
|
307
|
+
"""
|
|
308
|
+
if not isinstance(raw, dict):
|
|
309
|
+
return None
|
|
310
|
+
|
|
311
|
+
def count(value: Any) -> int:
|
|
312
|
+
return value if isinstance(value, int) and not isinstance(value, bool) and 0 <= value <= 1_000_000 else 0
|
|
313
|
+
|
|
314
|
+
def text(value: Any) -> str:
|
|
315
|
+
# Crossref's titles and journals can keep HTML entities ("Arthritis & Rheumatology")
|
|
316
|
+
# and markup ("<i>Glossostemon bruguieri</i>"); the card shows plain text.
|
|
317
|
+
if not isinstance(value, str):
|
|
318
|
+
return ""
|
|
319
|
+
return " ".join(re.sub(r"<[^<>]{1,40}>", "", html.unescape(value)).split())[:_MAX_RESULT_TEXT]
|
|
320
|
+
|
|
321
|
+
summary: dict[str, Any] = {
|
|
322
|
+
"content": raw.get("content") if raw.get("content") in _RESULT_CONTENTS else "main",
|
|
323
|
+
"main": count(raw.get("main")),
|
|
324
|
+
"supplements": count(raw.get("supplements")),
|
|
325
|
+
"no_supplements": count(raw.get("no_supplements")),
|
|
326
|
+
"sources": [[text(s[0]), count(s[1])] for s in (raw.get("sources") or [])[:8]
|
|
327
|
+
if isinstance(s, list) and len(s) == 2 and text(s[0]) and count(s[1])]
|
|
328
|
+
if isinstance(raw.get("sources"), list) else [],
|
|
329
|
+
"failures": [],
|
|
330
|
+
"stopped": raw.get("stopped") is True,
|
|
331
|
+
}
|
|
332
|
+
failures = raw.get("failures")
|
|
333
|
+
for item in (failures if isinstance(failures, list) else [])[:_MAX_RESULT_FAILURES]:
|
|
334
|
+
if not isinstance(item, dict) or not text(item.get("reason")):
|
|
335
|
+
continue
|
|
336
|
+
summary["failures"].append({
|
|
337
|
+
"cls": item.get("cls") if item.get("cls") in FAILURE_CLASSES else "unexplained",
|
|
338
|
+
**{key: text(item.get(key)) for key in ("reason", "title", "journal", "doi", "note")},
|
|
339
|
+
})
|
|
340
|
+
folder = raw.get("folder")
|
|
341
|
+
if isinstance(folder, str) and 0 < len(folder) <= 4096 and os.path.isabs(folder):
|
|
342
|
+
summary["folder"] = folder
|
|
343
|
+
started = raw.get("started")
|
|
344
|
+
if isinstance(started, (int, float)) and not isinstance(started, bool) and 0 < time.time() - started < 31 * 86400:
|
|
345
|
+
summary["started"] = datetime.fromtimestamp(started).isoformat(timespec="seconds")
|
|
346
|
+
return summary
|
|
347
|
+
|
|
348
|
+
|
|
268
349
|
@contextmanager
|
|
269
350
|
def tracked_download(current: str, output_dir: Any = None, batch: BatchContext | None = None,
|
|
270
351
|
content: str = "main"):
|
|
@@ -286,7 +367,7 @@ def tracked_download(current: str, output_dir: Any = None, batch: BatchContext |
|
|
|
286
367
|
done = batch.done if batch.done is not None else (None if _batch_state(batch.batch_id) else batch.index - 1)
|
|
287
368
|
_adopt_batch(batch.batch_id, batch.total, (done, batch.succeeded, batch.failed),
|
|
288
369
|
current=current, stage="starting",
|
|
289
|
-
phase=f"第 {batch.index}/{batch.total} 篇:进入机构访问")
|
|
370
|
+
phase=f"第 {batch.index}/{batch.total} 篇:进入机构访问" if batch.total > 1 else "进入机构访问")
|
|
290
371
|
_notify_stage("starting", current)
|
|
291
372
|
update(content=content if content in ("main", "supplements", "both") else "main")
|
|
292
373
|
if output_dir:
|