keepfold 0.6.4__py3-none-any.whl

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 (148) hide show
  1. keepfold/__init__.py +1 -0
  2. keepfold/_proc.py +102 -0
  3. keepfold/access.py +154 -0
  4. keepfold/agent_eval.py +162 -0
  5. keepfold/agent_text.py +56 -0
  6. keepfold/anki.py +285 -0
  7. keepfold/app/__init__.py +5 -0
  8. keepfold/app/actions.py +690 -0
  9. keepfold/app/desktop.py +677 -0
  10. keepfold/app/exports.py +254 -0
  11. keepfold/app/hello.py +79 -0
  12. keepfold/app/launch.py +114 -0
  13. keepfold/app/news.py +60 -0
  14. keepfold/app/server.py +3142 -0
  15. keepfold/app/status.py +811 -0
  16. keepfold/app/targets.py +1374 -0
  17. keepfold/app/winpath.py +54 -0
  18. keepfold/app/wizard.py +506 -0
  19. keepfold/ask.py +475 -0
  20. keepfold/askfile.py +322 -0
  21. keepfold/assets/LICENSE-d3.txt +13 -0
  22. keepfold/assets/agent_eval.json +235 -0
  23. keepfold/assets/app/app.css +611 -0
  24. keepfold/assets/app/app.js +2712 -0
  25. keepfold/assets/app/capture.html +16 -0
  26. keepfold/assets/app/capture.js +91 -0
  27. keepfold/assets/app/index.html +149 -0
  28. keepfold/assets/brain3d.js +3730 -0
  29. keepfold/assets/chat_eval.json +454 -0
  30. keepfold/assets/d3.v7.min.js +2 -0
  31. keepfold/assets/dashboard.css +774 -0
  32. keepfold/assets/dashboard.html.tmpl +170 -0
  33. keepfold/assets/dashboard.js +4262 -0
  34. keepfold/assets/help/GUIDE.md +544 -0
  35. keepfold/assets/help/help.md +83 -0
  36. keepfold/assets/keepfold.ico +0 -0
  37. keepfold/assets/whats_new.json +162 -0
  38. keepfold/backup.py +100 -0
  39. keepfold/brainmap.py +1382 -0
  40. keepfold/browse/__init__.py +10 -0
  41. keepfold/browse/build.py +1320 -0
  42. keepfold/browse/forget.py +510 -0
  43. keepfold/browse/legacy.py +95 -0
  44. keepfold/browse/lists.py +285 -0
  45. keepfold/browse/privacy.py +391 -0
  46. keepfold/browse/selftest.py +166 -0
  47. keepfold/browse/sites.py +1068 -0
  48. keepfold/browse/sources.py +329 -0
  49. keepfold/browse/store.py +991 -0
  50. keepfold/browse/takeout.py +312 -0
  51. keepfold/browse/titles.py +127 -0
  52. keepfold/browse/vectors.py +326 -0
  53. keepfold/browse_serve.py +332 -0
  54. keepfold/catalog.py +564 -0
  55. keepfold/chat.py +1464 -0
  56. keepfold/chat_archive.py +165 -0
  57. keepfold/chat_eval.py +583 -0
  58. keepfold/chat_facts.py +721 -0
  59. keepfold/chat_import.py +1045 -0
  60. keepfold/chat_pages.py +291 -0
  61. keepfold/chat_study.py +371 -0
  62. keepfold/chats.py +669 -0
  63. keepfold/claims.py +650 -0
  64. keepfold/cli.py +3254 -0
  65. keepfold/clients.py +96 -0
  66. keepfold/cloudllm.py +135 -0
  67. keepfold/contract.py +43 -0
  68. keepfold/corrections.py +134 -0
  69. keepfold/dashboard.py +959 -0
  70. keepfold/dates.py +202 -0
  71. keepfold/delta.py +146 -0
  72. keepfold/digest.py +72 -0
  73. keepfold/doctor.py +565 -0
  74. keepfold/duplicates.py +145 -0
  75. keepfold/egress.py +68 -0
  76. keepfold/eval_history.py +109 -0
  77. keepfold/events.py +554 -0
  78. keepfold/export_context.py +109 -0
  79. keepfold/fact_harvest.py +578 -0
  80. keepfold/forget.py +720 -0
  81. keepfold/harvest.py +334 -0
  82. keepfold/home.py +714 -0
  83. keepfold/importers.py +627 -0
  84. keepfold/index.py +733 -0
  85. keepfold/know.py +40 -0
  86. keepfold/learning_eval.py +261 -0
  87. keepfold/levels.py +595 -0
  88. keepfold/life_sources.py +747 -0
  89. keepfold/lint.py +241 -0
  90. keepfold/localllm.py +699 -0
  91. keepfold/loops.py +316 -0
  92. keepfold/mcp_server.py +4464 -0
  93. keepfold/migrate.py +552 -0
  94. keepfold/more_sources.py +709 -0
  95. keepfold/packs.py +148 -0
  96. keepfold/people.py +99 -0
  97. keepfold/planner.py +819 -0
  98. keepfold/prime.py +630 -0
  99. keepfold/prime_hook.py +265 -0
  100. keepfold/profiles.py +118 -0
  101. keepfold/quarantine.py +123 -0
  102. keepfold/recall_log.py +93 -0
  103. keepfold/redteam.py +393 -0
  104. keepfold/reflect.py +164 -0
  105. keepfold/relink.py +477 -0
  106. keepfold/render.py +406 -0
  107. keepfold/review.py +1181 -0
  108. keepfold/rollups.py +412 -0
  109. keepfold/safety_net.py +571 -0
  110. keepfold/sample.py +103 -0
  111. keepfold/sample_vault/areas/programming.algorithms.md +11 -0
  112. keepfold/sample_vault/areas/programming.basics.md +11 -0
  113. keepfold/sample_vault/concepts/big-o-notation.md +13 -0
  114. keepfold/sample_vault/concepts/functions.md +13 -0
  115. keepfold/sample_vault/concepts/loops.md +14 -0
  116. keepfold/sample_vault/concepts/recursion.md +13 -0
  117. keepfold/sample_vault/domains/programming.md +10 -0
  118. keepfold/sample_vault/journal/2026-01-12.md +9 -0
  119. keepfold/sample_vault/me/goals.md +17 -0
  120. keepfold/sample_vault/me/profile.md +19 -0
  121. keepfold/sample_vault/mistakes/programming.off-by-one-loop.md +16 -0
  122. keepfold/sample_vault/notes/recursion-needs-a-base-case.md +18 -0
  123. keepfold/sample_vault/problems/fizzbuzz.md +12 -0
  124. keepfold/sample_vault/projects/text-adventure.md +15 -0
  125. keepfold/sample_vault/resources/python-tutorial.md +16 -0
  126. keepfold/semantic.py +1254 -0
  127. keepfold/session.py +764 -0
  128. keepfold/share.py +69 -0
  129. keepfold/sources.py +612 -0
  130. keepfold/sync_copies.py +83 -0
  131. keepfold/tags.py +230 -0
  132. keepfold/taint.py +301 -0
  133. keepfold/tonight.py +195 -0
  134. keepfold/topics.py +1072 -0
  135. keepfold/update.py +300 -0
  136. keepfold/vault.py +942 -0
  137. keepfold/vecstore.py +218 -0
  138. keepfold/voice.py +260 -0
  139. keepfold/voice_memos.py +280 -0
  140. keepfold/watch.py +303 -0
  141. keepfold/where.py +119 -0
  142. keepfold/xray.py +516 -0
  143. keepfold/zotero.py +303 -0
  144. keepfold-0.6.4.dist-info/METADATA +644 -0
  145. keepfold-0.6.4.dist-info/RECORD +148 -0
  146. keepfold-0.6.4.dist-info/WHEEL +4 -0
  147. keepfold-0.6.4.dist-info/entry_points.txt +6 -0
  148. keepfold-0.6.4.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,677 @@
1
+ """The desktop app (`keepfold-app`): the app page in its own window, with a tray icon.
2
+
3
+ Threads. pywebview's Windows GUI (WinForms with Edge WebView2) must own the main thread;
4
+ pystray's Windows icon runs its own message loop on any thread:
5
+ - main: `webview.start()`, the window's GUI loop, until the window is destroyed;
6
+ - keepfold-app-http: the app server (`server.start` adds its auto-import and watch threads; the
7
+ desktop app has no idle stop);
8
+ - keepfold-tray: the tray icon (Open Keepfold, Start with Windows, Quit) and its notifications;
9
+ - keepfold-notify: the once-a-day notifications (reviews due, an exam in 3 days or tomorrow);
10
+ - keepfold-hotkey: quick capture's global hotkey (`Hotkey`, Windows only), a GetMessageW loop that
11
+ shows the capture box (a second, hidden window) on each press; Quit posts it WM_QUIT;
12
+ - keepfold-end: waits for `app.stop` (Quit in the tray or on the page, an update) and destroys
13
+ the window, which ends the main thread's GUI loop; `run` then stops the rest.
14
+ Closing the window only hides it, and its page sleeps a minute later (`Desktop.hide`). Without
15
+ pywebview or the WebView2 runtime the app opens in the browser, as `keepfold app` does.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import os
22
+ import sys
23
+ import threading
24
+ import traceback
25
+ from datetime import UTC, date, datetime, timedelta
26
+ from pathlib import Path
27
+ from urllib.parse import urlsplit
28
+
29
+ from keepfold.app import server, status
30
+
31
+ AUTOSTART = "Keepfold" # the HKCU Run value: `"<Keepfold.exe>" -m keepfold.app.launch --hidden`
32
+ # the AppUserModelID, also on the shortcuts: pins and groups as Keepfold
33
+ APP_ID = "Keepfold.Learner"
34
+ ICON = Path(__file__).resolve().parent.parent / "assets" / "keepfold.ico" # scripts/make_icon.py
35
+ SIZE, MIN_SIZE = (1200, 800), (640, 480)
36
+ AMBER, GROUND = "#ffb000", "#0b0b0a" # app.css's night --lit and --ground
37
+ NOTIFY = ("reviews", "exams", "jobs", "updates") # app.notify in config.yaml, all on by default
38
+ EXAM_DAYS = (3, 1)
39
+ FIRST_S, EVERY_S = 60, 30 * 60 # the first daily check after start, then every 30 minutes
40
+ KEEP_DAYS = 40 # a sent notification's key is remembered this long
41
+ SM_SHUTTINGDOWN = 0x2000
42
+ GWL_EXSTYLE, WS_EX_TOOLWINDOW = -20, 0x80
43
+ SLEEP_S = 60 # this long in the tray, the page sleeps (WebView2's TrySuspendAsync)
44
+ # quick capture's global hotkey (app.hotkey in config.yaml): choice -> (modifiers, key, label)
45
+ MOD_ALT, MOD_CONTROL, MOD_WIN, MOD_NOREPEAT = 0x1, 0x2, 0x8, 0x4000
46
+ VK_SPACE, VK_K = 0x20, 0x4B
47
+ WM_QUIT, WM_HOTKEY, WM_APP = 0x12, 0x312, 0x8000 # WM_APP: app.hotkey changed, register again
48
+ HOTKEYS = {"ctrl+alt+space": (MOD_CONTROL | MOD_ALT, VK_SPACE, "Ctrl+Alt+Space"),
49
+ "win+alt+space": (MOD_WIN | MOD_ALT, VK_SPACE, "Win+Alt+Space"),
50
+ "ctrl+alt+k": (MOD_CONTROL | MOD_ALT, VK_K, "Ctrl+Alt+K"),
51
+ "off": None}
52
+ HOTKEY_DEFAULT = "ctrl+alt+space"
53
+ BOX = (560, 120) # the quick-capture box, CSS px
54
+
55
+ _lock = threading.Lock()
56
+
57
+
58
+ # ---- ~/.keepfold/desktop.json: the window's place and the notifications already sent ----------
59
+
60
+
61
+ def state_file() -> Path:
62
+ return Path.home() / ".keepfold" / "desktop.json"
63
+
64
+
65
+ def load_state() -> dict:
66
+ try:
67
+ d = json.loads(state_file().read_text(encoding="utf-8"))
68
+ except (OSError, ValueError):
69
+ return {}
70
+ return d if isinstance(d, dict) else {}
71
+
72
+
73
+ def save_state(key: str, value) -> None:
74
+ """Set one key of desktop.json (temp file, then os.replace)."""
75
+ with _lock:
76
+ d = {**load_state(), key: value}
77
+ p = state_file()
78
+ p.parent.mkdir(parents=True, exist_ok=True)
79
+ tmp = p.with_name(f".desktop-{os.getpid()}.tmp")
80
+ tmp.write_text(json.dumps(d), encoding="utf-8")
81
+ os.replace(tmp, p)
82
+
83
+
84
+ def _app_cfg() -> dict:
85
+ a = status.config().get("app")
86
+ return a if isinstance(a, dict) else {}
87
+
88
+
89
+ def _merge_app(fn) -> None:
90
+ """`app:` in config.yaml becomes fn(app) (its other keys kept), under the config lock."""
91
+ from keepfold import taint
92
+ taint.write_config(lambda cfg: {"app": fn(
93
+ cfg["app"] if isinstance(cfg.get("app"), dict) else {})})
94
+
95
+
96
+ # ---- Start with Windows -----------------------------------------------------------------------
97
+
98
+
99
+ def autostart_command() -> str:
100
+ """`Keepfold.exe -m keepfold.app.launch --hidden` (installed), else `keepfold-app --hidden`
101
+ (beside `keepfold`): Keepfold starts in the tray, window hidden."""
102
+ from keepfold.app.launch import installed_app
103
+ if app := installed_app():
104
+ return f'"{app}" -m keepfold.app.launch --hidden'
105
+ from keepfold import clients
106
+ keepfold = Path(clients.keepfold_command())
107
+ exe = keepfold.with_name("keepfold-app" + keepfold.suffix)
108
+ if not exe.is_file():
109
+ raise ValueError(f"{exe.name} is not beside {keepfold.name}; reinstall Keepfold to start "
110
+ "it with Windows.")
111
+ return f'"{exe}" --hidden'
112
+
113
+
114
+ def autostart_state() -> dict:
115
+ on = sys.platform == "win32"
116
+ return {"supported": on, "enabled": on and status.run_get(AUTOSTART) is not None}
117
+
118
+
119
+ def set_autostart(enabled: bool) -> dict:
120
+ """Start with Windows on or off. Either choice counts as made, so the first-run default
121
+ (`first_run`) never overrides it."""
122
+ if sys.platform != "win32":
123
+ raise ValueError("Start with Windows is a Windows setting.")
124
+ if enabled:
125
+ status.run_set(autostart_command(), AUTOSTART)
126
+ else:
127
+ status.run_delete(AUTOSTART)
128
+ _merge_app(lambda a: {**a, "autostart_asked": True})
129
+ return autostart_state()
130
+
131
+
132
+ def first_run(echo=print) -> None:
133
+ """The desktop app's first start turns Start with Windows on (the owner's choice), once."""
134
+ if sys.platform != "win32" or _app_cfg().get("autostart_asked") is True:
135
+ return
136
+ try:
137
+ set_autostart(True)
138
+ except (OSError, ValueError) as e: # tried again at the next start
139
+ echo(f"Keepfold app: Start with Windows stays off ({e})")
140
+
141
+
142
+ # ---- notifications ----------------------------------------------------------------------------
143
+
144
+
145
+ def update_check() -> bool:
146
+ """`app.update_check`: the quiet update check, on unless set to false."""
147
+ return _app_cfg().get("update_check") is not False
148
+
149
+
150
+ def notify_settings() -> dict:
151
+ n = _app_cfg().get("notify")
152
+ n = n if isinstance(n, dict) else {}
153
+ return {k: n.get(k) is not False for k in NOTIFY}
154
+
155
+
156
+ def save_notify(body: dict) -> dict:
157
+ if not body or set(body) - set(NOTIFY) or not all(isinstance(v, bool) for v in body.values()):
158
+ raise ValueError(f"send true or false for any of {', '.join(NOTIFY)}")
159
+
160
+ def merge(a: dict) -> dict:
161
+ old = a.get("notify") if isinstance(a.get("notify"), dict) else {}
162
+ return {**a, "notify": {**old, **body}}
163
+ _merge_app(merge)
164
+ return notify_settings()
165
+
166
+
167
+ def hotkey_setting() -> str:
168
+ """app.hotkey: one of HOTKEYS; a missing or unknown value is the default."""
169
+ k = _app_cfg().get("hotkey")
170
+ return k if isinstance(k, str) and k in HOTKEYS else HOTKEY_DEFAULT
171
+
172
+
173
+ def save_hotkey(body: dict) -> str:
174
+ k = body.get("hotkey")
175
+ if not isinstance(k, str) or k not in HOTKEYS:
176
+ raise ValueError(f"hotkey must be one of {', '.join(HOTKEYS)}")
177
+ _merge_app(lambda a: {**a, "hotkey": k})
178
+ return k
179
+
180
+
181
+ def _user32(): # tests replace this: never a real global hotkey in a test
182
+ import ctypes
183
+ return ctypes.windll.user32
184
+
185
+
186
+ class Hotkey:
187
+ """Quick capture's global hotkey, on its own thread `keepfold-hotkey`: RegisterHotKey delivers
188
+ WM_HOTKEY to the thread that registered it, so that thread owns a GetMessageW loop. `change`
189
+ posts WM_APP (register app.hotkey again), `stop` posts WM_QUIT; the loop then ends with
190
+ UnregisterHotKey. A combination another app holds leaves `taken` set and nothing else."""
191
+
192
+ ID = 1
193
+
194
+ def __init__(self, on_press):
195
+ self.on_press = on_press
196
+ self.key: str | None = None # the choice registered (or tried)
197
+ self.taken = False
198
+ self.on = False # registered now
199
+ self.tid: int | None = None
200
+ self.done = threading.Event() # set after each (re-)registration
201
+ self.thread: threading.Thread | None = None
202
+
203
+ def label(self) -> str | None:
204
+ """"Ctrl+Alt+Space" while registered, else None (off, taken, not started)."""
205
+ return HOTKEYS[self.key][2] if self.on and self.key else None
206
+
207
+ def start(self) -> None:
208
+ self.thread = threading.Thread(target=self.loop, daemon=True, name="keepfold-hotkey")
209
+ self.thread.start()
210
+ self.done.wait(5)
211
+
212
+ def _register(self, u) -> None:
213
+ if self.on:
214
+ u.UnregisterHotKey(None, self.ID)
215
+ self.on = False
216
+ self.key = hotkey_setting()
217
+ spec = HOTKEYS[self.key]
218
+ self.on = bool(spec) and bool(u.RegisterHotKey(None, self.ID, spec[0] | MOD_NOREPEAT,
219
+ spec[1]))
220
+ self.taken = bool(spec) and not self.on
221
+ self.done.set()
222
+
223
+ def loop(self) -> None:
224
+ import ctypes
225
+ from ctypes import wintypes
226
+ u = _user32()
227
+ msg = wintypes.MSG()
228
+ self.tid = threading.get_native_id() # GetCurrentThreadId
229
+ u.PeekMessageW(ctypes.byref(msg), None, 0, 0, 0) # makes the queue PostThreadMessage needs
230
+ try:
231
+ self._register(u)
232
+ while u.GetMessageW(ctypes.byref(msg), None, 0, 0) > 0: # 0: WM_QUIT, -1: error
233
+ if msg.message == WM_HOTKEY:
234
+ try:
235
+ self.on_press()
236
+ except Exception: # noqa: BLE001 (a failed show never ends the hotkey)
237
+ traceback.print_exc(limit=1)
238
+ elif msg.message == WM_APP:
239
+ self._register(u)
240
+ finally:
241
+ if self.on:
242
+ u.UnregisterHotKey(None, self.ID)
243
+ self.on = False
244
+ self.done.set()
245
+
246
+ def _post(self, message: int) -> bool:
247
+ if self.tid is None or self.thread is None or not self.thread.is_alive():
248
+ return False
249
+ return bool(_user32().PostThreadMessageW(self.tid, message, 0, 0))
250
+
251
+ def change(self) -> None:
252
+ """Register app.hotkey again at once; returns once it has (or after 2 s)."""
253
+ self.done.clear()
254
+ if self._post(WM_APP):
255
+ self.done.wait(2)
256
+
257
+ def stop(self) -> None:
258
+ self._post(WM_QUIT)
259
+ if self.thread is not None:
260
+ self.thread.join(2)
261
+
262
+
263
+ def daily_notes(root: Path, now: datetime) -> list[tuple[str, str]]:
264
+ """Today's (key, text) notes: reviews due and exams in 3 days or tomorrow, counted and named
265
+ from non-private concepts and assessments only. Each key is sent once (`Notifier.daily`)."""
266
+ from keepfold import planner
267
+ from keepfold.catalog import Catalog
268
+ from keepfold.events import local_day
269
+ from keepfold.vault import Vault
270
+ on, vault, day = notify_settings(), Vault(root), local_day(now)
271
+ out = []
272
+ if on["reviews"]:
273
+ cat = Catalog.load(vault)
274
+ states, _ = planner.current_states(vault, day, cat)
275
+ hide = planner.hidden(vault, cat)
276
+ n = sum(1 for c, st in states.items() if c not in hide and planner.is_due(st, day))
277
+ if n:
278
+ out.append((f"reviews:{day}", f"{n} review{'s' * (n != 1)} due today"))
279
+ if on["exams"]:
280
+ for a in planner._upcoming(vault, date.fromisoformat(day)):
281
+ if not a["private"] and a["days"] in EXAM_DAYS:
282
+ when = "tomorrow" if a["days"] == 1 else f"in {a['days']} days"
283
+ name = (a["company"] or a["id"])[:60]
284
+ out.append((f"exam:{a['id']}:{a['date']}:{a['days']}", f"{name} test {when}"))
285
+ return out
286
+
287
+
288
+ class Notifier:
289
+ """Notifications through `send(text)` (the tray): the daily notes and each job's end."""
290
+
291
+ def __init__(self, app, send):
292
+ self.app, self.send = app, send
293
+
294
+ def daily(self, now: datetime | None = None) -> None:
295
+ from keepfold.events import local_day
296
+ if self.app.entry() is None: # no vault yet
297
+ return
298
+ now = now or datetime.now(UTC)
299
+ day = local_day(now)
300
+ sent = load_state().get("notified")
301
+ sent = sent if isinstance(sent, dict) else {}
302
+ new = [(k, text) for k, text in daily_notes(self.app.root, now) if k not in sent]
303
+ for _, text in new:
304
+ self.send(text)
305
+ if new:
306
+ keep = (date.fromisoformat(day) - timedelta(KEEP_DAYS)).isoformat()
307
+ save_state("notified", {**{k: v for k, v in sent.items()
308
+ if isinstance(v, str) and v >= keep},
309
+ **{k: day for k, _ in new}})
310
+
311
+ def loop(self, echo=print) -> None:
312
+ wait = FIRST_S
313
+ while not self.app.stop.wait(wait):
314
+ wait = EVERY_S
315
+ try:
316
+ self.daily()
317
+ except Exception as e: # noqa: BLE001 (the type only: a message could quote a page)
318
+ echo(f"Keepfold app: the notification check failed ({type(e).__name__})")
319
+
320
+ def job_ended(self, job) -> None:
321
+ """"<job> finished" or "<job> failed"; a cancelled job, or a background one whose result
322
+ is `quiet` (it found nothing to do), says nothing. Job names are the app's own words,
323
+ never a page's title."""
324
+ quiet = isinstance(job.result, dict) and job.result.get("quiet") is True
325
+ if job.cancelled.is_set() or quiet or not notify_settings()["jobs"]:
326
+ return
327
+ failed = job.error is not None or (
328
+ isinstance(job.result, dict) and job.result.get("ok") is False)
329
+ self.send(f"{job.name} {'failed' if failed else 'finished'}")
330
+
331
+
332
+ # ---- the window and the tray -----------------------------------------------------------------
333
+
334
+
335
+ def _shutting_down() -> bool: # tests replace this
336
+ """Windows is signing out or shutting down: the window must close, not hide."""
337
+ if sys.platform != "win32":
338
+ return False
339
+ import ctypes
340
+ return bool(ctypes.windll.user32.GetSystemMetrics(SM_SHUTTINGDOWN))
341
+
342
+
343
+ def _native(win, fn) -> bool:
344
+ """fn(form, control) on the GUI thread, given pywebview's WinForms form and its Edge WebView2
345
+ control; False, with nothing run, for another backend or a window already gone."""
346
+ form = getattr(win, "native", None)
347
+ control = getattr(getattr(form, "browser", None), "webview", None)
348
+ if not hasattr(type(control), "CoreWebView2"): # its value: only on the GUI thread
349
+ return False
350
+ try:
351
+ from System import Func, Type # pythonnet: pywebview's WinForms backend loaded it
352
+ form.Invoke(Func[Type](lambda: fn(form, control)))
353
+ return True
354
+ except Exception: # noqa: BLE001 (closing at Quit; pythonnet's errors)
355
+ traceback.print_exc(limit=1)
356
+ return False
357
+
358
+
359
+ def _hide(form, control) -> None:
360
+ # WinForms' Hide alone leaves WebView2's page visible (document.hidden false: its 3D brain
361
+ # and polls ran on, docs/benchmarks/memory.md); hiding the control while the form is still
362
+ # shown sets the WebView2 IsVisible false, so the page knows and can sleep
363
+ control.Visible = False
364
+ form.Hide()
365
+
366
+
367
+ def _show(form, control) -> None:
368
+ form.Show()
369
+ control.Visible = True # IsVisible again: a sleeping page wakes
370
+ form.Activate()
371
+
372
+
373
+ def _show_box(form, control) -> None:
374
+ """The quick-capture box: kept out of the taskbar (a tool window, set while hidden, so
375
+ the form keeps its handle and its WebView2), centred on the monitor with the mouse, a
376
+ third of the way down, then shown and focused."""
377
+ import ctypes
378
+
379
+ from System.Drawing import Point # pythonnet, loaded by pywebview's WinForms backend
380
+ from System.Windows.Forms import Cursor, Screen
381
+ if not form.Visible:
382
+ u, hwnd = ctypes.windll.user32, ctypes.c_void_p(form.Handle.ToInt64())
383
+ u.SetWindowLongW(hwnd, GWL_EXSTYLE, u.GetWindowLongW(hwnd, GWL_EXSTYLE)
384
+ | WS_EX_TOOLWINDOW)
385
+ area = Screen.FromPoint(Cursor.Position).WorkingArea
386
+ form.Location = Point(area.X + (area.Width - form.Width) // 2,
387
+ area.Y + area.Height // 3 - form.Height // 2)
388
+ _show(form, control)
389
+ control.Focus()
390
+
391
+
392
+ def _sleep(form, control) -> None:
393
+ if not form.Visible and control.CoreWebView2 is not None: # still hidden, WebView2 ready
394
+ control.CoreWebView2.TrySuspendAsync()
395
+
396
+
397
+ class Desktop:
398
+ """One running app's window and tray icon (threads: see the module doc)."""
399
+
400
+ def __init__(self, app, url: str):
401
+ self.app, self.url = app, url
402
+ self.win = self.tray = None
403
+ self.box = None # the quick-capture box: a second window, made once, shown and hidden
404
+ self.hotkey: Hotkey | None = None
405
+ self.quitting, self.state = False, "normal" # normal | minimized | maximized
406
+ self.fresh = False # started hidden and never shown: the first show loads start_url
407
+
408
+ def show(self) -> bool:
409
+ """Bring the window up (Open Keepfold, a second launch); with no window, the browser.
410
+ The page is the one for now (server.start_url: Tonight in the evening) in a new tab or
411
+ on the first show after a hidden start; a window already seen keeps its page."""
412
+ if self.win is None:
413
+ server._open(server.start_url(self.app))
414
+ return True
415
+ if self.fresh:
416
+ self.fresh = False
417
+ self.win.load_url(server.start_url(self.app))
418
+ if not _native(self.win, _show):
419
+ self.win.show()
420
+ if self.state == "minimized":
421
+ self.win.restore()
422
+ return True
423
+
424
+ def closing(self) -> bool:
425
+ """The window's X (pywebview's closing event; False cancels the close): remember its
426
+ place and hide it, Keepfold stays in the tray. Quit, a shutdown or no tray closes it."""
427
+ if self.state == "normal":
428
+ try:
429
+ w = self.win
430
+ save_state("window", {"width": w.width, "height": w.height, "x": w.x, "y": w.y})
431
+ except Exception: # noqa: BLE001 (a place not remembered never blocks closing)
432
+ traceback.print_exc(limit=1)
433
+ if self.quitting or self.tray is None or _shutting_down():
434
+ return True
435
+ self.app.lock() # the Private switch relocks when the window goes to the tray
436
+ # hidden from another thread: this handler runs on the GUI thread inside FormClosing
437
+ threading.Thread(target=self.hide, daemon=True, name="keepfold-hide").start()
438
+ return False
439
+
440
+ def hide(self) -> None:
441
+ """To the tray; SLEEP_S later, still there, its page sleeps: WebView2 pauses its
442
+ timers and animations and lets Windows take the renderer's memory back, and wakes it
443
+ when the window shows."""
444
+ if _native(self.win, _hide):
445
+ self.sleep_later()
446
+ else:
447
+ self.win.hide()
448
+
449
+ def capture(self) -> bool:
450
+ """The hotkey or the tray's Quick capture: show the box, its input focused."""
451
+ if self.box is None:
452
+ return False
453
+ if not _native(self.box, _show_box):
454
+ self.box.show()
455
+ return True
456
+
457
+ def hide_box(self) -> bool:
458
+ """Esc, Enter's saved line or the box losing focus: hide it (its text stays); SLEEP_S
459
+ later, still hidden, its page sleeps as the main window's does."""
460
+ if self.box is None:
461
+ return False
462
+ if _native(self.box, _hide):
463
+ self.sleep_later(self.box)
464
+ else:
465
+ self.box.hide()
466
+ return True
467
+
468
+ def box_closing(self) -> bool:
469
+ """Alt+F4 on the box hides it; only Quit closes it."""
470
+ if self.quitting:
471
+ return True
472
+ threading.Thread(target=self.hide_box, daemon=True, name="keepfold-hide").start()
473
+ return False
474
+
475
+ def capture_label(self) -> str:
476
+ key = self.hotkey.label() if self.hotkey is not None else None
477
+ return f"Quick capture ({key})" if key else "Quick capture"
478
+
479
+ def change_hotkey(self) -> None:
480
+ """app.hotkey changed: register it again now, and the tray's text follows."""
481
+ if self.hotkey is not None:
482
+ self.hotkey.change()
483
+ self.refresh_tray()
484
+
485
+ def sleep_later(self, win=None) -> None:
486
+ """SLEEP_S from now, `win` (the main window by default, or the capture box) sleeps if
487
+ it is still hidden (`_sleep`); a show in between keeps it awake."""
488
+ w = win or self.win
489
+ t = threading.Timer(SLEEP_S, lambda: self.quitting or _native(w, _sleep))
490
+ t.daemon = True
491
+ t.start()
492
+
493
+ def minimized(self) -> None:
494
+ self.state = "minimized"
495
+ self.app.lock() # the Private switch relocks when the window is minimised
496
+
497
+ def end(self) -> None:
498
+ """keepfold-end: once the app stops, close the window (that ends `webview.start`)."""
499
+ self.app.stop.wait()
500
+ self.quitting = True
501
+ if self.hotkey is not None:
502
+ self.hotkey.stop() # WM_QUIT: its thread unregisters the key
503
+ for w in (self.box, self.win): # the main window last: that ends webview.start
504
+ if w is None:
505
+ continue
506
+ try:
507
+ w.events.shown.wait(30) # a window not yet started cannot be destroyed
508
+ w.destroy()
509
+ except Exception: # noqa: BLE001 (already gone)
510
+ traceback.print_exc(limit=1)
511
+
512
+ def quit(self) -> None:
513
+ self.app.quit({}) # cancels a running job and sets app.stop
514
+
515
+ def notify(self, text: str) -> None:
516
+ if self.tray is not None:
517
+ self.tray.notify(text, "Keepfold")
518
+
519
+ def toggle_autostart(self) -> None:
520
+ try:
521
+ set_autostart(not autostart_state()["enabled"])
522
+ except (OSError, ValueError) as e:
523
+ self.notify(str(e)[:200])
524
+ self.refresh_tray()
525
+
526
+ def refresh_tray(self) -> None:
527
+ if self.tray is not None:
528
+ self.tray.update_menu()
529
+
530
+
531
+ LETTER_K = ("#...#", "#..#.", "#.#..", "##...", "#.#..", "#..#.", "#...#")
532
+ SMALL = 32 # up to this size the dots are whole-pixel squares, so the K stays crisp
533
+
534
+
535
+ def mark(size: int):
536
+ """The Keepfold logo at `size` px (Pillow, already a dependency): a dark rounded square with
537
+ an amber dot-matrix K, as the KEEPFOLD wordmark draws it. The tray, the window, the
538
+ shortcuts and Keepfold.exe all use it (scripts/make_icon.py writes assets/keepfold.ico)."""
539
+ from PIL import Image, ImageDraw
540
+ k = 1 if size <= SMALL else 4 # round dots are drawn at 4x and scaled down
541
+ n = size * k
542
+ img = Image.new("RGBA", (n, n), (0, 0, 0, 0))
543
+ draw = ImageDraw.Draw(img)
544
+ m = round(size * 0.06) * k
545
+ side = n - 2 * m
546
+ draw.rounded_rectangle((m, m, n - m - 1, n - m - 1), radius=round(side * 0.22), fill=GROUND)
547
+ rows, cols = len(LETTER_K), len(LETTER_K[0])
548
+ if k == 1: # whole pixels
549
+ pitch = max(1, round(side * 0.6 / rows))
550
+ x0, y0 = (n - cols * pitch) // 2, (n - rows * pitch) // 2
551
+ else:
552
+ pitch = side * 0.6 / rows
553
+ x0, y0 = (n - cols * pitch) / 2, (n - rows * pitch) / 2
554
+ gap = pitch * 0.1 # round dots are 80% of the pitch
555
+ for r, line in enumerate(LETTER_K):
556
+ for c, cell in enumerate(line):
557
+ if cell != "#":
558
+ continue
559
+ x, y = x0 + c * pitch, y0 + r * pitch
560
+ if k == 1:
561
+ draw.rectangle((x, y, x + pitch - 1, y + pitch - 1), fill=AMBER)
562
+ else:
563
+ draw.ellipse((x + gap, y + gap, x + pitch - gap, y + pitch - gap), fill=AMBER)
564
+ return img if k == 1 else img.resize((size, size), Image.LANCZOS)
565
+
566
+
567
+ def _icon_image():
568
+ """The tray icon: the logo at 64 px."""
569
+ return mark(64)
570
+
571
+
572
+ def _tray(d: Desktop):
573
+ """The tray icon on its own thread; a left click is Open Keepfold."""
574
+ import pystray
575
+ item = pystray.MenuItem
576
+ icon = pystray.Icon("keepfold", _icon_image(), "Keepfold", pystray.Menu(
577
+ item("Open Keepfold", lambda: d.show(), default=True),
578
+ item(lambda _: d.capture_label(), lambda: d.capture()),
579
+ item("Start with Windows", lambda: d.toggle_autostart(),
580
+ checked=lambda _: autostart_state()["enabled"]),
581
+ pystray.Menu.SEPARATOR,
582
+ item("Quit", lambda: d.quit())))
583
+ threading.Thread(target=icon.run, daemon=True, name="keepfold-tray").start()
584
+ return icon
585
+
586
+
587
+ def _webview():
588
+ """pywebview drawing with Edge WebView2, or an exception that says why not."""
589
+ import webview
590
+ if sys.platform == "win32": # webview.guilib is None until start(); initialize() is reused
591
+ if webview.initialize().renderer != "edgechromium": # MSHTML cannot run the app page
592
+ raise RuntimeError("the Microsoft Edge WebView2 Runtime is not installed")
593
+ return webview
594
+
595
+
596
+ def _geometry(webview) -> dict:
597
+ """The remembered size, and place while it is still on a screen (a monitor may be gone)."""
598
+ w = load_state().get("window")
599
+ out = {"width": SIZE[0], "height": SIZE[1]}
600
+ try:
601
+ width, height, x, y = (int(w[k]) for k in ("width", "height", "x", "y"))
602
+ except (KeyError, TypeError, ValueError):
603
+ return out
604
+ if width >= MIN_SIZE[0] and height >= MIN_SIZE[1]:
605
+ out.update(width=width, height=height)
606
+ if any(s.x <= x < s.x + s.width - 100 and s.y <= y < s.y + s.height - 100
607
+ for s in webview.screens):
608
+ out.update(x=x, y=y)
609
+ return out
610
+
611
+
612
+ def run(root: Path | None, *, hidden: bool = False, port: int = 0, echo=print) -> None:
613
+ """The desktop app until Quit; `hidden` starts it in the tray (Start with Windows). With no
614
+ window possible, the browser app as `keepfold app` runs it (nothing when hidden)."""
615
+ try:
616
+ webview = _webview()
617
+ except Exception as e: # noqa: BLE001 (ImportError, pythonnet's errors, no WebView2)
618
+ echo(f"Keepfold app: no app window ({type(e).__name__}: {e}); using the browser")
619
+ if not hidden: # at login: no browser tab nobody asked for
620
+ server.run(root, port=port, echo=echo)
621
+ return
622
+ # before any window: the taskbar shows and pins Keepfold, not Python
623
+ if sys.platform == "win32":
624
+ import ctypes
625
+ ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(APP_ID)
626
+ srv, app, url = server.start(root, port=port, echo=echo, idle=False)
627
+ d = app.desktop = Desktop(app, url)
628
+ d.fresh = hidden
629
+ threading.Thread(target=srv.serve_forever, kwargs={"poll_interval": 0.5}, daemon=True,
630
+ name="keepfold-app-http").start()
631
+ try:
632
+ d.tray = _tray(d)
633
+ except Exception as e: # noqa: BLE001 (no tray: closing the window quits)
634
+ echo(f"Keepfold app: no tray icon ({type(e).__name__}: {e})")
635
+ notes = Notifier(app, d.notify)
636
+ app.jobs.on_end = notes.job_ended
637
+ threading.Thread(target=notes.loop, args=(echo,), daemon=True, name="keepfold-notify").start()
638
+ first_run(echo)
639
+ echo(f"Keepfold app: {url.split('?')[0]}") # never the key (?t=): stdout may be a shared log
640
+ echo("Closing the window keeps Keepfold in the tray; Quit there stops it.")
641
+ try:
642
+ d.win = webview.create_window("Keepfold", url, hidden=hidden, min_size=MIN_SIZE,
643
+ background_color=GROUND, **_geometry(webview))
644
+ ev = d.win.events
645
+ ev.closing += d.closing
646
+ ev.minimized += d.minimized
647
+ ev.maximized += lambda: setattr(d, "state", "maximized")
648
+ ev.restored += lambda: setattr(d, "state", "normal")
649
+ parts = urlsplit(url) # quick capture's box: made now, hidden, shown by the hotkey
650
+ d.box = webview.create_window(
651
+ "Quick capture", f"{parts.scheme}://{parts.netloc}/capture?t={app.token}",
652
+ hidden=True, frameless=True, on_top=True, resizable=False, width=BOX[0],
653
+ height=BOX[1], background_color=GROUND)
654
+ d.box.events.closing += d.box_closing
655
+ d.sleep_later(d.box) # hidden until the first press: no awake renderer meanwhile
656
+ if sys.platform == "win32":
657
+ d.hotkey = Hotkey(d.capture)
658
+ d.hotkey.start()
659
+ d.refresh_tray() # its Quick capture text names the key
660
+ if hidden: # Start with Windows: the page sleeps until the window is first opened
661
+ d.sleep_later()
662
+ threading.Thread(target=d.end, daemon=True, name="keepfold-end").start()
663
+ webview.start(icon=str(ICON)) # blocks this (main) thread until the window is destroyed
664
+ except Exception as e: # noqa: BLE001 (WebView2 failed to start: the page in the browser)
665
+ echo(f"Keepfold app: the window failed ({type(e).__name__}: {e}); using the browser")
666
+ d.win = None
667
+ if not hidden:
668
+ d.show()
669
+ app.stop.wait() # the tray's Open Keepfold now opens the browser
670
+ finally:
671
+ app.stop.set()
672
+ if d.hotkey is not None:
673
+ d.hotkey.stop()
674
+ srv.shutdown()
675
+ if d.tray is not None:
676
+ d.tray.stop()
677
+ server.finish(srv, app)