-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
1061 lines (928 loc) · 38.1 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
1061 lines (928 loc) · 38.1 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.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using MenuItem = System.Windows.Controls.MenuItem;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Navigation;
using Microsoft.Win32;
using PkgInspector.Models;
using PkgInspector.Services;
using WinForms = System.Windows.Forms;
using MessageBox = System.Windows.MessageBox;
using Clipboard = System.Windows.Clipboard;
using TreeView = System.Windows.Controls.TreeView;
namespace PkgInspector;
public partial class MainWindow : Window, INotifyPropertyChanged
{
// Windows API for dark title bar
[DllImport("dwmapi.dll", PreserveSig = true)]
private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize);
private const int DWMWA_USE_IMMERSIVE_DARK_MODE = 20;
private readonly PackageInspectorService _inspectorService;
private readonly MsiInspectorService _msiInspectorService;
private PackageData? _currentPackage;
private ScriptInfo? _selectedScript;
private System.Windows.Threading.DispatcherTimer? _themeMonitor;
private bool _lastThemeState;
public MainWindow()
{
InitializeComponent();
_inspectorService = new PackageInspectorService();
_msiInspectorService = new MsiInspectorService();
DataContext = this;
// Set window icon from PNG resource (better alpha channel support than ICO)
try
{
var iconUri = new Uri("pack://application:,,,/Resources/app-icon.png");
var iconBitmap = new System.Windows.Media.Imaging.BitmapImage(iconUri);
Icon = iconBitmap;
}
catch { /* Ignore if icon can't be loaded */ }
// Auto-detect and apply system theme
DetectAndApplySystemTheme();
// Start monitoring for theme changes
StartThemeMonitoring();
// Check for command-line arguments
Loaded += async (s, e) =>
{
// Set dark title bar after window handle is created
SetDarkTitleBar(_lastThemeState);
await HandleCommandLineArgs();
};
}
private void StartThemeMonitoring()
{
_themeMonitor = new System.Windows.Threading.DispatcherTimer
{
Interval = TimeSpan.FromSeconds(2)
};
_themeMonitor.Tick += (s, e) =>
{
try
{
using var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize");
var usesDarkMode = key?.GetValue("AppsUseLightTheme") is int value && value == 0;
if (usesDarkMode != _lastThemeState)
{
_lastThemeState = usesDarkMode;
ApplyTheme(usesDarkMode);
}
}
catch { /* Ignore errors */ }
};
_themeMonitor.Start();
}
private void DetectAndApplySystemTheme()
{
try
{
// Check Windows registry for dark mode setting
using var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize");
var usesDarkMode = key?.GetValue("AppsUseLightTheme") is int value && value == 0;
_lastThemeState = usesDarkMode;
ApplyTheme(usesDarkMode);
}
catch
{
// Default to light mode if detection fails
_lastThemeState = false;
ApplyTheme(false);
}
}
private async Task HandleCommandLineArgs()
{
var args = Environment.GetCommandLineArgs();
// Skip the executable name
if (args.Length > 1)
{
var packagePath = args[1];
if (File.Exists(packagePath))
{
await LoadPackage(packagePath);
// Check for reveal options from environment
var revealFile = Environment.GetEnvironmentVariable("PKGINSPECTOR_REVEAL_FILE");
var revealScripts = Environment.GetEnvironmentVariable("PKGINSPECTOR_REVEAL_SCRIPTS");
if (!string.IsNullOrEmpty(revealScripts))
{
MainTabControl.SelectedIndex = 2; // Scripts tab
}
else if (!string.IsNullOrEmpty(revealFile))
{
MainTabControl.SelectedIndex = 1; // Files tab
// TODO: Navigate to specific file
}
}
}
}
#region Properties
public bool HasPackage => _currentPackage != null;
public string PackageName => _currentPackage?.Metadata?.Name ?? "Unknown Package";
public string PackageFileName => _currentPackage?.FileName ?? string.Empty;
public BuildInfo? PackageInfo => _currentPackage?.Metadata;
public int FileCount => _currentPackage?.Files.Count ?? 0;
public int ScriptCount => _currentPackage?.Scripts.Count ?? 0;
public string FileCountMessage => $"{FileCount} files in payload";
public bool HasDependencies => _currentPackage?.Metadata?.Dependencies?.Count > 0;
// MSI-specific identity. Empty when the loaded package is a .nupkg; the
// matching rows collapse in the XAML via the HasXxx flags.
public string ProductCode => _currentPackage?.ProductCode ?? string.Empty;
public bool HasProductCode => !string.IsNullOrEmpty(_currentPackage?.ProductCode);
public string UpgradeCode => _currentPackage?.UpgradeCode ?? string.Empty;
public bool HasUpgradeCode => !string.IsNullOrEmpty(_currentPackage?.UpgradeCode);
public string Identifier => _currentPackage?.Identifier ?? string.Empty;
public bool HasIdentifier => !string.IsNullOrEmpty(_currentPackage?.Identifier);
public string Architecture => _currentPackage?.Architecture ?? string.Empty;
public bool HasArchitecture => !string.IsNullOrEmpty(_currentPackage?.Architecture);
public string FullVersion => _currentPackage?.FullVersion ?? string.Empty;
// Only show FullVersion when it differs from the displayed Version
// (cimipkg stores the original date-based version separately from the MSI
// 3-part form, but for cimipkg MSIs the embedded YAML's product.version
// usually already carries the long form — no need to show it twice).
public bool HasFullVersion =>
!string.IsNullOrEmpty(_currentPackage?.FullVersion) &&
!string.Equals(_currentPackage.FullVersion, _currentPackage.Metadata?.Version, StringComparison.Ordinal);
public string Category => _currentPackage?.Metadata?.Category ?? string.Empty;
public bool HasCategory => !string.IsNullOrEmpty(_currentPackage?.Metadata?.Category);
public bool HasMsiIdentity =>
HasProductCode || HasUpgradeCode || HasIdentifier || HasArchitecture || HasFullVersion;
public List<FileTreeNode> FileTree => _currentPackage?.FileTree ?? new();
public List<ScriptInfo> Scripts => _currentPackage?.Scripts ?? new();
public ScriptInfo? SelectedScript
{
get => _selectedScript;
set
{
_selectedScript = value;
OnPropertyChanged(nameof(SelectedScript));
}
}
public string RawMetadata => _currentPackage?.RawMetadata ?? string.Empty;
public bool IsSigned => _currentPackage?.IsSigned ?? false;
public string SignedBy => _currentPackage?.SignedBy ?? string.Empty;
public string SignatureStatus => IsSigned ? "Signed" : "Unsigned";
public string SignatureDetails => IsSigned ? $"Signed by: {SignedBy}" : "Package is not digitally signed";
#endregion
#region Event Handlers
private void Home_Click(object sender, RoutedEventArgs e)
{
// Clear the current package to return to welcome screen
_currentPackage = null;
_selectedScript = null;
// Trigger property change notifications to update UI
OnPropertyChanged(nameof(HasPackage));
OnPropertyChanged(nameof(PackageName));
OnPropertyChanged(nameof(PackageFileName));
OnPropertyChanged(nameof(PackageInfo));
OnPropertyChanged(nameof(FileTree));
OnPropertyChanged(nameof(Scripts));
OnPropertyChanged(nameof(SelectedScript));
OnPropertyChanged(nameof(RawMetadata));
OnPropertyChanged(nameof(FileCount));
OnPropertyChanged(nameof(HasDependencies));
OnPropertyChanged(nameof(IsSigned));
OnPropertyChanged(nameof(SignatureStatus));
OnPropertyChanged(nameof(SignedBy));
OnPropertyChanged(nameof(ProductCode));
OnPropertyChanged(nameof(HasProductCode));
OnPropertyChanged(nameof(UpgradeCode));
OnPropertyChanged(nameof(HasUpgradeCode));
OnPropertyChanged(nameof(Identifier));
OnPropertyChanged(nameof(HasIdentifier));
OnPropertyChanged(nameof(Architecture));
OnPropertyChanged(nameof(HasArchitecture));
OnPropertyChanged(nameof(FullVersion));
OnPropertyChanged(nameof(HasFullVersion));
OnPropertyChanged(nameof(Category));
OnPropertyChanged(nameof(HasCategory));
OnPropertyChanged(nameof(HasMsiIdentity));
}
private void ApplyTheme(bool isDark)
{
var resources = System.Windows.Application.Current.Resources;
if (isDark)
{
// Apply dark mode colors
resources["BackgroundBrush"] = resources["DarkBackgroundBrush"];
resources["SurfaceBrush"] = resources["DarkSurfaceBrush"];
resources["BorderBrush"] = resources["DarkBorderBrush"];
resources["TextPrimaryBrush"] = resources["DarkTextPrimaryBrush"];
resources["TextSecondaryBrush"] = resources["DarkTextSecondaryBrush"];
resources["HoverBrush"] = resources["DarkHoverBrush"];
resources["SelectedBrush"] = resources["DarkSelectedBrush"];
}
else
{
// Restore light mode colors
resources["BackgroundBrush"] = new SolidColorBrush(System.Windows.Media.Color.FromRgb(0xFA, 0xFA, 0xFA));
resources["SurfaceBrush"] = new SolidColorBrush(System.Windows.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
resources["BorderBrush"] = new SolidColorBrush(System.Windows.Media.Color.FromRgb(0xE0, 0xE0, 0xE0));
resources["TextPrimaryBrush"] = new SolidColorBrush(System.Windows.Media.Color.FromRgb(0x21, 0x21, 0x21));
resources["TextSecondaryBrush"] = new SolidColorBrush(System.Windows.Media.Color.FromRgb(0x75, 0x75, 0x75));
resources["HoverBrush"] = new SolidColorBrush(System.Windows.Media.Color.FromRgb(0xF5, 0xF5, 0xF5));
resources["SelectedBrush"] = new SolidColorBrush(System.Windows.Media.Color.FromRgb(0xE3, 0xF2, 0xFD));
}
// Apply dark title bar (Windows 10 build 18985+)
SetDarkTitleBar(isDark);
}
private void SetDarkTitleBar(bool isDark)
{
try
{
var hwnd = new WindowInteropHelper(this).Handle;
if (hwnd != IntPtr.Zero)
{
int useImmersiveDarkMode = isDark ? 1 : 0;
DwmSetWindowAttribute(hwnd, DWMWA_USE_IMMERSIVE_DARK_MODE, ref useImmersiveDarkMode, sizeof(int));
}
}
catch
{
// Silently fail on older Windows versions
}
}
private async void OpenPackage_Click(object sender, RoutedEventArgs e)
{
var dialog = new Microsoft.Win32.OpenFileDialog
{
Filter = "Package Files (*.msi;*.nupkg)|*.msi;*.nupkg|All Files (*.*)|*.*",
Title = "Select a Package to Inspect"
};
if (dialog.ShowDialog() == true)
{
await LoadPackage(dialog.FileName);
}
}
private void Window_Drop(object sender, System.Windows.DragEventArgs e)
{
if (e.Data.GetDataPresent(System.Windows.DataFormats.FileDrop))
{
string[] files = (string[])e.Data.GetData(System.Windows.DataFormats.FileDrop);
if (files.Length > 0)
{
var file = files[0];
// .pkg is deprecated and no longer advertised in the file
// filter / welcome-screen text, but LoadPackage still handles
// it via PackageInspectorService and command-line + Recent
// Packages entry points still open .pkg files. Accept .pkg
// on drag/drop too so the three surfaces don't diverge —
// otherwise dragging a .pkg silently no-ops while
// double-clicking one from Recent still works.
if (file.EndsWith(".msi", StringComparison.OrdinalIgnoreCase) ||
file.EndsWith(".nupkg", StringComparison.OrdinalIgnoreCase) ||
file.EndsWith(".pkg", StringComparison.OrdinalIgnoreCase))
{
_ = LoadPackage(file);
}
}
}
}
private void Window_DragOver(object sender, System.Windows.DragEventArgs e)
{
if (e.Data.GetDataPresent(System.Windows.DataFormats.FileDrop))
{
e.Effects = System.Windows.DragDropEffects.Copy;
}
else
{
e.Effects = System.Windows.DragDropEffects.None;
}
e.Handled = true;
}
private void FilesTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
// Future: Show file preview or details
}
private void ScriptsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ScriptsListBox.SelectedItem is ScriptInfo script)
{
SelectedScript = script;
}
}
private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
try
{
Process.Start(new ProcessStartInfo
{
FileName = e.Uri.AbsoluteUri,
UseShellExecute = true
});
e.Handled = true;
}
catch
{
// Silently fail if can't open URL
}
}
#endregion
#region Methods
private async Task LoadPackage(string filePath)
{
try
{
Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
_currentPackage = Path.GetExtension(filePath).Equals(".msi", StringComparison.OrdinalIgnoreCase)
? await _msiInspectorService.InspectPackageAsync(filePath)
: await _inspectorService.InspectPackageAsync(filePath);
// Select first script if available
if (_currentPackage.Scripts.Count > 0)
{
SelectedScript = _currentPackage.Scripts[0];
}
// Add to recent packages
WelcomeScreen?.AddRecentPackage(filePath);
RefreshUI();
}
catch (Exception ex)
{
MessageBox.Show(
$"Failed to load package: {ex.Message}",
"Error",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
finally
{
Mouse.OverrideCursor = null;
}
}
private async void WelcomeScreen_PackageSelected(object? sender, string filePath)
{
await LoadPackage(filePath);
}
private void RefreshUI()
{
OnPropertyChanged(nameof(HasPackage));
OnPropertyChanged(nameof(PackageName));
OnPropertyChanged(nameof(PackageFileName));
OnPropertyChanged(nameof(PackageInfo));
OnPropertyChanged(nameof(FileCount));
OnPropertyChanged(nameof(ScriptCount));
OnPropertyChanged(nameof(FileCountMessage));
OnPropertyChanged(nameof(HasDependencies));
OnPropertyChanged(nameof(FileTree));
OnPropertyChanged(nameof(Scripts));
OnPropertyChanged(nameof(RawMetadata));
OnPropertyChanged(nameof(IsSigned));
OnPropertyChanged(nameof(SignedBy));
OnPropertyChanged(nameof(SignatureStatus));
OnPropertyChanged(nameof(SignatureDetails));
OnPropertyChanged(nameof(ProductCode));
OnPropertyChanged(nameof(HasProductCode));
OnPropertyChanged(nameof(UpgradeCode));
OnPropertyChanged(nameof(HasUpgradeCode));
OnPropertyChanged(nameof(Identifier));
OnPropertyChanged(nameof(HasIdentifier));
OnPropertyChanged(nameof(Architecture));
OnPropertyChanged(nameof(HasArchitecture));
OnPropertyChanged(nameof(FullVersion));
OnPropertyChanged(nameof(HasFullVersion));
OnPropertyChanged(nameof(Category));
OnPropertyChanged(nameof(HasCategory));
OnPropertyChanged(nameof(HasMsiIdentity));
// Expand all folders in the file tree after UI updates
// Force tree expansion with multiple attempts
Dispatcher.BeginInvoke(new Action(async () =>
{
await Task.Delay(100); // Initial delay for rendering
ExpandAllTreeViewItems();
await Task.Delay(100); // Second attempt
ExpandAllTreeViewItems();
await Task.Delay(200); // Third attempt
ExpandAllTreeViewItems();
}), System.Windows.Threading.DispatcherPriority.Loaded);
}
private void ExpandAllTreeViewItems()
{
if (FilesTreeView != null && FilesTreeView.Items.Count > 0)
{
// Force container generation and expansion
FilesTreeView.UpdateLayout();
FilesTreeView.InvalidateVisual();
foreach (var item in FilesTreeView.Items)
{
var treeViewItem = FilesTreeView.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
if (treeViewItem != null)
{
treeViewItem.IsExpanded = true;
treeViewItem.UpdateLayout();
treeViewItem.ApplyTemplate();
ExpandTreeViewItem(treeViewItem);
}
}
}
}
private void ExpandTreeViewItem(TreeViewItem item)
{
item.IsExpanded = true;
item.UpdateLayout();
// Give time for containers to generate
item.ApplyTemplate();
foreach (var childItem in item.Items)
{
var childTreeViewItem = item.ItemContainerGenerator.ContainerFromItem(childItem) as TreeViewItem;
if (childTreeViewItem != null)
{
ExpandTreeViewItem(childTreeViewItem);
}
}
}
private async void ExportPackage_Click(object sender, RoutedEventArgs e)
{
if (_currentPackage == null) return;
// Suppress CA1416 - this is a Windows-only app (net9.0-windows)
#pragma warning disable CA1416
var dialog = new System.Windows.Forms.FolderBrowserDialog
{
Description = "Select folder to export package contents",
ShowNewFolderButton = true
};
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
try
{
// Create subfolder with package name and version
var packageName = _currentPackage?.Metadata?.Name ?? "Package";
var packageVersion = _currentPackage?.Metadata?.Version ?? "Unknown";
// Sanitize folder name
var invalidChars = Path.GetInvalidFileNameChars();
var safeName = string.Concat(packageName.Split(invalidChars));
var safeVersion = string.Concat(packageVersion.Split(invalidChars));
var exportFolderName = $"{safeName}-{safeVersion}";
var exportPath = Path.Combine(dialog.SelectedPath, exportFolderName);
await ExportPackageToFolder(exportPath);
// Open the exported folder immediately
Process.Start(new ProcessStartInfo
{
FileName = exportPath,
UseShellExecute = true,
Verb = "open"
});
}
catch (Exception ex)
{
MessageBox.Show(
$"Failed to export package: {ex.Message}",
"Export Error",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
}
#pragma warning restore CA1416
}
private void FilesTreeView_RightClick(object sender, MouseButtonEventArgs e)
{
var treeView = sender as TreeView;
if (treeView == null) return;
var item = GetTreeViewItemAtPoint(treeView, e.GetPosition(treeView));
if (item != null && item.DataContext is FileTreeNode node)
{
item.IsSelected = true;
PopulateOpenWithMenu(FileContextMenu.Items[1] as MenuItem ?? new MenuItem(), node.FullPath, false);
}
}
private void ScriptsListBox_RightClick(object sender, MouseButtonEventArgs e)
{
PopulateOpenWithMenu(ScriptContextMenu.Items[1] as MenuItem ?? new MenuItem(), "", true);
}
private TreeViewItem? GetTreeViewItemAtPoint(System.Windows.Controls.TreeView treeView, System.Windows.Point point)
{
var element = treeView.InputHitTest(point) as DependencyObject;
while (element != null)
{
if (element is TreeViewItem item)
return item;
element = VisualTreeHelper.GetParent(element);
}
return null;
}
private void PopulateOpenWithMenu(MenuItem parentMenu, string relativePath, bool isPowerShell)
{
parentMenu.Items.Clear();
var apps = new List<(string Name, string Path)>
{
("Notepad", "notepad.exe"),
("VS Code", @"C:\Program Files\Microsoft VS Code\Code.exe"),
("PowerShell", "powershell.exe"),
("PowerShell ISE", @"C:\Windows\System32\WindowsPowerShell\v1.0\powershell_ise.exe")
};
if (isPowerShell)
{
apps.Add(("Windows Terminal", "wt.exe"));
}
foreach (var (name, path) in apps)
{
// Check if the app exists
if (File.Exists(path) || CheckProgramInPath(path))
{
var menuItem = new MenuItem { Header = name, Tag = path };
menuItem.Click += (s, e) => OpenItemWith(relativePath, path, isPowerShell);
parentMenu.Items.Add(menuItem);
}
}
if (parentMenu.Items.Count == 0)
{
parentMenu.Items.Add(new MenuItem { Header = "No applications found", IsEnabled = false });
}
}
private bool CheckProgramInPath(string program)
{
try
{
var pathEnv = Environment.GetEnvironmentVariable("PATH");
if (pathEnv != null)
{
var paths = pathEnv.Split(';');
foreach (var path in paths)
{
var fullPath = Path.Combine(path, program);
if (File.Exists(fullPath))
return true;
}
}
}
catch
{
// Ignore errors
}
return false;
}
private async void OpenItemWith(string relativePath, string appPath, bool isScript)
{
if (_currentPackage == null) return;
try
{
string tempFile;
if (isScript && SelectedScript != null)
{
// Export script to temp file
tempFile = Path.Combine(Path.GetTempPath(), $"pkginspector_{Guid.NewGuid()}", SelectedScript.Name);
Directory.CreateDirectory(Path.GetDirectoryName(tempFile)!);
await File.WriteAllTextAsync(tempFile, SelectedScript.Content);
}
else
{
// Export file from package
tempFile = await ExportSingleFile(relativePath);
}
// Open with specified application
Process.Start(new ProcessStartInfo
{
FileName = appPath,
Arguments = $"\"{tempFile}\"",
UseShellExecute = true
});
}
catch (Exception ex)
{
MessageBox.Show(
$"Failed to open item: {ex.Message}",
"Error",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
}
private async void ExportFileItem_Click(object sender, RoutedEventArgs e)
{
var node = GetSelectedFileNode();
if (node == null) return;
var dialog = new Microsoft.Win32.SaveFileDialog
{
FileName = node.Name,
Title = "Export File"
};
if (dialog.ShowDialog() == true)
{
try
{
var tempFile = await ExportSingleFile(node.FullPath);
File.Copy(tempFile, dialog.FileName, true);
MessageBox.Show(
$"File exported successfully to:\n{dialog.FileName}",
"Export Complete",
MessageBoxButton.OK,
MessageBoxImage.Information);
}
catch (Exception ex)
{
MessageBox.Show(
$"Failed to export file: {ex.Message}",
"Export Error",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
}
}
private async void ExportScriptItem_Click(object sender, RoutedEventArgs e)
{
if (SelectedScript == null) return;
var dialog = new Microsoft.Win32.SaveFileDialog
{
FileName = SelectedScript.Name,
DefaultExt = ".ps1",
Filter = "PowerShell Scripts (*.ps1)|*.ps1|All Files (*.*)|*.*",
Title = "Export Script"
};
if (dialog.ShowDialog() == true)
{
try
{
await File.WriteAllTextAsync(dialog.FileName, SelectedScript.Content);
MessageBox.Show(
$"Script exported successfully to:\n{dialog.FileName}",
"Export Complete",
MessageBoxButton.OK,
MessageBoxImage.Information);
}
catch (Exception ex)
{
MessageBox.Show(
$"Failed to export script: {ex.Message}",
"Export Error",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
}
}
private void CopyFilePath_Click(object sender, RoutedEventArgs e)
{
var node = GetSelectedFileNode();
if (node != null)
{
Clipboard.SetText(node.FullPath);
}
}
private FileTreeNode? GetSelectedFileNode()
{
// Find the TreeView control
var treeView = FindVisualChild<TreeView>(this);
if (treeView != null)
{
foreach (var item in GetAllTreeViewItems(treeView))
{
if (item.IsSelected && item.DataContext is FileTreeNode node)
{
return node;
}
}
}
return null;
}
private IEnumerable<TreeViewItem> GetAllTreeViewItems(ItemsControl parent)
{
for (int i = 0; i < parent.Items.Count; i++)
{
var item = parent.ItemContainerGenerator.ContainerFromIndex(i) as TreeViewItem;
if (item != null)
{
yield return item;
foreach (var child in GetAllTreeViewItems(item))
{
yield return child;
}
}
}
}
private static T? FindVisualChild<T>(DependencyObject parent) where T : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is T result)
return result;
var childOfChild = FindVisualChild<T>(child);
if (childOfChild != null)
return childOfChild;
}
return null;
}
private void CopyScriptPath_Click(object sender, RoutedEventArgs e)
{
if (SelectedScript != null)
{
Clipboard.SetText(SelectedScript.RelativePath);
}
}
private Task<string> ExportSingleFile(string relativePath)
{
if (_currentPackage == null)
throw new InvalidOperationException("No package loaded");
// Extract package to temp location
var tempDir = Path.Combine(Path.GetTempPath(), $"pkginspector_{Guid.NewGuid()}");
Directory.CreateDirectory(tempDir);
using (var archive = ZipFile.OpenRead(_currentPackage.FilePath))
{
var entry = archive.Entries.FirstOrDefault(e =>
e.FullName.Replace('/', '\\').EndsWith(relativePath.Replace('/', '\\'), StringComparison.OrdinalIgnoreCase));
if (entry != null)
{
var destPath = Path.Combine(tempDir, entry.Name);
using (var entryStream = entry.Open())
using (var fileStream = File.Create(destPath))
{
entryStream.CopyTo(fileStream);
}
return Task.FromResult(destPath);
}
}
throw new FileNotFoundException($"File not found in package: {relativePath}");
}
private async Task ExportPackageToFolder(string folderPath)
{
if (_currentPackage == null) return;
// Create export folder structure
Directory.CreateDirectory(folderPath);
var payloadPath = Path.Combine(folderPath, "payload");
var scriptsPath = Path.Combine(folderPath, "scripts");
// Export the report
var reportPath = Path.Combine(folderPath, "package-report.txt");
await ExportPackageInfo(reportPath, true);
// Export build-info.yaml
if (!string.IsNullOrEmpty(RawMetadata) && RawMetadata != "No metadata file found")
{
await File.WriteAllTextAsync(Path.Combine(folderPath, "build-info.yaml"), RawMetadata);
}
// Export payload files
if (_currentPackage.Files.Count > 0)
{
Directory.CreateDirectory(payloadPath);
using (var archive = ZipFile.OpenRead(_currentPackage.FilePath))
{
foreach (var file in _currentPackage.Files.Where(f => !f.IsDirectory))
{
var entryPath = "payload/" + file.RelativePath.Replace("\\", "/");
var entry = archive.GetEntry(entryPath);
if (entry != null)
{
var outputPath = Path.Combine(payloadPath, file.RelativePath);
var outputDir = Path.GetDirectoryName(outputPath);
if (!string.IsNullOrEmpty(outputDir))
{
Directory.CreateDirectory(outputDir);
}
entry.ExtractToFile(outputPath, true);
}
}
}
}
// Export scripts
if (_currentPackage.Scripts.Count > 0)
{
Directory.CreateDirectory(scriptsPath);
foreach (var script in _currentPackage.Scripts)
{
var scriptPath = Path.Combine(scriptsPath, script.Name);
await File.WriteAllTextAsync(scriptPath, script.Content);
}
}
}
private async Task ExportPackageInfo(string filePath, bool includePayload = false)
{
if (_currentPackage == null) return;
var sb = new System.Text.StringBuilder();
var isMarkdown = filePath.EndsWith(".md", StringComparison.OrdinalIgnoreCase);
if (isMarkdown)
{
sb.AppendLine($"# Package Inspection Report: {PackageName}");
sb.AppendLine();
sb.AppendLine($"**Package File:** `{PackageFileName}`");
sb.AppendLine($"**Inspection Date:** {DateTime.Now:yyyy-MM-DD HH:mm:ss}");
sb.AppendLine();
sb.AppendLine("## Package Overview");
sb.AppendLine();
sb.AppendLine($"| Property | Value |");
sb.AppendLine($"|----------|-------|");
sb.AppendLine($"| Name | {PackageInfo?.Name ?? "N/A"} |");
sb.AppendLine($"| Version | {PackageInfo?.Version ?? "N/A"} |");
sb.AppendLine($"| Description | {PackageInfo?.Description ?? "N/A"} |");
sb.AppendLine($"| Author | {PackageInfo?.Author ?? "N/A"} |");
sb.AppendLine($"| License | {PackageInfo?.License ?? "N/A"} |");
sb.AppendLine($"| Homepage | {PackageInfo?.Homepage ?? "N/A"} |");
sb.AppendLine($"| Target | {PackageInfo?.Target ?? "N/A"} |");
sb.AppendLine($"| Signature | {SignatureStatus} {(IsSigned ? $"({SignedBy})" : "")} |");
sb.AppendLine();
sb.AppendLine("## Installation Details");
sb.AppendLine();
sb.AppendLine($"- **Install Location:** `{PackageInfo?.InstallLocation ?? "N/A"}`");
sb.AppendLine($"- **Restart Action:** {PackageInfo?.RestartAction ?? "N/A"}");
sb.AppendLine($"- **File Count:** {FileCount}");
sb.AppendLine($"- **Script Count:** {ScriptCount}");
sb.AppendLine();
if (HasDependencies && PackageInfo?.Dependencies != null && PackageInfo.Dependencies.Count > 0)
{
sb.AppendLine("## Dependencies");
sb.AppendLine();
foreach (var dep in PackageInfo.Dependencies)
{
sb.AppendLine($"- {dep}");
}
sb.AppendLine();
}
sb.AppendLine("## Files");
sb.AppendLine();
foreach (var file in _currentPackage.Files.OrderBy(f => f.RelativePath))
{
var icon = file.IsDirectory ? "📁" : "📄";
sb.AppendLine($"- {icon} `{file.RelativePath}` {(file.IsDirectory ? "" : $"({file.SizeFormatted})")}");
}
sb.AppendLine();
if (_currentPackage.Scripts.Count > 0)
{
sb.AppendLine("## Scripts");
sb.AppendLine();
foreach (var script in _currentPackage.Scripts)
{
sb.AppendLine($"### {script.Name} ({script.Type})");
sb.AppendLine();
sb.AppendLine("```powershell");
sb.AppendLine(script.Content);
sb.AppendLine("```");
sb.AppendLine();
}
}
sb.AppendLine("## Raw Metadata");
sb.AppendLine();
sb.AppendLine("```yaml");
sb.AppendLine(RawMetadata);
sb.AppendLine("```");
}
else
{
// Plain text format
sb.AppendLine($"Package Inspection Report: {PackageName}");
sb.AppendLine(new string('=', 80));
sb.AppendLine();
sb.AppendLine($"Package File: {PackageFileName}");
sb.AppendLine($"Inspection Date: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
sb.AppendLine();
sb.AppendLine("PACKAGE OVERVIEW");
sb.AppendLine(new string('-', 80));
sb.AppendLine($"Name: {PackageInfo?.Name ?? "N/A"}");
sb.AppendLine($"Version: {PackageInfo?.Version ?? "N/A"}");
sb.AppendLine($"Description: {PackageInfo?.Description ?? "N/A"}");
sb.AppendLine($"Author: {PackageInfo?.Author ?? "N/A"}");
sb.AppendLine($"License: {PackageInfo?.License ?? "N/A"}");
sb.AppendLine($"Homepage: {PackageInfo?.Homepage ?? "N/A"}");
sb.AppendLine($"Target: {PackageInfo?.Target ?? "N/A"}");
sb.AppendLine($"Signature: {SignatureStatus} {(IsSigned ? $"({SignedBy})" : "")}");
sb.AppendLine();
sb.AppendLine("INSTALLATION DETAILS");
sb.AppendLine(new string('-', 80));