papersearch 0.4.8 → 0.4.9

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 CHANGED
@@ -165,7 +165,8 @@ paper-search carsi status --format text
165
165
  - Downloads show a small progress capsule in a corner of the screen: progress, whether the main text or the supplementary files are being fetched, and the publisher; it turns amber with a gentle breathing glow and sends a system notification, if enabled, when you need to sign in or complete a verification. Click the reminder to switch to the current task’s download browser. Hover to open it: skip this paper, mark the journal or publisher as no access, stop the whole task, report a problem, change wait times and the default download folder (the gear at the top right), or minimize it (–). Drag the pill or a non-control area of the expanded card to move it. On the school's login page a paper waits up to 3 minutes by default; anywhere else (human checks, publisher pages, ...) it ends after 1 minute.
166
166
  - The default download browser keeps running in the background without requesting foreground focus on startup, clicks, or navigation. It does not automatically minimize or hide its window. The capsule alerts you when intervention is needed; click the reminder to switch to the browser when ready. A completed check with no listed supplementary files is not a failure. Incomplete sign-in, unsupported discovery, and download failures remain distinct results.
167
167
  - Choose or type the default download folder in capsule settings, or run `paper-search config set DEFAULT_DOWNLOAD_PATH "/absolute/path/papers"`. New tasks use the saved folder; `--save-path` or `savePath` overrides it for one task. A running batch keeps its original folder.
168
- - capsule settings include “页面持续无进展” (page inactivity), defaulting to 30 seconds, adjustable from 1 to 600 seconds, with a restore-default action. School sign-in prompts appear immediately. Other pages prompt with an amber breathing glow only after making no progress for the selected interval. Automatic passage stays quiet, resumed progress clears the reminder, and active main-document navigation stays quiet within the existing page timeout. Receiving file data does not count as a stalled page. This setting changes the reminder delay without extending page timeouts.
168
+ - Since 0.4.9, prompts require a current login control or a verification step needing help. Idle time and school domains alone do not trigger human-action prompts. The verification reminder setting defaults to 30 seconds (1–600); handoff occurs by half of the remaining wait budget. Loading, absent and checked controls stay under automatic observation. Unavailable controls prompt a check without extending the overall deadline.
169
+ - Since 0.4.9, you can drop the capsule near a screen edge to snap it there. It opens inward. Along the left or right edge, you can drop it at any available height, and collapsing returns it to that height. When dragging between displays, the display under the pointer at release determines where it lands.
169
170
  - typing, selecting or clicking a control in the dedicated sign-in page, or taking over through the capsule, pauses the remaining sign-in budget, including pauses between inputs. The timer resumes after leaving the manual sign-in step; an untouched sign-in still times out.
170
171
  - macOS notifications use PaperSearch’s name and icon. Notification clicks share the capsule reminder’s action for restoring the current task’s browser. The initial extension setup offers a notification choice; new configurations default to off, and upgrades preserve existing preferences. The System notifications switch in the capsule’s settings saves immediately. Turning it off keeps the amber reminder. No separate notification tool is required; enabled notifications still follow macOS notification permissions and Focus settings.
171
172
  - Which publishers' main texts and supplementary files it can fetch is in the [publisher support table](skills/paper-search/references/publisher-support.md) (Chinese). Both have been fetched from Elsevier, Wiley, Springer Nature, OUP, Wolters Kluwer, Taylor & Francis, Sage, ACS, NEJM, ASCE, Dove and others; supplementary files from ASH, Thieme, PLOS, Copernicus, Annual Reviews, IOP, AMS, APS, Optica, IEEE, World Scientific, MDPI and Frontiers, as well as Figshare files linked to a paper, have also been fetched; remaining attachment routes are still being completed; sites not in the table are tried with the shared rules.
package/README.md CHANGED
@@ -165,7 +165,8 @@ paper-search carsi status --format text
165
165
  - 下载时屏幕角落会出现进度胶囊:显示进度、正在下正文还是附录、哪家出版社;需要你登录或验证时变成琥珀色,背景与边缘轻柔呼吸,并在开启系统通知时发送通知;点击“请登录学校”等提醒可切到当前任务的下载浏览器。鼠标指上去展开,可以跳过本篇、标记本刊或出版社无权限、终止整个任务、报告问题,右上角齿轮调整等待时间和默认下载文件夹,“–”最小化;按住胶囊或展开卡片的非按钮区域可拖动。停在学校登录页默认最多等 3 分钟,停在其他页面(人机验证、出版社页面等)默认 1 分钟后结束这一篇。
166
166
  - 默认下载浏览器在后台继续运行,启动、点击和跳转时不主动抢前台,也不会自动最小化或隐藏窗口;需要登录或验证时由胶囊提示,点击提醒即可切到浏览器处理。完成检查但页面未列出附件会显示“已检查,页面未列出补充材料”,不计为失败;登录未完成、暂不支持发现附件或下载失败会分别说明。
167
167
  - 默认下载文件夹可在胶囊设置中选择或输入,也可运行 `paper-search config set DEFAULT_DOWNLOAD_PATH "/完整路径/论文"`。保存后用于新任务;`--save-path` 或 `savePath` 可为单次任务指定其他目录,正在运行的批次保持原目录。
168
- - 胶囊齿轮新增“页面持续无进展”,默认 30 秒,可保存为 1–600 秒,并可恢复默认。学校账号登录立即提醒;其他页面持续无进展达到设定时间后,胶囊才变色呼吸、提示查看浏览器。自动通过保持安静,恢复进展后清除提醒;主页面仍在导航加载时,在原页面等待上限内暂不提醒;持续接收文件也不会被当作页面卡住。该设置只改变提醒时间,不延长页面等待上限。
168
+ - 自 0.4.9 起,仅在当前页面出现登录控件或验证确需接管时提醒;空闲时间和学校域名本身不再触发人工提醒。齿轮中的“验证提醒前最多等”默认 30 秒,可设为 1–600 秒;实际交接时间不晚于剩余等待预算的一半。验证框尚未出现、正在加载或已勾选处理中时继续自动观察;已知控件无法操作时提示检查,并保留原总时限。
169
+ - 自 0.4.9 起,把胶囊拖到屏幕边缘附近松手,会贴到对应边,展开时朝屏幕内部打开。沿左、右边可停在任意可用高度,收起后保留松手位置。跨屏拖动以松手时指针所在的屏幕为准。
169
170
  - 机构登录中,你在专用登录页输入、选择或点击控件,或点击胶囊接管后,暂停登录等待倒计时;输入间的停顿不消耗剩余时间。离开人工登录步骤后继续计时;无人操作仍按原限时结束。
170
171
  - macOS 通知改用 PaperSearch 自己的名称和图标,点击通知与点击胶囊提醒共用当前任务的浏览器恢复入口。首次配置机构下载扩展时可选择是否开启系统通知,新配置默认关闭;胶囊齿轮里的“系统通知”开关点击即保存,已有选择在升级后保留。关闭通知仍保留琥珀色呼吸提醒。无需另外安装通知工具;开启后横幅显示仍遵循 macOS 通知权限与专注模式设置。
171
172
  - 能取哪些出版社的正文和补充材料,见 [出版社支持表](skills/paper-search/references/publisher-support.md)。正文和补充材料都实测取得的有 Elsevier、Wiley、Springer Nature、OUP、Wolters Kluwer、Taylor & Francis、Sage、ACS、NEJM、ASCE、Dove 等,另已实测取得 ASH、Thieme、PLOS、Copernicus、Annual Reviews、IOP、AMS、APS、Optica、IEEE、World Scientific、MDPI、Frontiers 的补充材料及论文关联的 Figshare 附件;尚未取得的附件入口仍在补全;表里没有的网站按通用规则尝试。
@@ -40,14 +40,22 @@ body:not(.mac) #root { border-radius: 8px; border: none; }
40
40
  box-shadow: inset 0 0 0 2px var(--warn-dot), inset 0 0 16px rgba(217, 119, 6, 0.2);
41
41
  opacity: 0.2; animation: breathe 3.6s ease-in-out infinite;
42
42
  }
43
- .surface { position: relative; z-index: 1; transform-origin: top right; }
43
+ .surface { position: relative; z-index: 1; transform-origin: var(--origin-x, right) var(--origin-y, top); }
44
+ body.grow-right { --origin-x: left; }
45
+ body.grow-left { --origin-x: right; }
46
+ body.grow-down { --origin-y: top; }
47
+ body.grow-up { --origin-y: bottom; }
48
+ #root.animating > .surface { position: absolute; top: 0; left: 0; }
49
+ body.grow-left #root.animating > .surface { left: auto; right: 0; }
50
+ body.grow-up #root.animating > .surface { top: auto; bottom: 0; }
51
+ #root.card > .surface { overflow-y: auto; max-height: var(--content-max-height, none); }
44
52
  .fade .surface { animation: fade .22s ease-out; }
45
53
  .folder-setting { margin: 12px 0; }
46
54
  .folder-setting .folder-row { display:flex; gap:8px; margin-top:6px; }
47
55
  .folder-setting input { width:0; min-width:0; flex:1; text-align:left; }
48
56
  .folder-setting .hint { margin-top:5px; font-size:11px; color:var(--dim); }
49
57
  @media (prefers-reduced-motion: reduce) { .fade .surface, #root.warn::after { animation:none; } }
50
- @keyframes fade { from { opacity: 0; transform: translateY(-2px); } to { opacity: 1; transform: none; } }
58
+ @keyframes fade { from { opacity: 0; } to { opacity: 1; } }
51
59
  @keyframes breathe { 0%, 100% { opacity: 0.2; } 50% { opacity: 0.85; } }
52
60
 
53
61
  .attention-target { appearance: none; box-sizing: content-box; padding: 0; border: none; background: transparent; color: inherit; font: inherit; text-align: left; cursor: pointer; }
@@ -333,9 +341,10 @@ function render(force) {
333
341
  else if (V.mode === "done") html = doneCard();
334
342
  else html = idleCard();
335
343
  const cls = shape + (V.mode === "attention" && panel !== "settings" ? " warn" : "");
336
- if (html === lastHtml && cls === lastCls) return;
344
+ if (!force && html === lastHtml && cls === lastCls) return;
337
345
  const previous = root.getBoundingClientRect();
338
346
  root.style.width = ""; root.style.height = "";
347
+ root.style.removeProperty("--content-max-height");
339
348
  root.className = cls + " capsule-drag-region" + (cls !== lastCls ? " fade" : "");
340
349
  root.innerHTML = '<div class="surface">' + html + "</div>";
341
350
  lastHtml = html;
@@ -343,14 +352,44 @@ function render(force) {
343
352
  fit(previous);
344
353
  }
345
354
 
346
- let fitGeneration = 0;
347
- async function fit(previous) {
355
+ let fitGeneration = 0, layoutQueue = Promise.resolve();
356
+ let settledGeneration = 0, settledSize = null, settledExpanded = null;
357
+ function fit(previous) {
348
358
  const generation = ++fitGeneration;
349
359
  const pad = document.body.classList.contains("mac") ? 20 : 0;
350
360
  const target = root.getBoundingClientRect();
351
361
  const to = [Math.ceil(target.width), Math.ceil(target.height)];
352
362
  const from = previous.width && previous.height ? [previous.width, previous.height] : to;
363
+ const expanded = root.classList.contains("card");
353
364
  const border = document.body.classList.contains("mac") ? 1 : 0;
365
+ // Fix the content width before awaiting the native bridge. Otherwise an
366
+ // absolutely positioned surface shrink-wraps for a frame on every tick.
367
+ root.firstElementChild.style.width = Math.max(0, to[0] - border) + "px";
368
+ root.style.setProperty("--content-max-height", Math.max(0, to[1] - border) + "px");
369
+ if (settledGeneration === generation - 1 && settledExpanded === expanded && settledSize
370
+ && to.every((size, i) => size === settledSize[i] && Math.abs(size - from[i]) < 1)) {
371
+ // Elapsed time/countdowns update the text, not the window geometry.
372
+ root.style.width = to[0] + "px"; root.style.height = to[1] + "px";
373
+ settledGeneration = generation;
374
+ return;
375
+ }
376
+ // Do not paint the new natural size before the native frame catches up.
377
+ root.style.width = from[0] + "px"; root.style.height = from[1] + "px";
378
+ clearTimeout(hoverTimer); clearTimeout(leaveTimer);
379
+ root.classList.add("animating");
380
+ layoutQueue = layoutQueue.then(() => animateFit(generation, expanded, from, to, pad))
381
+ .catch(error => console.error("Capsule layout failed", error));
382
+ }
383
+ async function animateFit(generation, expanded, from, to, pad) {
384
+ if (generation !== fitGeneration || dragging || closing) return;
385
+ const layout = await api().begin_layout(expanded, to[0] + pad, to[1] + pad, generation);
386
+ if (generation !== fitGeneration || dragging || closing || !layout.vertical) return;
387
+ document.body.classList.remove("grow-up", "grow-down", "grow-left", "grow-right");
388
+ document.body.classList.add("grow-" + layout.vertical, "grow-" + layout.horizontal);
389
+ from = [layout.from_width - pad, layout.from_height - pad];
390
+ to = [layout.width - pad, layout.height - pad];
391
+ const border = document.body.classList.contains("mac") ? 1 : 0;
392
+ root.style.setProperty("--content-max-height", Math.max(0, to[1] - border) + "px");
354
393
  root.firstElementChild.style.width = Math.max(0, to[0] - border) + "px";
355
394
  const duration = matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : 240;
356
395
  const started = performance.now();
@@ -360,11 +399,20 @@ async function fit(previous) {
360
399
  const eased = 1 - Math.pow(1 - t, 3);
361
400
  const width = Math.round(from[0] + (to[0] - from[0]) * eased);
362
401
  const height = Math.round(from[1] + (to[1] - from[1]) * eased);
402
+ await api().resize(width + pad, height + pad, eased, generation);
403
+ if (generation !== fitGeneration || dragging || closing) return;
363
404
  root.style.width = width + "px"; root.style.height = height + "px";
364
- await api().resize(width + pad, height + pad);
365
405
  if (t === 1) break;
366
406
  await new Promise(requestAnimationFrame);
367
407
  }
408
+ if (generation === fitGeneration && !dragging && !closing) {
409
+ await api().finish_layout(generation);
410
+ if (generation === fitGeneration) {
411
+ root.classList.remove("animating");
412
+ settledGeneration = generation; settledSize = to; settledExpanded = expanded;
413
+ }
414
+ }
415
+ observeHover();
368
416
  }
369
417
 
370
418
  async function tick() {
@@ -375,6 +423,9 @@ async function tick() {
375
423
  // Once the prompt is handled an open card folds back unless the pointer is on it.
376
424
  if (before === "attention" && V.mode !== "attention" && !hovering && !dragging && !panel) open = false;
377
425
  render(false);
426
+ // Also detect a real pointer departure when clamping moved the window away
427
+ // from a stationary cursor (there may be no further native boundary event).
428
+ if (document.body.classList.contains("mac")) observeHover();
378
429
  }
379
430
 
380
431
  function say(text) { flash = { text: text, until: Date.now() + 6000 }; render(true); }
@@ -445,6 +496,7 @@ root.addEventListener("pointerdown", (event) => {
445
496
  if (event.button === 0 && api().activate_on_input) inputActivation = api().activate_on_input();
446
497
  if (event.button !== 0 || interactive(event.target)) return;
447
498
  dragging = true;
499
+ ++hoverRequest;
448
500
  ++fitGeneration;
449
501
  clearTimeout(hoverTimer); clearTimeout(leaveTimer);
450
502
  root.classList.add("dragging");
@@ -472,19 +524,21 @@ window.addEventListener("pointermove", event => {
472
524
  nextDragPoint = [event.screenX, event.screenY];
473
525
  if (!movingDrag) dragMove = flushDragMoves();
474
526
  });
475
- async function finishDrag() {
527
+ async function finishDrag(event) {
476
528
  if (!dragging || endingDrag) return;
477
529
  endingDrag = true;
478
530
  try {
479
531
  await dragReady;
480
532
  await dragMove;
481
- await api().set_dragging(false);
533
+ if (event.type === "pointerup") await api().set_dragging(false, event.screenX, event.screenY);
534
+ else await api().set_dragging(false);
482
535
  } finally {
483
536
  dragging = false; endingDrag = false;
484
537
  root.classList.remove("dragging");
485
538
  // Events queued by native tracking during a drag must not fold the card.
486
539
  render(true);
487
- setHover(root.matches(':hover'), true);
540
+ await layoutQueue;
541
+ observeHover(root.matches(':hover'), true);
488
542
  }
489
543
  }
490
544
  window.addEventListener("pointerup", finishDrag);
@@ -509,8 +563,30 @@ function setHover(inside, force = false) {
509
563
  leaveTimer = setTimeout(() => { if (!panel) { open = false; render(true); } }, 280);
510
564
  }
511
565
  }
512
- root.addEventListener("mouseenter", () => setHover(true));
513
- root.addEventListener("mouseleave", () => setHover(false));
566
+ let hoverRequest = 0, lastNativePointer = null;
567
+ async function observeHover(inside, force = false) {
568
+ if (dragging || endingDrag || closing) return;
569
+ if (!document.body.classList.contains("mac")) {
570
+ if (typeof inside === "boolean") setHover(inside, force);
571
+ return;
572
+ }
573
+ if (root.classList.contains("animating")) return;
574
+ const request = ++hoverRequest;
575
+ let pointer;
576
+ try { pointer = await api().hover_state(); }
577
+ catch (error) {
578
+ if (!closing) console.error("Capsule pointer query failed", error);
579
+ return;
580
+ }
581
+ if (request !== hoverRequest || dragging || endingDrag || closing || root.classList.contains("animating")) return;
582
+ // Moving/resizing the frame can generate enter/exit without mouse movement.
583
+ // It must not start a collapse/open loop, including across display boundaries.
584
+ if (!force && lastNativePointer && pointer.x === lastNativePointer.x && pointer.y === lastNativePointer.y) return;
585
+ lastNativePointer = pointer;
586
+ setHover(pointer.inside, force);
587
+ }
588
+ root.addEventListener("mouseenter", () => observeHover(true));
589
+ root.addEventListener("mouseleave", () => observeHover(false));
514
590
  document.addEventListener("keydown", (event) => {
515
591
  if (event.key === "Escape" && panel) { panel = ""; render(true); }
516
592
  if (event.key === "Enter" && panel === "settings") act("save");
@@ -563,6 +563,13 @@ def _launch_camoufox_persistent(user_data_dir: str, headless: bool, proxy: Any,
563
563
  from playwright.sync_api import sync_playwright
564
564
 
565
565
  opts = _camoufox_options(headless, proxy, args, humanize, kwargs)
566
+ if not headless:
567
+ # Gecko's automatic Troubleshoot Mode dialog blocks the download
568
+ # browser and disables its background helper. Keep recovery and the
569
+ # startup keyboard shortcut from opening it in this child only.
570
+ env = opts.get("env")
571
+ opts["env"] = {**(os.environ if env is None else env),
572
+ "MOZ_DISABLE_AUTO_SAFE_MODE": "1", "MOZ_DISABLE_SAFE_MODE_KEY": "1"}
566
573
  if os.name == "nt" and not headless:
567
574
  # Let the owned helper create the first window without activation.
568
575
  from .background import ADDON_DIR, install_startup_helper
@@ -14,11 +14,12 @@ from urllib.parse import urlsplit
14
14
  _OBSERVE_SCRIPT = """() => {
15
15
  const key = Symbol.for('papersearch.turnstile.ready');
16
16
  if (window[key]) return;
17
- const ready = window[key] = new WeakSet();
17
+ const ready = window[key] = new WeakMap();
18
+ let revision = 0;
18
19
  addEventListener('message', event => {
19
20
  if (event.origin !== 'https://challenges.cloudflare.com' || !event.source
20
21
  || event.data?.source !== 'cloudflare-challenge') return;
21
- if (event.data.event === 'interactiveBegin') ready.add(event.source);
22
+ if (event.data.event === 'interactiveBegin') ready.set(event.source, ++revision);
22
23
  else if (['interactiveEnd', 'complete', 'fail', 'tokenExpired']
23
24
  .includes(event.data.event)) ready.delete(event.source);
24
25
  });
@@ -99,7 +100,8 @@ def needs_manual_verification(page: Any) -> bool:
99
100
  return False
100
101
 
101
102
 
102
- def click_checkbox(page: Any, *, timeout_ms: int, checkpoint: Callable[[], None]) -> Literal[
103
+ def click_checkbox(page: Any, *, timeout_ms: int, checkpoint: Callable[[], None],
104
+ observation: Callable[[str], None] | None = None) -> Literal[
103
105
  "absent", "clicked", "unavailable"
104
106
  ]:
105
107
  """Try one visible checkbox; never force a click through an overlay.
@@ -110,11 +112,16 @@ def click_checkbox(page: Any, *, timeout_ms: int, checkpoint: Callable[[], None]
110
112
  """
111
113
  from playwright.sync_api import Error, TimeoutError
112
114
 
115
+ def note(reason: str) -> None:
116
+ if observation is not None:
117
+ observation(reason)
118
+
113
119
  until = time.monotonic() + max(0, timeout_ms) / 1000
120
+ unavailable = False
114
121
  for frame in page.frames:
115
122
  checkpoint()
116
123
  if time.monotonic() >= until:
117
- return "absent"
124
+ return "unavailable" if unavailable else "absent"
118
125
  if not is_turnstile_frame(str(frame.url or "")):
119
126
  continue
120
127
  try:
@@ -123,60 +130,68 @@ def click_checkbox(page: Any, *, timeout_ms: int, checkpoint: Callable[[], None]
123
130
  observe_checkbox(page)
124
131
  element = frame.frame_element()
125
132
  if not element.is_visible():
133
+ note("hidden_frame")
126
134
  continue
127
135
  controls = frame.locator('input[type="checkbox"], [role="checkbox"]')
128
136
  count = controls.count()
129
137
  position = None
130
138
  if count:
131
139
  if count != 1:
132
- return "unavailable"
140
+ note("multiple_controls")
141
+ unavailable = True
142
+ continue
133
143
  target = controls.first
134
- if not target.is_visible() or not target.is_enabled() or target.is_checked():
135
- return "unavailable"
144
+ if not target.is_visible():
145
+ note("hidden_control")
146
+ continue
147
+ if not target.is_enabled() or target.is_checked():
148
+ note("disabled_or_checked")
149
+ unavailable = True
150
+ continue
136
151
  else:
137
152
  title = (element.get_attribute("title") or "").lower()
138
153
  box = element.bounding_box()
139
154
  if ("cloudflare" not in title or "challenge" not in title or not box
140
155
  or not 250 <= box["width"] <= 350 or not 60 <= box["height"] <= 80):
141
- return "unavailable"
142
- if not element.evaluate("""iframe =>
143
- window[Symbol.for('papersearch.turnstile.ready')]?.has(iframe.contentWindow) === true
144
- """):
145
- return "absent" # loading/automatic check; no click has been attempted
156
+ geometry = f" width={box['width']:.0f} height={box['height']:.0f}" if box else ""
157
+ note("unsupported_geometry_or_title" + geometry)
158
+ unavailable = True
159
+ continue
160
+ readiness = element.evaluate("""iframe =>
161
+ window[Symbol.for('papersearch.turnstile.ready')]?.get(iframe.contentWindow) || 0
162
+ """)
163
+ if not readiness:
164
+ note("waiting_ready_signal")
165
+ continue # loading/automatic check; no click has been attempted
146
166
  target = element
147
167
  position = {"x": 28, "y": box["height"] / 2}
148
168
  checkpoint()
149
169
  remaining_ms = int((until - time.monotonic()) * 1000)
150
170
  if remaining_ms <= 0:
151
171
  return "unavailable"
152
- if position:
153
- # A covered/moving widget has not received an input action.
154
- # Keep its readiness until native actionability checks pass.
155
- # Trial clicks on an iframe can reach its child document in
156
- # Playwright. Hover checks visibility/stability/hit targeting
157
- # without ever dispatching a checkbox click.
158
- target.hover(timeout=remaining_ms, position=position, trial=True)
159
- checkpoint()
160
- remaining_ms = int((until - time.monotonic()) * 1000)
161
- if remaining_ms <= 0:
162
- return "unavailable"
163
- # One readiness signal permits only one closed-shadow click. Wait
164
- # for a fresh interactiveBegin before retrying; otherwise a stale
165
- # signal could toggle an already checked or processing widget.
166
- if position and not element.evaluate("""iframe =>
167
- window[Symbol.for('papersearch.turnstile.ready')]?.delete(iframe.contentWindow) === true
168
- """):
169
- return "absent"
170
- remaining_ms = int((until - time.monotonic()) * 1000)
171
- if remaining_ms <= 0:
172
- return "unavailable"
172
+ # click performs visibility, stability and hit-target checks itself.
173
+ # A separate humanized hover uses the same short action budget twice.
174
+ # Keep readiness on actionability timeout so an overlay can clear.
173
175
  # The engine observes the navigation separately. A dispatched click
174
176
  # must not be reported as unavailable while waiting for that load.
175
177
  target.click(timeout=remaining_ms, no_wait_after=True,
176
178
  **({"position": position} if position else {}))
179
+ if position:
180
+ try:
181
+ element.evaluate("""(iframe, revision) => {
182
+ const ready = window[Symbol.for('papersearch.turnstile.ready')];
183
+ if (ready?.get(iframe.contentWindow) === revision) ready.delete(iframe.contentWindow);
184
+ }""", readiness)
185
+ except Error as exc:
186
+ if not any(text in str(exc).lower() for text in (
187
+ "frame was detached", "frame has been detached", "element is not attached",
188
+ "execution context was destroyed")):
189
+ raise
190
+ note("click_dispatched")
177
191
  return "clicked"
178
192
  except TimeoutError:
179
- return "unavailable" # hidden/covered/stale; no repeated forced clicks
193
+ note("actionability_timeout")
194
+ unavailable = True
180
195
  except Error as exc:
181
196
  # Navigation can remove the widget before its action. Browser close,
182
197
  # crash, watchdog and cancellation errors must still reach the caller.
@@ -184,6 +199,8 @@ def click_checkbox(page: Any, *, timeout_ms: int, checkpoint: Callable[[], None]
184
199
  "frame was detached", "frame has been detached", "element is not attached",
185
200
  "execution context was destroyed",
186
201
  )):
187
- return "unavailable"
202
+ note("frame_detached")
203
+ unavailable = True
204
+ continue
188
205
  raise
189
- return "absent"
206
+ return "unavailable" if unavailable else "absent"
@@ -0,0 +1,266 @@
1
+ """Screen-independent capsule geometry; all coordinates use top-left logical pixels."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import logging
6
+ import math
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+
11
+ EDGE, TOP_GAP, BOTTOM_GAP = 20, 44, 56
12
+ SNAP_DISTANCE = 24
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class Rect:
17
+ x: float
18
+ y: float
19
+ width: float
20
+ height: float
21
+
22
+ @property
23
+ def right(self) -> float:
24
+ return self.x + self.width
25
+
26
+ @property
27
+ def bottom(self) -> float:
28
+ return self.y + self.height
29
+
30
+ def contains_center(self, other: Rect) -> bool:
31
+ return self.contains(other.x + other.width / 2, other.y + other.height / 2)
32
+
33
+ def contains(self, x: float, y: float) -> bool:
34
+ return self.x <= x < self.right and self.y <= y < self.bottom
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class ScreenArea:
39
+ name: str
40
+ bounds: Rect
41
+ work: Rect
42
+
43
+
44
+ def screen_for(rect: Rect, screens: list[ScreenArea]) -> ScreenArea:
45
+ """Prefer the centre's screen, otherwise the nearest screen (unplugged display)."""
46
+ for screen in screens:
47
+ if screen.bounds.contains_center(rect):
48
+ return screen
49
+ x, y = rect.x + rect.width / 2, rect.y + rect.height / 2
50
+ return min(screens, key=lambda s: max(s.bounds.x - x, 0, x - s.bounds.right) ** 2
51
+ + max(s.bounds.y - y, 0, y - s.bounds.bottom) ** 2)
52
+
53
+
54
+ def fit_rect(rect: Rect, work: Rect) -> Rect:
55
+ """Keep a rectangle in the work area; oversized content starts at its top/left."""
56
+ return Rect(max(work.x, min(rect.x, work.right - rect.width)),
57
+ max(work.y, min(rect.y, work.bottom - rect.height)), rect.width, rect.height)
58
+
59
+
60
+ def direction_for(rect: Rect, work: Rect) -> tuple[str, str]:
61
+ return ("down" if rect.y + rect.height / 2 < work.y + work.height / 2 else "up",
62
+ "right" if rect.x + rect.width / 2 < work.x + work.width / 2 else "left")
63
+
64
+
65
+ def _edge(start: float, end: float, low: float, high: float) -> int:
66
+ """Return -1/1 for the nearby edge, or 0 for free placement on this axis."""
67
+ left, right = start - low, high - end
68
+ if min(left, right) > SNAP_DISTANCE:
69
+ return 0
70
+ return -1 if left <= right else 1
71
+
72
+
73
+ class Placement:
74
+ """Persist only the collapsed home. Temporary expansion/clamping never moves it."""
75
+ def __init__(self, path: Path, corner: str) -> None:
76
+ self.path, self.corner = path, corner
77
+ self.home: Rect | None = None
78
+ self._dragged_card: Rect | None = None
79
+ self.screen: ScreenArea | None = None
80
+ self.direction = ("down" if corner == "top" else "up", "left")
81
+ self.edges = (0, 0)
82
+ self.expanded = False
83
+ self.scale = 1.0
84
+ self._saved: dict = {}
85
+ try:
86
+ data = json.loads(path.read_text(encoding="utf-8"))
87
+ if isinstance(data, dict):
88
+ self._saved = data
89
+ except FileNotFoundError:
90
+ pass
91
+ except (OSError, ValueError) as exc:
92
+ logging.getLogger(__name__).warning("Cannot read capsule placement: %s", type(exc).__name__)
93
+
94
+ def start(self, screens: list[ScreenArea], size: tuple[int, int], scale: float = 1.0) -> tuple[int, int]:
95
+ w, h = size
96
+ self.scale = scale
97
+ saved = self._saved
98
+ restored = None
99
+ saved_screen = None
100
+ self.edges = (0, 0)
101
+ try:
102
+ if saved.get("version") == 2:
103
+ values = [float(saved[k]) for k in ("x", "y", "width", "height")]
104
+ if all(math.isfinite(n) for n in values) and values[2] > 0 and values[3] > 0:
105
+ old_scale = float(saved.get("scale", 1))
106
+ if not math.isfinite(old_scale) or old_scale <= 0:
107
+ raise ValueError("Invalid saved DPI")
108
+ ratio = old_scale / scale
109
+ restored = Rect(values[0] * ratio, values[1] * ratio, values[2], values[3])
110
+ screen = next((s for s in screens if s.name == saved.get("screen")), None)
111
+ edges = saved.get("edges")
112
+ if screen and isinstance(edges, list) and len(edges) == 2 and all(
113
+ type(edge) is int and edge in (-1, 0, 1) for edge in edges):
114
+ self.edges = (edges[0], edges[1])
115
+ if any(self.edges):
116
+ saved_screen = screen
117
+ if screen and isinstance(saved.get("work"), list) and len(saved["work"]) == 2:
118
+ old_x, old_y = map(float, saved["work"])
119
+ if math.isfinite(old_x) and math.isfinite(old_y):
120
+ restored = Rect(restored.x + screen.work.x - old_x * ratio,
121
+ restored.y + screen.work.y - old_y * ratio,
122
+ restored.width, restored.height)
123
+ elif saved.get("corner") in ("top", "bottom"):
124
+ right, edge = float(saved["right"]), float(saved["edge"])
125
+ if math.isfinite(right) and math.isfinite(edge):
126
+ restored = Rect(right - w, edge if saved["corner"] == "top" else edge - h, w, h)
127
+ except (KeyError, TypeError, ValueError, OverflowError):
128
+ restored = None
129
+ if restored is not None and (saved_screen or any(s.bounds.contains_center(restored) for s in screens)):
130
+ self.screen = saved_screen or screen_for(restored, screens)
131
+ restored = Rect(restored.x, restored.y, min(restored.width, self.screen.work.width),
132
+ min(restored.height, self.screen.work.height))
133
+ self.home = self._fit(restored)
134
+ else:
135
+ self.edges = (0, 0)
136
+ self.screen = screens[0]
137
+ b = self.screen.bounds
138
+ self.home = fit_rect(Rect(b.right - EDGE - w,
139
+ b.y + TOP_GAP if self.corner == "top" else b.bottom - BOTTOM_GAP - h,
140
+ w, h), self.screen.work)
141
+ self.direction = self._direction(self.home)
142
+ return round(self.home.x), round(self.home.y)
143
+
144
+ def rescale(self, scale: float) -> None:
145
+ """Rebase global coordinates when a Windows drag crosses different DPIs."""
146
+ ratio = self.scale / scale
147
+ if ratio != 1:
148
+ if self.home is not None:
149
+ self.home = self._rescaled(self.home, ratio)
150
+ if self._dragged_card is not None:
151
+ self._dragged_card = self._rescaled(self._dragged_card, ratio)
152
+ self.scale = scale
153
+
154
+ @staticmethod
155
+ def _rescaled(rect: Rect, ratio: float) -> Rect:
156
+ return Rect(rect.x * ratio, rect.y * ratio, rect.width, rect.height)
157
+
158
+ def begin(self, expanded: bool, actual: Rect, screens: list[ScreenArea]) -> None:
159
+ if self.home is None:
160
+ self.home = actual
161
+ if not self.expanded:
162
+ # The first measured pill can differ from START_SIZE.
163
+ self.home = actual
164
+ self.screen = screen_for(self.home, screens)
165
+ if not self.expanded:
166
+ self.direction = self._direction(self.home)
167
+ if expanded:
168
+ self.expanded = True
169
+
170
+ def target(self, width: int, height: int, expanded: bool) -> Rect:
171
+ assert self.home is not None and self.screen is not None
172
+ home, work = self.home, self.screen.work
173
+ width, height = min(width, int(work.width)), min(height, int(work.height))
174
+ if expanded or not self.expanded:
175
+ anchor = (self._dragged_card if expanded else None) or home
176
+ vertical, horizontal = self.direction
177
+ x = anchor.right - width if horizontal == "left" else anchor.x
178
+ y = anchor.bottom - height if vertical == "up" else anchor.y
179
+ else:
180
+ # A different status can change the pill's width while it is open.
181
+ x, y = home.x, home.y
182
+ return self._fit(Rect(x, y, width, height))
183
+
184
+ def finish(self, expanded: bool, actual: Rect) -> None:
185
+ if not expanded:
186
+ self.home = actual
187
+ self._dragged_card = None
188
+ self.expanded = False
189
+ self.save()
190
+
191
+ def _fit(self, rect: Rect) -> Rect:
192
+ work = self.screen.work
193
+ horizontal, vertical = self.edges
194
+ x = work.x if horizontal < 0 else work.right - rect.width if horizontal > 0 else rect.x
195
+ y = work.y if vertical < 0 else work.bottom - rect.height if vertical > 0 else rect.y
196
+ return fit_rect(Rect(x, y, rect.width, rect.height), work)
197
+
198
+ def _direction(self, rect: Rect) -> tuple[str, str]:
199
+ vertical, horizontal = direction_for(rect, self.screen.work)
200
+ x, y = self.edges
201
+ return ("down" if y < 0 else "up" if y > 0 else vertical,
202
+ "right" if x < 0 else "left" if x > 0 else horizontal)
203
+
204
+ def _drop_edges(self, rect: Rect, work: Rect, pointer: tuple[float, float] | None) -> tuple[int, int]:
205
+ x = _edge(rect.x, rect.right, work.x, work.right)
206
+ y = _edge(rect.y, rect.bottom, work.y, work.bottom)
207
+ if pointer is None:
208
+ return x, y
209
+ px, py = pointer
210
+ mouse_x = _edge(px, px, work.x, work.right)
211
+ mouse_y = _edge(py, py, work.y, work.bottom)
212
+ if not self.expanded:
213
+ return mouse_x or x, mouse_y or y
214
+ # A large card can touch a second edge by size alone. Only a release
215
+ # near the corner docks both axes; otherwise keep the closer edge.
216
+ if mouse_x or mouse_y:
217
+ return mouse_x, mouse_y
218
+ if x and y:
219
+ dx = abs(rect.x - work.x if x < 0 else work.right - rect.right)
220
+ dy = abs(rect.y - work.y if y < 0 else work.bottom - rect.bottom)
221
+ if dx != dy:
222
+ return (x, 0) if dx < dy else (0, y)
223
+ px_gap = abs(px - (work.x if x < 0 else work.right))
224
+ py_gap = abs(py - (work.y if y < 0 else work.bottom))
225
+ return (x, 0) if px_gap <= py_gap else (0, y)
226
+ return x, y
227
+
228
+ def dragged(self, after: Rect, screens: list[ScreenArea],
229
+ pointer: tuple[float, float] | None = None) -> Rect:
230
+ # At a display seam the card's centre may still be on the previous
231
+ # display. Prefer the display where the user actually released it.
232
+ self.screen = next((s for s in screens if pointer and s.bounds.contains(*pointer)), None)
233
+ if self.screen is None:
234
+ self.screen = screen_for(after, screens)
235
+ work = self.screen.work
236
+ point = pointer if pointer and self.screen.bounds.contains(*pointer) else None
237
+ self.edges = self._drop_edges(after, work, point)
238
+ after = self._fit(Rect(after.x, after.y, min(after.width, work.width), min(after.height, work.height)))
239
+ self.direction = self._direction(after)
240
+ if self.home is None or not self.expanded:
241
+ self.home = after
242
+ else:
243
+ self._dragged_card = after
244
+ vertical, horizontal = self.direction
245
+ w, h = self.home.width, self.home.height
246
+ if point is not None and any(self.edges):
247
+ # The card's chosen growth corner must not quantize where the
248
+ # much smaller pill lands along the side.
249
+ self.home = Rect(point[0] - w / 2, point[1] - h / 2, w, h)
250
+ else:
251
+ self.home = Rect(after.right - w if horizontal == "left" else after.x,
252
+ after.bottom - h if vertical == "up" else after.y, w, h)
253
+ self.home = self._fit(self.home)
254
+ self.save()
255
+ return after
256
+
257
+ def save(self) -> None:
258
+ if self.home is None or self.screen is None:
259
+ return
260
+ try:
261
+ self.path.write_text(json.dumps({"version": 2, "x": self.home.x, "y": self.home.y,
262
+ "width": self.home.width, "height": self.home.height, "screen": self.screen.name,
263
+ "work": [self.screen.work.x, self.screen.work.y], "scale": self.scale,
264
+ "edges": self.edges}), encoding="utf-8")
265
+ except OSError as exc:
266
+ logging.getLogger(__name__).warning("Cannot save capsule placement: %s", type(exc).__name__)