-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
4298 lines (3689 loc) · 172 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
4298 lines (3689 loc) · 172 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using System.Xml.Linq;
using Microsoft.Win32;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using PdfSharp.Pdf.Content;
using PdfSharp.Pdf.Content.Objects;
using PdfSharp.Drawing;
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using Windows.Storage;
using Windows.Storage.Streams;
using Passpix.Services;
using Passpix.Models;
namespace Passpix
{
public partial class MainWindow : Window
{
private bool _isInitialized = false;
// Passpix States
private BitmapSource? _originalBitmap;
private BitmapSource? _croppedBitmap;
private WriteableBitmap? _processedPortrait;
private WriteableBitmap? _sheetBitmap;
private bool _isDragging;
private Point _dragStartPoint;
private double _selectorStartLeft;
private double _selectorStartTop;
private bool _isUpdatingUi;
private Rect _detectedFaceRelativeRect = new Rect();
// Zoom / Pan States
private double _zoom = 1.0;
private bool _isPanning;
private Point _lastMousePosition;
// Resizing States
private bool _isResizing;
private string _resizeHandle = "";
private double _resizeStartWidth;
private double _resizeStartHeight;
private double _resizeStartLeft;
private double _resizeStartTop;
private Point _resizeStartMousePoint;
// Background Removal Debouncer
private bool _isProcessingBg;
private bool _needReProcessBg;
// PDF Utility States
private List<string> _pdfFiles = new List<string>(); // Merge PDFs list
private string? _pdfToImgPath;
private List<string> _imgToPdfPaths = new List<string>();
private string? _rearrangePdfPath;
private List<int> _rearrangePageOrder = new List<int>();
private string? _splitPdfPath;
private HashSet<int> _splitSelectedPages = new HashSet<int>();
private string? _addDeletePdfPath;
private List<int> _addDeletePageOrder = new List<int>(); // -1 represents a blank page
private string? _rotatePdfPath;
private List<int> _rotatePageAngles = new List<int>(); // List of rotations (0, 90, 180, 270)
// Compressor States
private BitmapSource? _compressOriginalBitmap;
private string? _compressOriginalPath;
private string? _compressPdfPath;
public MainWindow()
{
InitializeComponent();
// Wire window events
Loaded += MainWindow_Loaded;
Closing += MainWindow_Closing;
_isInitialized = true;
}
#region Navigation & Sidebar Flow
private void ShowPanel(Grid activePanel)
{
PanelHome.Visibility = Visibility.Collapsed;
PanelPasspix.Visibility = Visibility.Collapsed;
PanelPdf.Visibility = Visibility.Collapsed;
PanelCompress.Visibility = Visibility.Collapsed;
PanelSettings.Visibility = Visibility.Collapsed;
activePanel.Visibility = Visibility.Visible;
}
private void BtnNavHome_Click(object sender, RoutedEventArgs e)
{
ShowPanel(PanelHome);
}
private void BtnNavPasspix_Click(object sender, RoutedEventArgs e)
{
ShowPanel(PanelPasspix);
ApplyPasspixDefaultSettings();
TriggerCropAndProcess();
}
private void BtnNavPdf_Click(object sender, RoutedEventArgs e)
{
ShowPanel(PanelPdf);
}
private void BtnNavCompress_Click(object sender, RoutedEventArgs e)
{
ShowPanel(PanelCompress);
}
private void BtnNavSettings_Click(object sender, RoutedEventArgs e)
{
ShowPanel(PanelSettings);
}
#endregion
#region Tool 1: Passpix (Passport Photo Toolkit)
private void BtnPasspixSelect_Click(object sender, RoutedEventArgs e)
{
var openFileDialog = new OpenFileDialog
{
Filter = "Image files (*.png;*.jpg;*.jpeg)|*.png;*.jpg;*.jpeg"
};
if (openFileDialog.ShowDialog() == true)
{
try
{
var fileUri = new Uri(openFileDialog.FileName);
var img = new BitmapImage();
img.BeginInit();
img.CacheOption = BitmapCacheOption.OnLoad;
img.UriSource = fileUri;
img.EndInit();
img.Freeze();
_originalBitmap = img;
ImgOriginal.Source = _originalBitmap;
LblPasspixFileName.Text = Path.GetFileName(openFileDialog.FileName);
TxtCropperPlaceholder.Visibility = Visibility.Collapsed;
// Reset Zoom and Translation
_zoom = 1.0;
ImgScale.ScaleX = 1.0;
ImgScale.ScaleY = 1.0;
ImgTranslate.X = 0;
ImgTranslate.Y = 0;
if (SettingsService.Current.PasspixAutoFaceDetectionCrop)
{
_detectedFaceRelativeRect = DetectFaceHeuristic(_originalBitmap);
}
else
{
_detectedFaceRelativeRect = new Rect();
}
// Trigger crop overlay initialization
Dispatcher.BeginInvoke(new Action(() => {
UpdateCropSelectorBounds();
TriggerCropAndProcess();
}), DispatcherPriority.Loaded);
}
catch (Exception ex)
{
MessageBox.Show($"Failed to load portrait image: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
private Rect GetImageCurrentBounds()
{
if (_originalBitmap == null || ImgOriginal.ActualWidth == 0 || ImgOriginal.ActualHeight == 0)
return new Rect();
var rect = GetImageDisplayRect();
// Translate displayed image top-left and bottom-right points to CanvasCropOverlay space
Point topLeft = ImgOriginal.TranslatePoint(new Point(rect.Left, rect.Top), CanvasCropOverlay);
Point bottomRight = ImgOriginal.TranslatePoint(new Point(rect.Right, rect.Bottom), CanvasCropOverlay);
double width = bottomRight.X - topLeft.X;
double height = bottomRight.Y - topLeft.Y;
return new Rect(topLeft.X, topLeft.Y, width, height);
}
private void ClampCropSelectorToImageBounds()
{
if (_originalBitmap == null) return;
var imgBounds = GetImageCurrentBounds();
if (imgBounds.Width <= 0 || imgBounds.Height <= 0) return;
double left = Canvas.GetLeft(RectCropSelector);
double top = Canvas.GetTop(RectCropSelector);
if (double.IsNaN(left)) left = imgBounds.Left;
if (double.IsNaN(top)) top = imgBounds.Top;
double width = RectCropSelector.Width;
double height = RectCropSelector.Height;
if (width > imgBounds.Width || height > imgBounds.Height)
{
double tw = 1.19;
double th = 1.53;
double.TryParse(TxtCropWidth.Text, out tw);
double.TryParse(TxtCropHeight.Text, out th);
if (tw <= 0) tw = 1.19;
if (th <= 0) th = 1.53;
double targetAspect = tw / th;
height = imgBounds.Height * 0.7;
width = height * targetAspect;
if (width > imgBounds.Width)
{
width = imgBounds.Width * 0.7;
height = width / targetAspect;
}
RectCropSelector.Width = width;
RectCropSelector.Height = height;
}
left = Math.Max(imgBounds.Left, Math.Min(left, imgBounds.Right - width));
top = Math.Max(imgBounds.Top, Math.Min(top, imgBounds.Bottom - height));
Canvas.SetLeft(RectCropSelector, left);
Canvas.SetTop(RectCropSelector, top);
// Temporary debug logging
double maxX = imgBounds.Right - width;
double maxY = imgBounds.Bottom - height;
System.Diagnostics.Debug.WriteLine($"ImageLeft: {imgBounds.Left:F2}");
System.Diagnostics.Debug.WriteLine($"ImageTop: {imgBounds.Top:F2}");
System.Diagnostics.Debug.WriteLine($"ImageWidth: {imgBounds.Width:F2}");
System.Diagnostics.Debug.WriteLine($"ImageHeight: {imgBounds.Height:F2}");
System.Diagnostics.Debug.WriteLine($"CropX: {left:F2}");
System.Diagnostics.Debug.WriteLine($"CropY: {top:F2}");
System.Diagnostics.Debug.WriteLine($"MaxCropX: {maxX:F2}");
System.Diagnostics.Debug.WriteLine($"MaxCropY: {maxY:F2}");
}
private void UpdateCropSelectorBounds()
{
if (_originalBitmap == null) return;
CanvasCropOverlay.Width = double.NaN;
CanvasCropOverlay.Height = double.NaN;
CanvasCropOverlay.Margin = new Thickness(0);
var imgBounds = GetImageCurrentBounds();
if (imgBounds.Width <= 0 || imgBounds.Height <= 0) return;
double tw = 1.19;
double th = 1.53;
double.TryParse(TxtCropWidth.Text, out tw);
double.TryParse(TxtCropHeight.Text, out th);
if (tw <= 0) tw = 1.19;
if (th <= 0) th = 1.53;
double targetAspect = tw / th;
double selWidth, selHeight, left, top;
if (SettingsService.Current.PasspixAutoFaceDetectionCrop &&
_detectedFaceRelativeRect.Width > 0 && _detectedFaceRelativeRect.Height > 0)
{
// Translate the relative face rectangle to screen coords of the current display bounds
double faceLeft = imgBounds.Left + _detectedFaceRelativeRect.X * imgBounds.Width;
double faceTop = imgBounds.Top + _detectedFaceRelativeRect.Y * imgBounds.Height;
double faceWidth = _detectedFaceRelativeRect.Width * imgBounds.Width;
double faceHeight = _detectedFaceRelativeRect.Height * imgBounds.Height;
// Center a box with targetAspect on the face
double faceCenterX = faceLeft + faceWidth / 2;
double faceCenterY = faceTop + faceHeight / 2;
selHeight = faceHeight * 1.5; // expand a bit
selWidth = selHeight * targetAspect;
if (selWidth > imgBounds.Width || selHeight > imgBounds.Height)
{
// Scale down to fit inside rect bounds
double scale = Math.Min(imgBounds.Width / selWidth, imgBounds.Height / selHeight);
selWidth *= scale;
selHeight *= scale;
}
left = faceCenterX - selWidth / 2;
top = faceCenterY - selHeight / 2;
// Clamp to display bounds
left = Math.Max(imgBounds.Left, Math.Min(left, imgBounds.Right - selWidth));
top = Math.Max(imgBounds.Top, Math.Min(top, imgBounds.Bottom - selHeight));
}
else
{
selHeight = imgBounds.Height * 0.7;
selWidth = selHeight * targetAspect;
if (selWidth > imgBounds.Width)
{
selWidth = imgBounds.Width * 0.7;
selHeight = selWidth / targetAspect;
}
left = imgBounds.Left + (imgBounds.Width - selWidth) / 2;
top = imgBounds.Top + (imgBounds.Height - selHeight) / 2;
}
RectCropSelector.Width = selWidth;
RectCropSelector.Height = selHeight;
Canvas.SetLeft(RectCropSelector, left);
Canvas.SetTop(RectCropSelector, top);
}
private void ImgOriginal_SizeChanged(object sender, SizeChangedEventArgs e)
{
UpdateCropSelectorBounds();
TriggerCropAndProcess();
}
private Rect GetImageDisplayRect()
{
if (_originalBitmap == null || ImgOriginal.ActualWidth == 0 || ImgOriginal.ActualHeight == 0)
return new Rect();
double sourceWidth = _originalBitmap.PixelWidth;
double sourceHeight = _originalBitmap.PixelHeight;
double controlWidth = ImgOriginal.ActualWidth;
double controlHeight = ImgOriginal.ActualHeight;
double ratioX = controlWidth / sourceWidth;
double ratioY = controlHeight / sourceHeight;
double ratio = Math.Min(ratioX, ratioY);
double displayWidth = sourceWidth * ratio;
double displayHeight = sourceHeight * ratio;
double left = (controlWidth - displayWidth) / 2;
double top = (controlHeight - displayHeight) / 2;
return new Rect(left, top, displayWidth, displayHeight);
}
#region Interactive Sizing & Drag Handles
private void RectCropSelector_MouseDown(object sender, MouseButtonEventArgs e)
{
if (_originalBitmap == null || _isResizing) return;
_isDragging = true;
_dragStartPoint = e.GetPosition(CanvasCropOverlay);
_selectorStartLeft = Canvas.GetLeft(RectCropSelector);
_selectorStartTop = Canvas.GetTop(RectCropSelector);
if (double.IsNaN(_selectorStartLeft)) _selectorStartLeft = 0;
if (double.IsNaN(_selectorStartTop)) _selectorStartTop = 0;
RectCropSelector.CaptureMouse();
e.Handled = true;
}
private void RectCropSelector_MouseMove(object sender, MouseEventArgs e)
{
if (!_isDragging) return;
Point currentPoint = e.GetPosition(CanvasCropOverlay);
double deltaX = currentPoint.X - _dragStartPoint.X;
double deltaY = currentPoint.Y - _dragStartPoint.Y;
double newLeft = _selectorStartLeft + deltaX;
double newTop = _selectorStartTop + deltaY;
var imgBounds = GetImageCurrentBounds();
newLeft = Math.Max(imgBounds.Left, Math.Min(newLeft, imgBounds.Right - RectCropSelector.Width));
newTop = Math.Max(imgBounds.Top, Math.Min(newTop, imgBounds.Bottom - RectCropSelector.Height));
Canvas.SetLeft(RectCropSelector, newLeft);
Canvas.SetTop(RectCropSelector, newTop);
TriggerCropAndProcess();
e.Handled = true;
}
private void RectCropSelector_MouseUp(object sender, MouseButtonEventArgs e)
{
if (_isDragging)
{
RectCropSelector.ReleaseMouseCapture();
_isDragging = false;
TriggerCropAndProcess();
}
e.Handled = true;
}
private void Handle_MouseDown(object sender, MouseButtonEventArgs e)
{
if (_originalBitmap == null) return;
var border = sender as Border;
if (border == null) return;
_isResizing = true;
_resizeHandle = border.Tag.ToString() ?? "";
_resizeStartMousePoint = e.GetPosition(CanvasCropOverlay);
_resizeStartWidth = RectCropSelector.Width;
_resizeStartHeight = RectCropSelector.Height;
_resizeStartLeft = Canvas.GetLeft(RectCropSelector);
_resizeStartTop = Canvas.GetTop(RectCropSelector);
if (double.IsNaN(_resizeStartLeft)) _resizeStartLeft = 0;
if (double.IsNaN(_resizeStartTop)) _resizeStartTop = 0;
border.CaptureMouse();
e.Handled = true;
}
private void Handle_MouseMove(object sender, MouseEventArgs e)
{
if (!_isResizing) return;
Point currentPoint = e.GetPosition(CanvasCropOverlay);
double deltaX = currentPoint.X - _resizeStartMousePoint.X;
double tw = 1.19;
double th = 1.53;
double.TryParse(TxtCropWidth.Text, out tw);
double.TryParse(TxtCropHeight.Text, out th);
if (tw <= 0) tw = 1.19;
if (th <= 0) th = 1.53;
double targetAspect = tw / th;
double newW = _resizeStartWidth;
double newH = _resizeStartHeight;
double newLeft = _resizeStartLeft;
double newTop = _resizeStartTop;
switch (_resizeHandle)
{
case "BR":
newW = Math.Max(30, _resizeStartWidth + deltaX);
newH = newW / targetAspect;
break;
case "BL":
newW = Math.Max(30, _resizeStartWidth - deltaX);
newH = newW / targetAspect;
newLeft = _resizeStartLeft + (_resizeStartWidth - newW);
break;
case "TR":
newW = Math.Max(30, _resizeStartWidth + deltaX);
newH = newW / targetAspect;
newTop = _resizeStartTop - (newH - _resizeStartHeight);
break;
case "TL":
newW = Math.Max(30, _resizeStartWidth - deltaX);
newH = newW / targetAspect;
newLeft = _resizeStartLeft + (_resizeStartWidth - newW);
newTop = _resizeStartTop - (newH - _resizeStartHeight);
break;
}
var imgBounds = GetImageCurrentBounds();
if (newLeft >= imgBounds.Left && newTop >= imgBounds.Top &&
(newLeft + newW) <= imgBounds.Right &&
(newTop + newH) <= imgBounds.Bottom)
{
RectCropSelector.Width = newW;
RectCropSelector.Height = newH;
Canvas.SetLeft(RectCropSelector, newLeft);
Canvas.SetTop(RectCropSelector, newTop);
TriggerCropAndProcess();
}
}
private void Handle_MouseUp(object sender, MouseButtonEventArgs e)
{
if (_isResizing)
{
var border = sender as Border;
border?.ReleaseMouseCapture();
_isResizing = false;
TriggerCropAndProcess();
}
e.Handled = true;
}
#endregion
#region Zooming and Panning Loaded Image
private void GridCropperContainer_MouseWheel(object sender, MouseWheelEventArgs e)
{
if (_originalBitmap == null) return;
double zoomFactor = e.Delta > 0 ? 1.15 : 0.85;
double newZoom = _zoom * zoomFactor;
if (newZoom >= 0.25 && newZoom <= 8.0)
{
_zoom = newZoom;
ImgScale.ScaleX = _zoom;
ImgScale.ScaleY = _zoom;
TriggerCropAndProcess();
}
}
private void GridCropperContainer_MouseDown(object sender, MouseButtonEventArgs e)
{
if (_originalBitmap == null) return;
// Click is outside the crop selector
if (e.ChangedButton == MouseButton.Left && e.OriginalSource != RectCropSelector && !IsDescendantOf(e.OriginalSource as DependencyObject, RectCropSelector))
{
_isPanning = true;
_lastMousePosition = e.GetPosition(GridCropperContainer);
GridCropperContainer.CaptureMouse();
e.Handled = true;
}
else if (e.ChangedButton == MouseButton.Right)
{
_isPanning = true;
_lastMousePosition = e.GetPosition(GridCropperContainer);
GridCropperContainer.CaptureMouse();
e.Handled = true;
}
}
private void GridCropperContainer_MouseMove(object sender, MouseEventArgs e)
{
if (_isPanning)
{
Point currentPos = e.GetPosition(GridCropperContainer);
double deltaX = currentPos.X - _lastMousePosition.X;
double deltaY = currentPos.Y - _lastMousePosition.Y;
ImgTranslate.X += deltaX;
ImgTranslate.Y += deltaY;
_lastMousePosition = currentPos;
TriggerCropAndProcess();
e.Handled = true;
}
}
private void GridCropperContainer_MouseUp(object sender, MouseButtonEventArgs e)
{
if (_isPanning)
{
GridCropperContainer.ReleaseMouseCapture();
_isPanning = false;
TriggerCropAndProcess();
e.Handled = true;
}
}
private bool IsDescendantOf(DependencyObject? element, DependencyObject parent)
{
while (element != null)
{
if (element == parent) return true;
element = VisualTreeHelper.GetParent(element);
}
return false;
}
#endregion
private void TxtCropDimensions_TextChanged(object sender, TextChangedEventArgs e)
{
if (_originalBitmap == null || _isUpdatingUi) return;
UpdateCropSelectorBounds();
}
private void ChkRemoveBg_Checked(object sender, RoutedEventArgs e) => TriggerCropAndProcess();
private void ChkRemoveBg_Unchecked(object sender, RoutedEventArgs e) => TriggerCropAndProcess();
private string GetCurrentBackgroundColorOption()
{
if (CmbSolidFill.SelectedItem is ComboBoxItem item)
{
string selectedText = item.Content?.ToString() ?? "";
if (selectedText.Equals("Custom Color...", StringComparison.OrdinalIgnoreCase))
{
return SettingsManager.Instance.DefaultBackgroundColor;
}
return selectedText;
}
return SettingsManager.Instance.DefaultBackgroundColor;
}
private void CmbCustomColor_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
e.Handled = true;
CmbSolidFill.IsDropDownOpen = false;
PromptAndApplyCustomColor();
}
private void PromptAndApplyCustomColor()
{
var colorPicker = new ColorPickerDialog();
colorPicker.Owner = Window.GetWindow(this);
string currentSettingsColor = SettingsService.Current.CustomBackgroundHex;
if (string.IsNullOrEmpty(currentSettingsColor))
{
currentSettingsColor = "#FFFFFF";
}
colorPicker.SelectedColor = GetPasspixColor(currentSettingsColor);
if (colorPicker.ShowDialog() == true)
{
Color chosen = colorPicker.SelectedColor;
string hexColor = $"#{chosen.R:X2}{chosen.G:X2}{chosen.B:X2}";
SettingsService.Current.IsUsingCustomBackground = true;
SettingsService.Current.CustomBackgroundHex = hexColor;
SettingsService.Current.CustomBackgroundColor = hexColor;
SettingsService.Current.PasspixDefaultBackgroundColor = hexColor;
SettingsService.Instance.SaveSettings();
_isUpdatingUi = true;
try
{
CmbCustomColor.Content = $"Custom Color ({hexColor})";
CmbSolidFill.SelectedItem = CmbCustomColor;
}
finally
{
_isUpdatingUi = false;
}
UpdatePreview();
GeneratePassportPreview();
RefreshGridSheet();
}
else
{
_isUpdatingUi = true;
try
{
RestoreCmbSolidFillSelection();
}
finally
{
_isUpdatingUi = false;
}
}
}
private void CmbSolidFill_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_isUpdatingUi) return;
if (CmbSolidFill.SelectedItem is ComboBoxItem selectedItem)
{
string selectedText = selectedItem.Content?.ToString() ?? "";
if (selectedText.StartsWith("Custom Color", StringComparison.OrdinalIgnoreCase))
{
PromptAndApplyCustomColor();
}
else
{
SettingsManager.Instance.DefaultBackgroundColor = selectedText;
SettingsService.Current.IsUsingCustomBackground = false;
SettingsService.Instance.SaveSettings();
}
}
TriggerCropAndProcess();
RefreshGridSheet();
}
private void RestoreCmbSolidFillSelection()
{
if (SettingsService.Current.IsUsingCustomBackground)
{
string hexColor = SettingsService.Current.CustomBackgroundHex;
CmbCustomColor.Content = $"Custom Color ({hexColor})";
CmbSolidFill.SelectedItem = CmbCustomColor;
return;
}
string savedColor = SettingsManager.Instance.DefaultBackgroundColor;
bool found = false;
foreach (ComboBoxItem item in CmbSolidFill.Items)
{
string itemText = item.Content?.ToString() ?? "";
if (itemText.Equals(savedColor, StringComparison.OrdinalIgnoreCase))
{
CmbSolidFill.SelectedItem = item;
found = true;
break;
}
}
if (!found)
{
CmbSolidFill.SelectedItem = CmbCustomColor;
}
}
private Color GetSelectedBackgroundColor()
{
if (SettingsService.Current.IsUsingCustomBackground)
{
try
{
string hex = SettingsService.Current.CustomBackgroundHex;
if (!string.IsNullOrEmpty(hex))
{
var convertedColor = ColorConverter.ConvertFromString(hex);
if (convertedColor is Color col)
{
return col;
}
}
}
catch { }
return Colors.White;
}
string bg = SettingsService.Current.PasspixDefaultBackgroundColor?.ToLower() ?? "white";
switch (bg)
{
case "white":
return Colors.White;
case "light blue":
return Color.FromRgb(214, 234, 248);
case "red":
return Colors.Red;
case "blue":
return Colors.Blue;
case "transparent":
return Colors.Transparent;
default:
return Colors.White;
}
}
private void UpdatePreview() => TriggerCropAndProcess();
private void GeneratePassportPreview() => TriggerCropAndProcess();
private void RefreshGridSheet() => RenderGridSheet();
private void CmbPageSize_SelectionChanged(object sender, SelectionChangedEventArgs e) => TriggerCropAndProcess();
private void TxtCopies_TextChanged(object sender, TextChangedEventArgs e) => TriggerCropAndProcess();
private async void TriggerCropAndProcess()
{
if (!_isInitialized || _originalBitmap == null) return;
ClampCropSelectorToImageBounds();
bool isInteracting = _isPanning || _isDragging || _isResizing;
bool willRunBgRemoval = ChkRemoveBg.IsChecked == true && !isInteracting;
// Debounce / Throttle ONNX runs
if (willRunBgRemoval)
{
if (_isProcessingBg)
{
_needReProcessBg = true;
return;
}
_isProcessingBg = true;
}
try
{
while (true)
{
_needReProcessBg = false;
await RunCropAndProcessInternal();
if (!_needReProcessBg || ChkRemoveBg.IsChecked != true || isInteracting)
{
break;
}
}
}
finally
{
if (willRunBgRemoval)
{
_isProcessingBg = false;
}
}
}
private async Task RunCropAndProcessInternal()
{
if (_originalBitmap == null || ImgOriginal.ActualWidth == 0 || ImgOriginal.ActualHeight == 0) return;
double left = Canvas.GetLeft(RectCropSelector);
double top = Canvas.GetTop(RectCropSelector);
if (double.IsNaN(left)) left = 0;
if (double.IsNaN(top)) top = 0;
try
{
var rect = GetImageDisplayRect();
if (rect.Width <= 0 || rect.Height <= 0) return;
// Map screen coordinates of selector to zoomed/panned image's local space
var transform = CanvasCropOverlay.TransformToVisual(ImgOriginal);
Point p0 = transform.Transform(new Point(left, top));
Point p1 = transform.Transform(new Point(left + RectCropSelector.Width, top + RectCropSelector.Height));
// Calculate relative position within the image content, then map to pixel coordinates
double relX0 = (p0.X - rect.Left) / rect.Width;
double relY0 = (p0.Y - rect.Top) / rect.Height;
double relX1 = (p1.X - rect.Left) / rect.Width;
double relY1 = (p1.Y - rect.Top) / rect.Height;
int cropX = (int)(relX0 * _originalBitmap.PixelWidth);
int cropY = (int)(relY0 * _originalBitmap.PixelHeight);
int cropW = (int)((relX1 - relX0) * _originalBitmap.PixelWidth);
int cropH = (int)((relY1 - relY0) * _originalBitmap.PixelHeight);
cropX = Math.Max(0, Math.Min(cropX, _originalBitmap.PixelWidth - 1));
cropY = Math.Max(0, Math.Min(cropY, _originalBitmap.PixelHeight - 1));
cropW = Math.Max(1, Math.Min(cropW, _originalBitmap.PixelWidth - cropX));
cropH = Math.Max(1, Math.Min(cropH, _originalBitmap.PixelHeight - cropY));
var cropRect = new Int32Rect(cropX, cropY, cropW, cropH);
_croppedBitmap = new CroppedBitmap(_originalBitmap, cropRect);
TxtCropResultPlaceholder.Visibility = Visibility.Collapsed;
bool isInteracting = _isPanning || _isDragging || _isResizing;
bool runBgRemoval = ChkRemoveBg.IsChecked == true && !isInteracting;
Color bgColor = GetSelectedBackgroundColor();
GridCroppedResultBg.Background = GetPasspixBrush();
if (runBgRemoval)
{
if (App.OnnxSession == null)
{
TxtCropResultPlaceholder.Text = "Loading AI Model...";
TxtCropResultPlaceholder.Visibility = Visibility.Visible;
PnlProgressRing.Visibility = Visibility.Visible;
if (App.ModelLoadingTask != null)
{
bool success = await App.ModelLoadingTask;
if (!success || App.OnnxSession == null)
{
TxtCropResultPlaceholder.Text = "AI Model unavailable";
PnlProgressRing.Visibility = Visibility.Collapsed;
_processedPortrait = CreateWriteableBitmap(_croppedBitmap);
ImgCroppedResult.Source = _processedPortrait;
if (TcPasspix.SelectedIndex == 1)
{
RenderGridSheet();
}
return;
}
}
}
TxtCropResultPlaceholder.Text = "Removing BG...";
TxtCropResultPlaceholder.Visibility = Visibility.Visible;
PnlProgressRing.Visibility = Visibility.Visible;
var inputBitmap = _croppedBitmap;
inputBitmap.Freeze();
var outPixels = await Task.Run(() => RemoveBackgroundWithOnnx(inputBitmap, bgColor));
PnlProgressRing.Visibility = Visibility.Collapsed;
if (_isPanning || _isDragging || _isResizing)
{
return;
}
if (outPixels != null)
{
int targetW = inputBitmap.PixelWidth;
int targetH = inputBitmap.PixelHeight;
_processedPortrait = new WriteableBitmap(targetW, targetH, 300.0, 300.0, PixelFormats.Bgra32, null);
_processedPortrait.WritePixels(new Int32Rect(0, 0, targetW, targetH), outPixels, targetW * 4, 0, 0);
if (SettingsService.Current.PasspixAutoFaceEnhancement)
{
EnhanceFace(_processedPortrait);
}
ImgCroppedResult.Source = _processedPortrait;
TxtCropResultPlaceholder.Visibility = Visibility.Collapsed;
}
else
{
_processedPortrait = CreateWriteableBitmap(inputBitmap);
if (SettingsService.Current.PasspixAutoFaceEnhancement)
{
EnhanceFace(_processedPortrait);
}
ImgCroppedResult.Source = _processedPortrait;
TxtCropResultPlaceholder.Text = "BG Removal Failed";
TxtCropResultPlaceholder.Visibility = Visibility.Visible;
}
}
else
{
PnlProgressRing.Visibility = Visibility.Collapsed;
_processedPortrait = CreateWriteableBitmap(_croppedBitmap);
if (SettingsService.Current.PasspixAutoFaceEnhancement)
{
EnhanceFace(_processedPortrait);
}
ImgCroppedResult.Source = _processedPortrait;
}
if (TcPasspix.SelectedIndex == 1 && !isInteracting)
{
RenderGridSheet();
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Passpix Process error: {ex.Message}");
}
}
private WriteableBitmap CreateWriteableBitmap(BitmapSource source)
{
var converted = new FormatConvertedBitmap(source, PixelFormats.Bgra32, null, 0);
return new WriteableBitmap(converted);
}
private Color GetPasspixColor(string colorName)
{
if (string.IsNullOrEmpty(colorName)) return Colors.White;
string normalized = colorName.ToLower().Trim();
if (normalized.StartsWith("#"))
{
try
{
var convertedColor = ColorConverter.ConvertFromString(normalized);
if (convertedColor is Color col)
{
return col;
}
}
catch { }
}
switch (normalized)
{
case "blue": return Color.FromRgb(30, 64, 175);
case "red": return Color.FromRgb(185, 28, 28);
case "light blue": return Color.FromRgb(186, 230, 253);
case "transparent": return Colors.Transparent;
case "white": return Colors.White;
default:
try
{
var convertedColor = ColorConverter.ConvertFromString("#" + normalized);
if (convertedColor is Color col)
{
return col;
}
}
catch { }
return Colors.White;
}
}
private Brush GetPasspixBrush()
{
Color col = GetSelectedBackgroundColor();
if (col == Colors.Transparent) return Brushes.Transparent;
return new SolidColorBrush(col);
}
private byte[]? RemoveBackgroundWithOnnx(BitmapSource src, Color fillCol)
{
if (App.OnnxSession == null) return null;
try
{
int targetW = src.PixelWidth;
int targetH = src.PixelHeight;