-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdiff_viewer_final.py
More file actions
7235 lines (5730 loc) · 332 KB
/
Copy pathdiff_viewer_final.py
File metadata and controls
7235 lines (5730 loc) · 332 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
import pygame
import sys
import os
import json
import ctypes
import time
import pyperclip
import re
import traceback
import difflib
from ctypes import wintypes
import threading
import winreg
import locale
import platform
version = "v2.66"
class StitchViewerApp:
def __init__(self, parent_pid=None, monitors=None, pos_x=None, pos_y=None, height=None, font_name=None, font_size=None, is_pro=False):
os.environ['SDL_HINT_RENDER_BATCHING'] = '1'
os.environ['SDL_MOUSE_FOCUS_CLICKTHROUGH'] = "1"
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
os.environ['SDL_WINDOWS_DPI_AWARENESS'] = 'permonitorv2'
if 'SDL_RENDER_DRIVER' in os.environ:
del os.environ['SDL_RENDER_DRIVER']
try:
def _pre_log(m):
try:
appdata = os.environ.get('APPDATA', '')
if appdata:
pre_dir = os.path.join(appdata, "CodeStitcher")
os.makedirs(pre_dir, exist_ok=True)
else:
if getattr(sys, "frozen", False) or "__compiled__" in globals():
pre_dir = os.path.dirname(os.path.abspath(sys.executable))
else:
pre_dir = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(pre_dir, "stitch_viewer_debug.log"), "a", encoding="utf-8") as f:
f.write(f"[{time.strftime('%H:%M:%S')}] [PRE-INIT] {m}\n")
except:
pass
_pre_log(f"__init__ started with parent_pid={parent_pid}, is_pro={is_pro}")
if os.name == 'nt':
try:
kernel32 = ctypes.windll.kernel32
user32 = ctypes.windll.user32
shell32 = ctypes.windll.shell32
kernel32.CreateMutexW.argtypes = [ctypes.c_void_p, wintypes.BOOL, wintypes.LPCWSTR]
kernel32.CreateMutexW.restype = wintypes.HANDLE
shell32.SetCurrentProcessExplicitAppUserModelID.argtypes = [wintypes.LPCWSTR]
shell32.SetCurrentProcessExplicitAppUserModelID.restype = ctypes.c_long
kernel32.GetLongPathNameW.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD]
kernel32.GetLongPathNameW.restype = wintypes.DWORD
user32.LoadImageW.argtypes = [wintypes.HINSTANCE, wintypes.LPCWSTR, wintypes.UINT, ctypes.c_int, ctypes.c_int, wintypes.UINT]
user32.LoadImageW.restype = wintypes.HANDLE
user32.SendMessageW.argtypes = [wintypes.HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM]
user32.SendMessageW.restype = wintypes.LPARAM
if platform.architecture()[0] == '64bit':
user32.GetWindowLongPtrW.argtypes = [wintypes.HWND, ctypes.c_int]
user32.GetWindowLongPtrW.restype = ctypes.c_void_p
user32.SetWindowLongPtrW.argtypes = [wintypes.HWND, ctypes.c_int, ctypes.c_void_p]
user32.SetWindowLongPtrW.restype = ctypes.c_void_p
self._GetWindowLong = user32.GetWindowLongPtrW
self._SetWindowLong = user32.SetWindowLongPtrW
else:
user32.GetWindowLongW.argtypes = [wintypes.HWND, ctypes.c_int]
user32.GetWindowLongW.restype = ctypes.c_long
user32.SetWindowLongW.argtypes = [wintypes.HWND, ctypes.c_int, ctypes.c_long]
user32.SetWindowLongW.restype = ctypes.c_long
self._GetWindowLong = user32.GetWindowLongW
self._SetWindowLong = user32.SetWindowLongW
user32.SetWindowPos.argtypes = [wintypes.HWND, wintypes.HWND, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, wintypes.UINT]
user32.SetWindowPos.restype = wintypes.BOOL
user32.ShowWindow.argtypes = [wintypes.HWND, ctypes.c_int]
user32.ShowWindow.restype = wintypes.BOOL
user32.SetForegroundWindow.argtypes = [wintypes.HWND]
user32.SetForegroundWindow.restype = wintypes.BOOL
user32.SetLayeredWindowAttributes.argtypes = [wintypes.HWND, wintypes.COLORREF, ctypes.c_byte, wintypes.DWORD]
user32.SetLayeredWindowAttributes.restype = wintypes.BOOL
user32.GetCursorPos.argtypes = [ctypes.POINTER(wintypes.POINT)]
user32.GetCursorPos.restype = wintypes.BOOL
user32.GetWindowRect.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.RECT)]
user32.GetWindowRect.restype = wintypes.BOOL
except Exception as e:
_pre_log(f"Warning: Failed to setup strict ctypes argtypes: {e}")
if os.name == 'nt':
try:
self.mutex_name = "Global\\CodeStitcherCodeStitcher_MUTEX"
self.mutex = ctypes.windll.kernel32.CreateMutexW(None, False, self.mutex_name)
if ctypes.windll.kernel32.GetLastError() == 183:
_pre_log("FATAL: Another Stitcher Viewer instance is already running. Enforcing single instance.")
sys.exit(0)
except Exception as e:
_pre_log(f"Warning: Failed to create Mutex lock: {e}")
self.parent_pid = parent_pid
self.is_pro = is_pro
if os.name == 'nt':
try:
myappid = 'uep.codestitcher.version.1.0'
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)
except Exception as e:
_pre_log(f"Warning: SetCurrentProcessExplicitAppUserModelID failed: {e}")
try:
pygame.init()
pygame.font.init()
pygame.key.set_repeat(400, 60)
_pre_log("Pygame initialized successfully with key repeat enabled.")
except Exception as e:
_pre_log(f"FATAL: Pygame init failed: {e}")
self.width = 1260
self.height = 750
self.title_bar_height = 19
self.GAP_WIDTH = 50
self.minimap_width = 24
if getattr(sys, "frozen", False) or "__compiled__" in globals():
self.script_dir = os.path.dirname(os.path.abspath(sys.executable))
if hasattr(sys, "_MEIPASS"):
self.asset_dir = sys._MEIPASS
else:
self.asset_dir = os.path.dirname(os.path.abspath(__file__))
else:
self.script_dir = os.path.dirname(os.path.abspath(__file__))
self.asset_dir = self.script_dir
if os.name == 'nt':
try:
buf = ctypes.create_unicode_buffer(1024)
if ctypes.windll.kernel32.GetLongPathNameW(self.script_dir, buf, 1024):
self.script_dir = buf.value
if ctypes.windll.kernel32.GetLongPathNameW(self.asset_dir, buf, 1024):
self.asset_dir = buf.value
except Exception as e:
_pre_log(f"Warning: Failed to expand short path: {e}")
self._log = self._log
self._log(f"Path verification -> script_dir: {self.script_dir} | asset_dir: {self.asset_dir}")
self.config = {
"search_dirs": monitors if monitors else [self.script_dir],
"CONF_WINDOW_HEIGHT": height if height else 750,
"CONF_FONT_NAME": font_name if font_name else 'consolas',
"CONF_FONT_SIZE": font_size if font_size else 13,
"CONF_REMEMBER_WINDOW_POS": True,
"CONF_VIEWER_ALWAYS_ON_TOP": True,
"CONF_VIEWER_WIDTH": 1260,
}
appdata = os.environ.get('APPDATA', '')
conf_dir = os.path.join(appdata, "CodeStitcher") if appdata else self.script_dir
ini_path = os.path.join(conf_dir, "cs_settings.ini")
ini_found_topmost = False
if os.path.exists(ini_path):
try:
with open(ini_path, 'r', encoding='utf-8') as f:
for line in f:
line_stripped = line.strip()
if line_stripped.startswith('CONF_VIEWER_ALWAYS_ON_TOP'):
val = line.split('=', 1)[1].strip().strip('"\'').lower()
self.config['CONF_VIEWER_ALWAYS_ON_TOP'] = (val == 'true')
ini_found_topmost = True
elif line_stripped.startswith('CONF_VIEWER_WIDTH'):
val = line.split('=', 1)[1].strip().strip('"\'')
try:
self.config['CONF_VIEWER_WIDTH'] = int(float(val))
except: pass
except: pass
if not ini_found_topmost:
self._update_ini_setting('CONF_VIEWER_ALWAYS_ON_TOP', 'True')
try:
self.width = max(800, int(float(self.config.get("CONF_VIEWER_WIDTH", 1260))))
except (ValueError, TypeError):
self.width = 1260
try:
conf_h = int(float(self.config.get('CONF_WINDOW_HEIGHT', 750))) - 1
self.height = max(500, conf_h)
self._log(f"Applied CONF_WINDOW_HEIGHT (with -1 offset): {self.height}")
except (ValueError, TypeError):
pass
self.tree_data = {}
self.render_list = []
self.active_entry_id = None
self._load_history()
pos_valid = False
parent_rect = self._get_parent_window_rect()
if parent_rect:
try:
lx = int(parent_rect[0]) - self.width - 10
ly = int(parent_rect[1])
if -4000 < lx < 12000 and -4000 < ly < 12000:
os.environ['SDL_VIDEO_WINDOW_POS'] = f"{lx},{ly}"
pos_valid = True
self._log(f"Spawning window on left hand side of parent: {lx},{ly}")
except (ValueError, TypeError):
pass
if not pos_valid:
os.environ['SDL_VIDEO_WINDOW_POS'] = "100,100"
self._log("Spawning window at default pos 100, 100")
self._log("Creating Pygame display surface...")
flags = pygame.NOFRAME | pygame.DOUBLEBUF
if hasattr(pygame, 'HIDDEN'):
flags |= getattr(pygame, 'HIDDEN')
try:
self.screen = pygame.display.set_mode((self.width, self.height), flags)
pygame.display.set_caption(f"Stitch Viewer {version}")
except Exception as e:
self._log(f"Warning: Hardware Doublebuf failed, reverting: {e}")
flags_fallback = pygame.NOFRAME
if hasattr(pygame, 'HIDDEN'): flags_fallback |= getattr(pygame, 'HIDDEN')
self.screen = pygame.display.set_mode((self.width, self.height), flags_fallback)
self.running = True
self.hwnd = None
if os.name == 'nt':
try:
self.hwnd = pygame.display.get_wm_info()['window']
self._log(f"Retrieved Window HWND: {self.hwnd}")
icon_path = os.path.join(self.asset_dir, "stitch_viewer.ico")
if not os.path.exists(icon_path):
icon_path = os.path.join(self.script_dir, "stitch_viewer.ico")
if not os.path.exists(icon_path):
icon_path = os.path.join(self.asset_dir, "code_stitcher.ico")
if not os.path.exists(icon_path):
icon_path = os.path.join(self.script_dir, "code_stitcher.ico")
if os.path.exists(icon_path):
WM_SETICON = 0x0080
hIcon = ctypes.windll.user32.LoadImageW(None, icon_path, 1, 0, 0, 0x0010 | 0x00000040)
if hIcon:
ctypes.windll.user32.SendMessageW(self.hwnd, WM_SETICON, 0, hIcon)
ctypes.windll.user32.SendMessageW(self.hwnd, WM_SETICON, 1, hIcon)
GWL_EXSTYLE = -20
WS_EX_TOOLWINDOW = 0x00000080
WS_EX_APPWINDOW = 0x00040000
SWP_NOMOVE = 0x0002
SWP_NOSIZE = 0x0001
SWP_NOZORDER = 0x0004
SWP_FRAMECHANGED = 0x0020
SWP_SHOWWINDOW = 0x0040
if hasattr(self, '_GetWindowLong') and hasattr(self, '_SetWindowLong'):
exstyle = self._GetWindowLong(self.hwnd, GWL_EXSTYLE)
if exstyle is not None:
new_exstyle = (exstyle & ~WS_EX_TOOLWINDOW) | WS_EX_APPWINDOW
self._SetWindowLong(self.hwnd, GWL_EXSTYLE, new_exstyle)
if self.config.get('CONF_VIEWER_ALWAYS_ON_TOP', True):
HWND_TOPMOST = -1
ctypes.windll.user32.SetWindowPos(self.hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_FRAMECHANGED | SWP_SHOWWINDOW)
def keep_on_top():
while getattr(self, 'running', True):
try:
if self.config.get('CONF_VIEWER_ALWAYS_ON_TOP', True):
ctypes.windll.user32.SetWindowPos(self.hwnd, -1, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE)
else:
ctypes.windll.user32.SetWindowPos(self.hwnd, -2, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE)
except BaseException:
pass
time.sleep(2)
threading.Thread(target=keep_on_top, daemon=True).start()
else:
ctypes.windll.user32.SetWindowPos(self.hwnd, None, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED | SWP_SHOWWINDOW)
SW_SHOW = 5
ctypes.windll.user32.ShowWindow(self.hwnd, SW_SHOW)
ctypes.windll.user32.SetForegroundWindow(self.hwnd)
self._log("Applied extended styles and brought to foreground successfully.")
def maintain_transparency():
while getattr(self, 'running', True):
try:
if getattr(self, '_current_alpha_byte', 255) < 255 and getattr(self, 'hwnd', None):
ctypes.windll.user32.SetLayeredWindowAttributes(self.hwnd, 0x00FF00FF, self._current_alpha_byte, 3)
except BaseException:
pass
time.sleep(5)
threading.Thread(target=maintain_transparency, daemon=True).start()
except Exception as e:
_pre_log(f"Warning: HWND modification failed: {e}")
font_name = self.config.get('CONF_FONT_NAME', 'consolas')
try:
font_size = int(float(self.config.get('CONF_FONT_SIZE', 13)))
except (ValueError, TypeError):
font_size = 13
self.font = pygame.font.SysFont(font_name, font_size)
self.font_bold = pygame.font.SysFont(font_name, font_size, bold=True)
self.title_font = pygame.font.SysFont(font_name, 14, bold=False)
self.close_font = pygame.font.SysFont(font_name, 18, bold=False)
self.button_font = pygame.font.SysFont(font_name, 11, bold=False)
self.tree_stat_font = pygame.font.SysFont(font_name, max(9, font_size - 2))
self.line_height = self.font.get_linesize() + 4
self.tree_row_height = 22
self.focused = True
self.left_panel_width = 150
self.scroll_left = 0
self.scroll_right = 0
self.scroll_right_target = 0.0
self.scroll_right_float = 0.0
self.scroll_right_x = 0
self.scroll_right_x_target = 0.0
self.scroll_right_x_float = 4490.0
self.max_right_width = 1
self.is_dragging_scroll_x = True
self._scroll_x_drag_offset = 0
self.max_edit_width = 0
self.is_dragging_editor_scroll_x = False
self._editor_scroll_x_offset = 0
self.hovered_history_idx = -1
self.hovered_line_idx = None
self.hovered_line_pane = None
self.old_lines = []
self.new_lines = []
self.diff_blocks = []
self.selection_start = None
self.selection_end = None
self.is_selecting = False
self.selecting_pane = None
self.is_dragging_minimap = False
self.search_text = ""
self.search_active = False
self.search_results = []
self.search_current_idx = -1
self.is_folded = False
self.visible_indices = []
self.actual_to_visual = []
self.search_rect = pygame.Rect(0,0,0,0)
self.fold_rect = pygame.Rect(0,0,0,0)
self.in_context_view = False
self.scroll_context = 0
self.substantial_changes = []
self.is_editing = False
self.edit_lines = []
self.edit_cursor_row = 0
self.edit_cursor_col = 0
self.edit_scroll_y = 0
self.edit_scroll_x = 0
self.edit_selection_start = None
self.edit_is_dragging = False
self.edit_undo_stack = []
self.edit_redo_stack = []
if self.render_list:
for item in self.render_list:
if item['type'] == 'entry':
self._select_entry(item['data'])
break
self._log("__init__ fully completed.")
except BaseException as fatal_e:
try:
appdata = os.environ.get('APPDATA', '')
if appdata:
err_dir = os.path.join(appdata, "CodeStitcher")
os.makedirs(err_dir, exist_ok=True)
else:
if getattr(sys, "frozen", False) or "__compiled__" in globals():
err_dir = os.path.dirname(os.path.abspath(sys.executable))
else:
err_dir = os.path.dirname(os.path.abspath(__file__))
log_path = os.path.join(err_dir, "stitch_viewer_debug.log")
with open(log_path, "a", encoding="utf-8") as f:
f.write(f"[{time.strftime('%H:%M:%S')}] FATAL INIT CRASH: {fatal_e}\n{traceback.format_exc()}\n")
except:
pass
raise
def _load_config(self):
"""Loads live-updating settings like Always On Top from the INI file."""
appdata = os.environ.get('APPDATA', '')
config_dir = os.path.join(appdata, "CodeStitcher") if appdata else getattr(self, 'script_dir', '')
ini_path = os.path.join(config_dir, "cs_settings.ini")
if os.path.exists(ini_path):
try:
with open(ini_path, 'r', encoding='utf-8') as f:
for line in f:
line_stripped = line.strip()
if line_stripped.startswith('CONF_VIEWER_ALWAYS_ON_TOP'):
val = line.split('=', 1)[1].strip().strip('"\'').lower()
new_always_on_top = (val == 'true')
if new_always_on_top != self.config.get('CONF_VIEWER_ALWAYS_ON_TOP', True):
self.config['CONF_VIEWER_ALWAYS_ON_TOP'] = new_always_on_top
self._log(f"Live updated Always On Top to: {new_always_on_top}")
elif line_stripped.startswith('CONF_VIEWER_WIDTH'):
val = line.split('=', 1)[1].strip().strip('"\'')
try:
new_width = max(800, int(float(val)))
if new_width != self.config.get('CONF_VIEWER_WIDTH', 1260):
self.config['CONF_VIEWER_WIDTH'] = new_width
self._log(f"Live updated CONF_VIEWER_WIDTH to: {new_width}")
self.width = new_width
self._reposition_and_resize_window()
except Exception as e:
self._log(f"Failed to parse live CONF_VIEWER_WIDTH: {e}")
except Exception as e:
self._log(f"Failed to reload config: {e}")
def _format_bytes(self, size):
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size < 1024.0:
return f"{size:.1f} {unit}" if unit != 'B' else f"{size} {unit}"
size /= 1024.0
return f"{size:.1f} PB"
def _get_parent_window_rect(self):
"""Helper to find the screen geometry bounds of the parent CodeStitcher process using raw platform types."""
if os.name != 'nt' or not self.parent_pid:
return None
rects = []
try:
WNDENUMPROC = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
GetWindowThreadProcessId = ctypes.windll.user32.GetWindowThreadProcessId
GetWindowThreadProcessId.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.DWORD)]
GetWindowThreadProcessId.restype = wintypes.DWORD
IsWindowVisible = ctypes.windll.user32.IsWindowVisible
IsWindowVisible.argtypes = [wintypes.HWND]
IsWindowVisible.restype = wintypes.BOOL
GetWindowRect = ctypes.windll.user32.GetWindowRect
GetWindowRect.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.RECT)]
GetWindowRect.restype = wintypes.BOOL
EnumWindows = ctypes.windll.user32.EnumWindows
EnumWindows.argtypes = [WNDENUMPROC, wintypes.LPARAM]
EnumWindows.restype = wintypes.BOOL
def enum_windows_callback(hwnd, lparam):
try:
w = rect.right - rect.left
h = rect.bottom - rect.top
if w > 200 and h > 200 and -4000 < rect.left < 12000 and -4000 < rect.top < 12000:
rects.append((rect.left, rect.top, rect.right, rect.bottom))
return False
except BaseException as err:
self._log(f"Error in enum_windows_callback: {err}")
return True
callback = WNDENUMPROC(enum_windows_callback)
EnumWindows(callback, 0)
except Exception as e:
self._log(f"Error enumerating windows safely: {e}")
return rects[0] if rects else None
def _get_ext_color(self, filename):
"""Returns standard consensus-free custom cohesive file system colors.
Harmonized to use the custom 4-color palette of the Stitch Viewer's core theme."""
ext = os.path.splitext(filename)[1].lower()
gold_orange = (235, 195, 115)
string_green = (106, 135, 89)
copper_rust = (215, 100, 75)
orchid_purple = (155, 110, 190)
mapping = {
'.py': gold_orange,
'.js': gold_orange,
'.jsx': gold_orange,
'.ts': gold_orange,
'.tsx': gold_orange,
'.sh': string_green,
'.bash': string_green,
'.bat': string_green,
'.ps1': string_green,
'.go': string_green,
'.cpp': copper_rust,
'.cc': copper_rust,
'.cxx': copper_rust,
'.cs': copper_rust,
'.java': copper_rust,
'.rs': copper_rust,
'.c': orchid_purple,
'.h': orchid_purple,
'.hpp': orchid_purple,
}
dull_exts = {
'.html', '.htm', '.css', '.scss', '.sass', '.less',
'.json', '.xml', '.yaml', '.yml', '.toml', '.ini', '.cfg', '.conf',
'.md', '.markdown', '.txt', '.csv', '.log'
}
if ext in dull_exts:
return (140, 140, 140)
return mapping.get(ext, (210, 210, 210))
def _reposition_and_resize_window(self):
"""Resizes the Pygame surface and aligns it next to the parent window on the left-hand side."""
if not getattr(self, 'hwnd', None) or os.name != 'nt':
return
parent_rect = self._get_parent_window_rect()
if parent_rect:
try:
lx = int(parent_rect[0]) - self.width - 10
ly = int(parent_rect[1])
if -4000 < lx < 12000 and -4000 < ly < 12000:
ctypes.windll.user32.SetWindowPos(self.hwnd, 0, lx, ly, self.width, self.height, 0x0004 | 0x0010)
except (ValueError, TypeError) as e:
self._log(f"Reposition failed: {e}")
try:
flags = self.screen.get_flags()
self.screen = pygame.display.set_mode((self.width, self.height), flags)
except Exception as e:
self._log(f"Surface resize failed: {e}")
def _update_ini_setting(self, key: str, value):
"""Helper to safely write values back to the ini file without overwriting other settings."""
appdata = os.environ.get('APPDATA', '')
if appdata:
config_dir = os.path.join(appdata, "CodeStitcher")
else:
config_dir = getattr(self, 'script_dir', '')
ini_path = os.path.join(config_dir, "cs_settings.ini")
if not os.path.exists(ini_path): return
try:
with open(ini_path, 'r', encoding='utf-8') as f:
content = f.read()
val_str = f'"{value}"' if isinstance(value, str) else str(value)
pat = re.compile(rf'^{key}\s*=.*$', re.MULTILINE)
if pat.search(content):
content = pat.sub(lambda m: f'{key} = {val_str}', content)
else:
content = content.rstrip() + f'\n{key} = {val_str}\n'
with open(ini_path, 'w', encoding='utf-8') as f:
f.write(content)
except: pass
def _restricted_walk(self, directory: str):
target_base = os.path.abspath(directory)
for root, dirs, files in os.walk(directory):
curr_path = os.path.abspath(root)
dirs[:] = [d for d in dirs if d not in ('.git', '__pycache__', 'node_modules', 'venv', 'env', '.redo')]
if not getattr(self, 'is_pro', False):
if curr_path == target_base:
dirs[:] = [d for d in dirs if d == "ep_backups"]
elif curr_path == os.path.join(target_base, "ep_backups"):
dirs[:] = []
else:
dirs[:] = []
yield root, dirs, files
def _load_history(self):
"""Loads history while preserving exact tree expansion states during live reloads.
Discovers all code files (even untracked) and groups external changes chronologically."""
old_tree_data = getattr(self, 'tree_data', {})
raw_history = []
search_dirs = self.config.get("search_dirs", [])
appdata = os.environ.get('APPDATA', '')
if appdata:
config_dir = os.path.join(appdata, "CodeStitcher")
else:
config_dir = getattr(self, 'script_dir', '')
ini_path = os.path.join(config_dir, "cs_settings.ini")
if os.path.exists(ini_path):
try:
with open(ini_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line.startswith("CONF_LAST_DIFF_FILE"):
parts = line.split("=", 1)
if len(parts) > 1:
val = parts[1].strip().strip('"').strip("'")
if val:
self.config["CONF_LAST_DIFF_FILE"] = val
break
except Exception:
pass
code_exts = {'.py', '.html', '.js', '.css', '.json', '.txt', '.md', '.c', '.cpp', '.cs', '.java', '.php', '.go', '.rs', '.ts', '.jsx', '.tsx', '.sh', '.bat'}
discovered_files = {}
for sdir in search_dirs:
if not os.path.exists(sdir): continue
for root, dirs, files in self._restricted_walk(sdir):
if os.path.basename(root) == "ep_backups":
continue
for f in files:
ext = os.path.splitext(f)[1].lower()
if ext in code_exts:
full_path = os.path.join(root, f)
try:
mtime = os.path.getmtime(full_path)
ts_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(mtime))
if f not in discovered_files or ts_str > discovered_files[f]['ts_str']:
discovered_files[f] = {'ts_str': ts_str, 'full_path': full_path}
except Exception:
pass
known_baks = set()
total_backups_bytes = 0
for sdir in search_dirs:
if not os.path.exists(sdir): continue
for root, dirs, files in self._restricted_walk(sdir):
if os.path.basename(root) != "ep_backups": continue
for f in files:
try:
total_backups_bytes += os.path.getsize(os.path.join(root, f))
except Exception:
pass
if "ep_history.json" in files:
json_path = os.path.join(root, "ep_history.json")
try:
with open(json_path, 'r', encoding='utf-8') as hf:
data = json.load(hf)
if isinstance(data, list):
for entry in data:
diff_text = entry.get("diff", "")
if diff_text.strip():
entry['lines_added'] = sum(1 for l in diff_text.splitlines() if l.startswith('+') and not l.startswith('+++'))
entry['lines_removed'] = sum(1 for l in diff_text.splitlines() if l.startswith('-') and not l.startswith('---'))
else:
entry['lines_added'] = 0
entry['lines_removed'] = 0
raw_history.append(entry)
if entry.get("backup_reference"):
known_baks.add(entry.get("backup_reference"))
except Exception:
pass
for f in files:
if f.endswith('.bak') and f not in known_baks:
m = re.search(r'^(.*)_(\d+)_([A-Z]+)_(\d+)\.bak$', f)
if m:
orig_name = m.group(1)
parent_dir = os.path.dirname(root)
full_path = os.path.join(parent_dir, orig_name)
try:
mtime = os.path.getmtime(os.path.join(root, f))
ts_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(mtime))
except Exception:
ts_str = "1970-01-01 00:00:00"
raw_history.append({
"file": orig_name,
"full_path": full_path,
"timestamp": ts_str,
"backup_reference": f,
"lines_added": 0,
"lines_removed": 0
})
self.total_backups_size_str = self._format_bytes(total_backups_bytes)
file_groups = {}
for entry in raw_history:
fname = entry.get("file", "Unknown")
if fname not in file_groups: file_groups[fname] = []
file_groups[fname].append(entry)
self.tree_data = {}
for fname, info in discovered_files.items():
self.tree_data[fname] = {
'expanded': False,
'runs': {},
'last_ts': info['ts_str'],
'full_path': info['full_path']
}
for fname, entries in file_groups.items():
entries.sort(key=lambda x: x.get("timestamp", ""))
current_run_id = "External Run"
current_sess = 0
for entry in entries:
ref = entry.get("backup_reference", "")
m = re.search(r'_(\d+)_([A-Z]+)_(\d+)\.bak$', ref)
if m:
sess, let, wr = m.groups()
current_run_id = f"Run {sess}"
current_sess = int(sess)
entry['is_internal'] = (int(wr) == 1)
entry['job_letter'] = let
entry['write_num'] = int(wr)
entry['sess'] = current_sess
else:
entry['is_internal'] = False
entry['job_letter'] = "E"
entry['write_num'] = 0
entry['sess'] = current_sess
entry['run_id'] = current_run_id
last_hist_ts = entries[-1].get("timestamp", "")
if fname not in self.tree_data:
self.tree_data[fname] = {
'expanded': False,
'runs': {},
'last_ts': last_hist_ts,
'full_path': entries[-1].get("full_path", "")
}
else:
if last_hist_ts > self.tree_data[fname]['last_ts']:
self.tree_data[fname]['last_ts'] = last_hist_ts
for entry in entries:
run_id = entry['run_id']
if run_id not in self.tree_data[fname]['runs']:
self.tree_data[fname]['runs'][run_id] = {'expanded': False, 'entries': [], 'sess': entry['sess']}
self.tree_data[fname]['runs'][run_id]['entries'].append(entry)
for fname, fdata in self.tree_data.items():
if not fdata['runs']:
fdata['runs']["Unversioned"] = {
'expanded': False,
'sess': 999999,
'entries': [{
'file': fname,
'full_path': fdata['full_path'],
'timestamp': fdata['last_ts'],
'backup_reference': "",
'is_internal': False,
'job_letter': "C",
'write_num': 0,
'sess': 999999,
'run_id': "Unversioned",
'lines_added': 0,
'lines_removed': 0,
'is_unversioned': True
}]
}
last_file = self.config.get("CONF_LAST_DIFF_FILE", "")
if not last_file and self.tree_data:
last_file = max(self.tree_data.keys(), key=lambda k: self.tree_data[k]['last_ts'])
for fname, fdata in self.tree_data.items():
if fname in old_tree_data:
fdata['expanded'] = old_tree_data[fname]['expanded']
for r_id, rdata in fdata['runs'].items():
if r_id in old_tree_data[fname]['runs']:
rdata['expanded'] = old_tree_data[fname]['runs'][r_id]['expanded']
else:
if fname == last_file:
fdata['expanded'] = True
if fdata['runs']:
latest_run = max(fdata['runs'].keys(), key=lambda k: fdata['runs'][k]['sess'])
fdata['runs'][latest_run]['expanded'] = True
else:
fdata['expanded'] = False
for r in fdata['runs'].values():
r['expanded'] = False
self._rebuild_render_list()
def _rebuild_render_list(self):
self.render_list = []
sorted_files = sorted(self.tree_data.items(), key=lambda x: x[1]['last_ts'], reverse=True)
for fname, fdata in sorted_files:
self.render_list.append({'type': 'file', 'name': fname, 'expanded': fdata['expanded'], 'data': None})
if fdata['expanded']:
sorted_runs = sorted(fdata['runs'].items(), key=lambda x: x[1]['sess'], reverse=True)
for run_id, rdata in sorted_runs:
self.render_list.append({'type': 'run', 'name': run_id, 'expanded': rdata['expanded'], 'file': fname, 'data': None})
if rdata['expanded']:
sorted_entries = sorted(rdata['entries'], key=lambda x: x.get('timestamp', ''), reverse=True)
for entry in sorted_entries:
self.render_list.append({'type': 'entry', 'name': fname, 'data': entry})
def _get_entry_id(self, entry):
return entry.get("timestamp", "") + entry.get("backup_reference", "")
def _select_entry(self, entry):
"""Loads the complete files, handling ghost records intelligently so the renderer doesn't glitch."""
if not entry: return
self.active_entry_id = self._get_entry_id(entry)
self.current_entry = entry
self.current_file = entry.get("file")
fname = entry.get("file", "")
if fname:
self._update_ini_setting('CONF_LAST_DIFF_FILE', fname)
self.config['CONF_LAST_DIFF_FILE'] = fname
full_path = entry.get("full_path", "")
bak_ref = entry.get("backup_reference", "")
self.active_file_path = full_path
self.in_context_view = False
self.scroll_context = 0
new_lines = []
self.new_file_size_str = "0 B"
if full_path:
if os.path.exists(full_path):
new_text = self._read_file_text(full_path)
new_lines = new_text.splitlines() if new_text else [""]
try:
self.new_file_size_str = self._format_bytes(os.path.getsize(full_path))
except Exception: pass
else:
new_lines = [
"// ------------------------------------------------ //",
"// ERROR: LIVE FILE DOES NOT EXIST //",
"// ------------------------------------------------ //"
]
old_lines = []
self.old_file_size_str = "0 B"
if full_path and bak_ref:
bak_path = os.path.join(os.path.dirname(full_path), "ep_backups", bak_ref)
if os.path.exists(bak_path):
old_text = self._read_file_text(bak_path)
old_lines = old_text.splitlines() if old_text else [""]
try:
self.old_file_size_str = self._format_bytes(os.path.getsize(bak_path))
except Exception: pass
else:
old_lines = [
"// ------------------------------------------------ //",
"// ERROR: HISTORICAL BACKUP FILE DOES NOT EXIST //",
f"// PATH: {bak_ref}",
"// This record exists in the history JSON, but the //",
"// physical .bak file was deleted or moved. //",
"// ------------------------------------------------ //"
]
elif entry.get('is_unversioned', False):
old_lines = [
"// ------------------------------------------------ //",
"// THIS IS AN UNVERSIONED LIVE FILE //",
"// NO HISTORICAL DATA EXISTS //",
"// ------------------------------------------------ //"
]
self._build_side_by_side(old_lines, new_lines)
self.scroll_right = 0
self.scroll_right_target = 0.0
self.scroll_right_float = 0.0
self.selection_start = None
self.selection_end = None
if getattr(self, 'search_text', ''):
self._update_search(jump=False)
def _nav_history(self, direction):
entry_indices = [i for i, item in enumerate(self.render_list) if item['type'] == 'entry']
if not entry_indices: return
curr_idx = -1
for i, idx in enumerate(entry_indices):
if self._get_entry_id(self.render_list[idx]['data']) == self.active_entry_id:
curr_idx = i
break
if curr_idx != -1:
new_idx = curr_idx + direction
if 0 <= new_idx < len(entry_indices):
target_item = self.render_list[entry_indices[new_idx]]
self._select_entry(target_item['data'])