-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdiffer.py
More file actions
executable file
·1222 lines (1031 loc) · 50.6 KB
/
differ.py
File metadata and controls
executable file
·1222 lines (1031 loc) · 50.6 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 os
from PUI.PySide6 import *
import PUI
from common import *
import json
import platform
import subprocess
from threading import Thread
import hashlib
import queue
import glob
import pypdfium2 as pdfium
import cv2
import tempfile
import atexit
import shutil
import git
import pcbnew
if platform.system() == "Darwin":
kicad_cli = "/Applications/KiCad/KiCad.app/Contents/MacOS/kicad-cli"
elif platform.system() == "Windows":
kicad_cli = "C:/Program Files/KiCad/9.0/bin/kicad-cli.exe"
else:
kicad_cli = "/usr/bin/kicad-cli"
try:
base_path = sys._MEIPASS
cands = None
if platform.system() == "Darwin":
cands = glob.glob(os.path.join(os.path.abspath(base_path, "..", "MacOS"), "kicad-cli*"))
elif platform.system() == "Windows":
cands = glob.glob(os.path.join(base_path, "KiCad", "bin", "kicad-cli*"))
if cands:
kicad_cli = cands[0]
except Exception:
pass
kicad_cli_version = "Error"
try:
kicad_cli_version = subprocess.check_output([kicad_cli, "--version"]).decode().strip()
except Exception:
pass
def convert_sch(path, outpath):
os.makedirs(outpath, exist_ok=True)
pdfpath = os.path.join(outpath, "sch.pdf")
if not os.path.exists(pdfpath):
yield f"Exporting PDF for {os.path.basename(path)}..."
cmd = [kicad_cli, "sch", "export", "pdf", "-o", pdfpath, path]
kwargs = {}
if platform.system() == "Windows":
kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW
subprocess.run(cmd, **kwargs)
if not os.path.exists(os.path.join(outpath, "sch")):
yield f"Exporting PNG for {os.path.basename(path)}..."
os.makedirs(os.path.join(outpath, "sch"), exist_ok=True)
pdf = pdfium.PdfDocument(pdfpath)
for p, page in enumerate(pdf):
opencv_image = page.render(
scale=7, # 72*x DPI is the default PDF resolution
rotation=0
).to_numpy()
opencv_image = cv2.cvtColor(opencv_image, cv2.COLOR_RGBA2RGB)
cv2.imwrite(os.path.join(outpath, "sch", f"sch_{p:02d}.png"), opencv_image)
def get_pcb_layers(path):
board = pcbnew.LoadBoard(path)
return [board.GetLayerName(layer) for layer in board.GetEnabledLayers().Seq()]
def convert_pcb(path, outpath):
os.makedirs(outpath, exist_ok=True)
pdfpath = os.path.join(outpath, f"pcb_pdf")
if not os.path.exists(pdfpath):
yield f"Exporting PDF for {os.path.basename(path)}..."
cmd = [kicad_cli, "pcb", "export", "pdf", "--mode-separate", "--layers", ",".join(get_pcb_layers(path)), "-o", pdfpath, path]
kwargs = {}
if platform.system() == "Windows":
kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW
subprocess.run(cmd, **kwargs)
if os.path.isdir(pdfpath):
os.makedirs(os.path.join(outpath, "pcb"), exist_ok=True)
for layer in get_pcb_layers(path):
png_path = os.path.join(outpath, "pcb", f"{layer}.png")
layerpdfpath = glob.glob(os.path.join(pdfpath, f"*{layer.replace('.', '_')}.pdf"))
if layerpdfpath:
yield f"Exporting {layer} to PNG for {os.path.basename(path)}..."
pdf = pdfium.PdfDocument(layerpdfpath[0])
opencv_image = pdf[0].render(
fill_color=(255, 255, 255, 0),
scale=7, # 72*x DPI is the default PDF resolution
rotation=0
).to_numpy()
cv2.imwrite(png_path, opencv_image)
class SchDiffView(PUIView):
def __init__(self, main):
super().__init__()
self.main = main
self.path_a = Prop()
self.path_b = Prop()
self.mask_mtime = Prop()
self.darker_mtime = Prop()
self.canvas_width = None
self.canvas_height = None
self.diff_width = None
self.diff_height = None
self.mousehold = False
self.scaled_params = Prop()
def setup(self):
self.state = State()
self.state.scale = None
self.state.splitter_x = 0.5
self.state.overlap = 0.05
def autoScale(self, canvas_width, canvas_height):
mask = os.path.join(self.main.temp_dir, "sch_mask.png")
if not os.path.exists(mask):
return
try:
mask = cv2.imread(mask, cv2.IMREAD_UNCHANGED) # IMREAD_UNCHANGED preserves alpha if present
if mask is None: # OpenCV returns None if image loading fails
return
# In OpenCV, shape is (height, width, channels) or (height, width) for grayscale
# So we need to swap compared to PIL's size which is (width, height)
dh, dw = mask.shape[:2] # Get first two dimensions (height, width)
except:
return
self.diff_width, self.diff_height = dw, dh
self.canvas_width, self.canvas_height = canvas_width, canvas_height
if dw == 0 or dh == 0:
return
cw = canvas_width
ch = canvas_height
sw = cw / dw
sh = ch / dh
scale = min(sw, sh) * 0.75
self.scale = scale
offx = (cw - (dw) * scale) / 2
offy = (ch - (dh) * scale) / 2
self.state.scale = (offx, offy, scale)
def toCanvas(self, x, y):
"""
Convert global coordinate system to canvas coordinate system
"""
offx, offy, scale = self.state.scale
return x * scale + offx, y * scale + offy
def fromCanvas(self, x, y):
"""
Convert canvas coordinate system to global coordinate system
"""
offx, offy, scale = self.state.scale
return (x - offx)/scale, (y - offy)/scale
def content(self):
# register update
self.main.state.diff_pair
self.state.splitter_x
self.state.overlap
self.state.scale
self.main.state.highlight_changes
self.main.state.build_time
(Canvas(self.painter).layout(weight=1)
.style(bgColor=0xF5F4EE)
.mousemove(self.mousemove)
.mousedown(self.mousedown)
.mouseup(self.mouseup)
.wheel(self.wheel))
def mousedown(self, e):
self.state.mousepos = e.x, e.y
self.mousehold = True
def mouseup(self, e):
self.mousehold = False
def mousemove(self, e):
if self.state.scale is None:
return
if self.canvas_width is None:
return
if self.mousehold:
pdx = e.x - self.state.mousepos[0]
pdy = e.y - self.state.mousepos[1]
offx, offy, scale = self.state.scale
offx += pdx
offy += pdy
self.state.scale = offx, offy, scale
else:
x, _ = self.fromCanvas(e.x, 0)
self.state.splitter_x = x / self.diff_width
self.state.mousepos = e.x, e.y
def wheel(self, e):
if e.modifiers & KeyModifier.CTRL:
zoom_factor = 1.7 # Factor for smoother zooming
noverlap = self.state.overlap * (zoom_factor ** (e.v_delta / 120))
self.state.overlap = max(0.0001, min(0.1, noverlap))
return
if self.state.scale is None:
return
offx, offy, scale = self.state.scale
zoom_factor = 1.2 # Factor for smoother zooming
nscale = scale * (zoom_factor ** (e.v_delta / 120))
# Limit the scale
nscale = min(self.scale*4, max(self.scale/8, nscale))
# Calculate new offsets
offx = e.x - (e.x - offx) * nscale / scale
offy = e.y - (e.y - offy) * nscale / scale
self.state.scale = offx, offy, nscale
def painter(self, canvas):
if self.state.scale is None:
self.autoScale(canvas.width, canvas.height)
return
path = os.path.join(self.main.state.cached_file_a, "sch", self.main.state.page_a)
if self.path_a.set(path):
self.image_a = canvas.loadImage(path)
self.scaled_image_a = None
path = os.path.join(self.main.state.cached_file_b, "sch", self.main.state.page_b)
if self.path_b.set(path):
self.image_b = canvas.loadImage(path)
self.scaled_image_b = None
path = os.path.join(self.main.temp_dir, "sch_darker.png")
if self.darker_mtime.set(os.path.getmtime(path)):
self.darker = canvas.loadImage(path)
self.scaled_darker = None
path = os.path.join(self.main.temp_dir, "sch_mask.png")
if self.mask_mtime.set(os.path.getmtime(path)):
self.mask = canvas.loadImage(path)
self.scaled_mask = None
offx, offy, scale = self.state.scale
scaled_diff_width = round(self.diff_width * scale)
scaled_diff_height = round(self.diff_height * scale)
if self.scaled_params.set(scale):
self.scaled_image_a = None
self.scaled_image_b = None
self.scaled_darker = None
self.scaled_mask = None
if self.scaled_image_a is None:
self.scaled_image_a = self.image_a.scale(scaled_diff_width, scaled_diff_height, True, 1)
if self.scaled_image_b is None:
self.scaled_image_b = self.image_b.scale(scaled_diff_width, scaled_diff_height, True, 1)
if self.scaled_darker is None:
self.scaled_darker = self.darker.scale(scaled_diff_width, scaled_diff_height, True, 1)
if self.scaled_mask is None:
self.scaled_mask = self.mask.scale(scaled_diff_width, scaled_diff_height, True, 1)
xL = round(min(scaled_diff_width, max(0, scaled_diff_width*(self.state.splitter_x - self.state.overlap))))
xR = round(max(0, min(scaled_diff_width, scaled_diff_width*(self.state.splitter_x + self.state.overlap))))
offx = round(offx)
offy = round(offy)
# A
x1, y1 = 0, 0
x2, y2 = xL, scaled_diff_height
canvas.drawImage(self.scaled_image_a,
x1+offx, y1+offy, width=(x2-x1), height=(y2-y1),
src_x=x1, src_y=y1, src_width=(x2-x1), src_height=(y2-y1))
# B
x1, y1 = xR, 0
x2, y2 = scaled_diff_width, scaled_diff_height
canvas.drawImage(self.scaled_image_b,
x1+offx, y1+offy, width=(x2-x1), height=(y2-y1),
src_x=x1, src_y=y1, src_width=(x2-x1), src_height=(y2-y1))
# Darker
x1, y1 = xL, 0
x2, y2 = xR, scaled_diff_height
canvas.drawImage(self.scaled_darker,
x1+offx, y1+offy, width=(x2-x1), height=(y2-y1),
src_x=x1, src_y=y1, src_width=(x2-x1), src_height=(y2-y1))
# Mask
if self.main.state.highlight_changes:
x1, y1 = 0, 0
x2, y2 = scaled_diff_width, scaled_diff_height
canvas.drawImage(self.scaled_mask,
x1+offx, y1+offy, width=(x2-x1), height=(y2-y1),
src_x=x1, src_y=y1, src_width=(x2-x1), src_height=(y2-y1), opacity=0.08)
# Overlap cursor
canvas.drawLine(xL+offx, 0, xL+offx, canvas.height, color=0, width=1)
canvas.drawLine(xR+offx, 0, xR+offx, canvas.height, color=0, width=1)
class PcbDiffView(PUIView):
def __init__(self, main):
super().__init__()
self.main = main
self.path_a = Prop()
self.path_b = Prop()
self.mask_mtime = Prop()
self.darker_mtime = Prop()
self.canvas_width = None
self.canvas_height = None
self.diff_width = None
self.diff_height = None
self.image_a = {}
self.image_b = {}
self.darker = {}
self.mask = None
self.scaled_mask = None
self.scaled_darker = {}
self.scaled_image_a = {}
self.scaled_image_b = {}
self.mousehold = False
self.scaled_params = Prop()
def setup(self):
self.state = State()
self.state.scale = None
self.state.splitter_x = 0.5
self.state.overlap = 0.05
def autoScale(self, canvas_width, canvas_height):
mask = os.path.join(self.main.temp_dir, "pcb_mask.png")
if not os.path.exists(mask):
return
try:
mask = cv2.imread(mask, cv2.IMREAD_UNCHANGED) # IMREAD_UNCHANGED preserves alpha if present
if mask is None: # OpenCV returns None if image loading fails
return
# In OpenCV, shape is (height, width, channels) or (height, width) for grayscale
# So we need to swap compared to PIL's size which is (width, height)
dh, dw = mask.shape[:2] # Get first two dimensions (height, width)
except:
return
self.diff_width, self.diff_height = dw, dh
self.canvas_width, self.canvas_height = canvas_width, canvas_height
if dw == 0 or dh == 0:
return
cw = canvas_width
ch = canvas_height
sw = cw / dw
sh = ch / dh
scale = min(sw, sh) * 0.75
self.scale = scale
offx = (cw - (dw) * scale) / 2
offy = (ch - (dh) * scale) / 2
self.state.scale = (offx, offy, scale)
def toCanvas(self, x, y):
"""
Convert global coordinate system to canvas coordinate system
"""
offx, offy, scale = self.state.scale
return x * scale + offx, y * scale + offy
def fromCanvas(self, x, y):
"""
Convert canvas coordinate system to global coordinate system
"""
offx, offy, scale = self.state.scale
return (x - offx)/scale, (y - offy)/scale
def content(self):
# register update
self.main.state.diff_pair
self.state.splitter_x
self.state.overlap
self.state.scale
self.main.state.show_layers
self.main.state.highlight_changes
self.main.state.build_time
(Canvas(self.painter).layout(weight=1)
.style(bgColor=0x001124)
.mousedown(self.mousedown)
.mouseup(self.mouseup)
.mousemove(self.mousemove)
.wheel(self.wheel))
def mousedown(self, e):
self.state.mousepos = e.x, e.y
self.mousehold = True
def mouseup(self, e):
self.mousehold = False
def mousemove(self, e):
if self.state.scale is None:
return
if self.canvas_width is None:
return
if self.mousehold:
pdx = e.x - self.state.mousepos[0]
pdy = e.y - self.state.mousepos[1]
offx, offy, scale = self.state.scale
offx += pdx
offy += pdy
self.state.scale = offx, offy, scale
else:
x, _ = self.fromCanvas(e.x, 0)
self.state.splitter_x = x / self.diff_width
self.state.mousepos = e.x, e.y
def wheel(self, e):
if e.modifiers & KeyModifier.CTRL:
zoom_factor = 1.7 # Factor for smoother zooming
noverlap = self.state.overlap * (zoom_factor ** (e.v_delta / 120))
self.state.overlap = max(0.0001, min(0.1, noverlap))
return
if self.state.scale is None:
return
offx, offy, scale = self.state.scale
zoom_factor = 1.2 # Factor for smoother zooming
nscale = scale * (zoom_factor ** (e.v_delta / 120))
# Limit the scale
nscale = min(self.scale*8, max(self.scale/8, nscale))
# Calculate new offsets
offx = e.x - (e.x - offx) * nscale / scale
offy = e.y - (e.y - offy) * nscale / scale
self.state.scale = offx, offy, nscale
def painter(self, canvas):
if self.state.scale is None:
self.autoScale(canvas.width, canvas.height)
return
immediate = False
layers = self.main.state.layers
mtime = [os.path.getmtime(fn) for fn in [os.path.join(self.main.temp_dir, "pcb_darker", f"{layer}.png") for layer in layers] if os.path.exists(fn)]
if mtime and self.darker_mtime.set(max(mtime)):
self.darker = {}
if self.path_a.set(self.main.state.cached_file_a):
self.image_a = {}
if self.path_b.set(self.main.state.cached_file_b):
self.image_b = {}
path = os.path.join(self.main.temp_dir, "pcb_mask.png")
if self.mask_mtime.set(os.path.getmtime(path)):
self.mask = None
if self.mask is None:
try:
self.mask = canvas.loadImage(path)
self.scaled_mask = None
immediate = True
except:
self.mask = False
for layer in layers:
if not self.main.state.show_layers.get(layer, True):
continue
if not layer in self.darker:
try:
self.darker[layer] = canvas.loadImage(os.path.join(self.main.temp_dir, "pcb_darker", f"{layer}.png"))
self.scaled_darker.pop(layer, None)
immediate = True
break
except:
self.darker[layer] = False
if not layer in self.image_a:
try:
self.image_a[layer] = canvas.loadImage(os.path.join(self.main.state.cached_file_a, "pcb", f"{layer}.png"))
self.scaled_image_a.pop(layer, None)
immediate = True
break
except:
self.image_a[layer] = False
if not layer in self.image_b:
try:
self.image_b[layer] = canvas.loadImage(os.path.join(self.main.state.cached_file_b, "pcb", f"{layer}.png"))
self.scaled_image_b.pop(layer, None)
immediate = True
break
except:
self.image_b[layer] = False
offx, offy, scale = self.state.scale
scaled_diff_width = round(self.diff_width * scale)
scaled_diff_height = round(self.diff_height * scale)
if self.scaled_params.set(scale):
self.scaled_image_a = {}
self.scaled_image_b = {}
self.scaled_darker = {}
self.scaled_mask = None
if not self.scaled_mask:
self.scaled_mask = self.mask.scale(scaled_diff_width, scaled_diff_height, True, 1)
incompleted = False
for layer in layers:
if not self.main.state.show_layers.get(layer, True):
continue
if not layer in self.scaled_darker and self.darker.get(layer):
self.scaled_darker[layer] = self.darker[layer].scale(scaled_diff_width, scaled_diff_height, True, 1)
incompleted = True
if not layer in self.scaled_image_a and self.image_a.get(layer):
self.scaled_image_a[layer] = self.image_a[layer].scale(scaled_diff_width, scaled_diff_height, True, 1)
incompleted = True
if not layer in self.scaled_image_b and self.image_b.get(layer):
self.scaled_image_b[layer] = self.image_b[layer].scale(scaled_diff_width, scaled_diff_height, True, 1)
incompleted = True
if incompleted:
break
xL = round(min(scaled_diff_width, max(0, scaled_diff_width*(self.state.splitter_x - self.state.overlap))))
xR = round(max(0, min(scaled_diff_width, scaled_diff_width*(self.state.splitter_x + self.state.overlap))))
offx = round(offx)
offy = round(offy)
for layer in layers[::-1]:
if not self.main.state.show_layers.get(layer, True):
continue
# A
x1, y1 = 0, 0
x2, y2 = xL, self.diff_height
if layer in self.scaled_image_a:
canvas.drawImage(self.scaled_image_a[layer],
x1+offx, y1+offy, width=(x2-x1 + 1), height=(y2-y1 + 1),
src_x=x1, src_y=y1, src_width=(x2-x1 + 1), src_height=(y2-y1 + 1), opacity=0.8)
else:
immediate = True
# B
x1, y1 = xR, 0
x2, y2 = self.diff_width, self.diff_height
if layer in self.scaled_image_b:
canvas.drawImage(self.scaled_image_b[layer],
x1+offx, y1+offy, width=(x2-x1 + 1), height=(y2-y1 + 1),
src_x=x1, src_y=y1, src_width=(x2-x1 + 1), src_height=(y2-y1 + 1), opacity=0.8)
else:
immediate = True
# Darker
x1, y1 = xL, 0
x2, y2 = xR, self.diff_height
if layer in self.scaled_darker:
canvas.drawImage(self.scaled_darker[layer],
x1+offx, y1+offy, width=(x2-x1 + 1), height=(y2-y1 + 1),
src_x=x1, src_y=y1, src_width=(x2-x1 + 1), src_height=(y2-y1 + 1), opacity=0.8)
else:
immediate = True
# Mask
if self.main.state.highlight_changes:
x1, y1 = 0, 0
x2, y2 = self.diff_width, self.diff_height
if self.scaled_mask:
canvas.drawImage(self.scaled_mask,
x1+offx, y1+offy, width=(x2-x1 + 1), height=(y2-y1 + 1),
src_x=x1, src_y=y1, src_width=(x2-x1 + 1), src_height=(y2-y1 + 1), opacity=0.3)
else:
immediate = True
# Overlap cursor
canvas.drawLine(xL+offx, 0, xL+offx, canvas.height, color=0x7e8792, width=1)
canvas.drawLine(xR+offx, 0, xR+offx, canvas.height, color=0x7e8792, width=1)
return immediate
class DifferUI(Application):
def __init__(self, *argv):
super().__init__(icon=resource_path("icon.ico"))
self.temp_dir = tempfile.mkdtemp(prefix="kikakuka_differ_")
atexit.register(self.cleanup)
self.state = State()
self.state.show_layers = {}
self.state.loading_diff = False
self.state.loading_a = False
self.state.loading_b = False
self.state.file_a = ""
self.state.file_b = ""
self.state.logs_a = None
self.state.logs_b = None
self.state.commit_a = ""
self.state.commit_b = ""
self.state.page_a = 0
self.state.page_b = 0
self.state.diff_pair = None
self.state.layers = []
self.state.highlight_changes = True
self.state.build_time = 0
self.state.use_workspace = False
self.state.cached_file_a = ""
self.state.cached_file_b = ""
self.state.message = ""
self.repo_a = None
self.repo_b = None
self.queue = queue.Queue()
Thread(target=self.bg_looper, daemon=True).start()
if len(argv) == 1:
filepath = argv[0]
with open(filepath, "r") as f:
self.state.use_workspace = True
self.base_dir = os.path.dirname(os.path.abspath(filepath))
self.workspace = json.load(f)
for project in self.workspace["projects"]:
if not os.path.isabs(project["path"]):
project["path"] = os.path.join(self.base_dir, project["path"])
findFiles(self.workspace, self.base_dir, [SCH_SUFFIX, PCB_SUFFIX])
elif len(argv) == 2:
self.state.file_a = os.path.abspath(argv[0])
self.state.file_b = os.path.abspath(argv[1])
self.build()
def cleanup(self):
if os.path.exists(self.temp_dir):
shutil.rmtree(self.temp_dir)
def content(self):
title = f"Kikakuka v{VERSION} Differ (KiCad CLI {kicad_cli_version}, Pypdfium2 {pdfium.version.PYPDFIUM_INFO}, OpenCV {cv2.__version__}, PUI {PUI.__version__} {PUI_BACKEND})"
with Window(maximize=True, title=title, icon=resource_path("icon.ico")):
with VBox():
if not os.path.exists(kicad_cli):
Label("KiCad CLI not found")
Spacer()
return
with HBox():
if self.state.use_workspace:
with HBox():
Label("File A")
with ComboBox(text_model=self.state("file_a")).layout(weight=1).change(lambda e: self.change_file_a()):
for project in self.workspace["projects"]:
if project["path"].lower().endswith(PNL_SUFFIX):
continue
for file in project["files"]:
folder_name = os.path.basename(os.path.dirname(file["path"]))
file_name = os.path.basename(file["path"])
folder_file = f"{folder_name}/{file_name}"
ComboBoxItem(folder_file, file["path"])
with HBox():
Label("File B")
with ComboBox(text_model=self.state("file_b")).layout(weight=1).change(lambda e: self.change_file_b()):
for project in self.workspace["projects"]:
if project["path"].lower().endswith(PNL_SUFFIX):
continue
for file in project["files"]:
folder_name = os.path.basename(os.path.dirname(file["path"]))
file_name = os.path.basename(file["path"])
folder_file = f"{folder_name}/{file_name}"
ComboBoxItem(folder_file, file["path"])
else:
with HBox():
Label("File A")
if self.state.file_a:
Label(self.state.file_a).layout(weight=1)
Button("Open").click(self.open_file_a)
if not self.state.file_a:
Spacer()
with HBox():
Label("File B")
if self.state.file_b:
Label(self.state.file_b).layout(weight=1)
Button("Open").click(self.open_file_b)
if not self.state.file_b:
Spacer()
with HBox():
with HBox().layout(weight=1):
Label("Revision")
if self.state.file_a and self.state.logs_a is None:
Label("Loading...").layout(weight=1)
elif self.state.logs_a:
with ComboBox(text_model=self.state("commit_a")).layout(weight=1).change(lambda e: self.select_commit_a()):
ComboBoxItem("WORKING", "")
for hex, msg in self.state.logs_a:
ComboBoxItem(msg.split("\n")[0].rstrip()[:50], hex)
else:
Label("N/A").layout(weight=1)
with HBox().layout(weight=1):
Label("Revision")
if self.state.file_b and self.state.logs_b is None:
Label("Loading...").layout(weight=1)
elif self.state.logs_b:
with ComboBox(text_model=self.state("commit_b")).layout(weight=1).change(lambda e: self.select_commit_b()):
ComboBoxItem("WORKING", "")
for hex, msg in self.state.logs_b:
ComboBoxItem(msg.split("\n")[0].rstrip()[:50], hex)
else:
Label("N/A").layout(weight=1)
with HBox():
if self.state.loading_diff is True:
Spacer()
Label("Loading diff...")
Spacer()
elif self.state.loading_diff:
Spacer()
Label(f"Loading diff for {self.state.loading_diff}...")
Spacer()
elif self.state.loading_a or self.state.loading_b:
Label(self.state.loading_a or "").layout(weight=1)
Label(self.state.loading_b or "").layout(weight=1)
elif self.state.file_a and self.state.file_a:
if os.path.splitext(self.state.file_a)[1].lower() == SCH_SUFFIX:
Button("PCB Diff").click(self.pcb_diff)
elif os.path.splitext(self.state.file_a)[1].lower() == PCB_SUFFIX:
Button("SCH Diff").click(self.sch_diff)
Label("Ctrl+Wheel to adjust overlap").layout(weight=1)
Label(self.state.message).layout(weight=1)
Checkbox("Highlight Changes", model=self.state("highlight_changes"))
else:
Spacer()
Label("Select two files to compare")
Spacer()
if self.state.file_a and self.state.file_b:
if os.path.splitext(self.state.file_a)[1].lower() != os.path.splitext(self.state.file_b)[1].lower():
Label("Files are different types")
Spacer()
return
if os.path.splitext(self.state.file_a)[1].lower() == SCH_SUFFIX and os.path.splitext(self.state.file_b)[1].lower() == SCH_SUFFIX:
with HBox():
with Scroll().layout(width=250):
with VBox():
if self.state.cached_file_a:
for i,png in enumerate(os.listdir(os.path.join(self.state.cached_file_a, "sch"))):
Image(os.path.join(self.state.cached_file_a, "sch", png)).layout(width=240).click(lambda e, png: self.select_page_a(png), png)
if png==self.state.page_a:
Label(f"* Page {i+1} *")
else:
Label(f"Page {i+1}")
else:
Label("Loading pages...")
Spacer()
if not self.state.page_a or not self.state.page_b:
Spacer()
else:
with VBox().layout(weight=1):
SchDiffView(self)
with Scroll().layout(width=250):
with VBox():
if self.state.cached_file_b:
for i,png in enumerate(os.listdir(os.path.join(self.state.cached_file_b, "sch"))):
Image(os.path.join(self.state.cached_file_b, "sch", png)).layout(width=240).click(lambda e, png: self.select_page_b(png), png)
if png==self.state.page_b:
Label(f"* Page {i+1} *")
else:
Label(f"Page {i+1}")
else:
Label("Loading pages...")
Spacer()
elif os.path.splitext(self.state.file_a)[1].lower() == PCB_SUFFIX:
with HBox():
with VBox().layout(weight=1):
PcbDiffView(self)
with VBox():
Label("Display Layers")
for layer in self.state.layers:
Checkbox(layer, model=self.state.show_layers(layer))
Spacer()
else:
with HBox():
with VBox().dragEnter(self.handleDragEnter).drop(self.drop_file_a):
Spacer()
with HBox():
Spacer()
Label("Drop File Here").style(fontSize=36)
Spacer()
Spacer()
with VBox().dragEnter(self.handleDragEnter).drop(self.drop_file_b):
Spacer()
with HBox():
Spacer()
Label("Drop File Here").style(fontSize=36)
Spacer()
Spacer()
def pcb_diff(self, e):
self.state.file_a = os.path.splitext(self.state.file_a)[0] + PCB_SUFFIX
self.state.file_b = os.path.splitext(self.state.file_b)[0] + PCB_SUFFIX
self.state.log_a = None
self.state.log_b = None
self.state.cached_file_a = None
self.state.cached_file_b = None
self.build()
def sch_diff(self, e):
self.state.file_a = os.path.splitext(self.state.file_a)[0] + SCH_SUFFIX
self.state.file_b = os.path.splitext(self.state.file_b)[0] + SCH_SUFFIX
self.state.log_a = None
self.state.log_b = None
self.state.cached_file_a = None
self.state.cached_file_b = None
self.build()
def handleDragEnter(self, event):
if event.mimeData().hasUrls():
if len(event.mimeData().urls()) == 1:
fn = event.mimeData().urls()[0].toLocalFile()
ext = os.path.splitext(fn)[1].lower()
if ext in [SCH_SUFFIX, PCB_SUFFIX]:
event.accept()
return True
event.ignore()
return False
def drop_file_a(self, event):
if event.mimeData().hasUrls():
if len(event.mimeData().urls()) == 1:
fn = event.mimeData().urls()[0].toLocalFile()
ext = os.path.splitext(fn)[1].lower()
if ext in [SCH_SUFFIX, PCB_SUFFIX]:
self.state.file_a = fn
self.state.log_a = None
self.build()
event.accept()
return True
event.ignore()
return False
def drop_file_b(self, event):
if event.mimeData().hasUrls():
if len(event.mimeData().urls()) == 1:
fn = event.mimeData().urls()[0].toLocalFile()
ext = os.path.splitext(fn)[1].lower()
if ext in [SCH_SUFFIX, PCB_SUFFIX]:
self.state.file_b = fn
self.state.log_b = None
self.build()
event.accept()
return True
event.ignore()
return False
def change_file_a(self):
self.state.logs_a = None
self.state.cached_file_a = ""
self.build()
def change_file_b(self):
self.state.logs_b = None
self.state.cached_file_b = ""
self.build()
def open_file_a(self, e):
fn = OpenFile("Open File A", types="KiCad PCB (*.kicad_pcb)|*.kicad_pcb|KiCad SCH (*.kicad_sch)|*.kicad_sch")
if fn:
self.state.file_a = fn
self.change_file_a()
def open_file_b(self, e):
fn = OpenFile("Open File B", types="KiCad PCB (*.kicad_pcb)|*.kicad_pcb|KiCad SCH (*.kicad_sch)|*.kicad_sch")
if fn:
self.state.file_b = fn
self.change_file_b()
def select_page_a(self, png):
self.state.page_a = png
self.build()
def select_page_b(self, png):
self.state.page_b = png
self.build()
def select_commit_a(self):
self.build()
def select_commit_b(self):
self.build()
def build(self):
self.queue.put(1)
def pad_to_same_size(self, image_a, image_b):
# Get dimensions - in OpenCV shape is (height, width, channels)
height_a, width_a = image_a.shape[:2]
height_b, width_b = image_b.shape[:2]
target_width = max(width_a, width_b)
target_height = max(height_a, height_b)
# If images are already the same size, return them unchanged
if width_a == width_b and height_a == height_b:
return image_a, image_b
# Check number of channels in each image
channels_a = image_a.shape[2] if len(image_a.shape) > 2 else 1
channels_b = image_b.shape[2] if len(image_b.shape) > 2 else 1
# Handle alpha channel (equivalent to RGBA in PIL)
has_alpha_a = channels_a == 4
has_alpha_b = channels_b == 4
# If one image has alpha and the other doesn't, convert both to have alpha
if has_alpha_a or has_alpha_b:
if not has_alpha_a:
# Convert BGR to BGRA
image_a = cv2.cvtColor(image_a, cv2.COLOR_BGR2BGRA)
if not has_alpha_b:
image_b = cv2.cvtColor(image_b, cv2.COLOR_BGR2BGRA)
# Update channels after conversion
channels_a = channels_b = 4
# Create padded images with transparent background (255,255,255,0)
if channels_a == 4: # BGRA
padded_a = np.zeros((target_height, target_width, 4), dtype=np.uint8)
padded_a[:, :] = [255, 255, 255, 0] # White transparent background
elif channels_a == 3: # BGR
padded_a = np.ones((target_height, target_width, 3), dtype=np.uint8) * 255 # White background
else: # Grayscale
padded_a = np.ones((target_height, target_width), dtype=np.uint8) * 255 # White background
if channels_b == 4:
padded_b = np.zeros((target_height, target_width, 4), dtype=np.uint8)
padded_b[:, :] = [255, 255, 255, 0]
elif channels_b == 3:
padded_b = np.ones((target_height, target_width, 3), dtype=np.uint8) * 255
else:
padded_b = np.ones((target_height, target_width), dtype=np.uint8) * 255
# Calculate center positions
paste_x_a = (target_width - width_a) // 2
paste_y_a = (target_height - height_a) // 2
paste_x_b = (target_width - width_b) // 2
paste_y_b = (target_height - height_b) // 2
# Paste original images onto padded versions
# In OpenCV, we use array slicing instead of paste
padded_a[paste_y_a:paste_y_a+height_a, paste_x_a:paste_x_a+width_a] = image_a
padded_b[paste_y_b:paste_y_b+height_b, paste_x_b:paste_x_b+width_b] = image_b
return padded_a, padded_b
def bg_looper(self):
while True:
self.queue.get()
try:
file_a = self.state.file_a
file_b = self.state.file_b
if file_a and self.state.logs_a is None:
self.repo_a = git.repo(file_a)
if self.repo_a:
self.state.commit_a = ""
self.state.logs_a = [(hex, msg) for hex,msg in git.log(self.repo_a)]
else:
self.state.logs_a = False