-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquicknotes.py
More file actions
4139 lines (3739 loc) · 182 KB
/
quicknotes.py
File metadata and controls
4139 lines (3739 loc) · 182 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Quick Notes, Shift+F7
Simplenote-inspired: two-column, flat, minimal.
Left , searchable list of saved notes
Right, editor (text / checklist / voice)
"""
import logging
import sys
import threading
import time
import tkinter as tk
import uuid
from datetime import datetime, timedelta
from typing import Callable
import customtkinter as ctk
import numpy as np
from theme import (
FONT_FAMILY,
OK, WARN, ERR,
)
from storage import load_notes, save_notes, save_notes_coalesced
from dialogs import PopupMenu, confirm, alert
logger = logging.getLogger(__name__)
SAMPLE_RATE = 16_000
_MAX_REC_S = 180 # 3-min hard cap on voice recording
_MAX_RENDERED = 250 # max note rows rendered in list (virtual perf cap)
_W, _H = 1216, 796 # window size, matches Claude desktop app
_LIST_W = 300 # left panel fixed width
# Chat-kind notes (Shift+F4 follow-ups) use the existing
# provider.refine() single-call API; the conversation is packed into
# the user text with "[YOU]" / "[ASSISTANT]" labels. The system prompt
# below is intentionally hard-handed: weaker phrasing made the model
# autocomplete the transcript and hallucinate dozens of fake turns of
# both sides. Marker tokens use [YOU] / [ASSISTANT] (square-bracket
# style) rather than "User:" / "Assistant:" so the input looks less
# like a transcript completion prompt to the underlying LLM.
_CHAT_SYSTEM_PROMPT = (
'CRITICAL OUTPUT RULES — read carefully:\n'
'\n'
'The user message contains a multi-turn conversation transcript '
'where each turn is prefixed by [YOU] or [ASSISTANT]. The LAST line '
'prefixed [YOU] is the user\'s CURRENT question. Every earlier '
'turn is just CONTEXT.\n'
'\n'
'1. Output ONLY your reply to the final [YOU] line.\n'
'2. NEVER prefix your reply with "Assistant:", "[ASSISTANT]", '
'or any role label. The reply text starts directly.\n'
'3. NEVER invent additional turns. Do not write "User:" or "[YOU]" '
'or pretend the user asked anything else.\n'
'4. NEVER continue the transcript past your single reply.\n'
'5. Answer concisely — two or three plain-text sentences. No '
'markdown, no bullet points, no caveats, no conversational filler.\n'
'\n'
'If you produce a transcript continuation, role labels, or '
'multiple turns, you have failed the task.'
)
# Patterns the model still sometimes leaks into the start of its reply
# despite the rules above. We strip them defensively so the user never
# sees "Assistant: ..." prefixes.
_LEADING_LABEL_RE = None # lazily compiled below
def _clean_chat_reply(text: str) -> str:
"""Strip any leading role label and cut off hallucinated transcript
continuation. Keeps only the model's reply to the LAST user turn.
Defensive layer on top of _CHAT_SYSTEM_PROMPT — even with a strong
prompt, smaller / cheaper LLMs sometimes leak a leading
"Assistant: " or invent extra "User: ..." turns. We chop both.
"""
import re
global _LEADING_LABEL_RE
if _LEADING_LABEL_RE is None:
_LEADING_LABEL_RE = re.compile(
r'^\s*(\[?(assistant|ai|model|bot)\]?\s*[:\-]?\s*)',
re.IGNORECASE)
out = text or ''
# 1. Strip leading role label.
out = _LEADING_LABEL_RE.sub('', out, count=1)
# 2. If the model hallucinated a "User:" / "[YOU]" continuation,
# cut everything from that marker onward — that's our cue.
cut_markers = ('\n[YOU]', '\nUser:', '\n[USER]', '\nuser:',
'\nYou:', '\nQ:', '\n>>> ', '\nUSER:')
earliest = len(out)
for m in cut_markers:
idx = out.find(m)
if idx != -1 and idx < earliest:
earliest = idx
out = out[:earliest].rstrip()
return out
# ── Palette, left panel follows app theme; editor stays dark/neutral ─────────
_WIN = '#0e0e0e' # outermost bg (app BG)
_LIST = '#141414' # left panel bg (app SURFACE)
_EDIT = '#1a1a1a' # right editor bg
_DIV = '#2a2a2a' # dividers (app BORDER)
_HOVER = '#1e1e1e' # row hover (app SURF2)
_SEL_BG = '#20163a' # selected row (accent-tinted dark)
_SRCH = '#1e1e1e' # search bar bg (app SURF2)
# App accent colours (match theme.py)
_ACCENT = '#7c3aed' # primary purple
_ACCENTL = '#9f67fa' # light purple (pill text)
_SURF2 = '#1e1e1e' # pill bg
_SURF3 = '#282828' # pressed/active bg
_SEL_EM = _ACCENT # star/pin accent
# Text
_T1 = '#f0f0f0' # primary text (app TEXT_P)
_T2 = '#909090' # secondary (app TEXT_S)
_T3 = '#606060' # dim / timestamps (app TEXT_D)
# Status
_ERR = '#ef4444'
_OK_C = '#22c55e'
_WARN_C = '#f59e0b'
_BLUE = '#60a5fa'
# Active font family, switched to monospace in light mode
_ACTIVE_FF = FONT_FAMILY # updated by _set_theme
# ── Palette presets (for light/dark theme switching) ─────────────────────────
_DARK_PALETTE = dict(
_WIN='#0e0e0e', _LIST='#141414', _EDIT='#1a1a1a',
_DIV='#2a2a2a', _HOVER='#1e1e1e', _SEL_BG='#20163a',
_SRCH='#1e1e1e', _SURF2='#1e1e1e', _SURF3='#282828',
_T1='#f0f0f0', _T2='#909090', _T3='#606060',
_ACTIVE_FF=FONT_FAMILY,
)
_LIGHT_PALETTE = dict(
_WIN='#ffffff', _LIST='#f7f7f7', _EDIT='#ffffff',
_DIV='#e0e0e0', _HOVER='#f0f0f0', _SEL_BG='#ede9fe',
_SRCH='#ebebeb', _SURF2='#ebebeb', _SURF3='#e5e5e5',
_T1='#111111', _T2='#555555', _T3='#999999',
_ACTIVE_FF='Consolas',
)
# ── Color label palette (chip_hex, border_hex, name) ─────────────────────────
NOTE_COLORS = [
(None, None, 'None'),
('#a78bfa', '#7c3aed', 'Purple'),
('#60a5fa', '#2563eb', 'Blue'),
('#4ade80', '#16a34a', 'Green'),
('#f87171', '#dc2626', 'Red'),
('#fbbf24', '#d97706', 'Amber'),
]
# ── Helpers ───────────────────────────────────────────────────────────────────
def _normalize_paste(text: str) -> str:
"""Strip heavy formatting from pasted text, plain body text only.
Handles clipboard content from Word, Google Docs, web pages, etc.:
• Normalise line endings (\r\n / \r → \n)
• Line/paragraph separators (U+2028/2029 → \n)
• Remove invisible/zero-width characters
• Non-breaking & narrow spaces → regular space
• Soft hyphen → remove
• Straighten smart / curly quotes
• Collapse runs of 3+ blank lines to a single blank line
"""
import re
# Line endings
text = text.replace('\r\n', '\n').replace('\r', '\n')
text = text.replace('
', '\n').replace('
', '\n')
# Invisible / zero-width characters
for ch in ('', '', '', '', '', ''):
text = text.replace(ch, '')
# Non-breaking and other whitespace-like spaces → regular space
for ch in (' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' '):
text = text.replace(ch, ' ')
# Smart / curly quotes → straight
text = text.replace('‘', "'").replace('’', "'") # ' '
text = text.replace('“', '"').replace('”', '"') # " "
text = text.replace('‚', ',').replace('„', '"') # ‚ „
text = text.replace('‹', '<').replace('›', '>') # ‹ ›
text = text.replace('«', '"').replace('»', '"') # « »
# Collapse 3+ consecutive blank lines → one blank line
text = re.sub(r'\n{3,}', '\n\n', text)
return text
def _rel_time(iso: str) -> str:
try:
dt = datetime.fromisoformat(iso)
d = datetime.now() - dt
if d < timedelta(minutes=1): return 'now'
if d < timedelta(hours=1): return f'{int(d.total_seconds()//60)}m'
if d < timedelta(days=1): return f'{int(d.total_seconds()//3600)}h'
if d < timedelta(days=7): return dt.strftime('%a')
return dt.strftime('%b %d')
except Exception:
return ''
def _word_count(text: str) -> str:
n = len(text.split())
return f'{n}w' if n else ''
def _note_kind(note: dict) -> str:
"""'chat' for chat-kind notes (Shift+F4 Ask follow-ups), else 'text'.
Legacy notes without the `kind` field default to 'text', so existing
data continues to render and save through the original code path."""
return 'chat' if note.get('kind') == 'chat' else 'text'
def _chat_title_from_messages(messages: list, fallback: str = 'New chat') -> str:
"""First non-empty user message becomes the auto-title for a chat
note. Truncated to keep list rows tidy."""
for m in messages or []:
if m.get('role') == 'user':
c = (m.get('content') or '').strip()
if c:
return c[:80]
return fallback
def _note_title(note: dict) -> str:
# Chat-kind: prefer the explicit (editable) title, fall back to the
# first user message. We do NOT mix in the text-note fallbacks
# because a chat note has its own fields.
if _note_kind(note) == 'chat':
t = (note.get('title') or '').strip()
if t:
return t[:48]
derived = _chat_title_from_messages(note.get('messages', []),
fallback='')
return derived[:48] if derived else '(new chat)'
# Text notes: prefer text first line, then checklist, then voice
raw = note.get('text', '').strip()
if raw:
lines = [l.strip() for l in raw.splitlines() if l.strip()]
if lines:
return lines[0][:48]
items = note.get('items', [])
if items and items[0].get('text'):
return items[0]['text'][:48]
voice = note.get('voice', '').strip()
if voice:
return voice[:48]
return '(new note)'
def _note_preview(note: dict) -> str:
# Chat-kind: last AI line (so the list shows what the chat is about).
if _note_kind(note) == 'chat':
msgs = note.get('messages', [])
for m in reversed(msgs):
if m.get('role') == 'assistant':
c = (m.get('content') or '').strip()
if c:
return c.splitlines()[0][:58]
n = sum(1 for m in msgs if m.get('content'))
return f'{n} message(s)' if n else 'New chat'
# Text notes: text body → checklist count → voice snippet
raw = note.get('text', '').strip()
if raw:
lines = [l.strip() for l in raw.splitlines() if l.strip()]
return lines[1][:58] if len(lines) > 1 else ''
items = note.get('items', [])
if items:
done = sum(1 for it in items if it.get('checked'))
return f'{done}/{len(items)} done'
voice = note.get('voice', '').strip()
if voice:
lines = voice.splitlines()
return lines[0][:58] if lines else ''
return ''
def _split_text(text: str) -> tuple[str, str]:
"""Split stored text into (title_line, body_rest)."""
if not text:
return '', ''
idx = text.find('\n')
if idx == -1:
return text.strip(), ''
return text[:idx].strip(), text[idx + 1:]
def _attach_tooltip(widget, text: str, delay_ms: int = 500) -> None:
_job = [None]
_tip = [None]
def _show():
_job[0] = None
if _tip[0] is not None or not widget.winfo_exists():
return
x = widget.winfo_rootx() + widget.winfo_width() // 2
y = widget.winfo_rooty() + widget.winfo_height() + 4
win = tk.Toplevel(widget)
win.overrideredirect(True)
win.attributes('-topmost', True)
win.configure(bg='#1a1a1a')
tk.Label(win, text=text, bg='#1a1a1a', fg='#b0b0b0',
font=(FONT_FAMILY, 9), padx=6, pady=2).pack()
win.update_idletasks()
sw = widget.winfo_screenwidth()
w = win.winfo_width()
if x + w > sw - 8:
x = sw - w - 8
win.geometry(f'+{x}+{y}')
_tip[0] = win
def _hide():
if _job[0] is not None:
try: widget.after_cancel(_job[0])
except Exception: pass
_job[0] = None
if _tip[0] is not None:
try: _tip[0].destroy()
except Exception: pass
_tip[0] = None
def _on_enter(e):
_hide()
_job[0] = widget.after(delay_ms, _show)
widget.bind('<Enter>', _on_enter, add='+')
widget.bind('<Leave>', lambda e: _hide(), add='+')
widget.bind('<ButtonPress-1>', lambda e: _hide(), add='+')
# ── Checklist editor ──────────────────────────────────────────────────────────
class _ChecklistEditor(ctk.CTkFrame):
def __init__(self, parent, items=None, **kw):
kw.setdefault('fg_color', 'transparent')
super().__init__(parent, **kw)
self._rows: list[tuple] = []
self._items = list(items) if items else [{'text': '', 'checked': False}]
self._render()
def get_items(self) -> list[dict]:
for i, (_, vc, vt, _) in enumerate(self._rows):
if i < len(self._items):
self._items[i]['text'] = vt.get()
self._items[i]['checked'] = bool(vc.get())
return [it for it in self._items if it['text'].strip()]
def focus_last(self) -> None:
if self._rows:
self._rows[-1][3].focus_set()
def _render(self) -> None:
for w in self.winfo_children():
w.destroy()
self._rows = []
for i, item in enumerate(self._items):
self._make_row(i, item)
self._make_add_btn()
def _make_row(self, idx: int, item: dict) -> None:
row = ctk.CTkFrame(self, fg_color='transparent')
row.pack(fill='x', pady=1)
row.columnconfigure(1, weight=1)
vc = tk.BooleanVar(value=bool(item.get('checked', False)))
cb = ctk.CTkCheckBox(
row, text='', variable=vc,
checkbox_width=15, checkbox_height=15, corner_radius=7,
fg_color=_BLUE, hover_color='#5a8adc', border_color='#404040',
command=lambda i=idx, v=vc: self._on_check(i, v.get()),
)
cb.grid(row=0, column=0, padx=(2, 8))
vt = tk.StringVar(value=item.get('text', ''))
entry = ctk.CTkEntry(
row, textvariable=vt,
font=(FONT_FAMILY, 13), fg_color='transparent',
border_width=0,
text_color=_T3 if item.get('checked') else _T1,
)
entry.grid(row=0, column=1, sticky='ew', padx=(0, 4))
entry.bind('<Return>', lambda e, i=idx: self._enter(i))
entry.bind('<BackSpace>', lambda e, i=idx: self._backspace(i))
self._rows.append((row, vc, vt, entry))
def _make_add_btn(self) -> None:
ctk.CTkButton(
self, text='+ Add item', width=90, height=22,
fg_color='transparent', hover_color=_HOVER,
text_color=_T3, font=(FONT_FAMILY, 11), corner_radius=3,
command=self._add_item,
).pack(anchor='w', pady=(4, 0))
def _flush(self) -> None:
for i, (_, vc, vt, _) in enumerate(self._rows):
if i < len(self._items):
self._items[i]['text'] = vt.get()
self._items[i]['checked'] = bool(vc.get())
def _on_check(self, idx: int, checked: bool) -> None:
if idx < len(self._items): self._items[idx]['checked'] = checked
if idx < len(self._rows):
self._rows[idx][3].configure(text_color=_T3 if checked else _T1)
def _enter(self, idx: int) -> None:
self._flush()
self._items.insert(idx + 1, {'text': '', 'checked': False})
self._render()
if idx + 1 < len(self._rows):
self._rows[idx + 1][3].focus_set()
def _backspace(self, idx: int) -> None:
_, _, vt, _ = self._rows[idx]
if vt.get() == '' and len(self._items) > 1:
self._flush()
self._items.pop(idx)
self._render()
prev = max(0, idx - 1)
if prev < len(self._rows):
self._rows[prev][3].focus_set()
def _add_item(self) -> None:
self._flush()
self._items.append({'text': '', 'checked': False})
self._render()
self.focus_last()
# ── Main window ───────────────────────────────────────────────────────────────
class QuickNotesWindow(ctk.CTkToplevel):
def __init__(self, root: tk.Tk,
transcribe_fn: Callable | None = None,
on_close: Callable | None = None,
mic_busy_fn: Callable | None = None,
vision_extractor: Callable | None = None,
provider=None,
initial_geometry: str = '',
on_geometry_change: Callable | None = None,
initial_theme: str = 'light',
on_theme_change: Callable | None = None) -> None:
"""
mic_busy_fn , optional callable() -> bool; returns True when the main
Whisper recorder is active. Quick Notes won't record while it's True.
vision_extractor, optional callable(img) -> str; Groq vision API extractor.
provider , optional LLM provider with .refine(text, prompt) -> str.
"""
super().__init__(root)
self._transcribe_fn = transcribe_fn
self._provider = provider
self._on_close = on_close
self._mic_busy_fn = mic_busy_fn
self._vision_extractor = vision_extractor
self._on_geometry_change = on_geometry_change
self._on_theme_change = on_theme_change
self._initial_geometry = initial_geometry
# Editor state
self._mode = 'text'
self._color = None
self._pinned = False
self._text_content = ''
self._checklist_items = [{'text': '', 'checked': False}]
self._voice_transcript = ''
self._editing_nid: str | None = None # nid of note open in editor, or None for new
self._prev_note_nid: str | None = None # nid of note open before current (for swipe-back)
# ── Chat-kind notes (Shift+F4 follow-ups) ─────────────────────────────
# Chat state is fully isolated from text-note state above:
# nothing in the text-note code path touches these, and the
# chat code path never touches the text-note fields. Lets us
# keep the rest of Quick Notes' editor untouched.
self._chat_messages: list = [] # [{role,content}, ...]
self._chat_title: str = '' # editable, derived from msg[0] if blank
self._chat_inflight_gen: int = 0 # bump → drop stale completions
# Reuse the same LLM provider the rest of Hotkeys uses; falls
# back to None when launched without one (chat send will then
# render an inline error instead of crashing).
self._chat_provider = provider
self._chat_pending: bool = False # "Working..." placeholder visible
# Debounced title save+refresh: cancel-and-reschedule pattern
# so the left list updates ~200ms after the user stops typing,
# not on every keystroke (which would hammer save_notes).
self._chat_title_save_after_id = None
# User-editable rendered transcript. Stored as the note's
# `text` field on disk so the user's edits persist; absent on
# newly created chats (then we render from messages instead).
self._chat_text_override: str = ''
self._chat_text_save_after_id = None
self._chat_text_render_in_progress = False
# Widget refs; cleared by _show_panel each rebuild.
self._chat_transcript = None
self._chat_input = None
self._chat_send_btn = None
self._chat_stop_btn = None
self._chat_title_var = None
# OCR state
self._ocr_pending = False
self._ocr_staged_img = None
self._ocr_status_visible = False
self._ocr_preview_visible = False
self._ocr_thumb_ref = None # PhotoImage GC guard
# Swipe gesture state
self._swipe_start_x = 0
self._swipe_start_y = 0
self._swipe_active = False
self._swipe_btn1_down = False # track L button ourselves (state flags unreliable)
self._swipe_btn3_down = False # track R button ourselves
self._swipe_just_completed = False # suppress spurious right-click after swipe
# Recording state
self._rec_state = 'idle'
self._rec_stream = None
self._rec_frames: list = []
self._rec_start = 0.0
self._pulse_job = None
# Gesture undo stack
self._gesture_undo_stack: list = []
# Window maximize state
self._maximized = False
self._restore_geo: str | None = None
# Drag
self._drag_ox = self._drag_oy = 0
# Search debounce
self._search_job = None
# Notes cache (avoids re-reading JSON on every keystroke)
self._notes_cache: list = []
self._notes_dirty = True
# Theme, apply saved palette to module globals before _build()
self._theme = initial_theme if initial_theme in ('light', 'dark') else 'light'
_palette = _LIGHT_PALETTE if self._theme == 'light' else _DARK_PALETTE
_mod = sys.modules[__name__]
for _k, _v in _palette.items():
setattr(_mod, _k, _v)
# Voice decide bar (inline recording confirmation)
self._voice_decide_bar = None
self._pending_audio = None
# Drag-and-drop state
self._note_drag_nid: str | None = None # note row being dragged to editor
self._drop_indicator = None # floating drop-target overlay
# Search placeholder tracking
self._srch_placeholder = True
self._selected_row_widgets: list = [] # widgets of currently selected note row
self._trash_expanded = False
# ── Window chrome ─────────────────────────────────────────────────────
# overrideredirect(True) gives us a borderless frame for the custom
# title bar, but on Windows it also hides the window from Alt+Tab
# and the taskbar by default, we restore both via WS_EX_APPWINDOW
# after the window is realised (see _enable_alt_tab below).
# We do NOT use -topmost: clicking another app must be able to put
# Notes in the background (Whiteboard behaves the same way).
self.withdraw()
self.overrideredirect(True)
self.title('Notes') # taskbar hover-preview + Alt+Tab caption
self.configure(fg_color=_WIN)
# Window icon + taskbar promotion handled in _enable_alt_tab()
# after deiconify(). Setting icon here (iconphoto/iconbitmap)
# silently no-ops on overrideredirect windows on Win32, and in
# one tried-and-failed iteration also interfered with the
# subsequent WS_EX_APPWINDOW transition.
self._build()
self._bind_keys()
# Centering and clamping use the Windows WORK AREA (screen minus
# taskbar), same helper the Whiteboard uses. The previous code
# used winfo_screenwidth/height which is the full monitor, so the
# bottom edge could end up behind the taskbar and the right edge
# could slide off-screen on multi-monitor setups.
from win_geometry import center_on_work_area, get_work_area
wa_x, wa_y, wa_w, wa_h = get_work_area()
self.update_idletasks()
if self._initial_geometry:
# Restore saved geometry, but clamp BOTH size and position to
# the WORK area. A saved width/height from an older version of
# this code (or a different monitor) could exceed the current
# work area; shrink it so the title bar and bottom edge always
# stay visible.
try:
# Parse the full WxH+X+Y from the saved string directly.
# We can't trust winfo_width()/winfo_x() here — the window
# is still withdrawn, so Tk reports its internal default
# frame size (~200x200) instead of the just-applied geo.
# That round-trip was clamping the real saved size down
# to ~200x200, which minsize(600,400) then bumped to the
# smallest legal window.
import re as _re
_full = _re.match(r'(\d+)x(\d+)([+-]\d+)([+-]\d+)',
self._initial_geometry)
if _full:
_sw, _sh = int(_full.group(1)), int(_full.group(2))
_sx, _sy = int(_full.group(3)), int(_full.group(4))
# Reject suspiciously tiny saves so we don't restore
# a useless minsize-shaped window forever.
if _sw < int(_W * 0.8) or _sh < int(_H * 0.8):
logger.info(
f'Quick Notes: ignoring tiny saved geometry '
f'({_sw}x{_sh}), falling back to default '
f'({_W}x{_H}) — likely an accidental resize.'
)
self._initial_geometry = ''
else:
# Clamp to the current monitor's work area using
# the parsed values, not winfo_*.
_sw = min(_sw, wa_w)
_sh = min(_sh, wa_h)
_sx = max(wa_x, min(_sx, wa_x + wa_w - _sw))
_sy = max(wa_y, min(_sy, wa_y + wa_h - _sh))
self.geometry(f'{_sw}x{_sh}+{_sx}+{_sy}')
else:
# Malformed save string — wipe so the default path runs.
self._initial_geometry = ''
except Exception:
self._initial_geometry = ''
if not self._initial_geometry:
# First-launch default: identical centering to the Whiteboard
# so users see the same layout for both Shift+F7 and Shift+F8.
# center_on_work_area shrinks the requested size if needed so
# the whole window always fits inside the work area, even on
# short monitors.
x, y, W, H = center_on_work_area(_W, _H)
self.geometry(f'{W}x{H}+{x}+{y}')
self.minsize(600, 400)
# Windows 11 rounded corners. Must target the OS top-level HWND;
# self.winfo_id() returns the inner child HWND for an
# overrideredirect window, and DwmSetWindowAttribute on the
# child silently no-ops (this is why the rounded corners never
# appeared). See win_helpers.top_level_hwnd().
try:
import ctypes as _ct
from win_helpers import top_level_hwnd
val = _ct.c_int(2)
_ct.windll.dwmapi.DwmSetWindowAttribute(
top_level_hwnd(self), 33, _ct.byref(val), _ct.sizeof(val))
except Exception:
pass
self.deiconify()
self.lift()
self._enable_native_resize()
# Promote the overrideredirect window into Alt+Tab + taskbar so
# the user can switch back after clicking another app. Has to
# happen after deiconify(), the HWND only exists once mapped.
self.after(60, self._enable_alt_tab)
self.after(80, self._focus_content)
# ── Build ─────────────────────────────────────────────────────────────────
def _build(self) -> None:
# Purple accent border (matches Shift+F8 Whiteboard's frame).
# The window is borderless (overrideredirect=True), so the border is
# drawn by an outer tk.Frame whose background is the accent color
# and which pads its inner content by 3px on every edge.
border = tk.Frame(self, bg=_ACCENT, highlightthickness=0)
border.pack(fill='both', expand=True)
outer = tk.Frame(border, bg=_WIN, highlightthickness=0)
outer.pack(fill='both', expand=True, padx=3, pady=3)
self._outer = outer # resize handles are placed inside this frame
# Left panel (note list)
left = tk.Frame(outer, bg=_LIST, width=_LIST_W)
left.pack(side='left', fill='y')
left.pack_propagate(False)
self._build_left(left)
# Vertical divider
tk.Frame(outer, bg=_DIV, width=1).pack(side='left', fill='y')
# Right panel (editor)
right = tk.Frame(outer, bg=_EDIT)
right.pack(side='left', fill='both', expand=True)
self._build_right(right)
# ── Left panel ────────────────────────────────────────────────────────────
def _build_left(self, parent) -> None:
# Header
hdr = tk.Frame(parent, bg=_LIST, height=44)
hdr.pack(fill='x')
hdr.pack_propagate(False)
hdr.bind('<ButtonPress-1>', self._drag_start)
hdr.bind('<B1-Motion>', self._drag_move)
hdr.bind('<Double-Button-1>', lambda e: self._toggle_maximize())
# Header label, app-style bold section title
lbl = tk.Label(hdr, text='Notes', bg=_LIST, fg=_T1,
font=(FONT_FAMILY, 13, 'bold'))
lbl.pack(side='left', padx=(14, 0), pady=12)
# Tk does NOT propagate <Double-Button-1> from a child Label to the
# parent Frame, so double-clicking right on the 'Notes' text would
# silently no-op. Re-bind drag + double-click on the label itself
# so the entire title bar feels like one consistent draggable /
# maximizable region (matches the native Win11 caption-bar UX).
lbl.bind('<ButtonPress-1>', self._drag_start)
lbl.bind('<B1-Motion>', self._drag_move)
lbl.bind('<Double-Button-1>', lambda e: self._toggle_maximize())
# New-note button, large, accent-filled, impossible to miss
nb = ctk.CTkButton(
hdr, text='+', width=32, height=32,
fg_color=_ACCENT, hover_color='#6d28d9',
text_color='#ffffff', font=(FONT_FAMILY, 15, 'bold'),
corner_radius=8, cursor='hand2',
anchor='center',
command=self._new_note,
)
nb.pack(side='right', padx=(0, 10), pady=6)
_attach_tooltip(nb, 'New note (saves current)')
# New-chat button, same size, sits just to the left of New-note.
# Creates a chat-kind note (Shift+F4 Ask-style follow-up thread).
cb = ctk.CTkButton(
hdr, text='💬', width=32, height=32,
fg_color=_SURF2, hover_color=_SURF3,
text_color=_T1, font=(FONT_FAMILY, 14),
corner_radius=8, cursor='hand2',
anchor='center',
command=self._new_chat,
)
cb.pack(side='right', padx=(0, 4), pady=6)
_attach_tooltip(cb, 'New chat (Ask-style follow-up thread)')
# Separator
tk.Frame(parent, bg=_DIV, height=1).pack(fill='x')
# Search bar, CTkEntry for rounded pill look
sf = tk.Frame(parent, bg=_LIST, pady=8, padx=10)
sf.pack(fill='x')
self._srch_entry = ctk.CTkEntry(
sf, height=28, corner_radius=6,
fg_color=_SRCH, border_color='#2a2a2a', border_width=1,
text_color=_T3, placeholder_text='Search notes…',
placeholder_text_color=_T3,
font=(FONT_FAMILY, 11),
)
self._srch_entry.pack(fill='x')
self._srch_entry.bind('<FocusIn>', self._srch_in)
self._srch_entry.bind('<FocusOut>', self._srch_out)
self._srch_entry.bind('<KeyRelease>', self._on_search_key)
# Separator
tk.Frame(parent, bg=_DIV, height=1).pack(fill='x')
# ── Small paste zone, just below search bar ────────────────────────
pz = tk.Frame(parent, bg=_LIST, height=26)
pz.pack(fill='x')
pz.pack_propagate(False)
pz_lbl = tk.Label(pz, text=' + Paste as note',
bg=_LIST, fg=_T3, font=(FONT_FAMILY, 9),
anchor='w', cursor='hand2')
pz_lbl.pack(fill='both', expand=True)
# Click on the label directly pastes; hover gives feedback
pz_lbl.bind('<Button-1>', self._paste_to_list)
pz_lbl.bind('<Enter>', lambda e: (pz_lbl.configure(fg=_T1), pz.configure(bg=_SURF3), pz_lbl.configure(bg=_SURF3)))
pz_lbl.bind('<Leave>', lambda e: (pz_lbl.configure(fg=_T3), pz.configure(bg=_LIST), pz_lbl.configure(bg=_LIST)))
for w in (pz, pz_lbl):
w.bind('<Button-3>', self._on_list_bg_rclick)
w.bind('<Control-v>', self._paste_to_list)
w.bind('<Control-V>', self._paste_to_list)
tk.Frame(parent, bg=_DIV, height=1).pack(fill='x')
# ── Trash toggle, bottom-pinned (36px, matches right-panel bottom bar) ─
self._trash_section = tk.Frame(parent, bg=_LIST, height=36)
self._trash_section.pack(side='bottom', fill='x')
self._trash_section.pack_propagate(False)
# Separator sits above the trash section, packed side='bottom' after the
# section so it appears just above it (same level as right-panel separator)
tk.Frame(parent, bg=_DIV, height=1).pack(side='bottom', fill='x')
self._trash_btn: tk.Label | None = None
# ── Scrollable note list (fills space above trash) ───────────────────
lf = tk.Frame(parent, bg=_LIST)
lf.pack(fill='both', expand=True)
self._list_canvas = tk.Canvas(lf, bg=_LIST, highlightthickness=0, bd=0)
self._list_canvas.pack(side='left', fill='both', expand=True)
# Focus canvas on click so it can receive Ctrl+V
self._list_canvas.bind('<Button-1>',
lambda e: self._list_canvas.focus_set(), add='+')
self._list_canvas.bind('<Control-v>', self._paste_to_list)
self._list_canvas.bind('<Control-V>', self._paste_to_list)
self._list_canvas.bind('<Button-3>', self._on_list_bg_rclick)
self._list_inner = tk.Frame(self._list_canvas, bg=_LIST)
self._list_win_id = self._list_canvas.create_window(
(0, 0), window=self._list_inner, anchor='nw')
self._list_inner.bind('<Configure>',
lambda e: self._list_canvas.configure(
scrollregion=self._list_canvas.bbox('all')))
self._list_inner.bind('<Button-3>', self._on_list_bg_rclick)
def _on_canvas_resize(e):
self._list_canvas.itemconfigure(self._list_win_id, width=e.width)
# Stretch inner frame to at least the canvas height so
# the empty area below notes is always right-clickable.
inner_h = self._list_inner.winfo_reqheight()
if inner_h < e.height:
self._list_canvas.itemconfigure(
self._list_win_id, height=e.height)
self._list_canvas.bind('<Configure>', _on_canvas_resize)
# Scroll routing: on Windows <MouseWheel> goes to the keyboard-focused widget,
# not the widget under the cursor. Intercept at the window level and forward
# to the canvas when the cursor is inside the list panel.
def _on_window_scroll(e):
try:
cx = self._list_canvas.winfo_rootx()
cy = self._list_canvas.winfo_rooty()
cw = self._list_canvas.winfo_width()
ch = self._list_canvas.winfo_height()
if cx <= e.x_root <= cx + cw and cy <= e.y_root <= cy + ch:
self._list_canvas.yview_scroll(int(-1 * (e.delta / 120)), 'units')
except Exception:
pass
# Bind at the toplevel, fires for every scroll anywhere in the window
self.bind('<MouseWheel>', _on_window_scroll, add='+')
# Dummy enter/leave stores (no-ops now, kept so _make_note_row doesn't break)
self._list_enter_fn = lambda e: None
self._list_leave_fn = lambda e: None
self._refresh_list()
def _srch_in(self, _=None) -> None:
# CTkEntry handles its own placeholder, just update text color on focus
try: self._srch_entry.configure(text_color=_T1)
except Exception: pass
def _srch_out(self, _=None) -> None:
try:
val = self._srch_entry.get().strip()
self._srch_entry.configure(text_color=_T1 if val else _T3)
except Exception: pass
def _get_search(self) -> str:
try:
val = self._srch_entry.get().strip()
return val.lower() if val else ''
except Exception:
return ''
def _invalidate_notes_cache(self) -> None:
"""Mark notes cache stale so next _refresh_list re-reads from disk."""
self._notes_dirty = True
def _rebuild_trash_section(self, trashed_notes: list) -> None:
"""Rebuild the bottom-pinned trash toggle (always visible, 36px)."""
for w in self._trash_section.winfo_children():
w.destroy()
arrow = '▾' if self._trash_expanded else '▸'
if trashed_notes:
label = f' {arrow} Trash ({len(trashed_notes)})'
fg = _T2
cursor = 'hand2'
else:
label = f' {arrow} Trash'
fg = _T3
cursor = 'arrow'
btn = tk.Label(
self._trash_section,
text=label, bg=_LIST, fg=fg,
font=(FONT_FAMILY, 10), cursor=cursor,
)
btn.pack(fill='both', expand=True)
if trashed_notes:
_toggle = lambda e: self._toggle_trash_section()
btn.bind('<Button-1>', _toggle)
self._trash_section.bind('<Button-1>', _toggle)
btn.bind('<Enter>', lambda e: btn.configure(fg=_T1))
btn.bind('<Leave>', lambda e: btn.configure(fg=_T2))
def _toggle_trash_section(self) -> None:
self._trash_expanded = not self._trash_expanded
self._refresh_list()
# ── Drag and drop ─────────────────────────────────────────────────────────
def _on_note_row_drag(self, event, nid: str) -> None:
"""Note row dragged rightward into editor → show open indicator."""
try:
abs_x = event.widget.winfo_rootx() + event.x
except Exception:
return
win_x = abs_x - self.winfo_rootx()
if win_x > _LIST_W + 30:
if self._note_drag_nid != nid:
self._note_drag_nid = nid
self._show_note_drag_indicator(nid)
else:
if self._note_drag_nid is not None:
self._note_drag_nid = None
self._hide_note_drag_indicator()
def _on_window_mouse_release(self, event) -> None:
"""Complete note-row drag to editor on mouse release."""
if self._note_drag_nid is not None:
nid = self._note_drag_nid
self._note_drag_nid = None
self._hide_note_drag_indicator()
rel_x = event.x_root - self.winfo_rootx()
if rel_x > _LIST_W + 10:
self._open_note(nid)
def _show_note_drag_indicator(self, nid: str) -> None:
"""Show a pill in the editor area indicating the note will be opened."""
try:
if self._drop_indicator is None or not self._drop_indicator.winfo_exists():
self._drop_indicator = tk.Label(
self._content_host,
text='↗ Open note',
bg=_ACCENT, fg='#ffffff',
font=(FONT_FAMILY, 11, 'bold'),
padx=12, pady=6,
)
self._drop_indicator.place(relx=0.5, rely=0.5, anchor='center')
self._drop_indicator.lift()
except Exception:
pass
def _hide_note_drag_indicator(self) -> None:
try:
if self._drop_indicator and self._drop_indicator.winfo_exists():
self._drop_indicator.place_forget()
except Exception:
pass
def _paste_to_list(self, event=None) -> str:
"""Ctrl+V on the list panel.
Two modes:
1. Clipboard has IMAGE → create empty note, open it, stage image
for OCR in the editor. The same _ocr_stage flow the editor's
own Ctrl+V uses, so user sees the image preview + Enter prompt.
2. Clipboard has TEXT → create note with that text (legacy behaviour).
Returns 'break' so the event doesn't propagate.
"""
# ── Mode 1: clipboard image → new note + OCR staging ─────────────────
try:
from vision import get_clipboard_image
img, err = get_clipboard_image()
if err:
logger.warning(f'Quick Notes: clipboard image read error: {err}')
elif img is not None:
# Create a fresh empty note and open it, then stage the image.
note = {
'id': str(uuid.uuid4()),
'text': '',
'items': [{'text': '', 'checked': False}],
'voice': '',
'color': None,
'pinned': False,
'created_at': datetime.now().isoformat(timespec='seconds'),
}
notes = load_notes()
notes.append(note)
save_notes(notes)
self._invalidate_notes_cache()
self._refresh_list()
# Open the new note for editing so _ocr_stage's preview/status
# lands in a visible context.
try:
self._open_note(note['id'])
except Exception as exc:
logger.warning(f'Quick Notes: open new note for OCR failed: {exc}')
# Stage the image for OCR on the next idle tick — the editor's
# widgets need to be mapped first.
try:
self.after_idle(lambda: self._ocr_stage(img))
except Exception as exc:
logger.warning(f'Quick Notes: schedule OCR stage failed: {exc}')
logger.info('Quick note created from clipboard image (OCR staged)')