-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtray_dialogs.py
More file actions
3350 lines (2941 loc) · 130 KB
/
tray_dialogs.py
File metadata and controls
3350 lines (2941 loc) · 130 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
"""Tray dialog classes — extracted from task_tray.py.
Contains:
- Theme system (_T, _fw, style builders)
- UI helper classes (_ClickableLabel, _TooltipCopyFilter, etc.)
- All dialog/popup classes (TrayPopup, EditTaskDialog, etc.)
- TaskListWidget helper utilities (_format_task_text, _apply_task_item_colors, etc.)
"""
import calendar as _cal_mod
import html as _html
import json
import logging
import os
import shutil
import sqlite3
import subprocess
import threading
import time
from datetime import date, datetime, timezone
from db_utils import (
PRIORITY_COLORS,
TASK_PRIORITIES,
TASK_SECTIONS as SECTIONS,
TaskDAO,
get_conn,
is_overdue,
now_iso,
priority_sort_key,
)
from PyQt6.QtWidgets import (
QApplication,
QWidget,
QVBoxLayout,
QHBoxLayout,
QLabel,
QCheckBox,
QLineEdit,
QTextEdit,
QPushButton,
QScrollArea,
QFrame,
QListWidget,
QListWidgetItem,
QDialog,
QFormLayout,
QComboBox,
QDialogButtonBox,
QDateEdit,
QCompleter,
QMessageBox,
QSpinBox,
QStyledItemDelegate,
QDateTimeEdit,
QFileDialog,
)
from PyQt6.QtGui import QColor, QDesktopServices, QFont, QPainter, QPixmap
from PyQt6.QtCore import (
QDate,
QDateTime,
QEvent,
QObject,
Qt,
QTimer,
QPoint,
QTime,
QUrl,
pyqtSignal,
)
logger = logging.getLogger("task_tray")
_DIALOG_OPEN_ERRORS = (RuntimeError, sqlite3.Error, OSError, ValueError)
_OPTIONAL_CONTEXT_ERRORS = (
ImportError,
sqlite3.Error,
OSError,
RuntimeError,
ValueError,
)
PRIORITIES = tuple(reversed(TASK_PRIORITIES)) # descending for UI display
# Upper-case priority colors for UI lookups
_PRIORITY_COLORS_UPPER = {k.upper(): v for k, v in PRIORITY_COLORS.items()}
_DEFAULT_PRIORITY_COLOR = "#718096"
# Entity type → badge color (shared between TaskReaderDialog + entity search cards)
_ENTITY_TYPE_COLORS = {
"concept": "#1a3a5c",
"tool": "#2d6a2e",
"person": "#8b4513",
"project": "#4a148c",
"technology": "#00695c",
"fact": "#555",
"claim": "#8b6914",
"process": "#2e4057",
}
_ENTITY_DEFAULT_COLOR = "#555"
# Columns needed by UI rendering (excludes parent_id, notes, assignee, shared_by, publish_requested_at)
_UI_COLS = "id, title, description, notes, status, section, priority, due_date, project, type, recurring, reminder_at, visibility, updated_at, created_at"
# Auto-refresh interval for TrayPopup and FullWindow refresh timers
_REFRESH_INTERVAL_MS = 30_000
# ── Clipboard helpers ────────────────────────────────────────────────
def _should_render_context_preview(pack_result) -> bool:
if not isinstance(pack_result, dict):
return False
if pack_result.get("items_included", 0) <= 0:
return False
if not (pack_result.get("body") or "").strip():
return False
return bool(pack_result.get("previewable", True))
_wl_copy_proc = None # Track wl-copy PID to prevent ghost windows
_HAS_WL_COPY = (
bool(os.environ.get("WAYLAND_DISPLAY")) and shutil.which("wl-copy") is not None
)
def _clipboard_write(text):
"""Write to clipboard. Wayland-aware with wl-copy fallback."""
global _wl_copy_proc
QApplication.clipboard().setText(text)
if _HAS_WL_COPY:
if _wl_copy_proc and _wl_copy_proc.poll() is None:
_wl_copy_proc.kill()
_wl_copy_proc.wait()
_wl_copy_proc = subprocess.Popen(
["wl-copy", "--", text],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
def _format_file_size(size: int | None) -> str:
"""Render a file size for compact attachment labels."""
value = max(0, int(size or 0))
units = ("B", "KB", "MB", "GB")
amount = float(value)
for unit in units:
if amount < 1024 or unit == units[-1]:
if unit == "B":
return f"{int(amount)} {unit}"
return f"{amount:.1f} {unit}"
amount /= 1024.0
return f"{value} B"
def create_tray_icon_pixmap(overdue_count=0):
"""Generate a 64x64 tray icon with optional overdue badge."""
pm = QPixmap(64, 64)
pm.fill(Qt.GlobalColor.transparent)
p = QPainter(pm)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
# Base: dark navy circle
p.setBrush(QColor("#1a2332"))
p.setPen(Qt.PenStyle.NoPen)
p.drawEllipse(4, 4, 56, 56)
# Checkmark
p.setPen(QColor("#ffffff"))
p.setFont(QFont("Segoe UI", 28, QFont.Weight.Bold))
p.drawText(pm.rect(), Qt.AlignmentFlag.AlignCenter, "\u2713")
# Overdue badge (red circle top-right)
if overdue_count > 0:
p.setBrush(QColor("#e53e3e"))
p.setPen(Qt.PenStyle.NoPen)
p.drawEllipse(38, 0, 26, 26)
p.setPen(QColor("#ffffff"))
p.setFont(QFont("Segoe UI", 12, QFont.Weight.Bold))
text = str(overdue_count) if overdue_count < 10 else "9+"
p.drawText(38, 0, 26, 26, Qt.AlignmentFlag.AlignCenter, text)
p.end()
return pm
# ── Theme System ─────────────────────────────────────────────────────
_THEMES = {
"black": {
"bg": "#000000",
"bg2": "#0a0a0a",
"bg3": "#1a1a1a",
"text": "#e2e8f0",
"text2": "#a0aec0",
"border": "#2d2d2d",
"accent": "#3182ce",
"accent_hover": "#4299e1",
"danger": "#e53e3e",
"done": "#38a169",
"note_bg": "#0d1a0d",
"overdue_bg": "#1a0000",
"overdue_fg": "#fc8181",
"header_bg": "#111111",
"urgent_bg": "#2d1a00",
"urgent_fg": "#f6ad55",
},
"blue": {
"bg": "#0f1923",
"bg2": "#1a2332",
"bg3": "#2d3748",
"text": "#e2e8f0",
"text2": "#a0aec0",
"border": "#4a5568",
"accent": "#3182ce",
"accent_hover": "#4299e1",
"danger": "#e53e3e",
"done": "#38a169",
"note_bg": "#1e2d3d",
"overdue_bg": "#291e26",
"overdue_fg": "#fc8181",
"header_bg": "#1e2836",
"urgent_bg": "#3b2c1c",
"urgent_fg": "#f6ad55",
},
"light": {
"bg": "#f7fafc",
"bg2": "#edf2f7",
"bg3": "#e2e8f0",
"text": "#1a202c",
"text2": "#4a5568",
"border": "#cbd5e0",
"accent": "#3182ce",
"accent_hover": "#2b6cb0",
"danger": "#e53e3e",
"done": "#38a169",
"note_bg": "#ebf8ff",
"overdue_bg": "#f5e4e5",
"overdue_fg": "#c53030",
"header_bg": "#e2e8f0",
"urgent_bg": "#fffbeb",
"urgent_fg": "#c05621",
},
}
_theme_name = "blue"
_font_size = 13
_bold = False
def _T():
"""Current theme palette."""
return _THEMES[_theme_name]
def _fw():
"""Current font-weight CSS value."""
return "bold" if _bold else "normal"
def _update_theme_colors():
"""Refresh module-level QColor variables from current theme."""
global _CLR_DONE, _CLR_NOTE_BG, _CLR_OVERDUE_BG, _CLR_OVERDUE_FG
global _CLR_HEADER_BG, _CLR_HEADER_FG, _CLR_OVERDUE_HDR_BG, _CLR_OVERDUE_HDR_FG
global _CLR_URGENT_HDR_BG, _CLR_URGENT_HDR_FG
t = _T()
_CLR_DONE = QColor(t["done"])
_CLR_NOTE_BG = QColor(t["note_bg"])
_CLR_OVERDUE_BG = QColor(t["overdue_bg"])
_CLR_OVERDUE_FG = QColor(t["overdue_fg"])
_CLR_HEADER_BG = QColor(t["header_bg"])
_CLR_HEADER_FG = QColor(t["text2"])
_CLR_OVERDUE_HDR_BG = QColor(t["overdue_bg"])
_CLR_OVERDUE_HDR_FG = QColor(t["overdue_fg"])
_CLR_URGENT_HDR_BG = QColor(t["urgent_bg"])
_CLR_URGENT_HDR_FG = QColor(t["urgent_fg"])
# Initialize with default theme
_update_theme_colors()
# ── Stylesheet builders ─────────────────────────────────────────────
def _build_main_style():
"""Build FullWindow stylesheet from current theme."""
t, fs = _T(), _font_size
return f"""
QMainWindow {{ background: {t["bg"]}; color: {t["text"]}; }}
QTabWidget::pane {{ border: none; background: {t["bg"]}; }}
QTabBar {{ background: {t["bg2"]}; }}
QTabBar::tab {{ padding: 8px 20px; font-weight: bold; font-size: {fs}px;
background: {t["bg2"]}; color: {t["text2"]};
border: 1px solid {t["bg3"]}; border-bottom: none;
margin-right: 2px; }}
QTabBar::tab:selected {{ background: {t["accent"]}; color: #ffffff; }}
QTabBar::tab:hover:!selected {{ background: {t["bg3"]}; color: {t["text"]}; }}
QToolBar {{ background: {t["bg2"]}; border-bottom: 1px solid {t["bg3"]}; spacing: 4px; }}
QToolBar QToolButton {{ background: {t["bg3"]}; color: {t["text"]}; border: 1px solid {t["border"]};
padding: 4px 12px; font-weight: bold; font-size: {fs}px; }}
QToolBar QToolButton:hover {{ background: {t["accent"]}; color: #ffffff; }}
QToolBar QToolButton:checked {{ background: {t["accent"]}; color: #ffffff; }}
QToolBar QToolButton#enrich_quick,
QToolBar QToolButton#enrich_standard,
QToolBar QToolButton#enrich_deep {{ background: {t["accent"]}; color: #ffffff; border: 1px solid {t["border"]}; font-weight: bold; }}
QToolBar QToolButton#enrich_quick:hover,
QToolBar QToolButton#enrich_standard:hover,
QToolBar QToolButton#enrich_deep:hover {{ background: #1a5cb0; color: #ffffff; }}
QStatusBar {{ background: {t["bg2"]}; color: {t["text2"]}; font-weight: bold;
border-top: 1px solid {t["bg3"]}; padding: 2px 8px; font-size: {fs - 1}px; }}
QMenu {{ background: {t["bg2"]}; color: {t["text"]}; border: 1px solid {t["border"]}; }}
QMenu::item:selected {{ background: {t["accent"]}; color: #ffffff; }}
QLineEdit#search {{ background: {t["bg3"]}; color: {t["text"]}; border: 2px solid {t["border"]};
border-radius: 4px; padding: 4px 8px; min-width: 200px; font-size: {fs}px; }}
QLineEdit#search:focus {{ border-color: {t["accent"]}; }}
"""
def _build_filter_style():
"""Build filter bar stylesheet from current theme."""
t, fs = _T(), _font_size
return f"""
QToolBar {{ background: {t["bg"]}; border-bottom: 1px solid {t["bg3"]}; spacing: 3px; padding: 2px 4px; }}
QToolButton {{ border-radius: 10px; padding: 2px 8px; font-size: {fs - 2}px; font-weight: 600;
border: 1px solid {t["border"]}; background: {t["bg3"]}; color: {t["text2"]}; }}
QToolButton:hover {{ background: {t["bg3"]}; color: {t["text"]}; }}
QToolButton:checked {{ background: {t["accent"]}; color: #fff; border-color: {t["accent"]}; }}
"""
def _build_list_style():
"""Build TaskListWidget stylesheet from current theme."""
t, fs, fw = _T(), _font_size, _fw()
return f"""
QListWidget {{ background: {t["bg"]}; color: {t["text"]}; border: none;
font-size: {fs}px; font-weight: {fw}; }}
QListWidget::item {{ padding: 8px 12px; border-bottom: 1px solid {t["bg3"]};
color: {t["text"]}; background: {t["bg"]}; }}
QListWidget::item:selected {{ background: {t["bg3"]}; color: #ffffff; }}
QListWidget::item:hover {{ background: {t["bg2"]}; }}
QListWidget::indicator {{ width: 18px; height: 18px; }}
QListWidget::indicator:unchecked {{ border: 2px solid {t["border"]};
background: {t["bg2"]}; border-radius: 3px; }}
QListWidget::indicator:checked {{ border: 2px solid {t["accent"]};
background: {t["accent"]}; border-radius: 3px; }}
"""
def _build_popup_style():
"""Build TrayPopup stylesheet from current theme."""
t, fs, fw = _T(), _font_size, _fw()
return f"""
QWidget {{ background: {t["bg2"]}; color: {t["text"]}; font-family: 'Segoe UI'; font-weight: {fw}; }}
QLabel#header {{ font-size: {fs + 2}px; font-weight: bold; padding: 10px 0 10px 14px; }}
QLabel#section-header {{ font-size: {fs - 2}px; color: {t["text2"]}; padding: 6px 14px 2px;
text-transform: uppercase; letter-spacing: 1px; }}
QCheckBox {{ font-size: {fs}px; padding: 6px 14px; }}
QCheckBox::indicator {{ width: 16px; height: 16px; }}
QLabel#priority {{ font-size: {fs - 3}px; font-weight: bold; padding: 2px 6px;
border-radius: 3px; }}
QLineEdit {{ background: {t["bg3"]}; border: 1px solid {t["border"]}; border-radius: 4px;
color: {t["text"]}; padding: 6px 10px; margin: 2px 14px; }}
QTextEdit {{ background: {t["bg3"]}; border: 1px solid {t["border"]}; border-radius: 4px;
color: {t["text"]}; padding: 6px 10px; margin: 2px 14px; font-family: 'Segoe UI';
font-size: {fs}px; }}
QComboBox {{ background: {t["bg3"]}; border: 1px solid {t["border"]}; border-radius: 4px;
color: {t["text"]}; padding: 4px 8px; margin: 2px 14px; }}
QComboBox QAbstractItemView {{ background: {t["bg3"]}; color: {t["text"]};
selection-background-color: {t["border"]}; }}
QPushButton#add-btn {{ background: transparent; border: none; color: {t["text2"]};
font-size: {fs + 5}px; font-weight: bold; padding: 4px 10px; }}
QPushButton#add-btn:hover {{ color: #ffffff; }}
QPushButton#submit-btn {{ background: {t["bg3"]}; border: 1px solid {t["border"]};
border-radius: 4px; color: {t["text"]}; padding: 6px;
margin: 2px 14px; font-weight: bold; }}
QPushButton#submit-btn:hover {{ background: {t["border"]}; }}
QPushButton#open-full {{ background: {t["bg3"]}; border: none; color: {t["text2"]};
padding: 8px; font-size: {fs - 1}px; }}
QPushButton#open-full:hover {{ background: {t["border"]}; color: #ffffff; }}
"""
def _build_dialog_style():
"""Build EditTaskDialog stylesheet from current theme."""
t, fs, fw = _T(), _font_size, _fw()
return f"""
QDialog {{ background: {t["bg"]}; color: {t["text"]}; font-weight: {fw}; }}
QLabel {{ color: {t["text2"]}; font-weight: bold; }}
QLineEdit {{ background: {t["bg2"]}; color: {t["text"]}; border: 2px solid {t["border"]};
border-radius: 4px; padding: 6px; font-size: {fs}px; }}
QLineEdit:focus {{ border-color: {t["accent"]}; }}
QTextEdit {{ background: {t["bg2"]}; color: {t["text"]}; border: 2px solid {t["border"]};
border-radius: 4px; padding: 6px; font-size: {fs}px; }}
QComboBox {{ background: {t["bg2"]}; color: {t["text"]}; border: 2px solid {t["border"]};
border-radius: 4px; padding: 6px; font-size: {fs}px; }}
QComboBox QAbstractItemView {{ background: {t["bg2"]}; color: {t["text"]};
selection-background-color: {t["border"]}; }}
QDateEdit {{ background: {t["bg2"]}; color: {t["text"]}; border: 2px solid {t["border"]};
border-radius: 4px; padding: 6px; font-size: {fs}px; }}
QDateEdit::drop-down {{ border: none; }}
QPushButton {{ background: {t["bg3"]}; color: {t["text"]}; border: 1px solid {t["border"]};
border-radius: 4px; padding: 6px 16px; font-weight: bold; font-size: {fs}px; }}
QPushButton:hover {{ background: {t["accent"]}; color: #ffffff; }}
QMenu {{ background: {t["bg2"]}; color: {t["text"]}; border: 1px solid {t["border"]}; }}
QMenu::item:selected {{ background: {t["accent"]}; color: #ffffff; }}
"""
def _build_reader_style():
"""Build TaskReaderDialog stylesheet from current theme."""
t, fs, fw = _T(), _font_size, _fw()
return f"""
QDialog {{ background: {t["bg"]}; font-weight: {fw}; }}
QLabel#reader-title {{ color: {t["text"]}; font-size: {fs + 5}px; font-weight: bold;
padding: 12px 16px 4px; }}
QLabel#reader-meta {{ color: {t["text2"]}; font-size: {fs - 1}px; padding: 2px 6px; }}
QLabel#reader-priority {{ font-size: {fs - 2}px; font-weight: bold; padding: 2px 8px;
border-radius: 3px; }}
QScrollArea {{ background: {t["bg"]}; border: none; }}
QLabel#reader-body {{ color: {t["text"]}; font-size: {fs}px; padding: 16px;
background: {t["bg"]}; }}
QFrame#reader-header {{ background: {t["bg2"]}; border-bottom: 1px solid {t["bg3"]}; }}
QPushButton {{ background: {t["bg3"]}; color: {t["text"]}; border: 1px solid {t["border"]};
border-radius: 4px; padding: 8px 20px; font-weight: bold;
font-size: {fs}px; }}
QPushButton:hover {{ background: {t["accent"]}; color: #ffffff; }}
"""
def _build_menu_style():
"""Build context menu stylesheet from current theme."""
t = _T()
return (
f"QMenu {{ background: {t['bg2']}; color: {t['text']}; border: 1px solid {t['border']}; }}"
f"QMenu::item:selected {{ background: {t['accent']}; color: #ffffff; }}"
)
# ── Utility functions ────────────────────────────────────────────────
def _recurring_label(raw: str | None) -> str:
"""Human-readable label for recurring config JSON."""
if not raw:
return ""
try:
cfg = json.loads(raw)
except (json.JSONDecodeError, TypeError):
return ""
every = cfg.get("every", "").lower()
try:
interval = int(cfg.get("interval", 1))
except (ValueError, TypeError):
interval = 1
if every == "day":
return "Daily" if interval == 1 else f"Every {interval} days"
if every == "week":
day = cfg.get("day", "?").title()
if interval == 1:
return f"Weekly ({day})"
if interval == 2:
return f"Biweekly ({day})"
return f"Every {interval} weeks ({day})"
if every == "month":
day = cfg.get("day", "?")
if interval == 1:
return f"Monthly (day {day})"
return f"Every {interval} months (day {day})"
if every == "year":
month = cfg.get("month")
day = cfg.get("day")
parts = []
if month:
try:
parts.append(_cal_mod.month_name[int(month)])
except (ValueError, TypeError, IndexError):
parts.append(str(month))
if day:
parts.append(str(day))
suffix = " ".join(parts) if parts else ""
if interval == 1:
return f"Yearly ({suffix})" if suffix else "Yearly"
return (
f"Every {interval} years ({suffix})"
if suffix
else f"Every {interval} years"
)
return ""
# Module-level TruthScore cache (refreshed every 30s)
_ts_cache: dict[str, str] = {}
_ts_cache_time: float = 0.0
def _batch_truth_scores(db_path=None):
"""Single query for all TruthScore badges. Cached for 30s."""
global _ts_cache, _ts_cache_time
now = time.monotonic()
if now - _ts_cache_time < 30:
return _ts_cache
try:
with get_conn(db_path) as conn:
rows = conn.execute(
"SELECT entity_name, AVG(specificity * 0.35 + falsifiability * 0.25 + "
"internal_consistency * 0.25 + novelty * 0.15) as iq "
"FROM knowledge_ratings GROUP BY entity_name"
).fetchall()
result = {}
for r in rows:
avg = r["iq"] or 0.0
if avg > 0.7:
result[r["entity_name"]] = "\U0001f7e2 " # green
elif avg >= 0.4:
result[r["entity_name"]] = "\U0001f7e1 " # yellow
else:
result[r["entity_name"]] = "\U0001f534 " # red
_ts_cache = result
_ts_cache_time = now
return result
except sqlite3.Error as exc:
logger.debug("TruthScore badge refresh failed: %s", exc)
return _ts_cache # return stale cache on error
def _get_truth_score_badge(task, db_path=None):
"""Query TruthScore for public entities and return a color-coded badge string."""
if task.get("visibility") != "public" or not task.get("title"):
return ""
cache = _batch_truth_scores(db_path)
return cache.get(task["title"], "\u2b1c ") # gray square = unrated
def _format_task_text(task, include_project=True, prefix=""):
"""Build display text: [N] [🔄] [⏳/🌐] [TS] [PRIORITY] title | Due: date | project — preview."""
type_prefix = "[N] " if task.get("type") == "note" else ""
recur = "\U0001f504 " if task.get("recurring") else ""
vis = task.get("visibility", "private")
vis_badge = (
"\u23f3 "
if vis == "pending_public"
else ("\U0001f310 " if vis == "public" else "")
)
ts_badge = _get_truth_score_badge(task) if vis == "public" else ""
priority = (task.get("priority") or "medium").upper()
due = f" | Due: {task['due_date']}" if task.get("due_date") else ""
proj = f" | {task['project']}" if include_project and task.get("project") else ""
desc = task.get("description") or ""
preview_source = desc
if not preview_source and task.get("notes"):
preview_source = f"[notes] {task['notes']}"
preview = (
f" — {preview_source[:50]}..."
if len(preview_source) > 50
else (f" — {preview_source}" if preview_source else "")
)
return f"{prefix}{type_prefix}{recur}{vis_badge}{ts_badge}[{priority}] {task['title']}{due}{proj}{preview}"
def _apply_task_item_colors(item, task):
"""Apply state-based colors to a QListWidgetItem (done, note, overdue)."""
if task["status"] == "done":
item.setForeground(_CLR_DONE)
if task.get("type") == "note":
item.setBackground(_CLR_NOTE_BG)
if is_overdue(task.get("due_date")) and task["status"] != "done":
item.setData(_OVERDUE_ROLE, True)
item.setBackground(_CLR_OVERDUE_BG)
item.setForeground(_CLR_OVERDUE_FG)
def _build_rich_tooltip(task):
"""Build consistent rich tooltip for task display."""
parts = []
rl = _recurring_label(task.get("recurring"))
if rl:
parts.append(f"\U0001f504 {rl}")
if task.get("description"):
parts.append(task["description"])
if task.get("notes"):
parts.append(f"Notes: {task['notes']}")
if task.get("priority"):
parts.append(f"Priority: {task['priority']}")
if task.get("due_date"):
parts.append(f"Due: {task['due_date']}")
if task.get("project"):
parts.append(f"Project: {task['project']}")
if task.get("section"):
parts.append(f"Section: {task['section']}")
return "\n".join(parts) if parts else None
def _build_detail_sections_from_record(task):
"""Fallback detail sections for premium read-only records."""
sections = []
for title, key in (
("Description", "description"),
("Notes", "notes"),
("Project", "project"),
("Client", "client_ref"),
("Mailbox", "mailbox_key"),
("Risk", "risk_level"),
("Updated", "updated_at"),
):
value = task.get(key)
if value:
sections.append({"title": title, "body": str(value)})
return sections
def _build_copy_text(task):
"""Build clipboard text for task (title always included)."""
parts = [task["title"]]
if task.get("description"):
parts.append(task["description"])
if task.get("notes"):
parts.append(f"Notes: {task['notes']}")
if task.get("priority"):
parts.append(f"Priority: {task['priority']}")
if task.get("due_date"):
parts.append(f"Due: {task['due_date']}")
if task.get("project"):
parts.append(f"Project: {task['project']}")
if task.get("section"):
parts.append(f"Section: {task['section']}")
if task.get("assignee"):
parts.append(f"Assignee: {task['assignee']}")
return "\n".join(parts)
def _suggested_sort_key(t):
"""Python sort key replicating get_suggested_tasks() SQL ordering."""
dd = t.get("due_date")
today_str = date.today().isoformat()
return (
0 if (dd and dd < today_str) else 1, # overdue first
priority_sort_key(t)[0], # priority (critical first)
0 if dd else 1, # has due date first
dd or "9999-99-99", # due date ascending
)
def _smart_group(tasks):
"""Group tasks intelligently: Overdue → Critical/High → By Project (due soon) → Rest.
Returns list of (label, task_list) tuples. Each task appears in exactly one group.
"""
overdue = []
urgent = []
by_project: dict[str, list] = {}
rest = []
for t in tasks:
if is_overdue(t.get("due_date")) and t["status"] != "done":
overdue.append(t)
elif t.get("priority", "medium") in ("critical", "high"):
urgent.append(t)
elif t.get("project"):
by_project.setdefault(t["project"], []).append(t)
else:
rest.append(t)
groups = []
if overdue:
groups.append(("⚠ Overdue", overdue))
if urgent:
groups.append(("Urgent", urgent))
for proj_name in sorted(by_project, key=lambda p: len(by_project[p]), reverse=True):
groups.append((proj_name, by_project[proj_name]))
if rest:
groups.append(("Other", rest))
return groups
# ── UI helper classes ────────────────────────────────────────────────
class _ClickableLabel(QLabel):
"""Label that emits clicked signal on mouse press."""
clicked = pyqtSignal()
def mousePressEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
self.clicked.emit()
super().mousePressEvent(event)
class _TooltipCopyFilter(QObject):
"""Copies full task summary to clipboard when tooltip is about to show."""
_last_copied_text = None # class-level debounce
def __init__(self, task, parent=None):
super().__init__(parent)
self._task = task
def eventFilter(self, obj, event):
if event.type() == QEvent.Type.ToolTip:
copy_text = _build_copy_text(self._task)
if copy_text != _TooltipCopyFilter._last_copied_text:
_clipboard_write(copy_text)
_TooltipCopyFilter._last_copied_text = copy_text
return False # let tooltip show normally
class _ListTooltipCopyFilter(QObject):
"""Copies task summary to clipboard when hovering items in TaskListWidget."""
def __init__(self, list_widget, parent=None):
super().__init__(parent)
self._list = list_widget
self._last_copied_text = None
def eventFilter(self, obj, event):
if event.type() == QEvent.Type.ToolTip:
pos = event.pos()
if obj is self._list:
pos = self._list.viewport().mapFrom(self._list, pos)
elif obj is not self._list.viewport():
pos = self._list.viewport().mapFrom(obj, pos)
item = self._list.itemAt(pos)
if item:
task_id = item.data(Qt.ItemDataRole.UserRole)
if task_id:
task = next(
(t for t in self._list._tasks if t["id"] == task_id),
None,
)
if task:
copy_text = _build_copy_text(task)
if copy_text != self._last_copied_text:
_clipboard_write(copy_text)
self._last_copied_text = copy_text
return False
_OVERDUE_ROLE = Qt.ItemDataRole.UserRole + 10
class _OverdueDelegate(QStyledItemDelegate):
"""Paints a 3px red left border on overdue task items."""
def paint(self, painter, option, index):
super().paint(painter, option, index)
if index.data(_OVERDUE_ROLE):
painter.save()
painter.setPen(Qt.PenStyle.NoPen)
painter.fillRect(
option.rect.x(),
option.rect.y(),
3,
option.rect.height(),
QColor(_T()["danger"]),
)
painter.restore()
class _CalendarShowFilter(QObject):
"""Open calendar at today's page when no date is set."""
def __init__(self, due_edit, parent=None):
super().__init__(parent)
self._due_edit = due_edit
def eventFilter(self, obj, event):
if event.type() == QEvent.Type.Show:
if self._due_edit.date() == self._due_edit.minimumDate():
today = QDate.currentDate()
obj.setCurrentPage(today.year(), today.month())
return False
# ── TrayPopup ───────────────────────────────────────────────────────
class TrayPopup(QWidget):
"""Compact popup showing top suggested tasks."""
_entity_search_done = pyqtSignal(list, int) # (entity_results, seq_id)
def __init__(self, db, on_open_full, parent=None):
super().__init__(
parent,
Qt.WindowType.Tool
| Qt.WindowType.FramelessWindowHint
| Qt.WindowType.WindowStaysOnTopHint,
)
self.db = db
self.on_open_full = on_open_full
self._tasks = []
self._entity_seq_id = 0
self._open_dialogs = []
self._entity_search_done.connect(self._on_entity_results)
self.setFixedWidth(380)
self.setMaximumHeight(500)
self.setStyleSheet(self._stylesheet())
self._search_engine = db.search_engine
self._build_ui()
# Auto-refresh timer (only ticks when visible)
self._refresh_timer = QTimer(self)
self._refresh_timer.timeout.connect(self.refresh)
# Search debounce (300ms)
self._search_timer = QTimer(self)
self._search_timer.setSingleShot(True)
self._search_timer.setInterval(300)
self._search_timer.timeout.connect(self.refresh)
def _stylesheet(self):
return _build_popup_style()
def _build_ui(self):
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
# Header row: "Tasks" + "+" button
header_row = QHBoxLayout()
header_row.setContentsMargins(0, 0, 8, 0)
header = QLabel("Tasks")
header.setObjectName("header")
header_row.addWidget(header)
header_row.addStretch()
self._add_btn = QPushButton("+")
self._add_btn.setObjectName("add-btn")
self._add_btn.setFixedSize(30, 30)
self._add_btn.clicked.connect(self._toggle_add_form)
header_row.addWidget(self._add_btn)
layout.addLayout(header_row)
# Collapsible add-task form (hidden by default)
self._add_form = QWidget()
self._add_form.setVisible(False)
form_layout = QVBoxLayout(self._add_form)
form_layout.setContentsMargins(0, 0, 0, 4)
form_layout.setSpacing(0)
self._add_title = QLineEdit()
self._add_title.setPlaceholderText("Title...")
form_layout.addWidget(self._add_title)
self._add_desc = QTextEdit()
self._add_desc.setPlaceholderText("Description (main task/note body)...")
self._add_desc.setMaximumHeight(60)
form_layout.addWidget(self._add_desc)
self._add_notes = QTextEdit()
self._add_notes.setPlaceholderText("Notes (internal / metadata, optional)...")
self._add_notes.setMaximumHeight(48)
form_layout.addWidget(self._add_notes)
self._add_due = QLineEdit()
self._add_due.setPlaceholderText("Due date (YYYY-MM-DD)")
form_layout.addWidget(self._add_due)
add_reminder_top = QHBoxLayout()
self._add_reminder_enabled = QCheckBox("Reminder")
self._add_reminder_enabled.toggled.connect(
self._set_add_reminder_controls_enabled
)
add_reminder_top.addWidget(self._add_reminder_enabled)
self._add_reminder = QDateTimeEdit()
self._add_reminder.setCalendarPopup(True)
self._add_reminder.setDisplayFormat("dd.MM.yyyy HH:mm")
self._add_reminder.setDateTime(QDateTime.currentDateTime().addSecs(3600))
add_reminder_top.addWidget(self._add_reminder, 1)
form_layout.addLayout(add_reminder_top)
add_reminder_shortcuts = QHBoxLayout()
self._add_reminder_shortcut_buttons = []
for label, minutes in [
("1h", 60),
("3h", 180),
("Tomorrow 9:00", -1),
]:
btn = QPushButton(label)
btn.clicked.connect(lambda checked, m=minutes: self._apply_add_reminder(m))
add_reminder_shortcuts.addWidget(btn)
self._add_reminder_shortcut_buttons.append(btn)
form_layout.addLayout(add_reminder_shortcuts)
self._set_add_reminder_controls_enabled(False)
self._add_priority = QComboBox()
self._add_priority.addItems(PRIORITIES)
self._add_priority.setCurrentText("medium")
form_layout.addWidget(self._add_priority)
self._add_type = QComboBox()
self._add_type.addItems(["Task", "Note"])
form_layout.addWidget(self._add_type)
submit = QPushButton("Add Task")
submit.setObjectName("submit-btn")
submit.clicked.connect(self._submit_task)
self._add_title.returnPressed.connect(self._submit_task)
form_layout.addWidget(submit)
layout.addWidget(self._add_form)
# Scroll area for tasks
self.scroll = QScrollArea()
self.scroll.setWidgetResizable(True)
self.scroll.setFrameShape(QFrame.Shape.NoFrame)
self.task_container = QWidget()
self.task_layout = QVBoxLayout(self.task_container)
self.task_layout.setContentsMargins(0, 0, 0, 0)
self.task_layout.setSpacing(0)
self.scroll.setWidget(self.task_container)
layout.addWidget(self.scroll)
# Search bar (bottom)
self._search_input = QLineEdit()
self._search_input.setObjectName("search")
self._search_input.setPlaceholderText("Search tasks...")
self._search_input.setClearButtonEnabled(True)
self._search_input.textChanged.connect(self._on_search)
layout.addWidget(self._search_input)
# Open full button
btn = QPushButton("Open Full Window")
btn.setObjectName("open-full")
btn.clicked.connect(self.on_open_full)
layout.addWidget(btn)
self._search_text = ""
def refresh(self):
"""Reload tasks from DB and rebuild list."""
self.db.promote_due_today()
while self.task_layout.count():
item = self.task_layout.takeAt(0)
if item.widget():
item.widget().deleteLater()
q = self._search_text
if q:
# Search ALL tasks (same as FullWindow) via SmartKey engine
all_tasks = self.db.get_all_active() + self.db.get_done_tasks()
self._search_engine.rebuild_index(all_tasks)
tasks = self._search_engine.search(
q, all_tasks, limit=20, conn=None, use_vector=False
)
# Show tasks immediately, entities arrive async
merged = [{**t, "_is_entity": False} for t in tasks]
# Async entity search (with vector — always on)
self._entity_seq_id += 1
_seq = self._entity_seq_id
_q = q
def _entity_worker(seq_id=_seq, query=_q):
results = self.db.search_entities_fast(query, limit=5)
self._entity_search_done.emit(results, seq_id)
threading.Thread(target=_entity_worker, daemon=True).start()
else:
tasks = self.db.get_suggested_tasks(limit=8)
merged = None # no search — use smart grouping
self._tasks = (
[m for m in merged if not m.get("_is_entity")] if merged else tasks
)
if q and merged:
# Flat interleaved list when searching
for item in merged:
if item.get("_is_entity"):
self.task_layout.addWidget(self._make_entity_row(item))
else:
self.task_layout.addWidget(self._make_task_row(item))
elif q:
lbl = QLabel("No matches")
lbl.setObjectName("section-header")
lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.task_layout.addWidget(lbl)
elif tasks:
groups = _smart_group(tasks)
for group_label, group_tasks in groups:
if not group_tasks:
continue
lbl = QLabel(f"{group_label} ({len(group_tasks)})")
lbl.setObjectName("section-header")
self.task_layout.addWidget(lbl)
for task in group_tasks:
self.task_layout.addWidget(self._make_task_row(task))
else:
lbl = QLabel("All clear!")
lbl.setObjectName("section-header")
lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.task_layout.addWidget(lbl)
self.task_layout.addStretch()
def _make_entity_row(self, entity):
"""Compact entity card for search results in TrayPopup."""
etype = (entity.get("entity_type") or "").lower()
color = _ENTITY_TYPE_COLORS.get(etype, _ENTITY_DEFAULT_COLOR)
row = QWidget()
row.setStyleSheet(f"border-left: 3px solid {color}; background: #0d1b2a;")
row.setCursor(Qt.CursorShape.PointingHandCursor)
hl = QHBoxLayout(row)
hl.setContentsMargins(14, 4, 14, 4)