Repository navigation
Expand file tree
/
Copy pathnote6.py
More file actions
1108 lines (974 loc) · 45.3 KB
/
Copy pathnote6.py
File metadata and controls
1108 lines (974 loc) · 45.3 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
#!/usr/bin/env python3
"""
Notepad App for Linux (Enhanced with Sidebar Font Control + Inline Rename)
----------------------------------------------------------------------------
All previous features plus:
- Independent font size adjustment for the page list (sidebar).
- New menu items: View → Increase Sidebar Font / Decrease Sidebar Font.
- Sidebar font size saved in preferences.
- Print support (File → Print, Ctrl+P) using lpr.
- Inline rename: double‑click a page name in the sidebar to edit it directly.
"""
import os
import sys
import json
import time
import shutil
import subprocess
import tempfile
import zipfile
import tkinter as tk
from tkinter import ttk, messagebox, simpledialog, filedialog
from pathlib import Path
# ----------------------------------------------------------------------
# Configuration & Constants
# ----------------------------------------------------------------------
APP_NAME = "Notepad"
PAGES_DIR = os.path.expanduser("~/.local/share/notepad/pages")
CONFIG_DIR = os.path.expanduser("~/.config/notepad")
PREFS_FILE = os.path.join(CONFIG_DIR, "prefs.json")
os.makedirs(PAGES_DIR, exist_ok=True)
os.makedirs(CONFIG_DIR, exist_ok=True)
# Default preferences (added listbox_font_size)
DEFAULT_PREFS = {
"font_family": "Courier",
"font_size": 12,
"listbox_font_size": 10, # New: font size for the page list
"dark_theme": False,
"auto_save_interval": 2000,
"ocr_language": "eng",
"scan_resolution": 300,
}
# ----------------------------------------------------------------------
# Preferences class (updated to include listbox_font_size)
# ----------------------------------------------------------------------
class Preferences:
"""Load and save user preferences from/to a JSON file."""
def __init__(self):
self.data = DEFAULT_PREFS.copy()
self.load()
def load(self):
try:
with open(PREFS_FILE, 'r') as f:
user_data = json.load(f)
self.data.update(user_data)
except (FileNotFoundError, json.JSONDecodeError):
pass
def save(self):
try:
with open(PREFS_FILE, 'w') as f:
json.dump(self.data, f, indent=2)
except Exception as e:
messagebox.showerror("Error", f"Could not save preferences:\n{e}")
def get(self, key):
return self.data.get(key, DEFAULT_PREFS.get(key))
def set(self, key, value):
self.data[key] = value
self.save()
# ----------------------------------------------------------------------
# Utility functions for scanning / OCR (unchanged)
# ----------------------------------------------------------------------
def check_command(cmd):
return shutil.which(cmd) is not None
def scan_and_ocr(parent_widget, resolution=None, lang='eng'):
if not check_command("scanimage"):
messagebox.showerror("Scanner missing",
"The 'scanimage' command (from sane-utils) is not installed.")
return None
if not check_command("tesseract"):
messagebox.showerror("Tesseract missing",
"Tesseract OCR is not installed.")
return None
if resolution is None:
resolution = 300
with tempfile.NamedTemporaryFile(suffix=".pnm", delete=False) as tmp_img:
img_path = tmp_img.name
try:
subprocess.run(["scanimage", "--resolution", str(resolution),
"--format=pnm", "--output-file", img_path],
check=True, capture_output=True, text=True)
with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as tmp_txt:
txt_path = tmp_txt.name
subprocess.run(["tesseract", img_path, txt_path[:-4], "-l", lang],
check=True, capture_output=True, text=True)
with open(txt_path, "r", encoding="utf-8") as f:
text = f.read()
return text
except subprocess.CalledProcessError as e:
messagebox.showerror("Scanning/OCR failed", e.stderr)
return None
except Exception as e:
messagebox.showerror("Error", f"Unexpected error: {e}")
return None
finally:
for path in [img_path, txt_path]:
try:
if os.path.exists(path):
os.unlink(path)
except:
pass
def ocr_from_image(parent_widget, lang='eng'):
if not check_command("tesseract"):
messagebox.showerror("Tesseract missing", "Tesseract OCR is not installed.")
return None
file_path = filedialog.askopenfilename(
title="Select an image for OCR",
filetypes=[("Image files", "*.png *.jpg *.jpeg *.tiff *.bmp *.pnm"), ("All files", "*.*")]
)
if not file_path:
return None
with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as tmp_txt:
txt_path = tmp_txt.name
try:
subprocess.run(["tesseract", file_path, txt_path[:-4], "-l", lang],
check=True, capture_output=True, text=True)
with open(txt_path, "r", encoding="utf-8") as f:
text = f.read()
return text
except subprocess.CalledProcessError as e:
messagebox.showerror("OCR failed", e.stderr)
return None
finally:
try:
os.unlink(txt_path)
except:
pass
# ----------------------------------------------------------------------
# Main Application Class (with sidebar font control + print + inline rename)
# ----------------------------------------------------------------------
class NotepadApp:
def __init__(self, root):
self.root = root
self.root.title(APP_NAME)
self.root.geometry("900x700")
self.prefs = Preferences()
self.current_page = None
self.dirty = False
self.pages_list = []
self.auto_save_job = None
# For inline editing of page names
self.edit_entry = None # Entry widget when editing
self.editing_index = None # Index of item being edited
self.original_name = "" # Original name before editing
self.create_menu()
self.create_widgets()
self.apply_theme() # sets colors and fonts for both text and listbox
self.refresh_page_list()
self.update_title()
# Bind keyboard shortcuts
self.root.bind("<Control-s>", lambda e: self.save_page())
self.root.bind("<Control-n>", lambda e: self.new_page())
self.root.bind("<Control-d>", lambda e: self.delete_page())
self.root.bind("<Control-r>", lambda e: self.rename_page())
self.root.bind("<Control-f>", lambda e: self.open_search_replace())
self.root.bind("<Control-Shift-F>", lambda e: self.open_full_text_search())
self.root.bind("<Control-p>", lambda e: self.print_page()) # New print shortcut
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
# ------------------------------------------------------------------
# Menu creation (added print and sidebar font controls)
# ------------------------------------------------------------------
def create_menu(self):
menubar = tk.Menu(self.root)
# File menu
file_menu = tk.Menu(menubar, tearoff=0)
file_menu.add_command(label="New Page", accelerator="Ctrl+N", command=self.new_page)
file_menu.add_command(label="Rename Page", accelerator="Ctrl+R", command=self.rename_page)
file_menu.add_command(label="Delete Page", accelerator="Ctrl+D", command=self.delete_page)
file_menu.add_separator()
file_menu.add_command(label="Save", accelerator="Ctrl+S", command=self.save_page)
file_menu.add_command(label="Save As...", command=self.save_page_as)
file_menu.add_separator()
file_menu.add_command(label="Print...", accelerator="Ctrl+P", command=self.print_page)
file_menu.add_separator()
file_menu.add_command(label="Export Library...", command=self.export_library)
file_menu.add_command(label="Import Library...", command=self.import_library)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=self.on_closing)
menubar.add_cascade(label="File", menu=file_menu)
# Edit menu
edit_menu = tk.Menu(menubar, tearoff=0)
edit_menu.add_command(label="Preferences", command=self.open_preferences)
menubar.add_cascade(label="Edit", menu=edit_menu)
# View menu (now with separate sidebar font controls)
view_menu = tk.Menu(menubar, tearoff=0)
view_menu.add_command(label="Toggle Dark Mode", command=self.toggle_dark_mode)
view_menu.add_separator()
view_menu.add_command(label="Increase Editor Font", command=self.increase_font)
view_menu.add_command(label="Decrease Editor Font", command=self.decrease_font)
view_menu.add_separator()
view_menu.add_command(label="Increase Sidebar Font", command=self.increase_listbox_font)
view_menu.add_command(label="Decrease Sidebar Font", command=self.decrease_listbox_font)
menubar.add_cascade(label="View", menu=view_menu)
# Search menu
search_menu = tk.Menu(menubar, tearoff=0)
search_menu.add_command(label="Find/Replace", accelerator="Ctrl+F", command=self.open_search_replace)
search_menu.add_command(label="Find in All Pages", accelerator="Ctrl+Shift+F", command=self.open_full_text_search)
menubar.add_cascade(label="Search", menu=search_menu)
# Help menu
help_menu = tk.Menu(menubar, tearoff=0)
help_menu.add_command(label="About", command=self.show_about)
menubar.add_cascade(label="Help", menu=help_menu)
self.root.config(menu=menubar)
# ------------------------------------------------------------------
# GUI Layout (set listbox font at creation)
# ------------------------------------------------------------------
def create_widgets(self):
"""Create left panel (page list + filter) and right panel (editor)."""
self.paned = tk.PanedWindow(self.root, orient=tk.HORIZONTAL, sashrelief=tk.RAISED, sashwidth=5)
self.paned.pack(fill=tk.BOTH, expand=True)
# Left frame: page management
left_frame = tk.Frame(self.paned, width=250)
self.paned.add(left_frame, minsize=200)
# Filter entry
filter_frame = tk.Frame(left_frame)
filter_frame.pack(fill=tk.X, padx=5, pady=5)
tk.Label(filter_frame, text="Filter:").pack(side=tk.LEFT)
self.filter_var = tk.StringVar()
self.filter_var.trace('w', lambda *args: self.refresh_page_list())
filter_entry = tk.Entry(filter_frame, textvariable=self.filter_var)
filter_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
# Sort options
sort_frame = tk.Frame(left_frame)
sort_frame.pack(fill=tk.X, padx=5, pady=2)
self.sort_var = tk.StringVar(value="name")
tk.Radiobutton(sort_frame, text="Name", variable=self.sort_var,
value="name", command=self.refresh_page_list).pack(side=tk.LEFT)
tk.Radiobutton(sort_frame, text="Modified", variable=self.sort_var,
value="mtime", command=self.refresh_page_list).pack(side=tk.LEFT)
# Listbox with scrollbar (font set from preferences)
list_frame = tk.Frame(left_frame)
list_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
self.listbox = tk.Listbox(
list_frame,
selectmode=tk.SINGLE,
exportselection=False,
font=(self.prefs.get('font_family'), self.prefs.get('listbox_font_size'))
)
scrollbar = tk.Scrollbar(list_frame, orient=tk.VERTICAL, command=self.listbox.yview)
self.listbox.config(yscrollcommand=scrollbar.set)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.listbox.bind('<<ListboxSelect>>', self.on_page_select)
# Double-click to start inline editing
self.listbox.bind('<Double-Button-1>', self.start_edit_page)
# Buttons under listbox
btn_frame = tk.Frame(left_frame)
btn_frame.pack(fill=tk.X, padx=5, pady=5)
tk.Button(btn_frame, text="New Page", command=self.new_page, width=10).pack(side=tk.LEFT, padx=2)
tk.Button(btn_frame, text="Rename", command=self.rename_page, width=8).pack(side=tk.LEFT, padx=2)
tk.Button(btn_frame, text="Delete", command=self.delete_page, width=8).pack(side=tk.LEFT, padx=2)
# Right frame: text editor
right_frame = tk.Frame(self.paned)
self.paned.add(right_frame, minsize=400)
# Text area with scrollbars (font set from preferences)
text_frame = tk.Frame(right_frame)
text_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
self.text = tk.Text(
text_frame,
wrap=tk.WORD,
undo=True,
font=(self.prefs.get('font_family'), self.prefs.get('font_size'))
)
v_scroll = tk.Scrollbar(text_frame, orient=tk.VERTICAL, command=self.text.yview)
h_scroll = tk.Scrollbar(text_frame, orient=tk.HORIZONTAL, command=self.text.xview)
self.text.config(yscrollcommand=v_scroll.set, xscrollcommand=h_scroll.set)
v_scroll.pack(side=tk.RIGHT, fill=tk.Y)
h_scroll.pack(side=tk.BOTTOM, fill=tk.X)
self.text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.text.bind('<<Modified>>', self.on_text_modified)
self.text.bind('<KeyRelease>', self.schedule_auto_save)
# Bottom action buttons
action_frame = tk.Frame(right_frame)
action_frame.pack(fill=tk.X, padx=5, pady=5)
tk.Button(action_frame, text="Save", command=self.save_page, width=10).pack(side=tk.LEFT, padx=2)
tk.Button(action_frame, text="Scan & OCR", command=self.scan_and_insert, width=12).pack(side=tk.LEFT, padx=2)
tk.Button(action_frame, text="OCR Image", command=self.ocr_image_and_insert, width=12).pack(side=tk.LEFT, padx=2)
tk.Button(action_frame, text="Exit", command=self.on_closing, width=8).pack(side=tk.RIGHT, padx=2)
# ------------------------------------------------------------------
# Page Management (unchanged, except added inline editing)
# ------------------------------------------------------------------
def refresh_page_list(self):
filter_text = self.filter_var.get().lower()
sort_by = self.sort_var.get()
pages = []
try:
for f in os.listdir(PAGES_DIR):
if f.endswith('.txt'):
base = f[:-4]
if filter_text in base.lower():
path = os.path.join(PAGES_DIR, f)
mtime = os.path.getmtime(path)
pages.append((base, mtime))
except OSError as e:
messagebox.showerror("Error", f"Cannot read pages directory:\n{e}")
return
if sort_by == "name":
pages.sort(key=lambda x: x[0].lower())
else:
pages.sort(key=lambda x: x[1], reverse=True)
self.pages_list = [p[0] for p in pages]
self.listbox.delete(0, tk.END)
for base in self.pages_list:
self.listbox.insert(tk.END, base)
if self.current_page and self.current_page in self.pages_list:
idx = self.pages_list.index(self.current_page)
self.listbox.selection_clear(0, tk.END)
self.listbox.selection_set(idx)
self.listbox.see(idx)
def get_page_path(self, page_name):
return os.path.join(PAGES_DIR, page_name + '.txt')
def on_page_select(self, event):
# If we are in the middle of editing, cancel it to avoid confusion
if self.edit_entry is not None:
self.cancel_edit()
selection = self.listbox.curselection()
if not selection:
return
page_name = self.listbox.get(selection[0])
if self.dirty and self.current_page:
self.save_page()
self.load_page(page_name)
def load_page(self, page_name):
self.current_page = page_name
path = self.get_page_path(page_name)
try:
with open(path, 'r', encoding='utf-8') as f:
content = f.read()
except FileNotFoundError:
content = ""
except Exception as e:
messagebox.showerror("Error", f"Could not load page:\n{e}")
return
self.text.delete(1.0, tk.END)
self.text.insert(1.0, content)
self.text.edit_modified(False)
self.dirty = False
self.update_title()
def save_page(self):
if not self.current_page:
self.save_page_as()
return
content = self.text.get(1.0, tk.END).rstrip('\n')
path = self.get_page_path(self.current_page)
try:
with open(path, 'w', encoding='utf-8') as f:
f.write(content)
self.text.edit_modified(False)
self.dirty = False
self.update_title()
except Exception as e:
messagebox.showerror("Save failed", f"Could not save page:\n{e}")
def save_page_as(self):
name = simpledialog.askstring("Save As", "Enter new page name:", parent=self.root)
if not name:
return
name = os.path.basename(name.strip())
if not name:
messagebox.showerror("Invalid name", "Page name cannot be empty.")
return
path = self.get_page_path(name)
if os.path.exists(path):
if not messagebox.askyesno("Overwrite", f"Page '{name}' already exists. Overwrite?"):
return
try:
content = self.text.get(1.0, tk.END).rstrip('\n')
with open(path, 'w', encoding='utf-8') as f:
f.write(content)
except Exception as e:
messagebox.showerror("Save failed", f"Could not save page:\n{e}")
return
if name != self.current_page:
self.current_page = name
self.refresh_page_list()
self.select_page_by_name(name)
self.text.edit_modified(False)
self.dirty = False
self.update_title()
def new_page(self):
name = simpledialog.askstring("New Page", "Enter page name:", parent=self.root)
if not name:
return
name = os.path.basename(name.strip())
if not name:
messagebox.showerror("Invalid name", "Page name cannot be empty.")
return
path = self.get_page_path(name)
if os.path.exists(path):
messagebox.showerror("Error", f"Page '{name}' already exists.")
return
try:
with open(path, 'w', encoding='utf-8') as f:
f.write("")
except Exception as e:
messagebox.showerror("Error", f"Could not create page:\n{e}")
return
self.refresh_page_list()
self.select_page_by_name(name)
def rename_page(self):
"""Rename via dialog (kept for compatibility)."""
if not self.current_page:
messagebox.showwarning("No page", "Please select a page to rename.")
return
new_name = simpledialog.askstring("Rename Page",
f"Rename '{self.current_page}' to:",
parent=self.root,
initialvalue=self.current_page)
if not new_name or new_name == self.current_page:
return
self._rename_page_impl(self.current_page, new_name)
def _rename_page_impl(self, old_name, new_name):
"""Actual rename logic, reused by inline editing."""
new_name = os.path.basename(new_name.strip())
if not new_name:
messagebox.showerror("Invalid name", "Page name cannot be empty.")
return False
if new_name == old_name:
return False # No change
old_path = self.get_page_path(old_name)
new_path = self.get_page_path(new_name)
if os.path.exists(new_path):
messagebox.showerror("Error", f"Page '{new_name}' already exists.")
return False
try:
os.rename(old_path, new_path)
except Exception as e:
messagebox.showerror("Rename failed", f"Could not rename page:\n{e}")
return False
# If the renamed page is currently open, update current_page
if self.current_page == old_name:
self.current_page = new_name
# Refresh list and select the renamed page
self.refresh_page_list()
self.select_page_by_name(new_name)
self.update_title()
return True
def delete_page(self):
if not self.current_page:
messagebox.showwarning("No page", "Please select a page to delete.")
return
if not messagebox.askyesno("Confirm Delete",
f"Are you sure you want to delete '{self.current_page}'?"):
return
path = self.get_page_path(self.current_page)
try:
os.remove(path)
except Exception as e:
messagebox.showerror("Delete failed", f"Could not delete page:\n{e}")
return
self.text.delete(1.0, tk.END)
self.text.edit_modified(False)
self.current_page = None
self.dirty = False
self.refresh_page_list()
self.update_title()
def select_page_by_name(self, page_name):
for i, disp in enumerate(self.listbox.get(0, tk.END)):
if disp == page_name:
self.listbox.selection_clear(0, tk.END)
self.listbox.selection_set(i)
self.listbox.see(i)
self.load_page(page_name)
break
# ------------------------------------------------------------------
# Inline editing of page names (new feature)
# ------------------------------------------------------------------
def start_edit_page(self, event):
"""Double-click on a listbox item: replace it with an Entry for editing."""
# If already editing, cancel previous edit
if self.edit_entry is not None:
self.cancel_edit()
# Get the index of the clicked item
index = self.listbox.nearest(event.y)
if index < 0:
return
# Ensure the click was actually on that item (nearest might be off)
bbox = self.listbox.bbox(index)
if bbox and (event.y < bbox[1] or event.y > bbox[1] + bbox[3]):
return
self.editing_index = index
self.original_name = self.listbox.get(index)
# Get the bounding box of the item to place the Entry over it
x, y, width, height = self.listbox.bbox(index)
# The listbox might be scrolled; we need to map to listbox coordinates
# The Entry will be placed as a child of the listbox, at (x, y)
self.edit_entry = tk.Entry(self.listbox, borderwidth=0, highlightthickness=1)
self.edit_entry.place(x=x, y=y, width=width, height=height)
self.edit_entry.insert(0, self.original_name)
self.edit_entry.select_range(0, tk.END)
self.edit_entry.icursor(tk.END)
self.edit_entry.focus()
# Bind events to finish editing
self.edit_entry.bind('<Return>', self.finish_edit)
self.edit_entry.bind('<Escape>', self.cancel_edit)
self.edit_entry.bind('<FocusOut>', self.finish_edit) # Commit on focus loss
def finish_edit(self, event=None):
"""Finish inline editing: rename the page if valid."""
if self.edit_entry is None or self.editing_index is None:
return
new_name = self.edit_entry.get().strip()
self.edit_entry.destroy()
self.edit_entry = None
idx = self.editing_index
self.editing_index = None
# If new name is empty or same as original, just cancel
if not new_name or new_name == self.original_name:
return
# Perform the rename using the shared implementation
self._rename_page_impl(self.original_name, new_name)
# Note: _rename_page_impl refreshes the list and selects the renamed page
def cancel_edit(self, event=None):
"""Cancel inline editing without changes."""
if self.edit_entry is not None:
self.edit_entry.destroy()
self.edit_entry = None
self.editing_index = None
self.original_name = ""
# ------------------------------------------------------------------
# Text editing helpers (unchanged)
# ------------------------------------------------------------------
def on_text_modified(self, event=None):
if self.text.edit_modified():
self.dirty = True
self.update_title()
self.text.edit_modified(False)
def schedule_auto_save(self, event=None):
if self.auto_save_job:
self.root.after_cancel(self.auto_save_job)
interval = self.prefs.get('auto_save_interval')
self.auto_save_job = self.root.after(interval, self.auto_save)
def auto_save(self):
if self.dirty and self.current_page:
self.save_page()
self.auto_save_job = None
def update_title(self):
base = APP_NAME
if self.current_page:
title = f"{base} - {self.current_page}"
if self.dirty:
title += " *"
else:
title = base
self.root.title(title)
# ------------------------------------------------------------------
# Theme and font (updated to handle listbox font)
# ------------------------------------------------------------------
def apply_theme(self):
"""Apply dark/light theme and fonts to both text and listbox."""
if self.prefs.get('dark_theme'):
bg = "#2b2b2b"
fg = "#ffffff"
insertbackground = 'white'
select_bg = '#4a4a4a'
else:
bg = "#ffffff"
fg = "#000000"
insertbackground = 'black'
select_bg = '#c0c0c0'
# Text widget
self.text.config(
bg=bg,
fg=fg,
insertbackground=insertbackground,
font=(self.prefs.get('font_family'), self.prefs.get('font_size'))
)
# Listbox (use its own font size)
self.listbox.config(
bg=bg,
fg=fg,
selectbackground=select_bg,
font=(self.prefs.get('font_family'), self.prefs.get('listbox_font_size'))
)
# Root background
self.root.config(bg=bg)
def toggle_dark_mode(self):
self.prefs.set('dark_theme', not self.prefs.get('dark_theme'))
self.apply_theme()
# Editor font controls
def increase_font(self):
size = self.prefs.get('font_size') + 1
self.prefs.set('font_size', size)
self.apply_theme()
def decrease_font(self):
size = max(8, self.prefs.get('font_size') - 1)
self.prefs.set('font_size', size)
self.apply_theme()
# Sidebar (listbox) font controls
def increase_listbox_font(self):
size = self.prefs.get('listbox_font_size') + 1
self.prefs.set('listbox_font_size', size)
self.apply_theme() # apply_theme now sets listbox font as well
def decrease_listbox_font(self):
size = max(6, self.prefs.get('listbox_font_size') - 1) # allow smaller than editor
self.prefs.set('listbox_font_size', size)
self.apply_theme()
# ------------------------------------------------------------------
# Print functionality (new)
# ------------------------------------------------------------------
def print_page(self):
"""Print the current page content using the system's lpr command."""
content = self.text.get(1.0, tk.END).rstrip('\n')
if not content.strip():
messagebox.showinfo("Print", "Nothing to print.")
return
if not check_command("lpr"):
messagebox.showerror("Print Error",
"The 'lpr' command is not available.\n"
"Please install CUPS or configure your printer.")
return
# Write content to a temporary file
try:
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt',
delete=False, encoding='utf-8') as tmp:
tmp.write(content)
tmp_path = tmp.name
except Exception as e:
messagebox.showerror("Print Error", f"Could not create temporary file:\n{e}")
return
# Send to printer
try:
subprocess.run(["lpr", tmp_path], check=True)
messagebox.showinfo("Print", "Document sent to the default printer.")
except subprocess.CalledProcessError as e:
messagebox.showerror("Print Error", f"Printing failed:\n{e}")
finally:
try:
os.unlink(tmp_path)
except:
pass
# ------------------------------------------------------------------
# Search & Replace (unchanged)
# ------------------------------------------------------------------
def open_search_replace(self):
SearchReplaceDialog(self.root, self.text)
def open_full_text_search(self):
FullTextSearchDialog(self.root, self)
# ------------------------------------------------------------------
# Preferences dialog (unchanged – does not include listbox font)
# ------------------------------------------------------------------
def open_preferences(self):
PreferencesDialog(self.root, self.prefs, self.apply_theme)
# ------------------------------------------------------------------
# Scanning / OCR (unchanged)
# ------------------------------------------------------------------
def scan_and_insert(self):
text = scan_and_ocr(self.root,
resolution=self.prefs.get('scan_resolution'),
lang=self.prefs.get('ocr_language'))
if text is not None:
self.text.insert(tk.INSERT, text)
self.dirty = True
self.update_title()
def ocr_image_and_insert(self):
text = ocr_from_image(self.root, lang=self.prefs.get('ocr_language'))
if text is not None:
self.text.insert(tk.INSERT, text)
self.dirty = True
self.update_title()
# ------------------------------------------------------------------
# Import / Export (unchanged)
# ------------------------------------------------------------------
def export_library(self):
filename = filedialog.asksaveasfilename(
title="Export Library As",
defaultextension=".zip",
filetypes=[("Zip files", "*.zip"), ("All files", "*.*")],
initialfile="notebook_backup.zip"
)
if not filename:
return
try:
with zipfile.ZipFile(filename, 'w', zipfile.ZIP_DEFLATED) as zf:
for page in self.pages_list:
page_path = self.get_page_path(page)
zf.write(page_path, arcname=page + '.txt')
messagebox.showinfo("Export Successful",
f"Exported {len(self.pages_list)} pages to:\n{filename}")
except Exception as e:
messagebox.showerror("Export Failed", f"Could not create zip file:\n{e}")
def import_library(self):
filename = filedialog.askopenfilename(
title="Import Library from Zip",
filetypes=[("Zip files", "*.zip"), ("All files", "*.*")]
)
if not filename:
return
overwrite_all = False
skip_all = False
try:
with zipfile.ZipFile(filename, 'r') as zf:
members = [m for m in zf.namelist() if m.endswith('.txt')]
if not members:
messagebox.showwarning("No Pages", "The selected zip file contains no .txt files.")
return
imported_count = 0
skipped_count = 0
overwritten_count = 0
for member in members:
base = os.path.basename(member)
if not base.endswith('.txt'):
continue
page_name = base[:-4]
target_path = self.get_page_path(page_name)
if os.path.exists(target_path):
if skip_all:
skipped_count += 1
continue
elif not overwrite_all:
response = messagebox.askyesnocancel(
"File Exists",
f"Page '{page_name}' already exists.\n"
"Yes = Overwrite, No = Skip, Cancel = Stop Import"
)
if response is None:
break
elif response:
overwritten_count += 1
else:
skipped_count += 1
continue
else:
overwritten_count += 1
else:
imported_count += 1
zf.extract(member, path=PAGES_DIR)
if os.path.dirname(member):
extracted_path = os.path.join(PAGES_DIR, member)
final_path = target_path
if extracted_path != final_path:
shutil.move(extracted_path, final_path)
dirpath = os.path.dirname(extracted_path)
while dirpath != PAGES_DIR:
try:
os.rmdir(dirpath)
except OSError:
break
dirpath = os.path.dirname(dirpath)
self.refresh_page_list()
summary = f"Import completed.\nNew: {imported_count}\nOverwritten: {overwritten_count}\nSkipped: {skipped_count}"
messagebox.showinfo("Import Summary", summary)
except Exception as e:
messagebox.showerror("Import Failed", f"Could not read zip file:\n{e}")
# ------------------------------------------------------------------
# Exit handling (unchanged)
# ------------------------------------------------------------------
def on_closing(self):
if self.dirty and self.current_page:
self.save_page()
self.root.destroy()
# ------------------------------------------------------------------
# About dialog (updated to mention inline rename)
# ------------------------------------------------------------------
def show_about(self):
about_text = f"""{APP_NAME} - Enhanced Notepad
Version 2.4
A simple but powerful notepad for Linux.
Pages stored in: {PAGES_DIR}
Features:
• Page filtering and sorting
• Full-text search across pages
• Auto-save, theming, font control
• Independent sidebar font size (View menu)
• Print support (File → Print, Ctrl+P)
• **Inline rename**: double‑click a page name in the sidebar to edit it
• Scan & OCR (requires sane-utils and tesseract)
• Import/Export entire library as a single zip file
No data loss – all pages are plain text files.
"""
messagebox.showinfo("About", about_text)
# ----------------------------------------------------------------------
# Search & Replace Dialog (unchanged)
# ----------------------------------------------------------------------
class SearchReplaceDialog(tk.Toplevel):
def __init__(self, parent, text_widget):
super().__init__(parent)
self.text_widget = text_widget
self.title("Find/Replace")
self.geometry("400x200")
self.resizable(False, False)
tk.Label(self, text="Find:").grid(row=0, column=0, padx=5, pady=5, sticky='e')
self.find_var = tk.StringVar()
tk.Entry(self, textvariable=self.find_var, width=30).grid(row=0, column=1, padx=5, pady=5)
tk.Label(self, text="Replace with:").grid(row=1, column=0, padx=5, pady=5, sticky='e')
self.replace_var = tk.StringVar()
tk.Entry(self, textvariable=self.replace_var, width=30).grid(row=1, column=1, padx=5, pady=5)
self.case_var = tk.BooleanVar()
tk.Checkbutton(self, text="Case sensitive", variable=self.case_var).grid(row=2, column=0, columnspan=2, pady=5)
btn_frame = tk.Frame(self)
btn_frame.grid(row=3, column=0, columnspan=2, pady=10)
tk.Button(btn_frame, text="Find Next", command=self.find_next).pack(side=tk.LEFT, padx=5)
tk.Button(btn_frame, text="Replace", command=self.replace).pack(side=tk.LEFT, padx=5)
tk.Button(btn_frame, text="Replace All", command=self.replace_all).pack(side=tk.LEFT, padx=5)
tk.Button(btn_frame, text="Close", command=self.destroy).pack(side=tk.LEFT, padx=5)
def find_next(self):
text = self.text_widget
search_query = self.find_var.get()
if not search_query:
return
text.tag_remove('sel', 1.0, tk.END)
start_pos = text.index(tk.INSERT)
found = text.search(search_query, start_pos, nocase=not self.case_var.get(),
stopindex=tk.END, forwards=True)
if not found:
found = text.search(search_query, 1.0, nocase=not self.case_var.get(),
stopindex=tk.END, forwards=True)
if found:
end = f"{found}+{len(search_query)}c"
text.tag_add('sel', found, end)
text.mark_set(tk.INSERT, end)
text.see(found)
else:
messagebox.showinfo("Find", f"'{search_query}' not found.")
def replace(self):
text = self.text_widget
search_query = self.find_var.get()
replace_text = self.replace_var.get()
if not search_query:
return
try:
selected = text.get(tk.SEL_FIRST, tk.SEL_LAST)
except tk.TclError:
self.find_next()
return
if (self.case_var.get() and selected == search_query) or \
(not self.case_var.get() and selected.lower() == search_query.lower()):
text.delete(tk.SEL_FIRST, tk.SEL_LAST)
text.insert(tk.INSERT, replace_text)
self.find_next()
else:
self.find_next()
def replace_all(self):
text = self.text_widget
search_query = self.find_var.get()
replace_text = self.replace_var.get()
if not search_query:
return
text.mark_set(tk.INSERT, 1.0)
count = 0
while True:
found = text.search(search_query, tk.INSERT, nocase=not self.case_var.get(),
stopindex=tk.END, forwards=True)
if not found:
break
end = f"{found}+{len(search_query)}c"
text.delete(found, end)
text.insert(found, replace_text)
count += 1
text.mark_set(tk.INSERT, f"{found}+{len(replace_text)}c")
messagebox.showinfo("Replace All", f"Replaced {count} occurrence(s).")
# ----------------------------------------------------------------------
# Full-Text Search Dialog (unchanged)
# ----------------------------------------------------------------------
class FullTextSearchDialog(tk.Toplevel):
def __init__(self, parent, app):
super().__init__(parent)
self.app = app
self.title("Find in All Pages")
self.geometry("600x400")
top_frame = tk.Frame(self)
top_frame.pack(fill=tk.X, padx=5, pady=5)
tk.Label(top_frame, text="Search for:").pack(side=tk.LEFT)
self.term_var = tk.StringVar()
tk.Entry(top_frame, textvariable=self.term_var, width=40).pack(side=tk.LEFT, padx=5)
self.case_var = tk.BooleanVar()
tk.Checkbutton(top_frame, text="Case sensitive", variable=self.case_var).pack(side=tk.LEFT, padx=5)
tk.Button(top_frame, text="Search", command=self.do_search).pack(side=tk.LEFT, padx=5)
list_frame = tk.Frame(self)
list_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
self.results_listbox = tk.Listbox(list_frame)
scrollbar = tk.Scrollbar(list_frame, orient=tk.VERTICAL, command=self.results_listbox.yview)
self.results_listbox.config(yscrollcommand=scrollbar.set)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.results_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.results_listbox.bind('<Double-Button-1>', self.open_result)
self.status_var = tk.StringVar()