Repository navigation
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
9191 lines (8353 loc) · 421 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
9191 lines (8353 loc) · 421 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.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Docnet.Core;
using Docnet.Core.Models;
using Microsoft.Win32;
using PdfSharpCore.Drawing;
using PdfSharpCore.Pdf;
using PdfSharpCore.Pdf.IO;
using KillerPDF.Services;
using PdfPigDoc = UglyToad.PdfPig.PdfDocument;
namespace KillerPDF
{
public partial class MainWindow : Window
{
private PdfDocument? _doc;
private string? _currentFile;
private string? _originalFile; // user's real file path; survives temp swaps from crop/rotate, used by Save
private Point _dragStartPoint;
// Zoom
private double _zoomLevel = 1.0;
private double _lastRenderZoom = 1.0;
private const double ZoomMin = 0.05;
private const double ZoomMax = 5.0;
private const double ZoomStep = 0.15;
private enum FitMode { None, Width, Page }
private FitMode _fitMode = FitMode.None;
private System.Windows.Threading.DispatcherTimer? _rerenderTimer;
private System.Threading.CancellationTokenSource? _secondaryRenderCts;
private enum ViewMode { Single, Continuous, TwoPage, Grid }
private ViewMode _viewMode = ViewMode.Continuous;
private readonly StackPanel _continuousPanel = null!;
private System.Threading.CancellationTokenSource? _continuousRenderCts;
private readonly List<double> _continuousTops = [];
private int _continuousScrollTarget = -1; // re-scroll here once its true height is known
private double _continuousPageW;
// Editing
private EditTool _currentTool = EditTool.Select;
private readonly Dictionary<int, List<PageAnnotation>> _annotations = [];
private readonly Dictionary<int, (int w, int h)> _renderDims = [];
// Stores the PDF /Rotate value for each page. The temp file used by Docnet has
// rotation stripped to zero so FPDF_GetPageWidth/Height returns MediaBox dims and
// the content isn't clipped; RotateBitmap is applied at render time instead.
private readonly Dictionary<int, int> _pageRotations = [];
// Form filling — text/check keyed by widget object number; radio keyed by field name
private readonly Dictionary<int, string> _formTextValues = [];
private readonly Dictionary<int, bool> _formCheckValues = [];
private readonly Dictionary<string, string> _formRadioValues = [];
private const string FormOverlayTag = "FormFieldOverlay";
// Undo stack — each entry is either an annotation removal or a full document snapshot.
private enum UndoKind { Annotation, Document }
private readonly record struct UndoEntry(UndoKind Kind, int PageIdx = -1, byte[]? DocBytes = null, bool WasDirty = false);
private readonly Stack<UndoEntry> _undoStack = new();
private bool _isDrawing;
private Point _drawStart;
private UIElement? _activePreview;
private InkAnnotation? _activeInk;
private TextBox? _activeTextBox;
private PageAnnotation? _selectedAnnotation;
private Border? _selectionBorder;
// Draw/Highlight settings
private Color _drawColor = Colors.Red;
private double _drawWidth = 3;
private byte _drawOpacity = 255;
private Color _highlightColor = Color.FromArgb(80, 255, 255, 0);
private Border? _drawSettingsBar;
// Text (typewriter) tool settings
private double _textFontSize = 24;
private TextAnnotation? _reeditOriginal; // placed-text annotation currently being re-edited
private Color _textColor = Colors.Black;
private Border? _textSettingsBar;
// Signature / image resize
private bool _isResizingSig;
private Point _resizeSigStart;
private double _resizeSigStartScale;
private PlacedAnnotation? _resizeSigAnnot;
private readonly List<Rectangle> _resizeHandles = []; // 4 corner handles for placed annotations
private string _resizeCorner = "SE"; // which corner is being dragged
private Point _resizeAnchor; // opposite corner, held fixed during resize
// Placed annotation drag-to-move
private bool _isDraggingAnnot;
private Point _dragAnnotStart;
// Middle-mouse / spacebar pan
private bool _isPanning;
private bool _spaceHeld;
private Point _panStart;
private double _panScrollH;
private double _panScrollV;
private Point _dragAnnotOrigPos;
private PageAnnotation? _dragAnnot; // placed image/signature OR typewriter text
// Crop tool
private Rect _cropCanvasRect;
private Rectangle? _cropPreviewRect;
private Rectangle? _cropPreviewRectBorder; // unused after refactor; kept to avoid null-ref in cleanup
private readonly List<System.Windows.Shapes.Path> _cropBrackets = []; // L-bracket corner visuals
private Border? _cropConfirmBar;
private readonly Button _toolCropBtn = null!;
private readonly List<Rectangle> _cropHandles = [];
private string? _activeCropHandleTag; // "NW" | "NE" | "SE" | "SW"
private Point _cropHandleDragStart;
private Rect _cropRectAtHandleDrag;
private int _cropPageIndex = -1; // page the crop rect was drawn on (grid/two-page aware)
private TextBox? _cropX1Box, _cropY1Box, _cropX2Box, _cropY2Box;
private TextBox? _cropRangeBox;
private bool _updatingCropInputs;
private bool _cropBarDragging;
private Point _cropBarDragOffset;
// PDF link overlays (rendered on top of the annotation canvas)
private readonly List<Canvas> _linkOverlays = [];
// Sidebar + multi-page view
private bool _sidebarCollapsed;
private bool _sidebarShowingOutlines;
private bool _outlinesFitted = false;
private double _savedPagesWidth = 180;
private double _savedOutlinesWidth = 300;
private readonly Button _sidebarToggleBtn = null!;
private readonly Border _sidebarBorder = null!;
private readonly ColumnDefinition _sidebarCol = null!;
private readonly WrapPanel _pageContentPanel = null!;
// Text selection
private bool _isSelecting;
private Point _selectStart;
private Rectangle? _selectRect;
private string? _selectedText;
// Search
private Border? _searchBar;
private TextBox? _searchBox;
private TextBlock? _searchStatus;
private readonly List<Rect> _searchHighlights = [];
// Signatures
private readonly SignatureStore _signatureStore = new();
private SavedSignature? _pendingSignature;
private Border? _signaturePopup;
// Manual element refs (XAML codegen doesn't resolve these)
private readonly Canvas _annotationCanvas = null!;
// Active annotation surface. Single view: always _annotationCanvas. Continuous view:
// set on mouse-down to the clicked page's overlay. Shared handlers target this.
private Canvas _activeCanvas = null!;
// Per-page overlay canvases for Continuous view, keyed by page index.
private readonly Dictionary<int, Canvas> _continuousCanvases = [];
private readonly Grid _pageContentGrid = null!;
private readonly Button _toolSelectBtn = null!;
private readonly Button _toolTextBtn = null!;
private readonly Button _toolHighlightBtn = null!;
private readonly Button _toolDrawBtn = null!;
private readonly Button _toolSignatureBtn = null!;
private readonly Button _toolImageBtn = null!;
private readonly Button _saveAsBtnRef = null!;
private readonly Button _closeFileBtnRef = null!;
private readonly ComboBox _zoomBox = null!;
private readonly StackPanel _portableBadge = null!;
private readonly TextBox _pageJumpBox = null!;
private readonly TextBlock _pageTotalLabel = null!;
// Dirty / unsaved-change tracking
private bool _isDirty = false;
// Whole-document search results (PDF-space rects per page)
private readonly Dictionary<int, List<(double left, double bottom, double right, double top)>> _allSearchRects = [];
private readonly List<int> _searchResultPages = [];
private int _searchPageCursor = -1;
public MainWindow()
{
InitializeComponent();
var v = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
if (v != null) VersionLabel.Text = $"v{v.Major}.{v.Minor}.{v.Build}";
_annotationCanvas = (Canvas)FindName("AnnotationCanvas")!;
_activeCanvas = _annotationCanvas;
_pageContentGrid = (Grid)FindName("PageContentGrid")!;
_toolSelectBtn = (Button)FindName("ToolSelectBtn")!;
_toolTextBtn = (Button)FindName("ToolTextBtn")!;
_toolHighlightBtn = (Button)FindName("ToolHighlightBtn")!;
_toolDrawBtn = (Button)FindName("ToolDrawBtn")!;
_toolSignatureBtn = (Button)FindName("ToolSignatureBtn")!;
_toolImageBtn = (Button)FindName("ToolImageBtn")!;
_toolCropBtn = (Button)FindName("ToolCropBtn")!;
_sidebarToggleBtn = (Button)FindName("SidebarToggleBtn")!;
_sidebarBorder = (Border)FindName("SidebarBorder")!;
_sidebarCol = (ColumnDefinition)FindName("SidebarCol")!;
_pageContentPanel = (WrapPanel)FindName("PageContentPanel")!;
_saveAsBtnRef = (Button)FindName("SaveAsBtn")!;
_closeFileBtnRef = (Button)FindName("CloseFileBtn")!;
_zoomBox = (ComboBox)FindName("ZoomBox")!;
_portableBadge = (StackPanel)FindName("PortableBadge")!;
_pageJumpBox = (TextBox)FindName("PageJumpBox")!;
_pageTotalLabel = (TextBlock)FindName("PageTotalLabel")!;
_continuousPanel = (StackPanel)FindName("ContinuousPanel")!;
PagePreviewPanel.ScrollChanged += PagePreviewPanel_ScrollChanged;
if (Enum.TryParse<ViewMode>(App.GetSetting("ViewMode"), out var savedVm))
_viewMode = savedVm;
OutlineTree.SelectedItemChanged += OutlineTree_SelectedItemChanged;
LoadSignatures();
BuildContextMenu();
SetTool(EditTool.Select);
ApplyGrainTexture();
SourceInitialized += MainWindow_SourceInitialized;
Closed += (_, _) => { _doc?.Close(); App.CleanupSessionTemps(); };
// Open a file passed via command-line / file association (e.g. double-clicking a .pdf)
// Also show the portable badge when running outside the install location.
ContentRendered += (_, _) => Services.ThemeManager.RefreshIcons();
Services.ThemeManager.ThemeChanged += OnThemeChanged;
Loaded += (_, _) =>
{
RestoreWindowSettings();
var args = Environment.GetCommandLineArgs();
if (args.Length > 1 && System.IO.File.Exists(args[1]))
{
OpenFile(args[1]);
}
else
{
// Reopen the last file if no CLI arg was provided
var lastFile = App.GetSetting("LastFile");
if (!string.IsNullOrEmpty(lastFile) && System.IO.File.Exists(lastFile))
OpenFile(lastFile!);
}
if (App.IsPortable())
_portableBadge.Visibility = Visibility.Visible;
};
}
// ============================================================
// Maximize-respects-taskbar fix (WindowStyle=None needs WM_GETMINMAXINFO)
// ============================================================
private void MainWindow_SourceInitialized(object? sender, EventArgs e)
{
var hwnd = new WindowInteropHelper(this).Handle;
HwndSource.FromHwnd(hwnd)?.AddHook(WndProc);
ThemeManager.ApplyDwm(hwnd);
}
// ============================================================
// Settings panel
// ============================================================
private void SettingsBtn_Click(object sender, RoutedEventArgs e)
{
// Sync radio buttons to current theme before showing
var cur = ThemeManager.Current;
ThemeDarkRadio.IsChecked = cur == Theme.Dark;
ThemeLightRadio.IsChecked = cur == Theme.Light;
ThemeHCRadio.IsChecked = cur == Theme.HighContrast;
ThemeBloodRadio.IsChecked = cur == Theme.Blood;
ThemeGreedRadio.IsChecked = cur == Theme.Greed;
ThemeCyanoticRadio.IsChecked = cur == Theme.Cyanotic;
// Sync language radios
var curLoc = KillerPDF.Services.LocaleManager.Current;
LangEnRadio.IsChecked = curLoc == KillerPDF.Services.Locale.EnUS;
LangEsRadio.IsChecked = curLoc == KillerPDF.Services.Locale.Es;
LangZhTWRadio.IsChecked = curLoc == KillerPDF.Services.Locale.ZhTW;
LangZhCNRadio.IsChecked = curLoc == KillerPDF.Services.Locale.ZhCN;
// Sync view mode radios
ViewSingleRadio.IsChecked = _viewMode == ViewMode.Single;
ViewContinuousRadio.IsChecked = _viewMode == ViewMode.Continuous;
ViewTwoPageRadio.IsChecked = _viewMode == ViewMode.TwoPage;
ViewGridRadio.IsChecked = _viewMode == ViewMode.Grid;
SettingsOverlay.Visibility = Visibility.Visible;
}
private void SettingsOverlay_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
=> SettingsOverlay.Visibility = Visibility.Collapsed;
private void SettingsOverlayCard_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
=> e.Handled = true;
private void SettingsOverlayClose_Click(object sender, RoutedEventArgs e)
=> SettingsOverlay.Visibility = Visibility.Collapsed;
private void OnThemeChanged()
{
// Refresh snapshot FindResource calls that were set as local values.
// SetResourceReference bindings update automatically; sidebar tabs and
// active tool button background still need an explicit refresh.
SetTool(_currentTool);
if (_sidebarShowingOutlines)
SwitchSidebarToOutlinesTab();
else
SwitchSidebarToPagesTab();
RefreshSelectionAccent();
}
private void ThemeDarkRadio_Checked(object sender, RoutedEventArgs e)
=> ThemeManager.Apply(Theme.Dark);
private void ThemeLightRadio_Checked(object sender, RoutedEventArgs e)
=> ThemeManager.Apply(Theme.Light);
private void ThemeHCRadio_Checked(object sender, RoutedEventArgs e)
=> ThemeManager.Apply(Theme.HighContrast);
private void ThemeBloodRadio_Checked(object sender, RoutedEventArgs e)
=> ThemeManager.Apply(Theme.Blood);
private void ThemeGreedRadio_Checked(object sender, RoutedEventArgs e)
=> ThemeManager.Apply(Theme.Greed);
private void ThemeCyanoticRadio_Checked(object sender, RoutedEventArgs e)
=> ThemeManager.Apply(Theme.Cyanotic);
private void LangEnRadio_Checked(object sender, RoutedEventArgs e)
=> KillerPDF.Services.LocaleManager.Apply(KillerPDF.Services.Locale.EnUS);
private void LangEsRadio_Checked(object sender, RoutedEventArgs e)
=> KillerPDF.Services.LocaleManager.Apply(KillerPDF.Services.Locale.Es);
private void LangZhTWRadio_Checked(object sender, RoutedEventArgs e)
=> KillerPDF.Services.LocaleManager.Apply(KillerPDF.Services.Locale.ZhTW);
private void LangZhCNRadio_Checked(object sender, RoutedEventArgs e)
=> KillerPDF.Services.LocaleManager.Apply(KillerPDF.Services.Locale.ZhCN);
private void ViewSingleRadio_Checked(object sender, RoutedEventArgs e) { SetViewMode(ViewMode.Single); SettingsOverlay.Visibility = Visibility.Collapsed; }
private void ViewContinuousRadio_Checked(object sender, RoutedEventArgs e) { SetViewMode(ViewMode.Continuous); SettingsOverlay.Visibility = Visibility.Collapsed; }
private void ViewTwoPageRadio_Checked(object sender, RoutedEventArgs e) { SetViewMode(ViewMode.TwoPage); SettingsOverlay.Visibility = Visibility.Collapsed; }
private void ViewGridRadio_Checked(object sender, RoutedEventArgs e) { SetViewMode(ViewMode.Grid); SettingsOverlay.Visibility = Visibility.Collapsed; }
private const int WM_GETMINMAXINFO = 0x0024;
private const int WM_DPICHANGED = 0x02E0;
private const uint MONITOR_DEFAULTTONEAREST = 0x00000002;
private const uint SWP_NOZORDER = 0x0004;
private const uint SWP_NOACTIVATE = 0x0010;
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == WM_GETMINMAXINFO)
{
WmGetMinMaxInfo(hwnd, lParam);
handled = true;
}
else if (msg == WM_DPICHANGED)
{
// Apply Windows' suggested rect so the window's apparent size is preserved
// on the new monitor. handled stays false so WPF's HwndSource also processes
// the message — updating its internal DPI scale and firing Window.DpiChanged.
var r = Marshal.PtrToStructure<RECT>(lParam);
SetWindowPos(hwnd, IntPtr.Zero, r.left, r.top,
r.right - r.left, r.bottom - r.top,
SWP_NOZORDER | SWP_NOACTIVATE);
// Re-render at the new DPI. DispatcherPriority.Loaded fires after WPF has
// finished its own DPI update, so VisualTreeHelper.GetDpi already reflects
// the new scale factor when RenderPage calls it.
Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Loaded,
(Action)(() =>
{
int idx = PageList.SelectedIndex;
if (idx >= 0) RenderPage(idx);
}));
}
else if (msg == WM_NCHITTEST && WindowState == WindowState.Normal)
{
int ht = WmNcHitTest(hwnd, lParam);
if (ht != 0) { handled = true; return new IntPtr(ht); }
}
return IntPtr.Zero;
}
private int WmNcHitTest(IntPtr hwnd, IntPtr lParam)
{
// lParam is screen coords: lo-word = X, hi-word = Y.
// Cast through short to preserve sign (handles negative coords on left/above primary monitor).
long lp = lParam.ToInt64();
int mx = unchecked((short)(lp & 0xFFFF));
int my = unchecked((short)((lp >> 16) & 0xFFFF));
if (!GetWindowRect(hwnd, out RECT rc)) return 0;
bool onLeft = mx < rc.left + ResizeBorder;
bool onRight = mx >= rc.right - ResizeBorder;
bool onTop = my < rc.top + ResizeBorder;
bool onBottom = my >= rc.bottom - ResizeBorder;
if (onTop && onLeft) return HTTOPLEFT;
if (onTop && onRight) return HTTOPRIGHT;
if (onBottom && onLeft) return HTBOTTOMLEFT;
if (onBottom && onRight) return HTBOTTOMRIGHT;
if (onLeft) return HTLEFT;
if (onRight) return HTRIGHT;
if (onTop) return HTTOP;
if (onBottom) return HTBOTTOM;
return 0;
}
private static void WmGetMinMaxInfo(IntPtr hwnd, IntPtr lParam)
{
var mmi = Marshal.PtrToStructure<MINMAXINFO>(lParam);
IntPtr monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
if (monitor != IntPtr.Zero)
{
var info = new MONITORINFO { cbSize = Marshal.SizeOf(typeof(MONITORINFO)) };
GetMonitorInfo(monitor, ref info);
RECT work = info.rcWork;
RECT mon = info.rcMonitor;
mmi.ptMaxPosition.x = Math.Abs(work.left - mon.left);
mmi.ptMaxPosition.y = Math.Abs(work.top - mon.top);
mmi.ptMaxSize.x = Math.Abs(work.right - work.left);
mmi.ptMaxSize.y = Math.Abs(work.bottom - work.top);
mmi.ptMaxTrackSize.x = mmi.ptMaxSize.x;
mmi.ptMaxTrackSize.y = mmi.ptMaxSize.y;
Marshal.StructureToPtr(mmi, lParam, true);
}
}
[DllImport("user32.dll")]
private static extern IntPtr MonitorFromWindow(IntPtr handle, uint flags);
[DllImport("user32.dll")]
private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFO lpmi);
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern bool SetWindowPos(
IntPtr hWnd, IntPtr hWndInsertAfter,
int X, int Y, int cx, int cy, uint uFlags);
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hwnd, out RECT rect);
private const int WM_NCLBUTTONDOWN = 0x00A1;
private const int WM_NCHITTEST = 0x0084;
private const int HTCAPTION = 2;
private const int HTLEFT = 10;
private const int HTRIGHT = 11;
private const int HTTOP = 12;
private const int HTTOPLEFT = 13;
private const int HTTOPRIGHT = 14;
private const int HTBOTTOM = 15;
private const int HTBOTTOMLEFT = 16;
private const int HTBOTTOMRIGHT = 17;
private const int ResizeBorder = 8;
[StructLayout(LayoutKind.Sequential)]
private struct POINT { public int x; public int y; }
[StructLayout(LayoutKind.Sequential)]
private struct RECT { public int left, top, right, bottom; }
[StructLayout(LayoutKind.Sequential)]
private struct MINMAXINFO
{
public POINT ptReserved;
public POINT ptMaxSize;
public POINT ptMaxPosition;
public POINT ptMinTrackSize;
public POINT ptMaxTrackSize;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private struct MONITORINFO
{
public int cbSize;
public RECT rcMonitor;
public RECT rcWork;
public uint dwFlags;
}
// ============================================================
// Window chrome
// ============================================================
private void TitleBar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.ClickCount == 2)
{
MaximizeBtn_Click(sender, e);
return;
}
// Delegate drag to Windows via WM_NCLBUTTONDOWN(HTCAPTION).
// This gives native restore-from-maximized-and-drag behavior:
// if the window is maximized, Windows restores it and follows the cursor
// exactly as a native title bar would.
e.Handled = true;
var hwnd = new WindowInteropHelper(this).Handle;
SendMessage(hwnd, WM_NCLBUTTONDOWN, new IntPtr(HTCAPTION), IntPtr.Zero);
}
private void Install_Click(object sender, RoutedEventArgs e)
{
var res = KillerDialog.Show(this,
Loc("Str_Dlg_InstallMsg"),
Loc("Str_Dlg_InstallTitle"), MessageBoxButton.OKCancel);
if (res != MessageBoxResult.OK) return;
// Hide the badge immediately so it doesn't flash if relaunch is slow
_portableBadge.Visibility = Visibility.Collapsed;
App.InstallAndRelaunch(_currentFile, wantDesktop: true);
}
private void MinimizeBtn_Click(object sender, RoutedEventArgs e) =>
WindowState = WindowState.Minimized;
private void MaximizeBtn_Click(object sender, RoutedEventArgs e) =>
WindowState = WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
private void CloseBtn_Click(object sender, RoutedEventArgs e) => Close();
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
if (_isDirty)
{
var res = KillerDialog.Show(this,
Loc("Str_Dlg_UnsavedExit"),
Loc("Str_Dlg_AppTitle"), MessageBoxButton.YesNo, MessageBoxImage.Warning);
if (res != MessageBoxResult.Yes)
{
e.Cancel = true;
return;
}
}
SaveWindowSettings();
base.OnClosing(e);
}
// ============================================================
// Settings persistence (window size, zoom, last file)
// ============================================================
private void SaveWindowSettings()
{
try
{
App.SetSetting("WindowState", WindowState.ToString());
if (WindowState == WindowState.Normal)
{
App.SetSetting("WindowWidth", ((int)ActualWidth).ToString());
App.SetSetting("WindowHeight", ((int)ActualHeight).ToString());
App.SetSetting("WindowTop", ((int)Top).ToString());
App.SetSetting("WindowLeft", ((int)Left).ToString());
}
App.SetSetting("FitMode", _fitMode.ToString());
App.SetSetting("ZoomLevel", _zoomLevel.ToString(System.Globalization.CultureInfo.InvariantCulture));
if (_currentFile is not null)
App.SetSetting("LastFile", _currentFile);
}
catch { /* best-effort */ }
}
private void RestoreWindowSettings()
{
try
{
if (int.TryParse(App.GetSetting("WindowWidth"), out int w) &&
int.TryParse(App.GetSetting("WindowHeight"), out int h) && w > 200 && h > 200)
{
Width = w;
Height = h;
}
if (int.TryParse(App.GetSetting("WindowTop"), out int savedTop) &&
int.TryParse(App.GetSetting("WindowLeft"), out int savedLeft))
{
// Verify the saved position is visible on the virtual desktop
// (covers all monitors). Falls back to CenterScreen (XAML default)
// if the monitor it was on is no longer connected.
double vLeft = SystemParameters.VirtualScreenLeft;
double vTop = SystemParameters.VirtualScreenTop;
double vRight = vLeft + SystemParameters.VirtualScreenWidth;
double vBottom = vTop + SystemParameters.VirtualScreenHeight;
bool onScreen = savedLeft + 100 < vRight && savedLeft + Width > vLeft
&& savedTop + 50 < vBottom && savedTop + Height > vTop;
if (onScreen)
{
Left = savedLeft;
Top = savedTop;
}
}
if (Enum.TryParse<WindowState>(App.GetSetting("WindowState"), out var ws) &&
ws == WindowState.Maximized)
{
WindowState = WindowState.Maximized;
}
if (double.TryParse(App.GetSetting("ZoomLevel"),
System.Globalization.NumberStyles.Float,
System.Globalization.CultureInfo.InvariantCulture, out double z) && z > 0)
{
_zoomLevel = Math.Max(ZoomMin, Math.Min(ZoomMax, z));
}
if (Enum.TryParse<FitMode>(App.GetSetting("FitMode"), out var fm))
_fitMode = fm;
}
catch { /* best-effort */ }
}
// ============================================================
// Context menu
// ============================================================
private void ApplyGrainTexture()
{
// Sparse bright-speck film grain — same style as the first pass,
// tuned so the texture is visible without being chunky.
const int size = 256;
var bmp = new WriteableBitmap(size, size, 96, 96, PixelFormats.Bgra32, null);
var pixels = new byte[size * size * 4]; // start fully transparent
var rng = new Random(1337);
for (int i = 0; i < pixels.Length; i += 4)
{
if (rng.Next(4) != 0) continue; // ~25% pixel density
byte v = (byte)rng.Next(160, 255); // bright specks
byte a = (byte)rng.Next(30, 80); // low-ish alpha for subtlety
pixels[i] = v;
pixels[i + 1] = v;
pixels[i + 2] = v;
pixels[i + 3] = a;
}
bmp.WritePixels(new System.Windows.Int32Rect(0, 0, size, size), pixels, size * 4, 0);
GrainBrush.ImageSource = bmp;
}
/// <summary>Generated film-grain tile, exposed so secondary windows (e.g. the
/// print preview) can paint the same texture over their document area.</summary>
public ImageSource? GrainTexture => GrainBrush?.ImageSource;
private void BuildContextMenu()
{
var menu = new ContextMenu();
menu.Items.Add(MakeMenuItem("Copy Text", (s, e) => CopySelectedText(), "Ctrl+C"));
menu.Items.Add(MakeMenuItem("Print", (s, e) => Print_Click(s!, e), "Ctrl+P"));
menu.Items.Add(new Separator());
menu.Items.Add(MakeMenuItem("Select Tool", (s, e) => SetTool(EditTool.Select)));
menu.Items.Add(MakeMenuItem("Text Tool", (s, e) => SetTool(EditTool.Text)));
menu.Items.Add(MakeMenuItem("Highlight Tool", (s, e) => SetTool(EditTool.Highlight)));
menu.Items.Add(MakeMenuItem("Draw Tool", (s, e) => SetTool(EditTool.Draw)));
menu.Items.Add(new Separator());
menu.Items.Add(MakeMenuItem("Rotate Page CW", (s, e) => RotatePages_Click(90)));
menu.Items.Add(MakeMenuItem("Rotate Page CCW", (s, e) => RotatePages_Click(-90)));
menu.Items.Add(new Separator());
menu.Items.Add(MakeMenuItem("Delete Selected", (s, e) => DeleteSelected(), "Delete"));
menu.Items.Add(MakeMenuItem("Undo Last", (s, e) => Undo_Click(s!, e), "Ctrl+Z"));
menu.Items.Add(MakeMenuItem("Clear Page Annotations", (s, e) => ClearAnnotations_Click(s!, e)));
_annotationCanvas.ContextMenu = menu;
}
private void PageList_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
if (_doc is null) return;
var menu = new ContextMenu();
menu.Items.Add(MakeMenuItem("Insert Blank Page After", (s, ev) => InsertBlankPage_Click(s!, ev)));
menu.Items.Add(new Separator());
menu.Items.Add(MakeMenuItem("Rotate CW", (s, ev) => RotatePages_Click(90)));
menu.Items.Add(MakeMenuItem("Rotate CCW", (s, ev) => RotatePages_Click(-90)));
menu.Items.Add(new Separator());
menu.Items.Add(MakeMenuItem("Move Page Up", (s, ev) => MoveUp_Click(s!, ev)));
menu.Items.Add(MakeMenuItem("Move Page Down", (s, ev) => MoveDown_Click(s!, ev)));
menu.Items.Add(new Separator());
menu.Items.Add(MakeMenuItem("Extract Page(s)", (s, ev) => Split_Click(s!, ev)));
menu.Items.Add(MakeMenuItem("Delete Page(s)", (s, ev) => Delete_Click(s!, ev)));
menu.PlacementTarget = PageList;
menu.IsOpen = true;
e.Handled = true;
}
private void RotatePages_Click(int delta)
{
if (_doc is null) return;
var selected = PageList.SelectedItems;
if (selected.Count == 0) return;
try
{
var indices = new List<int>();
foreach (PageThumbnailVm vm in selected) indices.Add(vm.PageIndex);
foreach (var idx in indices)
_doc.Pages[idx].Rotate = ((_doc.Pages[idx].Rotate + delta) % 360 + 360) % 360;
int restoreIdx = PageList.SelectedIndex;
SaveTempAndReload();
PageList.SelectedIndex = Math.Min(restoreIdx, PageList.Items.Count - 1);
// After a rotation the page aspect ratio changes; always fit-to-page so the
// full rotated page is visible regardless of the previous zoom level.
FitToPage();
Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Loaded, (Action)FitToPage);
SetStatus(string.Format(Loc("Str_Rotated"), indices.Count));
}
catch (Exception ex)
{
KillerDialog.Show(this, string.Format(Loc("Str_RotateFailed"), ex.Message), Loc("Str_Dlg_AppTitle"), MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private static MenuItem MakeMenuItem(string header, RoutedEventHandler click, string? gesture = null)
{
var item = new MenuItem { Header = header };
item.Click += click;
if (gesture != null)
item.InputGestureText = gesture;
return item;
}
// ============================================================
// File operations
// ============================================================
private void OpenFile(string path)
{
// Files on UNC / network shares - notably the WSL \\wsl$ 9P filesystem - can hand
// back partial reads, making the PDF parser see a truncated file ("Unexpected EOF").
// Copy such files to a local temp via File.ReadAllBytes (which reads to EOF) and open
// from there. `path` stays the user's real path for display and Save.
string srcPath = path;
if (IsNetworkPath(path))
{
try
{
var localCopy = App.MakeTempFile("netopen");
File.WriteAllBytes(localCopy, File.ReadAllBytes(path));
srcPath = localCopy;
}
catch { srcPath = path; }
}
try
{
if (_doc is not null) { _doc.Close(); _doc = null; }
_doc = PdfReader.Open(srcPath, PdfDocumentOpenMode.Modify);
// PdfSharp cannot save modified encrypted PDFs — it copies unmodified encrypted
// stream bytes verbatim but fails when it has to re-serialize a dirty object.
// Strip encryption silently at open time via Import so all edits work correctly.
if (PdfFileHasEncryption(srcPath))
{
// PdfSharp can read encrypted PDFs but cannot re-save them once modified.
// Strip encryption now via PDFium (lossless), falling back to Import mode.
_doc.Close(); _doc = null;
var repairedPath = App.MakeTempFile("repaired");
bool ok = TryPdfiumStripEncryption(srcPath, repairedPath)
|| TryImportRepairToPath(srcPath, repairedPath);
if (!ok) { TryRepairAndOpen(srcPath); return; }
_doc = PdfReader.Open(repairedPath, PdfDocumentOpenMode.Modify);
_currentFile = repairedPath;
FinishOpenFile(path, repairedPath);
MarkDirty(true);
return;
}
_currentFile = srcPath;
FinishOpenFile(path, srcPath);
}
catch (Exception ex) when (IsOwnerPasswordException(ex))
{
// PDF has owner/permissions restrictions but no open password —
// open read-only so the user can still view and print it.
try
{
if (_doc is not null) { _doc.Close(); _doc = null; }
_doc = PdfReader.Open(srcPath, PdfDocumentOpenMode.ReadOnly);
_currentFile = srcPath;
FinishOpenFile(path, srcPath);
SetStatus(string.Format(Loc("Str_OpenedReadOnly"), System.IO.Path.GetFileName(path), _doc.PageCount));
}
catch (Exception ex2)
{
KillerDialog.Show(this, string.Format(Loc("Str_Dlg_FailedOpen"), ex2.Message), Loc("Str_Dlg_AppTitle"), MessageBoxButton.OK, MessageBoxImage.Error);
}
}
catch (Exception ex) when (IsPasswordException(ex))
{
string? pw = PromptForPassword(path);
if (pw is null) return;
try
{
if (_doc is not null) { _doc.Close(); _doc = null; }
_doc = PdfReader.Open(srcPath, pw, PdfDocumentOpenMode.Modify);
// Save a decrypted temp copy so Docnet can render without needing the password
var tempDec = App.MakeTempFile("dec");
_doc.Save(tempDec);
_doc.Close();
_doc = PdfReader.Open(tempDec, PdfDocumentOpenMode.Modify);
_currentFile = tempDec;
FinishOpenFile(path, tempDec);
}
catch (Exception ex2)
{
KillerDialog.Show(this, string.Format(Loc("Str_Dlg_FailedOpen"), ex2.Message), Loc("Str_Dlg_AppTitle"), MessageBoxButton.OK, MessageBoxImage.Error);
}
}
catch (Exception ex) when (IsXRefException(ex))
{
// Some PDFs have malformed or non-standard XRef tables that PdfSharp can't
// open in Modify mode. Fall back to ReadOnly; if that also fails, offer repair.
try
{
if (_doc is not null) { _doc.Close(); _doc = null; }
_doc = PdfReader.Open(srcPath, PdfDocumentOpenMode.ReadOnly);
_currentFile = srcPath;
FinishOpenFile(path, srcPath);
SetStatus(string.Format(Loc("Str_OpenedReadOnlyXRef"), System.IO.Path.GetFileName(path), _doc.PageCount));
KillerDialog.Show(this,
$"\"{System.IO.Path.GetFileName(path)}\" has a non-standard structure and was opened read-only.\n\nEditing, saving, and some other features may not work correctly.",
"KillerPDF", MessageBoxButton.OK, MessageBoxImage.Warning);
}
catch
{
// ReadOnly also failed — offer to repair.
var result = KillerDialog.Show(this,
$"This PDF has a damaged structure and couldn't be opened.\n\nWould you like KillerPDF to attempt a repair? A repaired copy will be created — the original file will not be changed.\n\nNote: repaired files may be missing bookmarks, forms, and other interactive features.",
"KillerPDF", MessageBoxButton.YesNo, MessageBoxImage.Warning);
if (result == MessageBoxResult.Yes)
TryRepairAndOpen(srcPath);
}
}
catch (Exception ex) when (IsEofParseException(ex))
{
// PdfSharpCore rejects some structurally-valid PDFs with "Unexpected EOF" even
// though PDFium (and every common viewer) reads them fine. Re-save the file
// losslessly through PDFium to a clean temp and open that; fall back to an
// import repair, then to a rasterize repair as a last resort.
try
{
if (_doc is not null) { _doc.Close(); _doc = null; }
var repairedPath = App.MakeTempFile("repaired");
bool ok = TryPdfiumStripEncryption(srcPath, repairedPath)
|| TryImportRepairToPath(srcPath, repairedPath);
if (!ok) { TryRepairAndOpen(srcPath); return; }
_doc = PdfReader.Open(repairedPath, PdfDocumentOpenMode.Modify);
_currentFile = repairedPath;
FinishOpenFile(path, repairedPath);
// Open clean: the normalized copy is content-equivalent, so a view-only open
// should not nag to save. _currentFile points at the temp and _originalFile at
// the user's path, so the original is only ever overwritten if they choose to
// Save after making edits (FinishOpenFile already cleared the dirty flag).
SetStatus($"Opened {System.IO.Path.GetFileName(path)} ({_doc.PageCount} pages) - recovered via PDFium.");
}
catch (Exception ex2)
{
KillerDialog.Show(this, string.Format(Loc("Str_Dlg_FailedOpen"), ex2.Message), Loc("Str_Dlg_AppTitle"), MessageBoxButton.OK, MessageBoxImage.Error);
}
}
catch (Exception ex)
{
KillerDialog.Show(this, string.Format(Loc("Str_Dlg_FailedOpen"), ex.Message), Loc("Str_Dlg_AppTitle"), MessageBoxButton.OK, MessageBoxImage.Error);
}
}
// PdfSharpCore throws on some structurally-valid PDFs that PDFium opens fine - most
// often "Unexpected EOF" from SharpZipLib's Flate inflater while reading a FlateDecode
// cross-reference stream (multi-revision PDFs with incremental updates / dangling xref
// entries that tolerant parsers ignore). Match by message AND exception type across the
// whole inner-exception chain so a wrapped SharpZipBaseException is still recovered.
private static bool IsEofParseException(Exception ex)
{
for (Exception? e = ex; e != null; e = e.InnerException)
{
string msg = e.Message ?? string.Empty;
string type = e.GetType().FullName ?? string.Empty;
if (msg.IndexOf("EOF", StringComparison.OrdinalIgnoreCase) >= 0
|| msg.IndexOf("end of file", StringComparison.OrdinalIgnoreCase) >= 0
|| msg.IndexOf("Inflater", StringComparison.OrdinalIgnoreCase) >= 0
|| msg.IndexOf("FlateDecode", StringComparison.OrdinalIgnoreCase) >= 0
|| type.IndexOf("SharpZip", StringComparison.OrdinalIgnoreCase) >= 0)
return true;
}
return false;
}
private static bool IsXRefException(Exception ex) =>
ex.Message.IndexOf("XRef", StringComparison.OrdinalIgnoreCase) >= 0 ||
ex.Message.IndexOf("cross-reference", StringComparison.OrdinalIgnoreCase) >= 0 ||
ex.Message.IndexOf("trailer", StringComparison.OrdinalIgnoreCase) >= 0 ||
ex.Message.IndexOf("Invalid PDF file", StringComparison.OrdinalIgnoreCase) >= 0 ||
ex.Message.IndexOf("startxref", StringComparison.OrdinalIgnoreCase) >= 0 ||
ex.Message.IndexOf("Unexpected token", StringComparison.OrdinalIgnoreCase) >= 0;
// True for UNC paths (\\server\share, \\wsl$\..., \\wsl.localhost\...) and mapped
// network drives. Such files are copied locally before opening to avoid 9P short reads.
private static bool IsNetworkPath(string path)
{
if (string.IsNullOrEmpty(path)) return false;
if (path.StartsWith(@"\\", StringComparison.Ordinal)) return true;
try
{
var root = System.IO.Path.GetPathRoot(path);
if (!string.IsNullOrEmpty(root) && root!.Length >= 2 && root[1] == ':')
return new DriveInfo(root).DriveType == DriveType.Network;
}
catch { }
return false;
}
/// <summary>
/// Imports pages from <paramref name="sourcePath"/> into a fresh PdfDocument and saves it
/// to <paramref name="destPath"/>. Returns true on success, false on failure.
/// Unlike TryRepairAndOpen this has no UI side-effects and can be used mid-operation.
/// </summary>
/// <param name="stripRotations">
// ── PDFium P/Invoke ──────────────────────────────────────────────────────────
// PDFium (pdfium.dll) is already shipped with Docnet. We use it here to strip
// encryption from PDFs that PdfSharpCore can read but cannot re-save when modified.
[DllImport("pdfium.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr FPDF_LoadDocument(
[MarshalAs(UnmanagedType.LPStr)] string filePath,
[MarshalAs(UnmanagedType.LPStr)] string? password);
[DllImport("pdfium.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern void FPDF_CloseDocument(IntPtr document);
[DllImport("pdfium.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool FPDF_SaveWithVersion(
IntPtr document, ref FPDF_FILEWRITE fileWrite, uint flags, int fileVersion);
[StructLayout(LayoutKind.Sequential)]
private struct FPDF_FILEWRITE
{
public int version; // must be 1
public IntPtr WriteBlock; // cdecl: int WriteBlock(FPDF_FILEWRITE*, const void*, unsigned long)
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int PdfWriteBlockDelegate(IntPtr pThis, IntPtr pData, uint size);
private const uint FPDF_REMOVE_SECURITY = 3;
[DllImport("pdfium.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int FPDF_GetPageCount(IntPtr document);
[DllImport("pdfium.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr FPDF_LoadPage(IntPtr document, int page_index);
[DllImport("pdfium.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern void FPDF_ClosePage(IntPtr page);
[DllImport("pdfium.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern void FPDFPage_SetRotation(IntPtr page, int rotation);
[DllImport("pdfium.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool FPDFPage_GenerateContent(IntPtr page);
/// <summary>
/// Returns true if the PDF file has an /Encrypt entry in its trailer.
/// Scans the last 2 KB so it's fast; works regardless of how PdfSharp
/// reports security state after authenticating with an empty password.
/// </summary>
private static bool PdfFileHasEncryption(string path)
{
try
{
using var fs = File.OpenRead(path);
long scan = Math.Min(2048, fs.Length);
fs.Seek(-scan, SeekOrigin.End);
var buf = new byte[scan];
_ = fs.Read(buf, 0, buf.Length);
// Look for /Encrypt in the raw bytes (Latin-1 safe)
var text = System.Text.Encoding.GetEncoding(1252).GetString(buf);
return text.Contains("/Encrypt");
}
catch { return false; }
}
/// <summary>
/// Uses PDFium to save a copy of <paramref name="sourcePath"/> with all security/encryption
/// removed. Returns true on success. Falls back gracefully if PDFium is unavailable.
/// PDFium is already initialised by Docnet; no separate init call is needed.
/// </summary>
private static bool TryPdfiumStripEncryption(string sourcePath, string destPath)
{
try
{
// Ensure PDFium is initialised — Docnet does this lazily on first use,
// so force it now before we call PDFium P/Invoke directly.
try { _ = DocLib.Instance; } catch { }
var doc = FPDF_LoadDocument(sourcePath, null);
if (doc == IntPtr.Zero) return false;
try
{
using var ms = new MemoryStream();
PdfWriteBlockDelegate cb = (_, pData, size) =>
{