-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
963 lines (800 loc) · 34.9 KB
/
Copy pathmain.py
File metadata and controls
963 lines (800 loc) · 34.9 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
import os
import sys
from typing import Optional
from PySide6.QtCore import Qt, QRect, QSize
from PySide6.QtGui import (
QAction, QFont, QIcon, QKeySequence, QColor, QPainter, QPalette,
)
from PySide6.QtWidgets import (
QApplication, QMainWindow, QPlainTextEdit, QWidget,
QLabel, QDialog, QComboBox, QPushButton, QVBoxLayout,
QTextBrowser, QFileDialog, QMessageBox, QStatusBar,
QToolBar, QToolButton, QFrame, QDialogButtonBox,
)
import config as cfg
from classes.WindowManager import WindowManager
from classes.UtilHelper import markdown_to_html
# theme
def apply_theme(app: QApplication, theme: str) -> None:
app.setStyle("Fusion")
app.setPalette(QApplication.style().standardPalette())
# line-number widget
class LineNumberArea(QWidget):
def __init__(self, editor: "NotesEditor"):
super().__init__(editor)
self._editor = editor
def sizeHint(self) -> QSize:
return QSize(self._editor.line_number_area_width(), 0)
def paintEvent(self, event) -> None:
self._editor.paint_line_numbers(event)
class NotesEditor(QPlainTextEdit):
def __init__(self, parent=None):
super().__init__(parent)
self._line_area = LineNumberArea(self)
self.blockCountChanged.connect(self._update_width)
self.updateRequest.connect(self._update_area)
self.setFont(QFont(cfg.EDITOR_FONT_FAMILY, cfg.EDITOR_FONT_SIZE))
self._update_width(0)
def line_number_area_width(self) -> int:
digits = max(1, len(str(self.blockCount())))
return 10 + self.fontMetrics().horizontalAdvance("9") * digits + 8
def _update_width(self, _) -> None:
self.setViewportMargins(self.line_number_area_width(), 0, 0, 0)
def _update_area(self, rect: QRect, dy: int) -> None:
if dy:
self._line_area.scroll(0, dy)
else:
self._line_area.update(0, rect.y(), self._line_area.width(), rect.height())
if rect.contains(self.viewport().rect()):
self._update_width(0)
def resizeEvent(self, event) -> None:
super().resizeEvent(event)
cr = self.contentsRect()
self._line_area.setGeometry(
cr.left(), cr.top(), self.line_number_area_width(), cr.height()
)
def paint_line_numbers(self, event) -> None:
is_dark = self.palette().window().color().lightness() < 128
bg = QColor("#252526") if is_dark else QColor("#f3f3f3")
fg = QColor("#858585") if is_dark else QColor("#888888")
painter = QPainter(self._line_area)
painter.fillRect(event.rect(), bg)
painter.setPen(fg)
painter.setFont(self.font())
block = self.firstVisibleBlock()
block_num = block.blockNumber()
top = round(self.blockBoundingGeometry(block).translated(self.contentOffset()).top())
bottom = top + round(self.blockBoundingRect(block).height())
lh = self.fontMetrics().height()
while block.isValid() and top <= event.rect().bottom():
if block.isVisible() and bottom >= event.rect().top():
painter.drawText(
0, top, self._line_area.width() - 5, lh,
Qt.AlignmentFlag.AlignRight, str(block_num + 1),
)
block = block.next()
top = bottom
bottom = top + round(self.blockBoundingRect(block).height())
block_num += 1
# notes app
class NotesApp(QMainWindow):
def __init__(self):
super().__init__()
self.current_file: Optional[str] = None
self.is_modified: bool = False
self.wm = WindowManager(self)
self._word_wrap: bool = self.wm.get_setting("word_wrap", "on") == "on"
# Editor must be created before menu/toolbar reference it
self._build_editor()
self._build_menu()
self._build_toolbar()
self._build_status_bar()
self._apply_icon()
self._update_title()
self.wm.apply_initial_geometry()
# ------------------------------------------------------------------
# Icon
# ------------------------------------------------------------------
def _apply_icon(self) -> None:
if os.path.exists(cfg.APP_ICON):
self.setWindowIcon(QIcon(cfg.APP_ICON))
# ------------------------------------------------------------------
# Editor
# ------------------------------------------------------------------
def _build_editor(self) -> None:
self._editor = NotesEditor(self)
self._editor.setLineWrapMode(
QPlainTextEdit.LineWrapMode.WidgetWidth if self._word_wrap
else QPlainTextEdit.LineWrapMode.NoWrap
)
self._editor.document().modificationChanged.connect(self._on_modified)
self._editor.cursorPositionChanged.connect(self._update_status)
self.setCentralWidget(self._editor)
# ------------------------------------------------------------------
# Menu
# ------------------------------------------------------------------
def _build_menu(self) -> None:
mb = self.menuBar()
# --- File ---
file_menu = mb.addMenu("&File")
file_menu.addAction(self._act("&New", self._cmd_new, QKeySequence.StandardKey.New))
file_menu.addAction(self._act("&Open…", self._cmd_open, QKeySequence.StandardKey.Open))
file_menu.addAction(self._act("&Save", self._cmd_save, QKeySequence.StandardKey.Save))
file_menu.addAction(self._act("Save &As…", self._cmd_save_as, QKeySequence("Ctrl+Shift+S")))
file_menu.addSeparator()
file_menu.addAction(self._act("&Close", self._cmd_close))
file_menu.addSeparator()
file_menu.addAction(self._act("E&xit", self.close, QKeySequence("Ctrl+Q")))
# --- Edit ---
edit_menu = mb.addMenu("&Edit")
edit_menu.addAction(self._act("&Settings", self._cmd_settings))
edit_menu.addSeparator()
self._wrap_action = QAction("&Word Wrap", self)
self._wrap_action.setCheckable(True)
self._wrap_action.setChecked(self._word_wrap)
self._wrap_action.triggered.connect(self._cmd_toggle_wrap_menu)
edit_menu.addAction(self._wrap_action)
edit_menu.addSeparator()
edit_menu.addAction(self._act("&Copy", self._editor.copy, QKeySequence.StandardKey.Copy))
edit_menu.addAction(self._act("&Paste", self._editor.paste, QKeySequence.StandardKey.Paste))
edit_menu.addAction(self._act("C&ut", self._editor.cut, QKeySequence.StandardKey.Cut))
edit_menu.addSeparator()
edit_menu.addAction(self._act("Select &All", self._editor.selectAll, QKeySequence.StandardKey.SelectAll))
# --- Help ---
help_menu = mb.addMenu("&Help")
help_menu.addAction(self._act("&Manual", self._cmd_manual))
help_menu.addAction(self._act("&About", self._cmd_about))
def _act(self, label: str, slot, shortcut=None) -> QAction:
a = QAction(label, self)
if shortcut:
a.setShortcut(shortcut)
a.triggered.connect(slot)
return a
# ------------------------------------------------------------------
# Toolbar
# ------------------------------------------------------------------
def _build_toolbar(self) -> None:
tb = QToolBar("Main", self)
tb.setMovable(False)
tb.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextOnly)
self.addToolBar(tb)
icon_font = QFont("Segoe UI Emoji", 13)
def sep() -> QFrame:
f = QFrame()
f.setFrameShape(QFrame.Shape.VLine)
f.setFrameShadow(QFrame.Shadow.Sunken)
return f
def btn(icon: str, tip: str, slot, checkable: bool = False) -> QToolButton:
b = QToolButton()
b.setText(icon)
b.setFont(icon_font)
b.setToolTip(tip)
b.setCheckable(checkable)
b.setAutoRaise(True)
b.clicked.connect(slot)
return b
tb.addWidget(btn("🗋", "New (Ctrl+N)", self._cmd_new))
tb.addWidget(btn("📂", "Open (Ctrl+O)", self._cmd_open))
tb.addWidget(btn("💾", "Save (Ctrl+S)", self._cmd_save))
tb.addWidget(btn("📄", "Save As", self._cmd_save_as))
tb.addWidget(sep())
tb.addWidget(btn("✕", "Close", self._cmd_close))
tb.addWidget(sep())
tb.addWidget(btn("⚙", "Settings", self._cmd_settings))
self._wrap_btn = QToolButton()
self._wrap_btn.setText("⇥")
self._wrap_btn.setFont(icon_font)
self._wrap_btn.setToolTip("Word Wrap")
self._wrap_btn.setCheckable(True)
self._wrap_btn.setChecked(self._word_wrap)
self._wrap_btn.setAutoRaise(True)
self._wrap_btn.toggled.connect(self._cmd_toggle_wrap_toolbar)
tb.addWidget(self._wrap_btn)
tb.addWidget(sep())
tb.addWidget(btn("✂", "Cut (Ctrl+X)", self._editor.cut))
tb.addWidget(btn("⧉", "Copy (Ctrl+C)", self._editor.copy))
tb.addWidget(btn("📋", "Paste (Ctrl+V)", self._editor.paste))
tb.addWidget(btn("☰", "Select All", self._editor.selectAll))
tb.addWidget(sep())
tb.addWidget(btn("📖", "Manual", self._cmd_manual))
tb.addWidget(btn("ℹ", "About", self._cmd_about))
# ------------------------------------------------------------------
# Status bar
# ------------------------------------------------------------------
def _build_status_bar(self) -> None:
self._status = QStatusBar(self)
self.setStatusBar(self._status)
self._status.showMessage("Ready")
# ------------------------------------------------------------------
# Title & status
# ------------------------------------------------------------------
def _update_title(self) -> None:
name = os.path.basename(self.current_file) if self.current_file else "Untitled"
mod = " •" if self.is_modified else ""
self.setWindowTitle(f"{name}{mod} — {cfg.APP_NAME}")
def set_status(self, message: str) -> None:
self._status.showMessage(message)
def _update_status(self) -> None:
cursor = self._editor.textCursor()
line = cursor.blockNumber() + 1
col = cursor.columnNumber() + 1
name = os.path.basename(self.current_file) if self.current_file else "Untitled"
mod = " ●" if self.is_modified else ""
self._status.showMessage(f"{name}{mod} Ln {line}, Col {col}")
# ------------------------------------------------------------------
# Modified
# ------------------------------------------------------------------
def _on_modified(self, modified: bool) -> None:
self.is_modified = modified
self._update_title()
self._update_status()
def _reset_modified(self) -> None:
self._editor.document().setModified(False)
self.is_modified = False
self._update_title()
# ------------------------------------------------------------------
# Unsaved guard
# ------------------------------------------------------------------
def _check_unsaved(self) -> bool:
if not self.is_modified:
return True
answer = QMessageBox.question(
self, "Unsaved Changes",
"The document has unsaved changes.\nSave before continuing?",
QMessageBox.StandardButton.Save |
QMessageBox.StandardButton.Discard |
QMessageBox.StandardButton.Cancel,
)
if answer == QMessageBox.StandardButton.Cancel:
return False
if answer == QMessageBox.StandardButton.Save:
return self._cmd_save()
return True
# ------------------------------------------------------------------
# Window close
# ------------------------------------------------------------------
def closeEvent(self, event) -> None:
if not self._check_unsaved():
event.ignore()
return
self.wm.save_geometry()
event.accept()
# ------------------------------------------------------------------
# File commands
# ------------------------------------------------------------------
def _cmd_new(self) -> None:
if not self._check_unsaved():
return
self._editor.clear()
self.current_file = None
self._reset_modified()
self.set_status("New document")
def _cmd_open(self) -> None:
if not self._check_unsaved():
return
path, _ = QFileDialog.getOpenFileName(
self, "Open file", "",
"Text files (*.txt);;All files (*.*)",
)
if not path:
return
try:
with open(path, "r", encoding="utf-8") as fh:
content = fh.read()
except OSError as exc:
QMessageBox.critical(self, "Error", f"Cannot open file:\n{exc}")
return
self._editor.setPlainText(content)
self.current_file = path
self._reset_modified()
self.set_status(f"Opened: {path}")
def _cmd_save(self) -> bool:
if not self.current_file:
return self._cmd_save_as()
return self._write_to(self.current_file)
def _cmd_save_as(self) -> bool:
path, _ = QFileDialog.getSaveFileName(
self, "Save As", "",
"Text files (*.txt);;All files (*.*)",
)
if not path:
return False
return self._write_to(path)
def _write_to(self, path: str) -> bool:
try:
with open(path, "w", encoding="utf-8") as fh:
fh.write(self._editor.toPlainText())
except OSError as exc:
QMessageBox.critical(self, "Error", f"Cannot save file:\n{exc}")
return False
self.current_file = path
self._reset_modified()
self.set_status(f"Saved: {path}")
return True
def _cmd_close(self) -> None:
if not self._check_unsaved():
return
self._editor.clear()
self.current_file = None
self._reset_modified()
self.set_status("Closed")
# ------------------------------------------------------------------
# Edit commands
# ------------------------------------------------------------------
def _cmd_toggle_wrap_menu(self, checked: bool) -> None:
self._word_wrap = checked
self._apply_wrap()
self._wrap_btn.setChecked(self._word_wrap)
def _cmd_toggle_wrap_toolbar(self, checked: bool) -> None:
self._word_wrap = checked
self._apply_wrap()
self._wrap_action.setChecked(self._word_wrap)
def _apply_wrap(self) -> None:
self._editor.setLineWrapMode(
QPlainTextEdit.LineWrapMode.WidgetWidth if self._word_wrap
else QPlainTextEdit.LineWrapMode.NoWrap
)
self.wm.set_setting("word_wrap", "on" if self._word_wrap else "off")
def _cmd_settings(self) -> None:
dlg = QDialog(self)
dlg.setWindowTitle("Settings")
dlg.setWindowIcon(self.windowIcon())
dlg.setFixedSize(320, 160)
layout = QVBoxLayout(dlg)
layout.addWidget(QLabel("Colour theme is fixed to light."))
layout.addSpacing(12)
buttons = QDialogButtonBox(
QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
)
layout.addWidget(buttons)
def _apply() -> None:
apply_theme(QApplication.instance(), "light")
self.wm.set_setting("theme", "light")
dlg.accept()
buttons.accepted.connect(_apply)
buttons.rejected.connect(dlg.reject)
dlg.exec()
# ------------------------------------------------------------------
# Help commands
# ------------------------------------------------------------------
def _cmd_manual(self) -> None:
self._show_md_dialog("Manual", cfg.MANUAL_TEXT)
def _cmd_about(self) -> None:
self._show_md_dialog("About", cfg.ABOUT_TEXT)
def _show_md_dialog(self, title: str, text: str) -> None:
dlg = QDialog(self)
dlg.setWindowTitle(title)
dlg.setWindowIcon(self.windowIcon())
dlg.resize(620, 440)
layout = QVBoxLayout(dlg)
browser = QTextBrowser()
browser.setOpenExternalLinks(True)
browser.setHtml(markdown_to_html(text))
layout.addWidget(browser)
btn = QPushButton("Close")
btn.clicked.connect(dlg.accept)
layout.addWidget(btn, alignment=Qt.AlignmentFlag.AlignRight)
dlg.exec()
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
if __name__ == "__main__":
from classes.UtilHelper import get_user_settings_path, load_settings
app = QApplication(sys.argv)
app.setApplicationName(cfg.APP_NAME)
app.setApplicationVersion(cfg.APP_VERSION)
_settings = load_settings(get_user_settings_path(cfg.SETTINGS_FILENAME))
apply_theme(app, _settings.get("theme", cfg.WINDOW_THEME))
window = NotesApp()
window.show()
sys.exit(app.exec())
# ---------------------------------------------------------------------------
# Colour helpers
# ---------------------------------------------------------------------------
def _editor_colors() -> dict:
return {
"bg": "#ffffff",
"fg": "#1e1e1e",
"cursor": "#000000",
"select_bg": "#add6ff",
"line_bg": "#f3f3f3",
"line_fg": "#888888",
}
# ---------------------------------------------------------------------------
# NotesApp
# ---------------------------------------------------------------------------
class NotesApp(ctk.CTk):
def __init__(self):
super().__init__()
self.current_file: Optional[str] = None
self.is_modified: bool = False
self.wm = WindowManager(self)
self._word_wrap: bool = self.wm.get_setting("word_wrap", "on") == "on"
self._build_ui()
self._update_title()
self.wm.apply_initial_geometry()
self.protocol("WM_DELETE_WINDOW", self._on_close)
self._apply_icon(self)
# Initial line-number render after the window is drawn
self.after(100, self._update_line_numbers)
# ------------------------------------------------------------------
# UI construction
# ------------------------------------------------------------------
def _apply_icon(self, window) -> None:
try:
window.iconbitmap(cfg.APP_ICON)
except Exception:
pass
def _build_ui(self) -> None:
self._build_menu()
self._build_toolbar()
self._build_editor_area()
self._build_status_bar()
self._bind_shortcuts()
self._apply_editor_theme()
def _build_menu(self) -> None:
menubar = tk.Menu(self)
self.configure(menu=menubar)
# --- File ---
file_menu = tk.Menu(menubar, tearoff=False)
menubar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="New", accelerator="Ctrl+N", command=self._cmd_new)
file_menu.add_command(label="Open…", accelerator="Ctrl+O", command=self._cmd_open)
file_menu.add_command(label="Save", accelerator="Ctrl+S", command=self._cmd_save)
file_menu.add_command(label="Save As…", accelerator="Ctrl+Shift+S", command=self._cmd_save_as)
file_menu.add_separator()
file_menu.add_command(label="Close", command=self._cmd_close)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=self._on_close)
# --- Edit ---
edit_menu = tk.Menu(menubar, tearoff=False)
menubar.add_cascade(label="Edit", menu=edit_menu)
edit_menu.add_command(label="Settings", command=self._cmd_settings)
edit_menu.add_separator()
self._wrap_var = tk.BooleanVar(value=self._word_wrap)
edit_menu.add_checkbutton(label="Word Wrap", variable=self._wrap_var,
command=self._cmd_toggle_wrap_menu)
edit_menu.add_separator()
edit_menu.add_command(label="Copy", accelerator="Ctrl+C",
command=lambda: self.editor.event_generate("<<Copy>>"))
edit_menu.add_command(label="Paste", accelerator="Ctrl+V",
command=lambda: self.editor.event_generate("<<Paste>>"))
edit_menu.add_command(label="Cut", accelerator="Ctrl+X",
command=lambda: self.editor.event_generate("<<Cut>>"))
edit_menu.add_separator()
edit_menu.add_command(label="Select All", accelerator="Ctrl+A",
command=self._cmd_select_all)
# --- Help ---
help_menu = tk.Menu(menubar, tearoff=False)
menubar.add_cascade(label="Help", menu=help_menu)
help_menu.add_command(label="Manual", command=self._cmd_manual)
help_menu.add_command(label="About", command=self._cmd_about)
def _build_toolbar(self) -> None:
toolbar = tk.Frame(self, bd=1, relief="raised")
toolbar.pack(fill="x", side="top")
btn_opts = {
"relief": "flat", "overrelief": "raised",
"font": ("Segoe UI", 13), "width": 2, "padx": 2, "pady": 1,
"cursor": "arrow", "bd": 1,
}
def sep():
tk.Label(toolbar, text=" ", width=1).pack(side="left")
tk.Frame(toolbar, width=1, bd=0, bg="#bbbbbb").pack(side="left", fill="y", pady=3)
tk.Label(toolbar, text=" ", width=1).pack(side="left")
def btn(icon, cmd, toggle=False):
b = tk.Button(toolbar, text=icon, command=cmd, **btn_opts)
b.pack(side="left", padx=1, pady=2)
return b
# File group
btn("🗋", self._cmd_new)
btn("📂", self._cmd_open)
btn("💾", self._cmd_save)
btn("📄", self._cmd_save_as)
sep()
btn("✕", self._cmd_close)
sep()
# Edit group
btn("⚙", self._cmd_settings)
self._wrap_btn = btn("⇥", self._cmd_toggle_wrap_toolbar)
self._update_wrap_btn_relief()
sep()
btn("✂", lambda: self.editor.event_generate("<<Cut>>"))
btn("⧉", lambda: self.editor.event_generate("<<Copy>>"))
btn("📋", lambda: self.editor.event_generate("<<Paste>>"))
btn("☰", self._cmd_select_all)
sep()
# Help group
btn("📖", self._cmd_manual)
btn("ℹ", self._cmd_about)
def _update_wrap_btn_relief(self) -> None:
if hasattr(self, "_wrap_btn"):
self._wrap_btn.configure(relief="sunken" if self._word_wrap else "flat")
def _cmd_toggle_wrap_toolbar(self) -> None:
self._word_wrap = not self._word_wrap
self._wrap_var.set(self._word_wrap)
self.editor.configure(wrap="word" if self._word_wrap else "none")
self.wm.set_setting("word_wrap", "on" if self._word_wrap else "off")
self._update_wrap_btn_relief()
self._update_line_numbers()
def _build_editor_area(self) -> None:
container = ctk.CTkFrame(self, corner_radius=0, fg_color="transparent")
container.pack(fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(1, weight=1)
# Line-number canvas
self.line_canvas = tk.Canvas(container, width=52, highlightthickness=0, bd=0)
self.line_canvas.grid(row=0, column=0, sticky="ns")
# Main text editor
self.editor = tk.Text(
container,
wrap=("word" if self._word_wrap else "none"),
font=(cfg.EDITOR_FONT_FAMILY, cfg.EDITOR_FONT_SIZE),
undo=True,
autoseparators=True,
maxundo=-1,
padx=8,
pady=4,
bd=0,
highlightthickness=0,
)
self.editor.grid(row=0, column=1, sticky="nsew")
# Vertical scrollbar
self.vscroll = ctk.CTkScrollbar(container, command=self._on_vscroll)
self.vscroll.grid(row=0, column=2, sticky="ns")
self.editor.configure(yscrollcommand=self._on_editor_scroll)
# Bind events
for seq in ("<KeyRelease>", "<ButtonRelease>", "<MouseWheel>", "<Configure>"):
self.editor.bind(seq, self._update_line_numbers)
self.editor.bind("<<Modified>>", self._on_modified)
def _build_status_bar(self) -> None:
bar = ctk.CTkFrame(self, height=28, corner_radius=0)
bar.pack(fill="x", side="bottom")
bar.pack_propagate(False)
self._status_label = ctk.CTkLabel(bar, text="Ready", anchor="w",
font=("Segoe UI", 11))
self._status_label.pack(side="left", padx=10, fill="y")
def _bind_shortcuts(self) -> None:
self.bind("<Control-n>", lambda _e: self._cmd_new())
self.bind("<Control-o>", lambda _e: self._cmd_open())
self.bind("<Control-s>", lambda _e: self._cmd_save())
self.bind("<Control-S>", lambda _e: self._cmd_save_as())
self.bind("<Control-a>", lambda _e: self._cmd_select_all())
# ------------------------------------------------------------------
# Theme
# ------------------------------------------------------------------
def _apply_editor_theme(self) -> None:
c = _editor_colors()
self.editor.configure(
bg=c["bg"],
fg=c["fg"],
insertbackground=c["cursor"],
selectbackground=c["select_bg"],
)
self.line_canvas.configure(bg=c["line_bg"])
self._line_fg = c["line_fg"]
# ------------------------------------------------------------------
# Scroll helpers
# ------------------------------------------------------------------
def _on_vscroll(self, *args) -> None:
"""Scrollbar → editor."""
self.editor.yview(*args)
def _on_editor_scroll(self, first: str, last: str) -> None:
"""Editor viewport changed → update scrollbar and line numbers."""
self.vscroll.set(first, last)
self._update_line_numbers()
# ------------------------------------------------------------------
# Line numbers
# ------------------------------------------------------------------
def _update_line_numbers(self, event=None) -> None:
self.line_canvas.delete("all")
try:
font = (cfg.EDITOR_FONT_FAMILY, cfg.EDITOR_FONT_SIZE)
canvas_w = self.line_canvas.winfo_width() - 4
i = self.editor.index("@0,0")
while True:
dline = self.editor.dlineinfo(i)
if dline is None:
break
# Vertical centre of the display line
y = dline[1] + dline[3] // 2
self.line_canvas.create_text(
canvas_w, y,
anchor="e",
text=i.split(".")[0],
fill=self._line_fg,
font=font,
)
next_i = self.editor.index(f"{i}+1line")
if next_i == i:
break
i = next_i
except Exception:
pass
self._update_status()
# ------------------------------------------------------------------
# Status bar
# ------------------------------------------------------------------
def set_status(self, message: str) -> None:
self._status_label.configure(text=message)
def _update_status(self) -> None:
try:
cursor = self.editor.index("insert")
line, col = cursor.split(".")
name = self.current_file or "Untitled"
mod = " ●" if self.is_modified else ""
self.set_status(f"{name}{mod} Ln {line}, Col {int(col) + 1}")
except Exception:
pass
# ------------------------------------------------------------------
# Title
# ------------------------------------------------------------------
def _update_title(self) -> None:
name = self.current_file or "Untitled"
mod = " •" if self.is_modified else ""
self.title(f"{name}{mod} — {cfg.APP_NAME}")
# ------------------------------------------------------------------
# Modified flag
# ------------------------------------------------------------------
def _on_modified(self, event=None) -> None:
if self.editor.edit_modified():
self.is_modified = True
self._update_title()
self.editor.edit_modified(False)
self._update_line_numbers()
def _reset_modified(self) -> None:
self.is_modified = False
self.editor.edit_modified(False)
self._update_title()
# ------------------------------------------------------------------
# Guard: check for unsaved changes before destructive actions
# ------------------------------------------------------------------
def _check_unsaved(self) -> bool:
"""Returns True when it is safe to continue (saved / discarded / no changes)."""
if not self.is_modified:
return True
answer = messagebox.askyesnocancel(
"Unsaved Changes",
"The document has unsaved changes.\nSave before continuing?",
)
if answer is None:
return False # Cancel
if answer:
return self._cmd_save()
return True # Discard
# ------------------------------------------------------------------
# File commands
# ------------------------------------------------------------------
def _cmd_new(self) -> None:
if not self._check_unsaved():
return
self.editor.delete("1.0", "end")
self.current_file = None
self._reset_modified()
self._update_line_numbers()
self.set_status("New document")
def _cmd_open(self) -> None:
if not self._check_unsaved():
return
path = filedialog.askopenfilename(
title="Open file",
filetypes=[("Text files", "*.txt"), ("All files", "*.*")],
)
if not path:
return
try:
with open(path, "r", encoding="utf-8") as fh:
content = fh.read()
except OSError as exc:
messagebox.showerror("Error", f"Cannot open file:\n{exc}")
return
self.editor.delete("1.0", "end")
self.editor.insert("1.0", content)
self.current_file = path
self._reset_modified()
self._update_line_numbers()
self.set_status(f"Opened: {path}")
def _cmd_save(self) -> bool:
if not self.current_file:
return self._cmd_save_as()
return self._write_to(self.current_file)
def _cmd_save_as(self) -> bool:
path = filedialog.asksaveasfilename(
title="Save As",
defaultextension=".txt",
filetypes=[("Text files", "*.txt"), ("All files", "*.*")],
)
if not path:
return False
return self._write_to(path)
def _write_to(self, path: str) -> bool:
content = self.editor.get("1.0", "end-1c")
try:
with open(path, "w", encoding="utf-8") as fh:
fh.write(content)
except OSError as exc:
messagebox.showerror("Error", f"Cannot save file:\n{exc}")
return False
self.current_file = path
self._reset_modified()
self.set_status(f"Saved: {path}")
return True
def _cmd_close(self) -> None:
if not self._check_unsaved():
return
self.editor.delete("1.0", "end")
self.current_file = None
self._reset_modified()
self._update_line_numbers()
self.set_status("Closed")
def _on_close(self) -> None:
if not self._check_unsaved():
return
self.wm.save_geometry()
self.destroy()
# ------------------------------------------------------------------
# Edit commands
# ------------------------------------------------------------------
def _cmd_select_all(self) -> None:
self.editor.tag_add("sel", "1.0", "end")
self.editor.mark_set("insert", "end")
def _cmd_toggle_wrap(self) -> None:
"""Shared logic called by both menu and toolbar toggle."""
self.editor.configure(wrap="word" if self._word_wrap else "none")
self.wm.set_setting("word_wrap", "on" if self._word_wrap else "off")
if hasattr(self, "_wrap_btn"):
self._wrap_btn.configure(text=self._wrap_btn_label())
self._update_line_numbers()
def _cmd_toggle_wrap_menu(self) -> None:
self._word_wrap = self._wrap_var.get()
self._cmd_toggle_wrap()
self._update_wrap_btn_relief()
def _cmd_settings(self) -> None:
dlg = ctk.CTkToplevel(self)
dlg.title("Settings")
dlg.after(50, lambda: self._apply_icon(dlg))
dlg.geometry("360x220")
dlg.resizable(False, False)
dlg.grab_set()
ctk.CTkLabel(dlg, text="The colour theme is fixed to light.", font=("Segoe UI", 13, "bold")).pack(pady=(24, 6))
ctk.CTkLabel(dlg, text="No dark theme option is available.", font=("Segoe UI", 10)).pack(pady=(6, 0))
def _apply():
ctk.set_appearance_mode("light")
self.wm.set_setting("theme", "light")
self._apply_editor_theme()
self._update_line_numbers()
dlg.destroy()
ctk.CTkButton(dlg, text="Apply", command=_apply, width=120).pack(pady=24)
# ------------------------------------------------------------------
# Help commands
# ------------------------------------------------------------------
def _cmd_manual(self) -> None:
self._show_text_dialog("Manual", cfg.MANUAL_TEXT)
def _cmd_about(self) -> None:
self._show_text_dialog("About", cfg.ABOUT_TEXT)
def _show_text_dialog(self, title: str, text: str) -> None:
dlg = ctk.CTkToplevel(self)
dlg.title(title)
dlg.geometry("620x440")
dlg.grab_set()
dlg.after(50, lambda: self._apply_icon(dlg))
frame = ctk.CTkFrame(dlg, corner_radius=0, fg_color="transparent")
frame.pack(fill="both", expand=True, padx=12, pady=(12, 6))
box = tk.Text(frame, wrap="word", font=("Segoe UI", 12),
relief="flat", bd=0, highlightthickness=0,
padx=10, pady=8)
scroll = ctk.CTkScrollbar(frame, command=box.yview)
box.configure(yscrollcommand=scroll.set)
scroll.pack(side="right", fill="y")
box.pack(fill="both", expand=True)
render_markdown(box, text)
ctk.CTkButton(dlg, text="Close", command=dlg.destroy, width=100).pack(pady=(0, 12))
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
if __name__ == "__main__":
from classes.UtilHelper import get_user_settings_path, load_settings
_settings = load_settings(get_user_settings_path(cfg.SETTINGS_FILENAME))
ctk.set_appearance_mode("light")
ctk.set_default_color_theme("blue")
app = NotesApp()
app.mainloop()