-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTextFileCompareApp.py
More file actions
968 lines (846 loc) · 37.1 KB
/
TextFileCompareApp.py
File metadata and controls
968 lines (846 loc) · 37.1 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
import tkinter as tk
from tkinter import filedialog, messagebox, simpledialog
import difflib
import os
import json
from datetime import datetime
import webbrowser
import urllib.parse
import tempfile
import subprocess
import sys
from pathlib import Path
import re
# ---- Optional Drag & Drop support (graceful fallback if missing) ----
try:
from tkinterdnd2 import TkinterDnD, DND_FILES
DND_AVAILABLE = True
except Exception:
DND_AVAILABLE = False
class FileComparatorApp:
LICENSE_FILE = "file_comparator_license.json"
SETTINGS_FILE = "file_comparator_settings.json"
VALID_LICENSE_KEYS = {
# TODO: Replace these placeholders with your real keys
"TFS-DEMO-2025": {"type": "full"},
"DP-DEMO-2025": {"type": "full"},
}
def __init__(self, root):
self.root = root
self.root.title("Enhanced File Comparator")
self.file1_content = ""
self.file2_content = ""
self.file1_path = None
self.file2_path = None
# Licensing
self.is_licensed = False
self.license_metadata = None
# Theme setup
self.themes = {
"Light": {
"bg": "#f0f0f0",
"fg": "#000000",
"text_bg": "#ffffff",
"text_fg": "#000000",
"accent": "#005a9e",
"status_bg": "#e0e0e0",
"status_fg": "#000000",
"diff_added": "#d4ffd4",
"diff_removed": "#ffd4d4",
},
"Dark": {
"bg": "#1e1e1e",
"fg": "#ffffff",
"text_bg": "#252526",
"text_fg": "#ffffff",
"accent": "#1f6fbd",
"status_bg": "#333333",
"status_fg": "#ffffff",
"diff_added": "#264f78",
"diff_removed": "#6c2022",
},
"Sepia": {
"bg": "#f4ecd8",
"fg": "#5b4636",
"text_bg": "#fbf5e9",
"text_fg": "#5b4636",
"accent": "#8b5a2b",
"status_bg": "#e8ddc7",
"status_fg": "#5b4636",
"diff_added": "#e1f3d8",
"diff_removed": "#f7d7d7",
},
}
self.current_theme_name = "Light"
# Final content selection (for "share" feature)
self.final_content = None
self.final_source = None
# Track if DND is available
self.dnd_available = DND_AVAILABLE
# Build UI
self.create_widgets()
self.load_settings() # theme + geometry persistence
self.load_license()
self.apply_theme(self.current_theme_name)
self.set_app_icon()
# Keyboard accelerators
self.bind_shortcuts()
# Save settings on close
self.root.protocol("WM_DELETE_WINDOW", self.on_close)
# ---------- App icon ----------
def set_app_icon(self):
"""Attempt to set a custom app icon if app_icon.ico or app_icon.png exists."""
try:
if os.name == "nt":
if os.path.exists("app_icon.ico"):
self.root.iconbitmap("app_icon.ico")
return
# Fallback PNG (cross-platform)
if os.path.exists("app_icon.png"):
img = tk.PhotoImage(file="app_icon.png")
self.root.iconphoto(True, img)
self._icon_img = img # prevent GC
except Exception:
pass
# ------------- UI CREATION / THEMES / MENUS -----------------
def create_widgets(self):
menubar = tk.Menu(self.root)
# File menu
file_menu = tk.Menu(menubar, tearoff=0)
file_menu.add_command(label="Open File 1 (Ctrl+1)", command=lambda: self.upload_file(1))
file_menu.add_command(label="Open File 2 (Ctrl+2)", command=lambda: self.upload_file(2))
file_menu.add_separator()
file_menu.add_command(label="Reset", command=self.reset_app)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=self.root.quit)
menubar.add_cascade(label="File", menu=file_menu)
# Themes menu
theme_menu = tk.Menu(menubar, tearoff=0)
for theme_name in self.themes:
theme_menu.add_command(
label=theme_name,
command=lambda name=theme_name: self.apply_theme(name)
)
theme_menu.add_separator()
theme_menu.add_command(label="Cycle Theme (Ctrl+T)", command=self.cycle_theme)
menubar.add_cascade(label="Themes", menu=theme_menu)
# License menu
license_menu = tk.Menu(menubar, tearoff=0)
license_menu.add_command(label="Enter License Key", command=self.prompt_for_license)
license_menu.add_command(label="View License Status", command=self.show_license_status)
menubar.add_cascade(label="License", menu=license_menu)
# Help menu
help_menu = tk.Menu(menubar, tearoff=0)
help_menu.add_command(label="About (F1)", command=self.show_about)
menubar.add_cascade(label="Help", menu=help_menu)
self.root.config(menu=menubar)
# File 1 Section
self.file1_frame = tk.LabelFrame(self.root, text="File 1")
self.file1_frame.pack(padx=10, pady=5, fill=tk.BOTH, expand=True)
self.file1_text = tk.Text(self.file1_frame, height=10, width=40, wrap=tk.WORD)
self.file1_text.pack(side=tk.LEFT, padx=5, pady=5, fill=tk.BOTH, expand=True)
self.file1_text.bind("<KeyRelease>", lambda e: self.update_file_status(1))
self.upload_btn1 = tk.Button(self.file1_frame, text="Upload File 1", command=lambda: self.upload_file(1))
self.upload_btn1.pack(side=tk.RIGHT, padx=5, pady=5)
# File 2 Section
self.file2_frame = tk.LabelFrame(self.root, text="File 2")
self.file2_frame.pack(padx=10, pady=5, fill=tk.BOTH, expand=True)
self.file2_text = tk.Text(self.file2_frame, height=10, width=40, wrap=tk.WORD)
self.file2_text.pack(side=tk.LEFT, padx=5, pady=5, fill=tk.BOTH, expand=True)
self.file2_text.bind("<KeyRelease>", lambda e: self.update_file_status(2))
self.upload_btn2 = tk.Button(self.file2_frame, text="Upload File 2", command=lambda: self.upload_file(2))
self.upload_btn2.pack(side=tk.RIGHT, padx=5, pady=5)
# Drag & Drop registration (optional)
if self.dnd_available:
try:
self.file1_text.drop_target_register(DND_FILES)
self.file2_text.drop_target_register(DND_FILES)
self.file1_text.dnd_bind("<<Drop>>", lambda e: self.handle_drop(e, 1))
self.file2_text.dnd_bind("<<Drop>>", lambda e: self.handle_drop(e, 2))
except Exception:
# If anything goes wrong, just ignore and keep normal behavior
self.dnd_available = False
# Comparison / Share Section
self.control_frame = tk.Frame(self.root)
self.control_frame.pack(pady=10)
self.compare_btn = tk.Button(
self.control_frame,
text="Compare & Merge (Ctrl+M)",
state=tk.DISABLED,
command=self.compare_files
)
self.compare_btn.pack(side=tk.LEFT, padx=8)
self.share_btn = tk.Button(
self.control_frame,
text="Share Final Selection (Ctrl+S)",
state=tk.DISABLED,
command=self.share_final_content
)
self.share_btn.pack(side=tk.LEFT, padx=8)
# Make primary buttons styled (font, padding, etc.)
self.style_primary_buttons()
# Status label
self.status_label = tk.Label(self.root, text="Please upload or paste both files")
self.status_label.pack(pady=5, fill=tk.X)
# Licensing status label (bottom)
self.license_label = tk.Label(self.root, text="License: Checking...", anchor="w")
self.license_label.pack(side=tk.BOTTOM, fill=tk.X)
# ---- Drag & Drop helpers ----
def handle_drop(self, event, file_num):
"""Handle DND drop; event.data may contain one or more file paths (brace-wrapped if spaced)."""
paths = self._parse_dnd_file_list(event.data)
if not paths:
return
# Only take the first file
path = paths[0]
if os.path.isfile(path):
self.load_file_from_path(file_num, path)
def _parse_dnd_file_list(self, data: str):
"""Parse Tk DND file list (handles brace-quoted paths)."""
paths = []
buf = ""
in_brace = False
for ch in data:
if ch == "{":
in_brace = True
buf = ""
elif ch == "}":
in_brace = False
paths.append(buf)
buf = ""
elif ch == " " and not in_brace:
if buf:
paths.append(buf)
buf = ""
else:
buf += ch
if buf:
paths.append(buf)
# Normalize
paths = [p.strip() for p in paths if p.strip()]
return paths
def style_primary_buttons(self):
theme = self.themes[self.current_theme_name]
primary_font = ("Segoe UI", 11, "bold")
for btn in (self.compare_btn, self.share_btn):
btn.configure(
bg=theme["accent"],
fg="white",
font=primary_font,
activebackground=theme["accent"],
activeforeground="white",
padx=14,
pady=6,
relief=tk.RAISED,
bd=3,
disabledforeground="#bbbbbb",
)
def apply_theme(self, theme_name):
theme = self.themes.get(theme_name, self.themes["Light"])
self.current_theme_name = theme_name
self.root.configure(bg=theme["bg"])
for frame in (self.file1_frame, self.file2_frame, self.control_frame):
frame.configure(bg=theme["bg"], highlightbackground=theme["bg"])
for lf in (self.file1_frame, self.file2_frame):
try:
lf.configure(fg=theme["fg"])
except tk.TclError:
pass
for text_widget in (self.file1_text, self.file2_text):
text_widget.configure(
bg=theme["text_bg"],
fg=theme["text_fg"],
insertbackground=theme["text_fg"],
)
for button in (self.upload_btn1, self.upload_btn2):
button.configure(
bg=theme["accent"],
fg="white",
activebackground=theme["accent"],
activeforeground="white",
)
self.style_primary_buttons()
self.status_label.configure(bg=theme["status_bg"], fg=theme["status_fg"])
self.license_label.configure(bg=theme["status_bg"], fg=theme["status_fg"])
def cycle_theme(self):
names = list(self.themes.keys())
i = names.index(self.current_theme_name)
next_name = names[(i + 1) % len(names)]
self.apply_theme(next_name)
# ---------- Settings (theme + geometry persistence) ----------
def load_settings(self):
if not os.path.exists(self.SETTINGS_FILE):
return
try:
with open(self.SETTINGS_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
theme = data.get("theme")
geo = data.get("geometry")
if theme in self.themes:
self.current_theme_name = theme
if geo:
self.root.geometry(geo)
except Exception:
pass
def save_settings(self):
data = {"theme": self.current_theme_name, "geometry": self.root.winfo_geometry()}
try:
with open(self.SETTINGS_FILE, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
except Exception:
pass
# ------------- LICENSING -----------------
def load_license(self):
if not os.path.exists(self.LICENSE_FILE):
self.is_licensed = False
self.license_label.config(text="License: Free mode (no key found)")
return
try:
with open(self.LICENSE_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
except Exception:
self.is_licensed = False
self.license_label.config(text="License: Error reading license file")
return
key = data.get("key")
if not key:
self.is_licensed = False
self.license_label.config(text="License: Invalid license file")
return
if self.validate_license_key(key):
self.is_licensed = True
self.license_metadata = data
self.license_label.config(text=f"License: Activated ({key})")
self.root.title("Enhanced File Comparator - Licensed")
else:
self.is_licensed = False
self.license_label.config(text="License: Invalid or expired key")
def save_license(self, key):
data = {"key": key, "activated_on": datetime.utcnow().isoformat()}
try:
with open(self.LICENSE_FILE, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
except Exception as e:
messagebox.showerror("Error", f"Could not save license file:\n{e}")
return
self.license_metadata = data
self.is_licensed = True
self.license_label.config(text=f"License: Activated ({key})")
self.root.title("Enhanced File Comparator - Licensed")
def validate_license_key(self, key):
if key in self.VALID_LICENSE_KEYS:
return True
parts = key.split("-")
if len(parts) == 4 and parts[0] in {"FCA", "TFS", "DP"}:
return True
return False
def prompt_for_license(self):
key = simpledialog.askstring("Enter License Key", "Please enter your license key:")
if not key:
return
if self.validate_license_key(key.strip()):
self.save_license(key.strip())
messagebox.showinfo("License", "License key accepted. Thank you!")
else:
messagebox.showerror("License", "Invalid license key. Please check and try again.")
def show_license_status(self):
if self.is_licensed:
key = self.license_metadata.get("key") if self.license_metadata else "Unknown"
activated_on = self.license_metadata.get("activated_on") if self.license_metadata else "Unknown"
messagebox.showinfo("License Status", f"Status: Licensed\nKey: {key}\nActivated on: {activated_on}")
else:
messagebox.showinfo("License Status", "Status: Free mode\n\nYou can enter a license key from the License menu to activate.")
# ------------- CORE APP LOGIC -----------------
def upload_file(self, file_num):
file_path = filedialog.askopenfilename()
if file_path:
self.load_file_from_path(file_num, file_path)
def load_file_from_path(self, file_num, file_path):
try:
with open(file_path, 'r', encoding="utf-8") as file:
content = file.read()
except UnicodeDecodeError:
with open(file_path, 'r', errors="ignore") as file:
content = file.read()
if file_num == 1:
self.file1_text.delete(1.0, tk.END)
self.file1_text.insert(tk.END, content)
self.file1_path = file_path
self.file1_frame.config(text=f"File 1 — {os.path.basename(file_path)}")
else:
self.file2_text.delete(1.0, tk.END)
self.file2_text.insert(tk.END, content)
self.file2_path = file_path
self.file2_frame.config(text=f"File 2 — {os.path.basename(file_path)}")
self.update_file_status(file_num)
def update_file_status(self, file_num):
self.check_both_provided()
def check_both_provided(self):
file1_provided = self.file1_text.get(1.0, tk.END).strip() != ""
file2_provided = self.file2_text.get(1.0, tk.END).strip() != ""
if file1_provided and file2_provided:
self.compare_btn.config(state=tk.NORMAL)
self.status_label.config(text="Files ready for comparison")
else:
self.compare_btn.config(state=tk.DISABLED)
missing = []
if not file1_provided:
missing.append("File 1")
if not file2_provided:
missing.append("File 2")
self.status_label.config(text=f"Missing: {', '.join(missing) if missing else 'None'}")
def compare_files(self):
file1_content = self.file1_text.get(1.0, tk.END)
file2_content = self.file2_text.get(1.0, tk.END)
if file1_content == file2_content:
messagebox.showinfo("Comparison Result", "Files are identical!")
self.final_content = file1_content
self.final_source = "File 1 (identical)"
self.share_btn.config(state=tk.NORMAL)
self.status_label.config(text="Files are identical. Final selection set to File 1.")
return
differ = difflib.Differ()
diff = list(differ.compare(file1_content.splitlines(keepends=True),
file2_content.splitlines(keepends=True)))
self.show_side_by_side_diff(file1_content, file2_content, diff)
def _bind_linked_scroll(self, text1, text2):
"""Link mouse-wheel scrolling between two Text widgets."""
def on_wheel_text1(event):
delta = -1 * int(event.delta / 120) if event.delta else 1
text1.yview_scroll(delta, "units")
text2.yview_scroll(delta, "units")
return "break"
def on_wheel_text2(event):
delta = -1 * int(event.delta / 120) if event.delta else 1
text1.yview_scroll(delta, "units")
text2.yview_scroll(delta, "units")
return "break"
# Windows / macOS style
text1.bind("<MouseWheel>", on_wheel_text1)
text2.bind("<MouseWheel>", on_wheel_text2)
# Linux style
text1.bind("<Button-4>", lambda e: (text1.yview_scroll(-1, "units"), text2.yview_scroll(-1, "units")))
text1.bind("<Button-5>", lambda e: (text1.yview_scroll(1, "units"), text2.yview_scroll(1, "units")))
text2.bind("<Button-4>", lambda e: (text1.yview_scroll(-1, "units"), text2.yview_scroll(-1, "units")))
text2.bind("<Button-5>", lambda e: (text1.yview_scroll(1, "units"), text2.yview_scroll(1, "units")))
# ---- Word-level diff helper ----
def _tokenize(self, s):
# Split into words & punctuation while preserving spaces/newlines
return re.findall(r'\w+|\s+|[^\w\s]', s, re.UNICODE)
def _highlight_span(self, text_widget, start_char, end_char, tag):
start_index = text_widget.index(f"1.0+{start_char}c")
end_index = text_widget.index(f"1.0+{end_char}c")
text_widget.tag_add(tag, start_index, end_index)
def _apply_word_level_diff(self, t1, t2, s1, s2):
"""Apply inline (word-level) highlights on top of content already inserted."""
theme = self.themes[self.current_theme_name]
# Configure tags (use same colors as line-level for consistency)
t1.tag_config("w_delete", background=theme["diff_removed"])
t1.tag_config("w_replace", underline=True)
t2.tag_config("w_insert", background=theme["diff_added"])
t2.tag_config("w_replace", underline=True)
a = self._tokenize(s1)
b = self._tokenize(s2)
sm = difflib.SequenceMatcher(None, a, b)
# Convert token index to char offsets for each side
a_offsets = [0]
for tok in a:
a_offsets.append(a_offsets[-1] + len(tok))
b_offsets = [0]
for tok in b:
b_offsets.append(b_offsets[-1] + len(tok))
for tag, i1, i2, j1, j2 in sm.get_opcodes():
if tag == "equal":
continue
if tag == "delete":
# highlight in t1 only
self._highlight_span(t1, a_offsets[i1], a_offsets[i2], "w_delete")
elif tag == "insert":
# highlight in t2 only
self._highlight_span(t2, b_offsets[j1], b_offsets[j2], "w_insert")
elif tag == "replace":
# underline both sides to show changed tokens
self._highlight_span(t1, a_offsets[i1], a_offsets[i2], "w_replace")
self._highlight_span(t2, b_offsets[j1], b_offsets[j2], "w_replace")
def show_side_by_side_diff(self, file1_content, file2_content, diff):
theme = self.themes[self.current_theme_name]
diff_window = tk.Toplevel(self.root)
diff_window.title("Side-by-Side Comparison")
diff_window.configure(bg=theme["bg"])
# Left Frame for File 1
file1_frame = tk.Frame(diff_window, bg=theme["bg"])
file1_frame.pack(side=tk.LEFT, padx=10, pady=10, fill=tk.BOTH, expand=True)
name1 = os.path.basename(self.file1_path) if self.file1_path else "File 1"
file1_label = tk.Label(file1_frame, text=name1, bg=theme["bg"], fg=theme["fg"])
file1_label.pack(anchor="w")
file1_text = tk.Text(file1_frame, height=20, width=50, wrap=tk.WORD,
bg=theme["text_bg"], fg=theme["text_fg"],
insertbackground=theme["text_fg"])
file1_text.pack(side=tk.LEFT, padx=5, pady=5, fill=tk.BOTH, expand=True)
file1_text.insert(tk.END, file1_content)
# Right Frame for File 2
file2_frame = tk.Frame(diff_window, bg=theme["bg"])
file2_frame.pack(side=tk.LEFT, padx=10, pady=10, fill=tk.BOTH, expand=True)
name2 = os.path.basename(self.file2_path) if self.file2_path else "File 2"
file2_label = tk.Label(file2_frame, text=name2, bg=theme["bg"], fg=theme["fg"])
file2_label.pack(anchor="w")
file2_text = tk.Text(file2_frame, height=20, width=50, wrap=tk.WORD,
bg=theme["text_bg"], fg=theme["text_fg"],
insertbackground=theme["text_fg"])
file2_text.pack(side=tk.LEFT, padx=5, pady=5, fill=tk.BOTH, expand=True)
file2_text.insert(tk.END, file2_content)
# Scrollbars
file1_scroll = tk.Scrollbar(file1_frame, command=file1_text.yview)
file1_scroll.pack(side=tk.RIGHT, fill=tk.Y)
file1_text.configure(yscrollcommand=file1_scroll.set)
file2_scroll = tk.Scrollbar(file2_frame, command=file2_text.yview)
file2_scroll.pack(side=tk.RIGHT, fill=tk.Y)
file2_text.configure(yscrollcommand=file2_scroll.set)
# Link scrolling via mouse wheel
self._bind_linked_scroll(file1_text, file2_text)
# Line-level highlights
line_idx1 = 1
line_idx2 = 1
for line in diff:
code = line[:2]
if code == " ":
line_idx1 += 1
line_idx2 += 1
elif code == "- ":
file1_text.tag_add("removed", f"{line_idx1}.0", f"{line_idx1}.end")
line_idx1 += 1
elif code == "+ ":
file2_text.tag_add("added", f"{line_idx2}.0", f"{line_idx2}.end")
line_idx2 += 1
elif code == "? ":
continue
file1_text.tag_config("removed", background=theme["diff_removed"])
file2_text.tag_config("added", background=theme["diff_added"])
# Status bar in diff window
diff_status = tk.Label(
diff_window,
text="Select which version you want to keep as final.",
bg=theme["status_bg"],
fg=theme["status_fg"],
anchor="w"
)
diff_status.pack(fill=tk.X, padx=10, pady=(0, 5))
# Word-level toggle
word_var = tk.BooleanVar(value=False)
def toggle_word_level():
# Clear previous word-level tags
for tag in ("w_delete", "w_insert", "w_replace"):
file1_text.tag_remove(tag, "1.0", "end")
file2_text.tag_remove(tag, "1.0", "end")
if word_var.get():
self._apply_word_level_diff(file1_text, file2_text, file1_content, file2_content)
diff_status.config(text="Word-level differences highlighted.")
else:
diff_status.config(text="Word-level highlight turned off.")
toggle_frame = tk.Frame(diff_window, bg=theme["bg"])
toggle_frame.pack(fill=tk.X, padx=10)
tk.Checkbutton(
toggle_frame,
text="Word-level highlight",
variable=word_var,
command=toggle_word_level,
bg=theme["bg"],
fg=theme["fg"],
selectcolor=theme["status_bg"],
activebackground=theme["bg"],
activeforeground=theme["fg"]
).pack(anchor="w")
# Bottom controls
bottom_frame = tk.Frame(diff_window, bg=theme["bg"])
bottom_frame.pack(fill=tk.X, pady=10)
tk.Button(
bottom_frame,
text="Use File 1 as Final",
command=lambda: self.set_final_from_diff(
file1_content, "File 1", status_label=diff_status, window=diff_window
)
).pack(side=tk.LEFT, padx=5)
tk.Button(
bottom_frame,
text="Use File 2 as Final",
command=lambda: self.set_final_from_diff(
file2_content, "File 2", status_label=diff_status, window=diff_window
)
).pack(side=tk.LEFT, padx=5)
tk.Button(
bottom_frame,
text="Use Merged as Final",
command=lambda: self.set_final_from_diff(
self.build_merged_content(file1_content, file2_content),
"Merged",
status_label=diff_status,
window=diff_window
)
).pack(side=tk.LEFT, padx=5)
tk.Button(
bottom_frame,
text="Copy Diff Summary",
command=lambda: (
self.copy_to_clipboard("".join(diff)),
diff_status.config(text="Diff summary copied to clipboard")
)
).pack(side=tk.LEFT, padx=5)
tk.Button(
bottom_frame,
text="Export Diff Summary...",
command=lambda: self.export_diff_summary("".join(diff))
).pack(side=tk.LEFT, padx=5)
tk.Button(
bottom_frame,
text="Close",
command=diff_window.destroy
).pack(side=tk.RIGHT, padx=5)
def build_merged_content(self, file1_content, file2_content):
return file1_content.rstrip("\n") + "\n\n--- Merged Content ---\n\n" + file2_content.lstrip("\n")
def set_final_from_diff(self, content, source_label, status_label=None, window=None):
self.final_content = content
self.final_source = source_label
self.share_btn.config(state=tk.NORMAL)
self.status_label.config(text=f"Final selection set to: {source_label}")
if status_label is not None:
status_label.config(text=f"Final selection set to: {source_label}")
if window is not None:
try:
window.title(f"Side-by-Side Comparison — Final: {source_label}")
except Exception:
pass
def export_diff_summary(self, diff_text):
path = filedialog.asksaveasfilename(
defaultextension=".diff.txt",
filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")],
title="Save Diff Summary"
)
if not path:
return
try:
with open(path, "w", encoding="utf-8") as f:
f.write(diff_text)
messagebox.showinfo("Export", f"Diff summary saved to:\n{path}")
except Exception as e:
messagebox.showerror("Export Error", f"Could not save diff summary:\n{e}")
def save_merged_file(self, file1_content, file2_content):
merged_content = self.build_merged_content(file1_content, file2_content)
file_path = filedialog.asksaveasfilename(
defaultextension=".txt",
filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")]
)
if file_path:
try:
with open(file_path, 'w', encoding="utf-8") as file:
file.write(merged_content)
messagebox.showinfo("Success", f"File saved to: {file_path}")
except Exception as e:
messagebox.showerror("Error", f"Could not save file:\n{e}")
# ------------- SHARING (FILE / CLIPBOARD / EMAIL / WHATSAPP) -------------
def share_final_content(self):
if not self.final_content:
messagebox.showwarning("Share", "No final selection available yet. Compare files first.")
return
theme = self.themes[self.current_theme_name]
dialog = tk.Toplevel(self.root)
dialog.title("Share Final Content")
dialog.configure(bg=theme["bg"])
dialog.transient(self.root)
dialog.grab_set()
label = tk.Label(
dialog,
text="Choose how you want to share the final content:",
bg=theme["bg"],
fg=theme["fg"],
wraplength=350,
justify=tk.LEFT
)
label.pack(padx=20, pady=(15, 10))
btn_frame = tk.Frame(dialog, bg=theme["bg"])
btn_frame.pack(padx=20, pady=10)
def close_and(fn):
def _inner():
dialog.destroy()
fn()
return _inner
tk.Button(
btn_frame,
text="Save to File",
command=close_and(self.share_via_file),
bg=theme["accent"],
fg="white",
activebackground=theme["accent"],
activeforeground="white"
).pack(side=tk.LEFT, padx=5, pady=5)
tk.Button(
btn_frame,
text="Copy to Clipboard",
command=close_and(self.share_via_clipboard),
bg=theme["accent"],
fg="white",
activebackground=theme["accent"],
activeforeground="white"
).pack(side=tk.LEFT, padx=5, pady=5)
tk.Button(
btn_frame,
text="Share via Email",
command=close_and(self.share_via_email),
bg=theme["accent"],
fg="white",
activebackground=theme["accent"],
activeforeground="white"
).pack(side=tk.LEFT, padx=5, pady=5)
tk.Button(
btn_frame,
text="Share via WhatsApp",
command=close_and(self.share_via_whatsapp),
bg=theme["accent"],
fg="white",
activebackground=theme["accent"],
activeforeground="white"
).pack(side=tk.LEFT, padx=5, pady=5)
tk.Button(
dialog,
text="Cancel",
command=dialog.destroy,
bg=theme["status_bg"],
fg=theme["status_fg"],
activebackground=theme["status_bg"],
activeforeground=theme["status_fg"]
).pack(pady=(0, 15))
dialog.wait_window(dialog)
def share_via_file(self):
file_path = filedialog.asksaveasfilename(
defaultextension=".txt",
filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")],
title=f"Save Final ({self.final_source})"
)
if file_path:
try:
with open(file_path, "w", encoding="utf-8") as f:
f.write(self.final_content)
messagebox.showinfo("Share", f"Final content saved to:\n{file_path}")
except Exception as e:
messagebox.showerror("Error", f"Could not save file:\n{e}")
def share_via_clipboard(self):
self.copy_to_clipboard(self.final_content)
def _fallback_long_share(self, channel_name):
try:
temp_dir = Path(tempfile.gettempdir())
temp_path = temp_dir / "TextFileCompareApp_Final.txt"
temp_path.write_text(self.final_content, encoding="utf-8")
self.copy_to_clipboard(self.final_content)
try:
if os.name == "nt":
os.startfile(str(temp_path))
elif sys.platform == "darwin":
subprocess.run(["open", str(temp_path)])
else:
subprocess.run(["xdg-open", str(temp_path)])
except Exception:
pass
messagebox.showinfo(
f"Share via {channel_name}",
f"The text was too long for direct {channel_name} share.\n\n"
f"- Full content saved to: {temp_path}\n"
f"- Content copied to clipboard.\n\n"
f"Please attach or paste it manually in your {channel_name} message."
)
except Exception as e:
messagebox.showerror(f"{channel_name} Error", f"Fallback failed:\n{e}")
def share_via_email(self):
try:
subject = f"File Comparator - {self.final_source or 'Final Content'}"
max_chars = 1500
body = self.final_content
truncated = False
if len(body) > max_chars:
body = body[:max_chars] + "\n\n[Message truncated: full content is longer than this.]"
truncated = True
mailto_url = f"mailto:?subject={urllib.parse.quote(subject)}&body={urllib.parse.quote(body)}"
if len(mailto_url) > 1900 or not webbrowser.open(mailto_url):
self._fallback_long_share("Email")
return
if truncated:
messagebox.showinfo("Email", "Content is quite long.\nOnly the first part was added to the email body.")
except Exception:
self._fallback_long_share("Email")
def share_via_whatsapp(self):
try:
max_chars = 1000
text = self.final_content
truncated = False
if len(text) > max_chars:
text = text[:max_chars] + "\n\n[Message truncated: full content is longer than this.]"
truncated = True
wa_url = "https://wa.me/?text=" + urllib.parse.quote(text)
if len(wa_url) > 1900 or not webbrowser.open(wa_url):
self._fallback_long_share("WhatsApp")
return
if truncated:
messagebox.showinfo("WhatsApp", "Content is quite long.\nOnly the first part was sent to WhatsApp.")
except Exception:
self._fallback_long_share("WhatsApp")
def copy_to_clipboard(self, content):
self.root.clipboard_clear()
self.root.clipboard_append(content)
messagebox.showinfo("Success", "Content copied to clipboard")
# ------------- OTHER UI -------------
def reset_app(self):
self.file1_text.delete(1.0, tk.END)
self.file2_text.delete(1.0, tk.END)
self.compare_btn.config(state=tk.DISABLED)
self.share_btn.config(state=tk.DISABLED)
self.final_content = None
self.final_source = None
self.file1_path = None
self.file2_path = None
self.file1_frame.config(text="File 1")
self.file2_frame.config(text="File 2")
self.status_label.config(text="Please upload or paste both files")
def show_about(self):
theme = self.themes[self.current_theme_name]
about_win = tk.Toplevel(self.root)
about_win.title("About Enhanced File Comparator")
about_win.configure(bg=theme["bg"])
about_win.transient(self.root)
about_win.grab_set()
text = (
"Enhanced File Comparator\n\n"
"- Load or paste two text files\n"
"- Drag & Drop files (if tkinterdnd2 is installed)\n"
"- Compare and view differences side-by-side\n"
"- Highlight added/removed lines (line-level)\n"
"- Optional word-level highlights for more precise changes\n"
"- Choose File 1, File 2, or a merged version as your final result\n"
"- Share the final content by saving to file, copying to clipboard,\n"
" sending via email, or sharing via WhatsApp\n\n"
"Licensing is shared with your Text File Searcher / DataPrep-Pro tools."
)
label = tk.Label(about_win, text=text, bg=theme["bg"], fg=theme["fg"], justify=tk.LEFT, wraplength=420)
label.pack(padx=20, pady=15)
ok_btn = tk.Button(about_win, text="OK", command=about_win.destroy,
bg=theme["accent"], fg="white",
activebackground=theme["accent"], activeforeground="white")
ok_btn.pack(pady=(0, 15))
about_win.wait_window(about_win)
# ---------- Shortcuts ----------
def bind_shortcuts(self):
self.root.bind("<Control-Key-1>", lambda e: self.upload_file(1))
self.root.bind("<Control-Key-2>", lambda e: self.upload_file(2))
self.root.bind("<Control-m>", lambda e: self.compare_files())
self.root.bind("<Control-s>", lambda e: self.share_final_content())
self.root.bind("<Control-t>", lambda e: self.cycle_theme())
self.root.bind("<F1>", lambda e: self.show_about())
# ---------- Close handler ----------
def on_close(self):
self.save_settings()
self.root.destroy()
if __name__ == "__main__":
# Use TkinterDnD if available to enable drag & drop; otherwise normal Tk
if DND_AVAILABLE:
root = TkinterDnD.Tk()
else:
root = tk.Tk()
app = FileComparatorApp(root)
root.mainloop()