Repository navigation
Expand file tree
/
Copy pathApp.xaml.cs
More file actions
1349 lines (1190 loc) · 59.5 KB
/
Copy pathApp.xaml.cs
File metadata and controls
1349 lines (1190 loc) · 59.5 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.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Threading;
using KillerPDF.Services;
using Microsoft.Win32;
namespace KillerPDF
{
public partial class App : Application
{
// ============================================================
// Paths
// ============================================================
private static readonly string AppName = "KillerPDF";
private static readonly string ExeName = "KillerPDF.exe";
private static readonly string InstallDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"Programs", AppName);
private static readonly string InstallExe = Path.Combine(InstallDir, ExeName);
private static readonly string StartMenuDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Programs), AppName);
private static readonly string StartMenuLnk = Path.Combine(StartMenuDir, $"{AppName}.lnk");
private static readonly string DesktopLnk = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), $"{AppName}.lnk");
// ============================================================
// Shell interop
// ============================================================
[DllImport("shell32.dll")]
private static extern void SHChangeNotify(uint wEventId, uint uFlags, IntPtr dwItem1, IntPtr dwItem2);
private const uint SHCNE_ASSOCCHANGED = 0x08000000;
private const uint SHCNF_IDLIST = 0x0000;
// ============================================================
// Startup
// ============================================================
protected override void OnStartup(StartupEventArgs e)
{
DispatcherUnhandledException += OnDispatcherException;
AppDomain.CurrentDomain.UnhandledException += OnDomainException;
TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
base.OnStartup(e);
if (!CheckPdfiumIntegrity()) { Shutdown(2); return; }
// Handle uninstall flag (called by Add/Remove Programs)
if (e.Args.Length > 0 &&
string.Equals(e.Args[0], "/uninstall", StringComparison.OrdinalIgnoreCase))
{
Uninstall();
Shutdown();
return;
}
ShutdownMode = ShutdownMode.OnLastWindowClose;
CleanupStaleTemps();
ThemeManager.Initialize();
LocaleManager.Initialize();
new MainWindow().Show();
}
// ============================================================
// Crash handling
// ============================================================
//
// NOTE: AccessViolationException is not catchable on .NET 4.8 without
// [HandleProcessCorruptedStateExceptions], which we deliberately omit.
private void OnDispatcherException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
var logPath = CrashReporter.Capture(e.Exception, "Dispatcher");
bool cont = ShowCrashDialog(e.Exception, logPath, isFatal: false);
e.Handled = true; // always handle; we manage the exit ourselves
if (!cont)
{
CleanupSessionTemps();
Shutdown(1);
}
}
private void OnDomainException(object sender, UnhandledExceptionEventArgs e)
{
var ex = e.ExceptionObject as Exception
?? new Exception(e.ExceptionObject?.ToString() ?? "Unknown error");
var logPath = CrashReporter.Capture(ex, "AppDomain");
try
{
if (Dispatcher != null && !Dispatcher.HasShutdownStarted)
Dispatcher.Invoke(() => ShowCrashDialog(ex, logPath, isFatal: true));
else
ShowCrashDialog(ex, logPath, isFatal: true);
}
catch { /* at least the log was written */ }
CleanupSessionTemps();
// CLR will terminate the process after this handler returns.
}
private void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
{
e.SetObserved(); // prevent process teardown
var logPath = CrashReporter.Capture(e.Exception, "TaskScheduler");
try
{
if (Dispatcher != null && !Dispatcher.HasShutdownStarted)
Dispatcher.BeginInvoke(new Action(
() => ShowCrashDialog(e.Exception, logPath, isFatal: false)));
}
catch { /* best-effort */ }
}
/// <summary>
/// Dark-themed crash report dialog. Returns true if the user chose Continue.
/// Must be called on the UI thread.
/// </summary>
private static bool ShowCrashDialog(Exception ex, string logPath, bool isFatal)
{
bool shouldContinue = false;
// ── Palette ─────────────────────────────────────────────
var bg = new SolidColorBrush(Color.FromRgb(0x1a, 0x1a, 0x1a));
var dimBg = new SolidColorBrush(Color.FromRgb(0x25, 0x25, 0x25));
var codeBg = new SolidColorBrush(Color.FromRgb(0x12, 0x12, 0x12));
var red = new SolidColorBrush(Color.FromRgb(0xef, 0x44, 0x44));
var green = new SolidColorBrush(Color.FromRgb(0x1e, 0xa5, 0x4c));
var greenHov = new SolidColorBrush(Color.FromRgb(0x27, 0xc8, 0x60));
var dimText = new SolidColorBrush(Color.FromRgb(0x77, 0x77, 0x77));
var midText = new SolidColorBrush(Color.FromRgb(0xaa, 0xaa, 0xaa));
var redHov = new SolidColorBrush(Color.FromRgb(0xc4, 0x2b, 0x1c));
var grayBtn = new SolidColorBrush(Color.FromRgb(0x33, 0x33, 0x33));
var grayHov = new SolidColorBrush(Color.FromRgb(0x44, 0x44, 0x44));
var quitNorm = new SolidColorBrush(Color.FromRgb(0x5a, 0x10, 0x10));
var quitHov = new SolidColorBrush(Color.FromRgb(0xc4, 0x2b, 0x1c));
var win = new Window
{
Title = "KillerPDF — Unexpected Error",
Width = 680,
Height = 520,
MinWidth = 480,
MinHeight = 360,
WindowStartupLocation = WindowStartupLocation.CenterScreen,
ResizeMode = ResizeMode.CanResize,
WindowStyle = WindowStyle.None,
Background = bg,
ShowInTaskbar = true
};
// ── Layout ──────────────────────────────────────────────
var root = new Grid();
root.RowDefinitions.Add(new RowDefinition { Height = new GridLength(36) });
root.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
root.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
root.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
// ── Title bar ───────────────────────────────────────────
var titleBar = new DockPanel { Background = dimBg };
Grid.SetRow(titleBar, 0);
titleBar.MouseLeftButtonDown += (_, ea) =>
{
if (ea.ButtonState == MouseButtonState.Pressed) win.DragMove();
};
var xBtn = MakeTitleBarCloseButton(dimText, redHov);
xBtn.Click += (_, _) => { shouldContinue = false; win.Close(); };
DockPanel.SetDock(xBtn, Dock.Right);
titleBar.Children.Add(xBtn);
titleBar.Children.Add(new TextBlock
{
Text = "KillerPDF — Unexpected Error",
Foreground = dimText,
FontSize = 12,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(12, 0, 0, 0)
});
root.Children.Add(titleBar);
// ── Error header ─────────────────────────────────────────
var headerPanel = new StackPanel
{
Background = dimBg,
Margin = new Thickness(0, 1, 0, 0)
};
Grid.SetRow(headerPanel, 1);
var headerInner = new StackPanel { Margin = new Thickness(20, 14, 20, 14) };
var typeRow = new StackPanel { Orientation = Orientation.Horizontal };
typeRow.Children.Add(new TextBlock
{
Text = "⚠ ",
Foreground = red,
FontSize = 18,
VerticalAlignment = VerticalAlignment.Center
});
typeRow.Children.Add(new TextBlock
{
Text = ex.GetType().Name,
Foreground = red,
FontSize = 16,
FontWeight = FontWeights.SemiBold,
VerticalAlignment = VerticalAlignment.Center
});
headerInner.Children.Add(typeRow);
headerInner.Children.Add(new TextBlock
{
Text = ex.Message,
Foreground = Brushes.White,
FontSize = 13,
TextWrapping = TextWrapping.Wrap,
Margin = new Thickness(0, 6, 0, 0)
});
headerInner.Children.Add(new TextBlock
{
Text = $"Log: {logPath}",
Foreground = dimText,
FontSize = 11,
Margin = new Thickness(0, 6, 0, 0)
});
headerPanel.Children.Add(headerInner);
root.Children.Add(headerPanel);
// ── Stack trace ──────────────────────────────────────────
var traceBox = new TextBox
{
Text = FormatExceptionChain(ex),
Background = codeBg,
Foreground = midText,
FontFamily = new FontFamily("Consolas,Courier New"),
FontSize = 11,
IsReadOnly = true,
VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,
TextWrapping = TextWrapping.NoWrap,
BorderThickness = new Thickness(0),
Padding = new Thickness(12, 8, 12, 8),
Margin = new Thickness(0, 1, 0, 0)
};
Grid.SetRow(traceBox, 2);
root.Children.Add(traceBox);
// ── Button bar ───────────────────────────────────────────
var btnBorder = new Border
{
Background = dimBg,
Padding = new Thickness(16, 10, 16, 10)
};
Grid.SetRow(btnBorder, 3);
var btnPanel = new DockPanel();
// Left: utility buttons
var leftBtns = new StackPanel { Orientation = Orientation.Horizontal };
var copyBtn = MakeCrashButton("Copy Report", grayBtn, grayHov, Brushes.White, 100);
copyBtn.Click += (_, _) =>
{
try { Clipboard.SetText(BuildFullCrashReport(ex)); } catch { }
};
leftBtns.Children.Add(copyBtn);
var logsBtn = MakeCrashButton("Open Logs", grayBtn, grayHov, Brushes.White, 88);
logsBtn.Margin = new Thickness(8, 0, 0, 0);
logsBtn.Click += (_, _) =>
{
try
{
Directory.CreateDirectory(CrashReporter.LogDir);
Process.Start(new ProcessStartInfo(CrashReporter.LogDir) { UseShellExecute = true });
}
catch { }
};
leftBtns.Children.Add(logsBtn);
var githubBtn = MakeCrashButton("Report on GitHub", grayBtn, grayHov,
new SolidColorBrush(Color.FromRgb(0x60, 0xc0, 0xff)), 128);
githubBtn.Margin = new Thickness(8, 0, 0, 0);
githubBtn.Click += (_, _) =>
{
try
{
var ver = Assembly.GetExecutingAssembly().GetName().Version;
var msgLen = Math.Min(80, ex.Message.Length);
var title = Uri.EscapeDataString(
$"Crash: {ex.GetType().Name}: {ex.Message[..msgLen]}");
var stack = ex.StackTrace?.Length > 800
? ex.StackTrace[..800] + "\n... (truncated)"
: ex.StackTrace ?? "(no stack trace)";
var body = Uri.EscapeDataString(
$"**Version:** {ver?.ToString(3)}\n" +
$"**OS:** {Environment.OSVersion}\n" +
$"**Exception:** `{ex.GetType().FullName}`\n" +
$"**Message:** {ex.Message}\n\n" +
$"```\n{stack}\n```\n\n" +
$"_Log folder: `{CrashReporter.LogDir}`_");
Process.Start(new ProcessStartInfo(
$"https://github.com/SteveTheKiller/KillerPDF/issues/new?title={title}&body={body}")
{ UseShellExecute = true });
}
catch { }
};
leftBtns.Children.Add(githubBtn);
DockPanel.SetDock(leftBtns, Dock.Left);
btnPanel.Children.Add(leftBtns);
// Right: Continue / Quit
var rightBtns = new StackPanel
{
Orientation = Orientation.Horizontal,
HorizontalAlignment = HorizontalAlignment.Right
};
var contBtn = MakeCrashButton("Continue", green, greenHov,
new SolidColorBrush(Color.FromRgb(0x0a, 0x0a, 0x0a)), 88);
contBtn.IsEnabled = !isFatal;
contBtn.FontWeight = isFatal ? FontWeights.Normal : FontWeights.SemiBold;
contBtn.Margin = new Thickness(0, 0, 8, 0);
contBtn.Click += (_, _) => { shouldContinue = true; win.Close(); };
var quitBtnCtrl = MakeCrashButton("Quit", quitNorm, quitHov, Brushes.White, 72);
quitBtnCtrl.FontWeight = isFatal ? FontWeights.SemiBold : FontWeights.Normal;
quitBtnCtrl.Click += (_, _) => { shouldContinue = false; win.Close(); };
rightBtns.Children.Add(contBtn);
rightBtns.Children.Add(quitBtnCtrl);
DockPanel.SetDock(rightBtns, Dock.Right);
btnPanel.Children.Add(rightBtns);
btnBorder.Child = btnPanel;
root.Children.Add(btnBorder);
win.Content = root;
win.ShowDialog();
return shouldContinue;
}
private static Button MakeTitleBarCloseButton(SolidColorBrush fg, SolidColorBrush hoverBg)
{
var t = new ControlTemplate(typeof(Button));
var b = new FrameworkElementFactory(typeof(Border));
b.SetBinding(Border.BackgroundProperty,
new System.Windows.Data.Binding("Background")
{
RelativeSource = new System.Windows.Data.RelativeSource(
System.Windows.Data.RelativeSourceMode.TemplatedParent)
});
var cp = new FrameworkElementFactory(typeof(ContentPresenter));
cp.SetValue(ContentPresenter.HorizontalAlignmentProperty, HorizontalAlignment.Center);
cp.SetValue(ContentPresenter.VerticalAlignmentProperty, VerticalAlignment.Center);
b.AppendChild(cp);
t.VisualTree = b;
var s = new Style(typeof(Button));
s.Setters.Add(new Setter(Button.BackgroundProperty, Brushes.Transparent));
s.Setters.Add(new Setter(Button.ForegroundProperty, fg));
s.Setters.Add(new Setter(Button.TemplateProperty, t));
var trig = new Trigger { Property = UIElement.IsMouseOverProperty, Value = true };
trig.Setters.Add(new Setter(Button.BackgroundProperty, hoverBg));
trig.Setters.Add(new Setter(Button.ForegroundProperty, Brushes.White));
s.Triggers.Add(trig);
return new Button
{
Content = "",
FontFamily = new FontFamily("Segoe MDL2 Assets"),
FontSize = 11,
Width = 46,
BorderThickness = new Thickness(0),
VerticalAlignment = VerticalAlignment.Stretch,
VerticalContentAlignment = VerticalAlignment.Center,
Cursor = Cursors.Arrow,
Style = s
};
}
private static Button MakeCrashButton(string label,
SolidColorBrush normal, SolidColorBrush hover, SolidColorBrush fg,
double width = 88)
=> new()
{
Content = label,
Width = width,
Height = 28,
Style = MakeLauncherButtonStyle(normal, hover, fg)
};
private static string FormatExceptionChain(Exception ex)
{
var sb = new StringBuilder();
var inner = ex;
var depth = 0;
while (inner != null && depth < 5)
{
if (depth > 0) { sb.AppendLine(); sb.AppendLine("=== Inner Exception ==="); }
sb.AppendLine($"{inner.GetType().FullName}: {inner.Message}");
sb.AppendLine(inner.StackTrace ?? "(no stack trace)");
inner = inner.InnerException;
depth++;
}
return sb.ToString().TrimEnd();
}
private static string BuildFullCrashReport(Exception ex)
{
var sb = new StringBuilder();
var ver = Assembly.GetExecutingAssembly().GetName().Version;
sb.AppendLine($"KillerPDF v{ver?.ToString(3)}");
sb.AppendLine($"Time : {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
sb.AppendLine($"OS : {Environment.OSVersion}");
sb.AppendLine();
sb.Append(FormatExceptionChain(ex));
return sb.ToString();
}
// ============================================================
// Public surface used by MainWindow (portable badge / install)
// ============================================================
/// <summary>
/// True when running from outside the installed location (i.e. portable mode).
/// </summary>
internal static bool IsPortable()
{
string currentExe = Process.GetCurrentProcess().MainModule!.FileName;
return !string.Equals(currentExe, InstallExe, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Installs KillerPDF, offers to set as default PDF handler, then relaunches
/// from the installed location. Returns false if installation failed or was
/// already installed from this path.
/// </summary>
internal static void InstallAndRelaunch(string? fileToOpen, bool wantDesktop)
{
DoInstall(wantDesktop);
if (!IsDefaultPdfHandler())
{
var res = KillerDialog.Show(null,
"Would you like to set KillerPDF as your default PDF viewer?\n\n" +
"Opens Windows Settings → Default Apps.",
"KillerPDF", MessageBoxButton.YesNo);
if (res == MessageBoxResult.Yes)
Process.Start(new ProcessStartInfo("ms-settings:defaultapps")
{ UseShellExecute = true });
}
var psi = new ProcessStartInfo(InstallExe);
if (fileToOpen != null)
psi.Arguments = $"\"{fileToOpen}\"";
Process.Start(psi);
Application.Current.Shutdown();
}
// ============================================================
// Registry helpers
// ============================================================
// ============================================================
// Temp file tracking
// ============================================================
/// <summary>
/// User-private temp directory for session working files (encrypted PDFs, etc.).
/// %LOCALAPPDATA% is user-private and not indexed by Windows Search.
/// </summary>
internal static readonly string TempDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"KillerPDF", "Temp");
private static readonly List<string> _sessionTemps = [];
/// <summary>
/// Creates a tracked temp path of the form killerpdf_<tag>_<guid>.pdf
/// under %LOCALAPPDATA%\KillerPDF\Temp\.
/// All registered paths are deleted when CleanupSessionTemps() is called.
/// </summary>
internal static string MakeTempFile(string tag)
{
try { Directory.CreateDirectory(TempDir); } catch { }
var path = Path.Combine(TempDir, $"killerpdf_{tag}_{Guid.NewGuid():N}.pdf");
lock (_sessionTemps) _sessionTemps.Add(path);
return path;
}
/// <summary>Deletes all temp files registered this session (best-effort).</summary>
internal static void CleanupSessionTemps()
{
lock (_sessionTemps)
{
foreach (var f in _sessionTemps)
try { if (File.Exists(f)) File.Delete(f); } catch { }
_sessionTemps.Clear();
}
}
/// <summary>
/// Deletes killerpdf_*.pdf files left over from previous crashed sessions.
/// Sweeps both the current TempDir and the legacy %TEMP% location.
/// Locked files (still open by another instance) are silently skipped.
/// </summary>
internal static void CleanupStaleTemps()
{
// Current location
try
{
if (Directory.Exists(TempDir))
foreach (var f in Directory.GetFiles(TempDir, "killerpdf_*.pdf"))
try { File.Delete(f); } catch { }
}
catch { }
// Legacy %TEMP% location — sweep once for users upgrading from older builds
try
{
foreach (var f in Directory.GetFiles(Path.GetTempPath(), "killerpdf_*.pdf"))
try { File.Delete(f); } catch { }
}
catch { }
}
internal static string? GetSetting(string name)
{
try
{
using var key = Registry.CurrentUser.OpenSubKey(@"Software\KillerPDF\Settings");
return key?.GetValue(name) as string;
}
catch { return null; }
}
internal static void SetSetting(string name, string value)
{
try
{
using var key = Registry.CurrentUser.CreateSubKey(@"Software\KillerPDF\Settings");
key.SetValue(name, value);
}
catch { /* best-effort */ }
}
private static bool IsInstalled()
{
using var key = Registry.CurrentUser.OpenSubKey(@"Software\KillerPDF");
if (key is null) return false;
return key.GetValue("Installed") is int i && i == 1;
}
private static bool IsDefaultPdfHandler()
{
using var key = Registry.CurrentUser.OpenSubKey(
@"Software\Microsoft\Windows\Shell\Associations\FileAssociations\.pdf\UserChoice");
return key?.GetValue("ProgId") is string progId &&
progId.Equals("KillerPDF.pdf", StringComparison.OrdinalIgnoreCase);
}
// ============================================================
// Launcher dialog
// ============================================================
/// <summary>
/// Builds a button Style with a custom ControlTemplate so hover colours
/// actually render (WPF's default template ignores Background changes on hover).
/// </summary>
private static Style MakeLauncherButtonStyle(
SolidColorBrush normal, SolidColorBrush hover, SolidColorBrush fg)
{
var template = new ControlTemplate(typeof(Button));
var border = new FrameworkElementFactory(typeof(Border));
border.SetValue(Border.CornerRadiusProperty, new CornerRadius(3));
border.SetBinding(Border.BackgroundProperty,
new System.Windows.Data.Binding("Background")
{
RelativeSource = new System.Windows.Data.RelativeSource(
System.Windows.Data.RelativeSourceMode.TemplatedParent)
});
var cp = new FrameworkElementFactory(typeof(ContentPresenter));
cp.SetValue(ContentPresenter.HorizontalAlignmentProperty, HorizontalAlignment.Center);
cp.SetValue(ContentPresenter.VerticalAlignmentProperty, VerticalAlignment.Center);
cp.SetValue(ContentPresenter.MarginProperty, new Thickness(0, 6, 0, 6));
border.AppendChild(cp);
template.VisualTree = border;
var style = new Style(typeof(Button));
style.Setters.Add(new Setter(Button.BackgroundProperty, normal));
style.Setters.Add(new Setter(Button.ForegroundProperty, fg));
style.Setters.Add(new Setter(Button.BorderThicknessProperty, new Thickness(0)));
style.Setters.Add(new Setter(Button.TemplateProperty, template));
style.Setters.Add(new Setter(Button.CursorProperty, Cursors.Hand));
var hoverTrigger = new Trigger { Property = UIElement.IsMouseOverProperty, Value = true };
hoverTrigger.Setters.Add(new Setter(Button.BackgroundProperty, hover));
style.Triggers.Add(hoverTrigger);
return style;
}
/// <summary>
/// Shows the Install / Run dialog.
/// Returns (cancelled, install, wantDesktopShortcut).
/// </summary>
private static (bool cancelled, bool install, bool desktop) ShowLauncher(bool alreadyInstalled)
{
bool cancelled = true;
bool install = false;
bool desktop = true;
var bg = new SolidColorBrush(Color.FromRgb(0x1a, 0x1a, 0x1a));
var dimBg = new SolidColorBrush(Color.FromRgb(0x25, 0x25, 0x25));
var accent = new SolidColorBrush(Color.FromRgb(0x4a, 0xde, 0x80));
var dimText = new SolidColorBrush(Color.FromRgb(0x77, 0x77, 0x77));
var win = new Window
{
Title = AppName,
Width = 400,
Height = 280,
WindowStartupLocation = WindowStartupLocation.CenterScreen,
ResizeMode = ResizeMode.NoResize,
WindowStyle = WindowStyle.None,
Background = bg
};
// ── Root grid: title bar row + content row ──────────────────
var root = new Grid();
root.RowDefinitions.Add(new RowDefinition { Height = new GridLength(36) });
root.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
// ── Title bar ───────────────────────────────────────────────
var titleBar = new DockPanel { Background = dimBg };
Grid.SetRow(titleBar, 0);
// Drag anywhere on the title bar
titleBar.MouseLeftButtonDown += (_, e) =>
{
if (e.ButtonState == MouseButtonState.Pressed) win.DragMove();
};
// Close button — custom template so Background trigger actually renders
var closeBtnTemplate = new ControlTemplate(typeof(Button));
var closeBorder = new FrameworkElementFactory(typeof(Border));
closeBorder.SetBinding(Border.BackgroundProperty,
new System.Windows.Data.Binding("Background")
{
RelativeSource = new System.Windows.Data.RelativeSource(
System.Windows.Data.RelativeSourceMode.TemplatedParent)
});
var closeContent = new FrameworkElementFactory(typeof(ContentPresenter));
closeContent.SetValue(ContentPresenter.HorizontalAlignmentProperty, HorizontalAlignment.Center);
closeContent.SetValue(ContentPresenter.VerticalAlignmentProperty, VerticalAlignment.Center);
closeBorder.AppendChild(closeContent);
closeBtnTemplate.VisualTree = closeBorder;
var redHover = new SolidColorBrush(Color.FromRgb(0xc4, 0x2b, 0x1c));
var closeBtnStyle = new Style(typeof(Button));
closeBtnStyle.Setters.Add(new Setter(Button.BackgroundProperty, Brushes.Transparent));
closeBtnStyle.Setters.Add(new Setter(Button.ForegroundProperty, dimText));
closeBtnStyle.Setters.Add(new Setter(Button.TemplateProperty, closeBtnTemplate));
var hoverTrigger = new Trigger { Property = UIElement.IsMouseOverProperty, Value = true };
hoverTrigger.Setters.Add(new Setter(Button.BackgroundProperty, redHover));
hoverTrigger.Setters.Add(new Setter(Button.ForegroundProperty, Brushes.White));
closeBtnStyle.Triggers.Add(hoverTrigger);
var closeBtn = new Button
{
Content = "\uE711",
FontFamily = new FontFamily("Segoe MDL2 Assets"),
FontSize = 11,
Width = 46,
BorderThickness = new Thickness(0),
VerticalAlignment = VerticalAlignment.Stretch,
VerticalContentAlignment = VerticalAlignment.Center,
Cursor = Cursors.Arrow,
Style = closeBtnStyle
};
closeBtn.Click += (_, _) => win.Close();
DockPanel.SetDock(closeBtn, Dock.Right);
titleBar.Children.Add(closeBtn);
// App label in title bar
titleBar.Children.Add(new TextBlock
{
Text = AppName,
Foreground = dimText,
FontSize = 12,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(12, 0, 0, 0)
});
root.Children.Add(titleBar);
// ── Content ─────────────────────────────────────────────────
var content = new StackPanel { Margin = new Thickness(36, 22, 36, 28) };
Grid.SetRow(content, 1);
content.Children.Add(new TextBlock
{
Text = AppName,
FontSize = 26,
FontWeight = FontWeights.Bold,
Foreground = accent
});
var version = Assembly.GetExecutingAssembly().GetName().Version;
content.Children.Add(new TextBlock
{
Text = $"Version {version?.ToString(3)}",
Foreground = dimText,
FontSize = 12,
Margin = new Thickness(0, 2, 0, 18)
});
content.Children.Add(new TextBlock
{
Text = alreadyInstalled
? "A newer version is available. Install it or run without updating."
: "Install KillerPDF on this computer, or run it without installing.",
Foreground = Brushes.White,
TextWrapping = TextWrapping.Wrap,
Margin = new Thickness(0, 0, 0, 16)
});
var desktopChk = new CheckBox
{
IsChecked = true,
Margin = new Thickness(0, 0, 0, 22),
Content = new TextBlock { Text = "Create desktop shortcut", Foreground = Brushes.White }
};
content.Children.Add(desktopChk);
var btnRow = new StackPanel
{
Orientation = Orientation.Horizontal,
HorizontalAlignment = HorizontalAlignment.Right
};
var runBtn = new Button
{
Content = "Run",
Width = 88,
Margin = new Thickness(0, 0, 8, 0),
Style = MakeLauncherButtonStyle(
normal: new SolidColorBrush(Color.FromRgb(0x30, 0x30, 0x30)),
hover: new SolidColorBrush(Color.FromRgb(0x16, 0x63, 0x34)),
fg: Brushes.White)
};
var installBtn = new Button
{
Content = alreadyInstalled ? "Update" : "Install",
Width = 110,
Style = MakeLauncherButtonStyle(
normal: accent,
hover: new SolidColorBrush(Color.FromRgb(0x4a, 0xf0, 0x90)),
fg: new SolidColorBrush(Color.FromRgb(0x0a, 0x0a, 0x0a))),
FontWeight = FontWeights.SemiBold
};
runBtn.Click += (_, _) =>
{
cancelled = false; install = false;
win.Close();
};
installBtn.Click += (_, _) =>
{
cancelled = false; install = true;
desktop = desktopChk.IsChecked == true;
win.Close();
};
btnRow.Children.Add(runBtn);
btnRow.Children.Add(installBtn);
content.Children.Add(btnRow);
root.Children.Add(content);
win.Content = root;
win.ShowDialog();
return (cancelled, install, desktop);
}
// ============================================================
// Security — Authenticode verification + pdfium integrity
// ============================================================
// ── WinVerifyTrust P/Invoke ──────────────────────────────────────────
[StructLayout(LayoutKind.Sequential)]
private struct WINTRUST_FILE_INFO
{
public uint cbStruct;
public IntPtr pcwszFilePath; // LPCWSTR
public IntPtr hFile;
public IntPtr pgKnownSubject;
}
[StructLayout(LayoutKind.Sequential)]
private struct WINTRUST_DATA
{
public uint cbStruct;
public IntPtr pPolicyCallbackData;
public IntPtr pSIPClientData;
public uint dwUIChoice; // 2 = WTD_UI_NONE
public uint fdwRevocationChecks; // 0 = WTD_REVOKE_NONE
public uint dwUnionChoice; // 1 = WTD_CHOICE_FILE
public IntPtr pUnion; // → WINTRUST_FILE_INFO
public uint dwStateAction; // 0 = WTD_STATEACTION_IGNORE
public IntPtr hWVTStateData;
public IntPtr pwszURLReference;
public uint dwProvFlags; // 0 = allow network fetch of intermediates
public uint dwUIContext;
public IntPtr pSignatureSettings;
}
private static readonly Guid WTD_VERIFY_GENERIC =
new("00AAC56B-CD44-11d0-8CC2-00C04FC295EE");
[DllImport("wintrust.dll", ExactSpelling = true, SetLastError = false,
CharSet = CharSet.Unicode)]
private static extern uint WinVerifyTrust(
IntPtr hwnd, ref Guid pgActionID, IntPtr pWVTData);
// ── Public helpers ───────────────────────────────────────────────────
/// <summary>
/// Calls WinVerifyTrust to validate an Authenticode signature.
/// Returns (Valid, SubjectCN, Thumbprint).
/// Valid=false for unsigned, expired (past grace), or tampered files.
/// </summary>
internal static (bool Valid, string Subject, string Thumbprint)
VerifyAuthenticode(string filePath)
{
var subject = "(not signed)";
var thumbprint = string.Empty;
// Try to read cert info regardless of signature validity
try
{
var raw = X509Certificate.CreateFromSignedFile(filePath);
var cert = new X509Certificate2(raw);
subject = cert.GetNameInfo(X509NameType.SimpleName, forIssuer: false);
thumbprint = cert.Thumbprint ?? string.Empty;
}
catch { /* unsigned or unreadable */ }
// Full chain + revocation check via WinVerifyTrust
var pathPtr = Marshal.StringToHGlobalUni(filePath);
var fileInfoPtr = Marshal.AllocHGlobal(Marshal.SizeOf<WINTRUST_FILE_INFO>());
var dataPtr = Marshal.AllocHGlobal(Marshal.SizeOf<WINTRUST_DATA>());
try
{
Marshal.StructureToPtr(new WINTRUST_FILE_INFO
{
cbStruct = (uint)Marshal.SizeOf<WINTRUST_FILE_INFO>(),
pcwszFilePath = pathPtr
}, fileInfoPtr, false);
Marshal.StructureToPtr(new WINTRUST_DATA
{
cbStruct = (uint)Marshal.SizeOf<WINTRUST_DATA>(),
dwUIChoice = 2, // WTD_UI_NONE
dwUnionChoice = 1, // WTD_CHOICE_FILE
pUnion = fileInfoPtr,
dwProvFlags = 0 // allow network fetch of intermediate certs
}, dataPtr, false);
var actionId = WTD_VERIFY_GENERIC;
uint hr = WinVerifyTrust(IntPtr.Zero, ref actionId, dataPtr);
return (hr == 0, subject, thumbprint);
}
finally
{
Marshal.FreeHGlobal(dataPtr);
Marshal.FreeHGlobal(fileInfoPtr);
Marshal.FreeHGlobal(pathPtr);
}
}
/// <summary>
/// Convenience wrapper: verify the currently running EXE.
/// </summary>
internal static (bool Valid, string Subject, string Thumbprint) GetExeSignerInfo()
{
try
{
return VerifyAuthenticode(Process.GetCurrentProcess().MainModule!.FileName);
}
catch
{
return (false, "(not signed)", string.Empty);
}
}
/// <summary>SHA256 hex of the currently running EXE (for the About dialog).</summary>
internal static string GetExeSha256()
{
try
{
var path = Process.GetCurrentProcess().MainModule!.FileName;
using var sha = SHA256.Create();
using var fs = File.OpenRead(path);
return BitConverter.ToString(sha.ComputeHash(fs)).Replace("-", "");
}
catch { return "(unavailable)"; }
}
// ── About dialog ────────────────────────────────────────────────────────
internal static void ShowAboutDialog(Window owner)
{
// Gather info on a background thread so the UI isn't blocked by hashing
var version = System.Reflection.Assembly.GetExecutingAssembly()
.GetName().Version?.ToString(3) ?? "?";
var (sigValid, sigSubject, sigThumbprint) = GetExeSignerInfo();
var sha256 = GetExeSha256();
// ── Layout ──────────────────────────────────────────────────────
var bg = new SolidColorBrush(Color.FromRgb(0x1e, 0x1e, 0x1e));
var bgCard = new SolidColorBrush(Color.FromRgb(0x2a, 0x2a, 0x2a));
var fg = new SolidColorBrush(Color.FromRgb(0xe0, 0xe0, 0xe0));
var fgDim = new SolidColorBrush(Color.FromRgb(0x77, 0x77, 0x77));
var accent = new SolidColorBrush(Color.FromRgb(0x1e, 0xa5, 0x4c));
var mono = new FontFamily("Consolas");
// Title bar
var titleBar = new Grid
{
Background = new SolidColorBrush(Color.FromRgb(0x25, 0x25, 0x25)),
Height = 32
};
titleBar.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
titleBar.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
var titleText = new TextBlock
{
Text = $"About KillerPDF",
Foreground = fg, VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(12, 0, 0, 0), FontSize = 13, FontWeight = FontWeights.SemiBold
};
Grid.SetColumn(titleText, 0);
titleBar.Children.Add(titleText);
Window? dlg = null;
var closeBtn = MakeTitleBarCloseButton(
new SolidColorBrush(Color.FromRgb(0xcc, 0xcc, 0xcc)),
new SolidColorBrush(Color.FromRgb(0xc0, 0x3b, 0x3b)));
closeBtn.Click += (_, __) => dlg!.Close();
Grid.SetColumn(closeBtn, 1);
titleBar.Children.Add(closeBtn);
// Helper: labelled row (onClick makes the value a clickable hyperlink)
static StackPanel MakeRow(string label, string value,
SolidColorBrush labelBrush, SolidColorBrush valueBrush,
FontFamily? valueFont = null, bool wrap = false, Action? onClick = null)
{
var sp = new StackPanel { Orientation = Orientation.Vertical, Margin = new Thickness(0, 0, 0, 10) };
sp.Children.Add(new TextBlock
{
Text = label, Foreground = labelBrush,
FontSize = 10, Margin = new Thickness(0, 0, 0, 2)
});
if (onClick != null)
{
var tb = new TextBlock
{
FontFamily = valueFont ?? new FontFamily("Segoe UI"),
FontSize = 12,
Cursor = Cursors.Hand
};
var hl = new Hyperlink(new Run(value))
{
Foreground = valueBrush,
TextDecorations = null
};
hl.Click += (_, _) => onClick();
tb.Inlines.Add(hl);
sp.Children.Add(tb);
}