papersearch 0.4.11 → 0.5.0

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 (169) hide show
  1. package/.env.example +8 -0
  2. package/README.en.md +97 -75
  3. package/README.md +98 -76
  4. package/assets/overview.en.png +0 -0
  5. package/assets/overview.png +0 -0
  6. package/carsi/paper_search_carsi/adapters/ams/__init__.py +12 -0
  7. package/carsi/paper_search_carsi/adapters/elsevier/__init__.py +5 -2
  8. package/carsi/paper_search_carsi/adapters/elsevier/sciencedirect.py +18 -1
  9. package/carsi/paper_search_carsi/adapters/iop/__init__.py +11 -2
  10. package/carsi/paper_search_carsi/adapters/platforms/atypon/__init__.py +24 -14
  11. package/carsi/paper_search_carsi/api_keys.py +138 -0
  12. package/carsi/paper_search_carsi/assets/api_keys.json +146 -0
  13. package/carsi/paper_search_carsi/assets/capsule.html +327 -30
  14. package/carsi/paper_search_carsi/assets/capsule_en.json +437 -0
  15. package/carsi/paper_search_carsi/browser/preview.py +16 -3
  16. package/carsi/paper_search_carsi/browser/watchdog.py +15 -0
  17. package/carsi/paper_search_carsi/capsule_placement.py +51 -31
  18. package/carsi/paper_search_carsi/cli.py +46 -4
  19. package/carsi/paper_search_carsi/cli_config.py +51 -0
  20. package/carsi/paper_search_carsi/config.py +2 -0
  21. package/carsi/paper_search_carsi/download_diagnostics.py +1 -0
  22. package/carsi/paper_search_carsi/download_directory.py +5 -33
  23. package/carsi/paper_search_carsi/engine/access_rules.py +11 -0
  24. package/carsi/paper_search_carsi/engine/batch.py +13 -1
  25. package/carsi/paper_search_carsi/engine/batch_access.py +3 -0
  26. package/carsi/paper_search_carsi/engine/batch_capture.py +39 -10
  27. package/carsi/paper_search_carsi/engine/batch_common.py +4 -0
  28. package/carsi/paper_search_carsi/engine/batch_institution.py +27 -18
  29. package/carsi/paper_search_carsi/engine/bridge.py +7 -3
  30. package/carsi/paper_search_carsi/engine/pdf_guard.py +3 -6
  31. package/carsi/paper_search_carsi/engine/supplements.py +34 -6
  32. package/carsi/paper_search_carsi/extractors/pdf_extractor.py +4 -18
  33. package/carsi/paper_search_carsi/i18n.py +46 -0
  34. package/carsi/paper_search_carsi/orchestrator.py +14 -1
  35. package/carsi/paper_search_carsi/pdf_text.py +84 -0
  36. package/carsi/paper_search_carsi/pdf_utils.py +3 -12
  37. package/carsi/paper_search_carsi/progress_capsule.py +181 -19
  38. package/carsi/paper_search_carsi/progress_macos.py +35 -10
  39. package/carsi/paper_search_carsi/progress_reporter.py +76 -9
  40. package/carsi/paper_search_carsi/progress_view.py +7 -1
  41. package/carsi/paper_search_carsi/server.py +9 -1
  42. package/carsi/paper_search_carsi/user_settings.py +17 -4
  43. package/carsi/pyproject.toml +6 -4
  44. package/dist/capabilities/citation-expansion/CitationService.d.ts +8 -0
  45. package/dist/capabilities/citation-expansion/CitationService.d.ts.map +1 -1
  46. package/dist/capabilities/citation-expansion/CitationService.js +14 -4
  47. package/dist/capabilities/citation-expansion/CitationService.js.map +1 -1
  48. package/dist/capabilities/citation-expansion/CrossrefReferences.d.ts +18 -0
  49. package/dist/capabilities/citation-expansion/CrossrefReferences.d.ts.map +1 -0
  50. package/dist/capabilities/citation-expansion/CrossrefReferences.js +83 -0
  51. package/dist/capabilities/citation-expansion/CrossrefReferences.js.map +1 -0
  52. package/dist/capabilities/citation-expansion/OpenAlexGraph.d.ts +36 -0
  53. package/dist/capabilities/citation-expansion/OpenAlexGraph.d.ts.map +1 -0
  54. package/dist/capabilities/citation-expansion/OpenAlexGraph.js +120 -0
  55. package/dist/capabilities/citation-expansion/OpenAlexGraph.js.map +1 -0
  56. package/dist/capabilities/citation-expansion/handler.d.ts +14 -5
  57. package/dist/capabilities/citation-expansion/handler.d.ts.map +1 -1
  58. package/dist/capabilities/citation-expansion/handler.js +64 -14
  59. package/dist/capabilities/citation-expansion/handler.js.map +1 -1
  60. package/dist/capabilities/citation-expansion/schemas.d.ts +1 -5
  61. package/dist/capabilities/citation-expansion/schemas.d.ts.map +1 -1
  62. package/dist/capabilities/citation-expansion/schemas.js +2 -2
  63. package/dist/capabilities/citation-expansion/schemas.js.map +1 -1
  64. package/dist/capabilities/citation-expansion/tools.d.ts +0 -18
  65. package/dist/capabilities/citation-expansion/tools.d.ts.map +1 -1
  66. package/dist/capabilities/citation-expansion/tools.js +4 -16
  67. package/dist/capabilities/citation-expansion/tools.js.map +1 -1
  68. package/dist/capabilities/citation-expansion/types.d.ts +4 -0
  69. package/dist/capabilities/citation-expansion/types.d.ts.map +1 -1
  70. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts.map +1 -1
  71. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js +2 -0
  72. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js.map +1 -1
  73. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts +8 -0
  74. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts.map +1 -1
  75. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +36 -24
  76. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js.map +1 -1
  77. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts +3 -1
  78. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts.map +1 -1
  79. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js +5 -1
  80. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js.map +1 -1
  81. package/dist/capabilities/pdf-discovery/carsi/index.d.ts +1 -1
  82. package/dist/capabilities/pdf-discovery/carsi/index.d.ts.map +1 -1
  83. package/dist/capabilities/pdf-discovery/carsi/index.js +1 -1
  84. package/dist/capabilities/pdf-discovery/carsi/index.js.map +1 -1
  85. package/dist/capabilities/pdf-discovery/carsi/types.d.ts +5 -0
  86. package/dist/capabilities/pdf-discovery/carsi/types.d.ts.map +1 -1
  87. package/dist/capabilities/pdf-discovery/outputLayout.d.ts.map +1 -1
  88. package/dist/capabilities/pdf-discovery/outputLayout.js +2 -1
  89. package/dist/capabilities/pdf-discovery/outputLayout.js.map +1 -1
  90. package/dist/capabilities/pdf-discovery/tiers/entitledAccess.d.ts.map +1 -1
  91. package/dist/capabilities/pdf-discovery/tiers/entitledAccess.js +1 -0
  92. package/dist/capabilities/pdf-discovery/tiers/entitledAccess.js.map +1 -1
  93. package/dist/cli.js +85 -12
  94. package/dist/cli.js.map +1 -1
  95. package/dist/config/ConfigService.d.ts +1 -1
  96. package/dist/config/ConfigService.d.ts.map +1 -1
  97. package/dist/config/ConfigService.js +3 -0
  98. package/dist/config/ConfigService.js.map +1 -1
  99. package/dist/config/apiKeySignup.d.ts +11 -1
  100. package/dist/config/apiKeySignup.d.ts.map +1 -1
  101. package/dist/config/apiKeySignup.js +18 -6
  102. package/dist/config/apiKeySignup.js.map +1 -1
  103. package/dist/config/apiKeyTest.d.ts +18 -0
  104. package/dist/config/apiKeyTest.d.ts.map +1 -0
  105. package/dist/config/apiKeyTest.js +109 -0
  106. package/dist/config/apiKeyTest.js.map +1 -0
  107. package/dist/config/selfCommand.d.ts +8 -0
  108. package/dist/config/selfCommand.d.ts.map +1 -0
  109. package/dist/config/selfCommand.js +10 -0
  110. package/dist/config/selfCommand.js.map +1 -0
  111. package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
  112. package/dist/infrastructure/runlog/failureClass.js +2 -0
  113. package/dist/infrastructure/runlog/failureClass.js.map +1 -1
  114. package/dist/management/capability-profile/index.js +4 -4
  115. package/dist/management/capability-profile/index.js.map +1 -1
  116. package/dist/management/carsi/autoUpdate.d.ts +21 -0
  117. package/dist/management/carsi/autoUpdate.d.ts.map +1 -0
  118. package/dist/management/carsi/autoUpdate.js +88 -0
  119. package/dist/management/carsi/autoUpdate.js.map +1 -0
  120. package/dist/management/carsi/installer.d.ts +1 -1
  121. package/dist/management/carsi/installer.d.ts.map +1 -1
  122. package/dist/management/carsi/installer.js +38 -7
  123. package/dist/management/carsi/installer.js.map +1 -1
  124. package/dist/management/carsi/runtime.d.ts +9 -0
  125. package/dist/management/carsi/runtime.d.ts.map +1 -1
  126. package/dist/management/carsi/runtime.js +11 -0
  127. package/dist/management/carsi/runtime.js.map +1 -1
  128. package/dist/management/carsi/settingsWindow.d.ts +30 -0
  129. package/dist/management/carsi/settingsWindow.d.ts.map +1 -0
  130. package/dist/management/carsi/settingsWindow.js +51 -0
  131. package/dist/management/carsi/settingsWindow.js.map +1 -0
  132. package/dist/management/diagnostics/index.d.ts.map +1 -1
  133. package/dist/management/diagnostics/index.js +16 -0
  134. package/dist/management/diagnostics/index.js.map +1 -1
  135. package/dist/management/skills/nextSteps.d.ts +2 -0
  136. package/dist/management/skills/nextSteps.d.ts.map +1 -0
  137. package/dist/management/skills/nextSteps.js +16 -0
  138. package/dist/management/skills/nextSteps.js.map +1 -0
  139. package/dist/management/updates/index.d.ts +6 -1
  140. package/dist/management/updates/index.d.ts.map +1 -1
  141. package/dist/management/updates/index.js +18 -11
  142. package/dist/management/updates/index.js.map +1 -1
  143. package/dist/platforms/ACMSearcher.d.ts.map +1 -1
  144. package/dist/platforms/ACMSearcher.js +3 -2
  145. package/dist/platforms/ACMSearcher.js.map +1 -1
  146. package/dist/platforms/CrossrefSearcher.d.ts.map +1 -1
  147. package/dist/platforms/CrossrefSearcher.js +4 -3
  148. package/dist/platforms/CrossrefSearcher.js.map +1 -1
  149. package/dist/platforms/OpenAlexSearcher.d.ts.map +1 -1
  150. package/dist/platforms/OpenAlexSearcher.js +4 -1
  151. package/dist/platforms/OpenAlexSearcher.js.map +1 -1
  152. package/dist/registry/platformMetadata.d.ts.map +1 -1
  153. package/dist/registry/platformMetadata.js +1 -0
  154. package/dist/registry/platformMetadata.js.map +1 -1
  155. package/dist/utils/plainText.d.ts +7 -0
  156. package/dist/utils/plainText.d.ts.map +1 -0
  157. package/dist/utils/plainText.js +19 -0
  158. package/dist/utils/plainText.js.map +1 -0
  159. package/package.json +3 -3
  160. package/skills/paper-search/SKILL.md +20 -15
  161. package/skills/paper-search/references/browser-download.md +1 -1
  162. package/skills/paper-search/references/capability-routing.md +5 -3
  163. package/skills/paper-search/references/carsi-setup.md +6 -3
  164. package/skills/paper-search/references/cli-contract.md +9 -4
  165. package/skills/paper-search/references/management-layer.md +4 -4
  166. package/skills/paper-search/references/publisher-support.md +4 -4
  167. package/skills/paper-search/references/troubleshooting.md +1 -1
  168. package/NOTICE +0 -23
  169. package/carsi/NOTICE +0 -5
@@ -0,0 +1,46 @@
1
+ """The progress window in English: ``assets/capsule_en.json`` maps each Chinese
2
+ text it can show (its own, the download's prompts and phases, PaperSearch's
3
+ failure reasons) to a short English one. The page translates what it shows with
4
+ it; the system notifications use it here. A text the table does not know stays
5
+ as it is."""
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import re
10
+ from functools import lru_cache
11
+ from pathlib import Path
12
+
13
+ TABLE = Path(__file__).resolve().parent / "assets" / "capsule_en.json"
14
+ LANGUAGES = ("zh", "en")
15
+ _HAN = re.compile(r"[\u4e00-\u9fff]")
16
+
17
+
18
+ @lru_cache(maxsize=1)
19
+ def table() -> dict:
20
+ return json.loads(TABLE.read_text(encoding="utf-8"))
21
+
22
+
23
+ @lru_cache(maxsize=1)
24
+ def _patterns() -> list[tuple[re.Pattern, str]]:
25
+ # The table's replacements are written for JavaScript ($1); Python's are \g<1>.
26
+ return [(re.compile(source), re.sub(r"\$(\d)", r"\\g<\1>", target)) for source, target in table()["patterns"]]
27
+
28
+
29
+ def _one(text: str) -> str:
30
+ core = text.strip()
31
+ if not core or not _HAN.search(core):
32
+ return text
33
+ exact = table()["exact"].get(core)
34
+ if exact is None:
35
+ for pattern, target in _patterns():
36
+ if pattern.search(core):
37
+ exact = pattern.sub(target, core)
38
+ break
39
+ return text if exact is None else text.replace(core, exact)
40
+
41
+
42
+ def translate(text: str, lang: str) -> str:
43
+ """``text`` in ``lang``; its " · " parts one by one, as the page does."""
44
+ if lang != "en" or not text:
45
+ return text
46
+ return " · ".join(_one(part) for part in text.split(" · "))
@@ -6,6 +6,8 @@ sources and no renaming; the caller names and verifies the file.
6
6
  """
7
7
  from __future__ import annotations
8
8
 
9
+ import html
10
+ import re
9
11
  import threading
10
12
  from pathlib import Path
11
13
  from typing import Any
@@ -25,6 +27,11 @@ _INFLIGHT: set[str] = set()
25
27
  _INFLIGHT_LOCK = threading.Lock()
26
28
 
27
29
 
30
+ def plain_title(title: str) -> str:
31
+ """A metadata title as plain text: no markup or entities (Crossref gives <i>…</i> and &amp;)."""
32
+ return " ".join(html.unescape(re.sub(r"<[^>]+>", "", str(title))).split())[:500]
33
+
34
+
28
35
  def download_institutional(
29
36
  identifier: str,
30
37
  output_dir: str | Path | None = None,
@@ -33,6 +40,7 @@ def download_institutional(
33
40
  supplements: str | None = None,
34
41
  user_wait: str | None = None,
35
42
  diagnostics_dir: str | None = None,
43
+ title: str | None = None,
36
44
  ) -> dict[str, Any]:
37
45
  """Download one DOI through institutional access only.
38
46
 
@@ -69,6 +77,8 @@ def download_institutional(
69
77
  extra["user_wait"] = user_wait
70
78
  if diagnostics_dir:
71
79
  extra["diagnostics_dir"] = diagnostics_dir
80
+ if title:
81
+ extra["title"] = title
72
82
  return _download_impl(doi, output_dir, **extra)
73
83
  finally:
74
84
  with _INFLIGHT_LOCK:
@@ -77,8 +87,11 @@ def download_institutional(
77
87
 
78
88
  def _download_impl(doi: str, output_dir: str | Path | None, *,
79
89
  supplements: str | None = None, user_wait: str | None = None,
80
- diagnostics_dir: str | None = None) -> dict[str, Any]:
90
+ diagnostics_dir: str | None = None, title: str | None = None) -> dict[str, Any]:
81
91
  config = load_config()
92
+ if title:
93
+ # The caller's title for the PDF identity check (bridge's PaperRecord).
94
+ config["record_title"] = plain_title(title)
82
95
  if user_wait == "short":
83
96
  config["user_wait"] = "short"
84
97
  if supplements in ("with", "only"):
@@ -0,0 +1,84 @@
1
+ """Reading PDFs: page count, page text, and whether a transfer ended whole.
2
+
3
+ Every PDF the backend reads goes through here, so the library can change in one
4
+ place. It is pypdfium2 (PDFium, Chrome's PDF engine; BSD/Apache, about 10 MB),
5
+ which replaced PyMuPDF (AGPL, about 54 MB) in 2026-11. PDFium allows one call at
6
+ a time in a process, even on different documents, so every call takes a lock."""
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ import threading
11
+ from pathlib import Path
12
+
13
+ _LOCK = threading.Lock()
14
+ # The last startxref of a file and the cross-reference it names.
15
+ _STARTXREF = re.compile(rb"startxref\s+(\d+)\s+%%EOF")
16
+ _XREF_OBJECT = re.compile(rb"\d+\s+\d+\s+obj\b")
17
+
18
+
19
+ class PdfError(Exception):
20
+ """Not a PDF the library can read, or one without pages."""
21
+
22
+
23
+ def _open(source: bytes | str | Path):
24
+ import pypdfium2
25
+
26
+ try:
27
+ return pypdfium2.PdfDocument(bytes(source) if isinstance(source, (bytes, bytearray)) else str(source))
28
+ except pypdfium2.PdfiumError as exc:
29
+ raise PdfError(str(exc)) from exc
30
+
31
+
32
+ def page_count(source: bytes | str | Path) -> int:
33
+ with _LOCK:
34
+ document = _open(source)
35
+ try:
36
+ return len(document)
37
+ finally:
38
+ document.close()
39
+
40
+
41
+ def page_texts(source: bytes | str | Path, pages: int | None = None) -> list[str]:
42
+ """The text of each of the first ``pages`` pages (all when None)."""
43
+ with _LOCK:
44
+ document = _open(source)
45
+ try:
46
+ count = len(document)
47
+ if not count:
48
+ raise PdfError("no pages")
49
+ texts = []
50
+ for index in range(count if pages is None else min(pages, count)):
51
+ page = document[index]
52
+ textpage = page.get_textpage()
53
+ try:
54
+ texts.append(_clean(textpage.get_text_bounded()))
55
+ finally:
56
+ textpage.close()
57
+ page.close()
58
+ return texts
59
+ finally:
60
+ document.close()
61
+
62
+
63
+ def text(source: bytes | str | Path, pages: int | None = None) -> str:
64
+ """The first ``pages`` pages' text (all when None), a line break between pages."""
65
+ return "\n".join(page_texts(source, pages))
66
+
67
+
68
+ def _clean(text: str) -> str:
69
+ # PDFium ends lines with \r\n and writes a hyphen it found at a line's end as \x02.
70
+ return text.replace("\r\n", "\n").replace("\r", "\n").replace("\x02", "-")
71
+
72
+
73
+ def complete(body: bytes) -> bool:
74
+ """Whether the bytes end as a whole PDF: %%EOF after a startxref that points
75
+ at a cross-reference table or stream. A cut-off or damaged transfer, which
76
+ a reader would have to repair, does not."""
77
+ found = list(_STARTXREF.finditer(body[-2048:]))
78
+ if not found:
79
+ return False
80
+ offset = int(found[-1].group(1))
81
+ if offset >= len(body):
82
+ return False
83
+ head = body[offset:offset + 64].lstrip()
84
+ return head.startswith(b"xref") or _XREF_OBJECT.match(head) is not None
@@ -77,19 +77,10 @@ def is_suspicious_pdf(path: Path) -> bool:
77
77
  # Very small files are suspicious regardless
78
78
  if size < 50_000:
79
79
  return True
80
+ from . import pdf_text
81
+
80
82
  try:
81
- import fitz # type: ignore[import-not-found]
82
- except Exception:
83
- # No pymupdf: fall back to the cheap regex heuristic
84
- with path.open("rb") as fh:
85
- content = fh.read(512_000)
86
- # Count PDF page objects: look for "/Type /Page" not followed by "s"
87
- import re
88
- pages = len(re.findall(rb"/Type\s*/Page\b", content))
89
- return pages <= 1
90
- try:
91
- with fitz.open(path) as doc:
92
- return int(doc.page_count) <= 1
83
+ return pdf_text.page_count(path) <= 1
93
84
  except Exception:
94
85
  return True # unreadable PDF — treat as suspicious
95
86
  except OSError:
@@ -12,6 +12,8 @@ Windows. Without pywebview or a usable engine the classic window
12
12
 
13
13
  Usage: ``paper-search-carsi progress`` (or ``python -m paper_search_carsi.progress_capsule``).
14
14
  Spawned automatically by ``progress_reporter.ensure_progress_bar`` when a download starts.
15
+ ``paper-search-carsi settings`` opens it at the settings (download folder,
16
+ waits and reminders, API keys), also with no download running.
15
17
  """
16
18
 
17
19
  from __future__ import annotations
@@ -24,12 +26,17 @@ import time
24
26
  from pathlib import Path
25
27
  from typing import Any
26
28
 
27
- from . import download_directory, progress_view, user_settings
29
+ from . import api_keys, download_directory, i18n, progress_view, user_settings
28
30
  from .capsule_placement import Placement, Rect, ScreenArea
29
- from .progress_reporter import progress_path, read_state
31
+ from .progress_reporter import progress_path, read_state, take_settings_request
30
32
 
31
33
  ASSETS = Path(__file__).with_name("assets")
32
34
  PAGE = ASSETS / "capsule.html"
35
+
36
+
37
+ def page_html() -> str:
38
+ """The page with its English table in it (the window loads it as one string)."""
39
+ return PAGE.read_text(encoding="utf-8").replace("/*CAPSULE_EN*/null", i18n.TABLE.read_text(encoding="utf-8"))
33
40
  # PaperSearch's icon (assets/icon.svg) for the Dock and the Windows taskbar.
34
41
  ICON, TASKBAR_ICON = ASSETS / "icon-512.png", ASSETS / "icon-64.png"
35
42
  # The first, collapsed frame; the page then reports the size it needs.
@@ -103,6 +110,7 @@ class Notifier:
103
110
  if not new:
104
111
  return
105
112
  message = str(new[-1].get("message") or "需要你在浏览器里处理")
113
+ message = i18n.translate(message, user_settings.language())
106
114
  threading.Thread(target=self._send, args=("PaperSearch", message, state), daemon=True).start()
107
115
 
108
116
 
@@ -124,6 +132,10 @@ class Api:
124
132
  self._layout: tuple[int, bool, Rect, Rect] | None = None
125
133
  self._closed = False
126
134
  self._close_requested: float | None = None
135
+ try:
136
+ self._lang = user_settings.language()
137
+ except Exception:
138
+ self._lang = "zh"
127
139
 
128
140
  # --- what to show -----------------------------------------------------
129
141
  def platform(self) -> str:
@@ -133,9 +145,12 @@ class Api:
133
145
  """The capsule's view of the progress file; ``hovering`` keeps a finished window open."""
134
146
  self._hovering = bool(hovering) or self._dragging
135
147
  try:
136
- return progress_view.view(read_state(), time.time())
148
+ shown = progress_view.view(read_state(), time.time())
137
149
  except Exception:
138
- return {"mode": "idle"}
150
+ shown = {"mode": "idle"}
151
+ shown["lang"] = self._lang
152
+ request = take_settings_request() # `paper-search-carsi settings`: show the settings
153
+ return {**shown, "open_settings": request} if request else shown
139
154
 
140
155
  # --- watching the task, also while the capsule is minimized ------------
141
156
  def watch(self) -> None:
@@ -219,6 +234,21 @@ class Api:
219
234
  except Exception as exc:
220
235
  return f"记录失败:{type(exc).__name__}"
221
236
 
237
+ def open_article(self, doi: str) -> str:
238
+ """The article's page (doi.org) in the user's own browser, to fetch what the
239
+ batch could not; only a DOI is opened, never another address."""
240
+ doi = str(doi or "").strip()
241
+ if not progress_view.DOI.fullmatch(doi):
242
+ return "打开失败:不是有效的 DOI"
243
+ import webbrowser
244
+ from urllib.parse import quote
245
+
246
+ try:
247
+ opened = webbrowser.open("https://doi.org/" + quote(doi, safe="/:;()._-"))
248
+ except Exception as exc:
249
+ return f"打开失败:{type(exc).__name__}"
250
+ return "已在浏览器打开这篇文章" if opened else "打开失败:没有找到默认浏览器"
251
+
222
252
  def open_folder(self) -> bool:
223
253
  return progress_view.open_folder(str((read_state() or {}).get("output_dir") or ""))
224
254
 
@@ -227,11 +257,23 @@ class Api:
227
257
  values = user_settings.current()
228
258
  return {
229
259
  "fields": [{"name": f.name, "label": f.label, "unit": f.unit, "value": values[f.name],
230
- "default": f.default} for f in user_settings.FIELDS],
260
+ "default": f.default, "page": f.page} for f in user_settings.FIELDS],
231
261
  "notify": user_settings.notify_enabled(),
232
262
  "download_dir": download_directory.current(),
263
+ "language": self._lang,
233
264
  }
234
265
 
266
+ def set_language(self, lang: str) -> dict[str, Any]:
267
+ """The language switch saves at once and the page follows it."""
268
+ if lang not in i18n.LANGUAGES:
269
+ return {"ok": False, "error": "语言只能是中文或英文"}
270
+ try:
271
+ user_settings.set_language(lang)
272
+ except (OSError, ValueError) as exc:
273
+ return {"ok": False, "error": f"保存失败:{type(exc).__name__}"}
274
+ self._lang = lang
275
+ return {"ok": True, "language": lang}
276
+
235
277
  def set_notifications(self, enabled: bool) -> dict[str, Any]:
236
278
  """The notification switch saves immediately, independently of other fields."""
237
279
  if not isinstance(enabled, bool):
@@ -243,11 +285,14 @@ class Api:
243
285
  return {"ok": False, "error": f"保存失败:{type(exc).__name__}"}
244
286
  return {"ok": True, "notify": enabled}
245
287
 
246
- def save_settings(self, values: dict[str, Any], notify_on: bool, download_dir: str | None = None) -> dict[str, Any]:
247
- """Check every field, then save them all; nothing is saved when one is wrong."""
288
+ def save_settings(self, values: dict[str, Any], download_dir: str | None = None) -> dict[str, Any]:
289
+ """Check the fields of one settings page, then save them all; nothing is
290
+ saved when one is wrong. The notification switch saves on its own."""
248
291
  checked, errors = {}, {}
249
292
  for field in user_settings.FIELDS:
250
- value, problem = user_settings.check(field, str((values or {}).get(field.name, "")))
293
+ if field.name not in (values or {}):
294
+ continue
295
+ value, problem = user_settings.check(field, str(values[field.name]))
251
296
  if problem:
252
297
  errors[field.name] = problem
253
298
  else:
@@ -263,11 +308,65 @@ class Api:
263
308
  if download_dir is not None:
264
309
  download_directory.save(download_dir)
265
310
  user_settings.save(checked)
266
- user_settings.set_notify(bool(notify_on))
267
311
  except Exception as exc:
268
312
  return {"ok": False, "errors": {"": f"保存失败:{type(exc).__name__}"}}
269
313
  return {"ok": True}
270
314
 
315
+ # --- API keys: values go to the config, never back to the page ---------
316
+ def api_keys(self) -> dict[str, Any]:
317
+ try:
318
+ return {"ok": True, **api_keys.listing()}
319
+ except Exception as exc:
320
+ return {"ok": False, "error": f"读取配置失败:{type(exc).__name__}"}
321
+
322
+ def api_key_values(self, service: str) -> dict[str, Any]:
323
+ """The values of the row the user opened, for its hidden fields."""
324
+ try:
325
+ return {"ok": True, "values": api_keys.saved(str(service or ""))}
326
+ except ValueError as exc:
327
+ return {"ok": False, "error": str(exc)}
328
+ except Exception as exc:
329
+ return {"ok": False, "error": f"读取配置失败:{type(exc).__name__}"}
330
+
331
+ def save_api_key(self, service: str, values: dict[str, Any]) -> dict[str, Any]:
332
+ try:
333
+ api_keys.save(str(service or ""), {str(k): str(v) for k, v in (values or {}).items()})
334
+ except ValueError as exc:
335
+ return {"ok": False, "error": str(exc)}
336
+ except Exception as exc:
337
+ return {"ok": False, "error": f"保存失败:{type(exc).__name__}"}
338
+ return self.api_keys()
339
+
340
+ def clear_api_key(self, service: str) -> dict[str, Any]:
341
+ try:
342
+ api_keys.clear(str(service or ""))
343
+ except ValueError as exc:
344
+ return {"ok": False, "error": str(exc)}
345
+ except Exception as exc:
346
+ return {"ok": False, "error": f"清除失败:{type(exc).__name__}"}
347
+ return self.api_keys()
348
+
349
+ def test_api_key(self, service: str, values: dict[str, Any]) -> dict[str, Any]:
350
+ """Whether the service takes what is in the row's fields (saved or not)."""
351
+ try:
352
+ return api_keys.test(str(service or ""), {str(k): str(v) for k, v in (values or {}).items()})
353
+ except ValueError as exc:
354
+ return {"status": "error", "message": str(exc)}
355
+
356
+ def open_signup(self, service: str, guide: bool = False) -> dict[str, Any]:
357
+ """The service's page for getting a key, or its guide; only the listed pages open."""
358
+ found = api_keys.find(str(service or ""))
359
+ address = found and (found.get("guide") if guide else found["url"])
360
+ if not address:
361
+ return {"ok": False, "message": "打开失败:没有这一项"}
362
+ import webbrowser
363
+
364
+ try:
365
+ opened = webbrowser.open(address)
366
+ except Exception as exc:
367
+ return {"ok": False, "message": f"打开失败:{type(exc).__name__}"}
368
+ return {"ok": True} if opened else {"ok": False, "message": "打开失败:没有找到默认浏览器"}
369
+
271
370
  def choose_download_directory(self) -> str | None:
272
371
  """Native directory picker; cancelling leaves the field unchanged."""
273
372
  import webview
@@ -277,6 +376,13 @@ class Api:
277
376
  return str(selected[0]) if selected else None
278
377
 
279
378
  # --- the window -------------------------------------------------------
379
+ def _button_held(self) -> bool:
380
+ if sys.platform == "darwin" and self._native_geometry:
381
+ return _mac_button_held()
382
+ if sys.platform == "win32":
383
+ return _windows_button_held()
384
+ return True
385
+
280
386
  def _drag_point(self, x: float, y: float) -> tuple[float, float]:
281
387
  if sys.platform == "darwin" and self._native_geometry:
282
388
  return _mac_pointer()
@@ -322,6 +428,10 @@ class Api:
322
428
  if not self._dragging or self._drag_origin is None:
323
429
  return
324
430
  sx, sy, x, y = self._drag_origin
431
+ if not self._button_held():
432
+ # The page reports the release late, and the pointer may have
433
+ # moved on since: the window stays where it was let go.
434
+ return
325
435
  # WebView coordinates can rebase across monitors. Native pointer
326
436
  # deltas stay global; on Windows they are physical until the move.
327
437
  screen_x, screen_y = self._drag_point(screen_x, screen_y)
@@ -493,6 +603,22 @@ def _mac_pointer() -> tuple[float, float]:
493
603
  return _cocoa_call(read)
494
604
 
495
605
 
606
+ def _mac_button_held() -> bool:
607
+ import AppKit
608
+
609
+ return bool(_cocoa_call(lambda: AppKit.NSEvent.pressedMouseButtons() & 1))
610
+
611
+
612
+ def _windows_button_held() -> bool:
613
+ import ctypes
614
+
615
+ user32 = ctypes.windll.user32
616
+ # The physical button state: the primary one is the right button when the
617
+ # user swapped them (SM_SWAPBUTTON).
618
+ button = 0x02 if user32.GetSystemMetrics(23) else 0x01
619
+ return bool(user32.GetAsyncKeyState(button) & 0x8000)
620
+
621
+
496
622
  def _windows_pointer() -> tuple[float, float]:
497
623
  import ctypes
498
624
  from ctypes import wintypes
@@ -582,16 +708,29 @@ def _windows_screen_areas(window: Any = None) -> list[ScreenArea]:
582
708
  return [s for _, s in sorted(areas, key=lambda item: not item[0])]
583
709
 
584
710
 
711
+ def _cocoa_rect(frame: Rect) -> Any:
712
+ """``frame`` (top-left coordinates from the primary screen's top) as a Cocoa rect."""
713
+ import AppKit
714
+
715
+ top = AppKit.NSScreen.screens()[0].frame().size.height
716
+ return AppKit.NSMakeRect(frame.x, top - frame.y - frame.height, frame.width, frame.height)
717
+
718
+
719
+ def _moved_origin(ns_window: Any) -> tuple[float, float]:
720
+ """pywebview's moved-event origin, also for a window not yet on any screen: it read
721
+ that window's screen, found none, and the capsule remembered on a second display
722
+ never opened (2026-11-07). The primary screen stands in."""
723
+ import AppKit
724
+
725
+ frame = ns_window.frame()
726
+ screen = (ns_window.screen() or AppKit.NSScreen.screens()[0]).frame()
727
+ return frame.origin.x, screen.size.height - frame.size.height - frame.origin.y
728
+
729
+
585
730
  def _set_window_frame(window: Any, frame: Rect) -> None:
586
731
  """Move and resize in one native operation, without activating the window."""
587
732
  if sys.platform == "darwin":
588
- import AppKit
589
-
590
- def apply():
591
- top = AppKit.NSScreen.screens()[0].frame().size.height
592
- window.native.setFrame_display_(AppKit.NSMakeRect(
593
- frame.x, top - frame.y - frame.height, frame.width, frame.height), True)
594
- _cocoa_call(apply)
733
+ _cocoa_call(lambda: window.native.setFrame_display_(_cocoa_rect(frame), True))
595
734
  elif sys.platform == "win32":
596
735
  window._capsule_set_frame(frame)
597
736
  else:
@@ -628,7 +767,14 @@ def _round_windows_corners(window: Any) -> None:
628
767
  pass
629
768
 
630
769
 
631
- def _classic() -> None:
770
+ def _classic(separate: bool = False) -> None:
771
+ """The classic window. ``separate``: in a process of its own, where pywebview has
772
+ already set up Cocoa in this one; Tk's own setup then crashed (2026-11-07)."""
773
+ if separate:
774
+ import subprocess
775
+
776
+ subprocess.run([sys.executable, "-m", "paper_search_carsi.progress_bar"], check=False)
777
+ return
632
778
  from .progress_bar import main as classic_window
633
779
 
634
780
  classic_window()
@@ -650,11 +796,24 @@ def _prepare_nonactivating_start(window: Any) -> None:
650
796
  return self.pywebview_window is window
651
797
 
652
798
  objc.classAddMethods(cocoa.BrowserView.WebKitHost, [acceptsFirstMouse_])
799
+
800
+ def windowDidMove_(self, notification):
801
+ i = cocoa.BrowserView.get_instance('window', notification.object())
802
+ if i:
803
+ i.pywebview_window.events.moved.set(*_moved_origin(i.window))
804
+
805
+ objc.classAddMethods(cocoa.BrowserView.WindowDelegate, [windowDidMove_])
653
806
  original = cocoa.BrowserView.first_show
654
807
 
655
808
  def first_show(view):
656
809
  if view.pywebview_window is not window:
657
810
  return original(view)
811
+ home = getattr(window, "_capsule_home", None)
812
+ if home is not None:
813
+ # The remembered place, from the primary screen's top like every
814
+ # other capsule move: pywebview's own x/y count from the screen
815
+ # with the active window, another display when one is in use.
816
+ view.window.setFrame_display_(_cocoa_rect(home), False)
658
817
  if not view.hidden:
659
818
  view.window.orderFrontRegardless()
660
819
  view.shown.set()
@@ -747,13 +906,15 @@ def main() -> None:
747
906
  _classic()
748
907
  return
749
908
  try:
750
- page = PAGE.read_text(encoding="utf-8")
909
+ page = page_html()
751
910
  screens = _screen_areas()
752
911
  placement = Placement(progress_path().parent / "capsule.json", _corner())
753
912
  x, y = placement.start(screens, START_SIZE, _window_scale())
754
913
  size = (round(placement.home.width), round(placement.home.height))
755
914
  api = Api(placement, Notifier(), progress_view.AutoClose.from_env())
756
915
  dark = progress_view.dark_mode()
916
+ if sys.platform == "darwin":
917
+ x = y = None # placed at placement.home on its first show (_prepare_nonactivating_start)
757
918
  window = webview.create_window(
758
919
  "PaperSearch", html=page, js_api=api, width=size[0], height=size[1], x=x, y=y,
759
920
  min_size=MIN_SIZE, resizable=False, frameless=True, easy_drag=False, on_top=True, focus=True,
@@ -761,6 +922,7 @@ def main() -> None:
761
922
  background_color="#202124" if dark else "#FFFFFF",
762
923
  )
763
924
  api._window = window
925
+ window._capsule_home = placement.home if sys.platform == "darwin" else None
764
926
  if sys.platform == "darwin":
765
927
  from .progress_macos import install_notification_handler
766
928
 
@@ -793,7 +955,7 @@ def main() -> None:
793
955
 
794
956
  close()
795
957
  progress_view.release_window_lock()
796
- _classic()
958
+ _classic(separate=sys.platform == "darwin")
797
959
  return
798
960
  progress_view.release_window_lock()
799
961
  if sys.platform == "darwin":
@@ -8,11 +8,13 @@ from __future__ import annotations
8
8
  import atexit
9
9
  import json
10
10
  import logging
11
+ import os
11
12
  from pathlib import Path
12
13
  import plistlib
13
14
  import struct
14
15
  import subprocess
15
16
  import threading
17
+ import zlib
16
18
  from typing import Any, Callable
17
19
 
18
20
  logger = logging.getLogger(__name__)
@@ -22,13 +24,29 @@ _callback: Callable[[str, str], Any] | None = None
22
24
  _bridge_lock = threading.RLock()
23
25
 
24
26
 
25
- def _write_if_changed(path: Path, content: bytes, mode: int = 0o644) -> None:
27
+ LSREGISTER = ("/System/Library/Frameworks/CoreServices.framework/Frameworks/"
28
+ "LaunchServices.framework/Support/lsregister")
29
+
30
+
31
+ def _write_if_changed(path: Path, content: bytes, mode: int = 0o644) -> bool:
32
+ """Write ``content`` unless the file already holds it; True when written."""
26
33
  if path.is_file() and path.read_bytes() == content:
27
- return
34
+ return False
28
35
  temporary = path.with_name(path.name + ".tmp")
29
36
  temporary.write_bytes(content)
30
37
  temporary.chmod(mode)
31
38
  temporary.replace(path)
39
+ return True
40
+
41
+
42
+ def _register(app: Path) -> None:
43
+ """Have Launch Services read the bundle again, its icon included; best effort."""
44
+ try:
45
+ os.utime(app)
46
+ subprocess.run([LSREGISTER, "-f", str(app)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
47
+ timeout=10, check=False)
48
+ except (OSError, subprocess.SubprocessError):
49
+ pass
32
50
 
33
51
 
34
52
  def prepare_app(app_root: Path | None = None) -> Path:
@@ -41,21 +59,28 @@ def prepare_app(app_root: Path | None = None) -> Path:
41
59
  macos, resources = app / "Contents/MacOS", app / "Contents/Resources"
42
60
  macos.mkdir(parents=True, exist_ok=True)
43
61
  resources.mkdir(parents=True, exist_ok=True)
44
- _write_if_changed(app / "Contents/Info.plist", plistlib.dumps({
45
- "CFBundleIdentifier": BUNDLE_ID,
46
- "CFBundleName": "PaperSearch", "CFBundleDisplayName": "PaperSearch",
47
- "CFBundleExecutable": "PaperSearch", "CFBundlePackageType": "APPL",
48
- "CFBundleInfoDictionaryVersion": "6.0", "CFBundleVersion": "1",
49
- "CFBundleIconFile": "PaperSearch.icns", "LSUIElement": True,
50
- }))
51
62
  chunks = []
52
63
  for size, kind in ((32, b"icp5"), (64, b"icp6"), (512, b"ic09")):
53
64
  image = (assets / f"icon-{size}.png").read_bytes()
54
65
  chunks.append(kind + struct.pack(">I", len(image) + 8) + image)
55
66
  body = b"".join(chunks)
56
- _write_if_changed(resources / "PaperSearch.icns", b"icns" + struct.pack(">I", len(body) + 8) + body)
67
+ icns = b"icns" + struct.pack(">I", len(body) + 8) + body
68
+ # macOS keeps a bundle's icon from its cache while the bundle seems unchanged:
69
+ # notifications still showed the old icon after the new one was written into
70
+ # the bundle (2026-11-08). The version follows the icon, and a changed bundle
71
+ # is registered again.
72
+ changed = _write_if_changed(app / "Contents/Info.plist", plistlib.dumps({
73
+ "CFBundleIdentifier": BUNDLE_ID,
74
+ "CFBundleName": "PaperSearch", "CFBundleDisplayName": "PaperSearch",
75
+ "CFBundleExecutable": "PaperSearch", "CFBundlePackageType": "APPL",
76
+ "CFBundleInfoDictionaryVersion": "6.0", "CFBundleVersion": str(zlib.crc32(icns)),
77
+ "CFBundleIconFile": "PaperSearch.icns", "LSUIElement": True,
78
+ }))
79
+ changed = _write_if_changed(resources / "PaperSearch.icns", icns) or changed
57
80
  executable = macos / "PaperSearch"
58
81
  _write_if_changed(executable, (assets / "papersearch-notifier").read_bytes(), 0o755)
82
+ if changed:
83
+ _register(app)
59
84
  return executable
60
85
 
61
86