-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
566 lines (498 loc) · 24.9 KB
/
MainWindow.xaml.cs
File metadata and controls
566 lines (498 loc) · 24.9 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
using System;
using System.IO;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using SevenZip;
using Path = System.IO.Path;
using System.ComponentModel;
using System.Threading;
using System.Windows.Media;
using System.Linq;
using System.Windows.Data;
using SizeInt = System.Drawing.Size;
namespace ZipImageViewer
{
public partial class MainWindow : BorderlessWindow, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public ObservableKeyedCollection<string, ObjectInfo> ObjectList { get; } =
new ObservableKeyedCollection<string, ObjectInfo>(o => o.VirtualPath);
private DpiScale DpiScale;
public double ThumbRealWidth => Setting.ThumbnailSize.Item1 / DpiScale.DpiScaleX;
public double ThumbRealHeight => Setting.ThumbnailSize.Item2 / DpiScale.DpiScaleY;
private string currentPath = "";
public string CurrentPath {
get { return currentPath; }
set {
if (currentPath == value) return;
currentPath = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CurrentPath)));
}
}
public int ThumbChangeDelay => Convert.ToInt32(virWrapPanel.VisualChildrenCount * 200 + App.Random.Next(2, 5) * 1000 * Setting.ThumbSwapDelayMultiplier);
//public int ThumbChangeDelay => ObjectList.Count(oi => oi.ImageSources?.Length > 1) * 200 + App.Random.Next(2, 5) * 1000;
private CancellationTokenSource tknSrc_LoadThumb;
private readonly object lock_LoadThumb = new object();
public string InitialPath;
public Visibility AuxVisibility {
get { return (Visibility)GetValue(AuxVisibilityProperty); }
set { SetValue(AuxVisibilityProperty, value); }
}
public static readonly DependencyProperty AuxVisibilityProperty =
DependencyProperty.Register("AuxVisibility", typeof(Visibility), typeof(MainWindow), new PropertyMetadata(Visibility.Visible));
private VirtualizingWrapPanel virWrapPanel;
private Rect lastWindowRect;
internal Rect lastViewWindowRect;
public MainWindow()
{
InitializeComponent();
}
#region MainWindow Event Handlers
private void MainWin_Loaded(object sender, RoutedEventArgs e)
{
virWrapPanel = Helpers.GetVisualChild<VirtualizingWrapPanel>(TV1);
DpiScale = VisualTreeHelper.GetDpi(this);
Setting.ThumbnailSize.PropertyChanged += ThumbnailSizeChanged;
var view = (ListCollectionView)((CollectionViewSource)FindResource("ObjectListViewSource")).View;
view.CustomSort = new FolderSorter();
if (InitialPath?.Length > 0)
Task.Run(() => LoadPath(InitialPath));
else if (Setting.LastPath?.Length > 0)
Task.Run(() => LoadPath(Setting.LastPath));
else if (Helpers.OpenFolderDialog(this) is string path)
Task.Run(() => LoadPath(path));
}
private void ThumbnailSizeChanged(object sender, PropertyChangedEventArgs e) {
if (PropertyChanged == null) return;
if (e.PropertyName == nameof(Setting.ThumbnailSize.Item1))
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(nameof(ThumbRealWidth)));
if (e.PropertyName == nameof(Setting.ThumbnailSize.Item2))
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(nameof(ThumbRealHeight)));
}
private void MainWin_Unloaded(object sender, RoutedEventArgs e) {
Setting.StaticPropertyChanged -= ThumbnailSizeChanged;
tknSrc_LoadThumb?.Cancel();
ObjectList.Clear();
Setting.LastPath = CurrentPath;
if (WindowState != WindowState.Maximized) {
Setting.LastWindowSize = new Size(Width, Height);
}
if (Application.Current.Windows.Count == 0)
Application.Current.Shutdown();
}
private void MainWin_DpiChanged(object sender, DpiChangedEventArgs e) {
DpiScale = VisualTreeHelper.GetDpi(this);
if (PropertyChanged == null) return;
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(nameof(ThumbRealWidth)));
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(nameof(ThumbRealHeight)));
}
private void MainWin_Drop(object sender, DragEventArgs e)
{
var paths = (string[])e.Data.GetData(DataFormats.FileDrop);
if (paths == null || paths.Length == 0) return;
Task.Run(() => LoadPath(paths[0]));
}
private void TV1_MouseDown(object sender, MouseButtonEventArgs e) {
if (!e.Source.Equals(sender)) return;
if (e.ClickCount == 1 && e.ChangedButton == MouseButton.Right) {
Nav_Up(null, null);
e.Handled = true;
}
else if (e.ClickCount == 2 && e.ChangedButton == MouseButton.Left) {
if (Helpers.OpenFolderDialog(this) is string path) Task.Run(() => LoadPath(path));
e.Handled = true;
}
}
#endregion
private void Callback_AddToImageList(ObjectInfo objInfo) {
var add = true;
Dispatcher.Invoke(() => {
if (AuxVisibility == Visibility.Collapsed && (objInfo.SourcePaths == null || objInfo.SourcePaths.Length == 0))
add = false;
});
if (add) ObjectList.Add(objInfo);
}
private void clearObjectList() {
//might not need this now
foreach (var objInfo in ObjectList) {
objInfo.SourcePaths = null;
}
ObjectList.Clear();
Dispatcher.Invoke(() => virWrapPanel.ScrollOwner.ScrollToTop());
}
/// <summary>
/// Display file system objects in the path as thumbnails, or open viewer depending on the file type and parameters.
/// Main open logic is set here.
/// Support cancellation. Used in Task.
/// Flags are inferred from path. Not for opening image in an archive.
/// </summary>
internal void LoadPath(string path, ViewWindow viewWin = null) {
LoadPath(new ObjectInfo(path), viewWin);
}
/// <summary>
/// Display file system objects in the path as thumbnails, or open viewer depending on the file type and parameters.
/// Main open logic is set here.
/// Support cancellation. Used in Task.
/// </summary>
internal void LoadPath(ObjectInfo objInfo, ViewWindow viewWin = null) {
//infer path type (flags)
if (objInfo.Flags == FileFlags.Unknown)
objInfo.Flags = Helpers.GetPathType(new DirectoryInfo(objInfo.FileSystemPath));
// action based on flags
if (objInfo.Flags.HasFlag(FileFlags.Directory)) {
//directory -> load thumbs
try {
tknSrc_LoadThumb?.Cancel();
Monitor.Enter(lock_LoadThumb);
tknSrc_LoadThumb = new CancellationTokenSource();
CurrentPath = objInfo.FileSystemPath;
clearObjectList();
LoadFolder(new DirectoryInfo(objInfo.FileSystemPath), tknSrc: tknSrc_LoadThumb);
}
finally {
tknSrc_LoadThumb = null;
Monitor.Exit(lock_LoadThumb);
}
}
else if (objInfo.Flags.HasFlag(FileFlags.Archive)) {
if (objInfo.Flags.HasFlag(FileFlags.Image)) {
//image inside archive -> open viewer
LoadFile(objInfo.FileSystemPath, objInfo.Flags,
isThumb: false,
fileNames: new[] { objInfo.FileName },
cldInfoCb: oi => Dispatcher.Invoke(() => {
if (viewWin == null) new ViewWindow(this, ObjectList) { ObjectInfo = oi }.Show();
else viewWin.ObjectInfo = oi;
}));
}
else {
//archive itself -> extract and load thumbs
try {
tknSrc_LoadThumb?.Cancel();
Monitor.Enter(lock_LoadThumb);
tknSrc_LoadThumb = new CancellationTokenSource();
CurrentPath = objInfo.FileSystemPath;
clearObjectList();
LoadFile(objInfo.FileSystemPath, objInfo.Flags, cldInfoCb: Callback_AddToImageList, tknSrc: tknSrc_LoadThumb);
}
finally {
tknSrc_LoadThumb = null;
Monitor.Exit(lock_LoadThumb);
}
}
}
else if (objInfo.Flags.HasFlag(FileFlags.Image)) {
//plain image file -> open viewer
LoadFile(objInfo.FileSystemPath, objInfo.Flags,
isThumb: false,
objInfoCb: oi => Dispatcher.Invoke(() => {
if (viewWin == null) new ViewWindow(this, ObjectList) { ObjectInfo = oi }.Show();
else viewWin.ObjectInfo = oi;
}));
}
}
/// <summary>
/// Load thumbnails in folder.
/// </summary>
private void LoadFolder(DirectoryInfo dirInfo, CancellationTokenSource tknSrc = null) {
CurrentPath = dirInfo.FullName;
foreach (var childInfo in dirInfo.EnumerateFileSystemInfos()) {
if (tknSrc?.IsCancellationRequested == true) return;
//when the child is a folder
if (childInfo is DirectoryInfo childDirInfo) {
//get the first image source and image file list
IEnumerable<FileSystemInfo> childFsInfos = null;
try { childFsInfos = childDirInfo.EnumerateFileSystemInfos(); } catch { continue; }
var thumbs = new List<string>();
foreach (var fsInfo in childFsInfos) {
if (tknSrc?.IsCancellationRequested == true) return;
var fType = Helpers.GetPathType(fsInfo);
if (fType != FileFlags.Image) continue;
thumbs.Add(fsInfo.FullName);
}
//add to list
if (tknSrc?.IsCancellationRequested == true) return;
var objInfo = new ObjectInfo(childDirInfo.FullName, FileFlags.Directory, thumbs.ToArray());
Callback_AddToImageList(objInfo);
}
//when the child is a file
else {
var options = new LoadOptions(childInfo.FullName) {
Flags = Helpers.GetPathType(childInfo),
DecodeSize = (SizeInt)Setting.ThumbnailSize,
ObjInfoCallback = Callback_AddToImageList,
};
//if (options.Flags == FileFlags.Archive) options.ExtractCount = App.PreviewCount;
LoadFile(options, tknSrc);
}
}
}
/// <summary>
/// Load image based on the type of file and try passwords when possible.
/// If filePath points to an archive, LoadOptions.ExtractCount will be used to decide how many images in the archive are processed.
/// Can be called from a background thread.
/// Callback can be used to manipulate the loaded images. For e.g. display it in the ViewWindow, or add to ObjectList as thumbnails.
/// Callback is called for each image loaded.
/// Use Dispatcher if callback needs to access the UI thread.
/// <param name="flags">Only checks for Image and Archive.</param>
/// </summary>
private void LoadFile(string filePath, FileFlags flags,
bool isThumb = true, string[] fileNames = null,
Action<ObjectInfo> objInfoCb = null, Action<ObjectInfo> cldInfoCb = null,
CancellationTokenSource tknSrc = null)
{
var options = new LoadOptions(filePath) {
Flags = flags,
DecodeSize = isThumb ? (SizeInt)Setting.ThumbnailSize : default,
FileNames = fileNames,
ObjInfoCallback = objInfoCb,
CldInfoCallback = cldInfoCb,
};
LoadFile(options, tknSrc);
}
private void LoadFile(LoadOptions options, CancellationTokenSource tknSrc = null)
{
if (tknSrc?.IsCancellationRequested == true) return;
//objInfo to be returned
var objInfo = new ObjectInfo(options.FilePath, options.Flags) {
FileName = Path.GetFileName(options.FilePath)
};
//when file is an image
if (options.Flags.HasFlag(FileFlags.Image) && !options.Flags.HasFlag(FileFlags.Archive))
objInfo.SourcePaths = new[] { options.FilePath };
//when file is an archive
else if (options.Flags.HasFlag(FileFlags.Archive)) {
//some files may get loaded from cache therefore unaware of whether password is correct
//the HashSet records processed files through retries
var done = new HashSet<string>();
ImageSource[] dummy = null;
for (int caseIdx = 0; caseIdx < 4; caseIdx++) {
if (tknSrc?.IsCancellationRequested == true) break;
var success = false;
switch (caseIdx) {
//first check if there is a match in saved passwords
case 0 when Setting.MappedPasswords.TryGetValue(options.FilePath, out ObservablePair<string, string> pwd):
options.Password = pwd.Item2;
success = ExtractZip(options, objInfo, done, ref dummy, tknSrc);
break;
//then try no password
case 1:
options.Password = null;
success = ExtractZip(options, objInfo, done, ref dummy, tknSrc);
break;
//then try all saved passwords with no filename
case 2:
foreach (var fp in Setting.FallbackPasswords) {
options.Password = fp;
success = ExtractZip(options, objInfo, done, ref dummy, tknSrc);
if (success) break;
}
break;
case 3:
//if all fails mark with icon and when clicked
//prompt for a generic or dedicated password then extract with it
//-------------logic needed here-------------
objInfo.Flags |= FileFlags.Error;
objInfo.Comments = $"Extraction failed. Bad password or not supported image formats.";
break;
}
if (success) break;
}
}
if (tknSrc?.IsCancellationRequested == true) return;
options.ObjInfoCallback?.Invoke(objInfo);
}
//private static bool ExtractZip(LoadOptions options, ObjectInfo objInfo, CancellationTokenSource tknSrc = null)
//{
// if (tknSrc?.IsCancellationRequested == true) return false;
// using (var fs = new FileStream(options.FilePath, FileMode.Open, FileAccess.Read)) {
// return ExtractZip(fs, options, objInfo, tknSrc);
// }
//}
/// <summary>
/// Returns true or false based on whether extraction succeeds.
/// </summary>
private static bool ExtractZip(LoadOptions options, ObjectInfo objInfo, HashSet<string> done, ref ImageSource[] imgSources, CancellationTokenSource tknSrc = null)
{
if (tknSrc?.IsCancellationRequested == true) return false;
SevenZipExtractor ext = null;
try
{
ext = options.Password?.Length > 0 ? new SevenZipExtractor(options.FilePath, options.Password) :
new SevenZipExtractor(options.FilePath);
var isThumb = options.DecodeSize.Width + options.DecodeSize.Height > 0;
bool fromDisk = false;
//get files in archive to extract
string[] toDo;
if (options.FileNames?.Length > 0)
toDo = options.FileNames;
else
toDo = ext.ArchiveFileData
.Where(d => !d.IsDirectory && Helpers.GetPathType(d.FileName) == FileFlags.Image)
.Select(d => d.FileName).ToArray();
var sources = new List<ImageSource>();
foreach (var fileName in toDo) {
if (tknSrc?.IsCancellationRequested == true) return false;
//skip if already done
if (done.Contains(fileName)) continue;
if (options.ExtractCount > 0) {
ImageSource source = null;
var thumbPathInDb = Path.Combine(options.FilePath, fileName);
if (isThumb) {
//try load from cache
source = SQLiteHelper.GetFromThumbDB(thumbPathInDb, options.DecodeSize);
}
if (source == null) {
#if DEBUG
Console.WriteLine("Extracting " + fileName);
#endif
fromDisk = true;
//load from disk
using (var ms = new MemoryStream()) {
ext.ExtractFile(fileName, ms);
source = Helpers.GetImageSource(ms, options.DecodeSize);
}
if (isThumb && source != null) SQLiteHelper.AddToThumbDB(source, thumbPathInDb, options.DecodeSize);
}
sources.Add(source);
}
if (options.CldInfoCallback != null) {
var cldInfo = new ObjectInfo(options.FilePath, FileFlags.Image | FileFlags.Archive, new[] { fileName }) { FileName = fileName };
options.CldInfoCallback.Invoke(cldInfo);
}
done.Add(fileName);
if (done.Count >= options.ExtractCount)
break;
}
imgSources = sources.ToArray();
//update objInfo
objInfo.SourcePaths = toDo;
//save password for the future
if (fromDisk && options.Password?.Length > 0)
Setting.MappedPasswords[options.FilePath] = new ObservablePair<string, string>(options.FilePath, options.Password);
return true;
}
catch (Exception ex)
{
if (ex is ExtractionFailedException ||
ex is SevenZipArchiveException ||
ex is NotSupportedException) return false;
if (ext != null) {
ext.Dispose();
ext = null;
}
throw;
}
finally
{
if (ext != null) {
ext.Dispose();
ext = null;
}
}
}
private void TN1_Click(object sender, MouseButtonEventArgs e) {
if (e.Source.Equals(sender)) {
e.Handled = true;
var tn = (Thumbnail)sender;
var objInfo = tn.ObjectInfo;
if (e.ClickCount == 1) {
switch (e.ChangedButton) {
case MouseButton.Left:
Task.Run(() => LoadPath(objInfo));
break;
}
}
}
}
private void Nav_Up(object sender, RoutedEventArgs e) {
Task.Run(() => LoadPath(Path.GetDirectoryName(CurrentPath)));
}
private void Sidebar_Click(object sender, RoutedEventArgs e) {
switch (((FrameworkContentElement)sender).Name) {
case nameof(HY_Options):
new SettingsWindow(this).ShowDialog();
break;
case nameof(HY_ImmersionMode):
AuxVisibility = AuxVisibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
ButtonCloseVisibility = AuxVisibility;
ButtonMinVisibility = AuxVisibility;
ButtonMaxVisibility = AuxVisibility;
TitleVisibility = AuxVisibility;
//for (int i = 0; i < LB1.Items.Count; i++) {
// var thumb = (ContentPresenter)LB1.ItemContainerGenerator.ContainerFromIndex(i);
// var objInfo = (ObjectInfo)thumb.DataContext;
// if (objInfo.ImageSources == null || objInfo.ImageSources.Length == 0)
// thumb.Visibility = AuxVisibility;
//}
if (AuxVisibility == Visibility.Collapsed) {
virWrapPanel.ScrollOwner.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden;
if (WindowState == WindowState.Maximized) {
WindowState = WindowState.Normal;
lastWindowRect = new Rect(Left, Top, Width, Height);
var info = NativeHelpers.GetMonitorFromWindow(this);
Top = info.Top;
Left = info.Left;
Width = info.Width;
Height = info.Height;
}
//remove error thumbs
foreach (var item in ObjectList.Where(oi => oi.SourcePaths == null || oi.SourcePaths.Length == 0).ToArray()) {
ObjectList.Remove(item);
}
}
else {
virWrapPanel.ScrollOwner.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
if (lastWindowRect.Size.Width + lastWindowRect.Size.Height > 0) {
Top = lastWindowRect.Top;
Left = lastWindowRect.Left;
Width = lastWindowRect.Width;
Height = lastWindowRect.Height;
}
Task.Run(() => LoadPath(CurrentPath));
}
break;
}
}
private void CTM_Click(object sender, RoutedEventArgs e) {
var mi = (MenuItem)sender;
var ctm = (ContextMenu)mi.CommandParameter;
switch (mi.DataContext) {
case ObjectInfo oi:
switch (mi.Header) {
case "View in Explorer":
Helpers.Run("explorer", $"/select, \"{oi.FileSystemPath}\"");
break;
case "Open in New Window":
if (oi.Flags.HasFlag(FileFlags.Image)) {
LoadPath(oi);
}
else if (oi.Flags.HasFlag(FileFlags.Directory) ||
oi.Flags.HasFlag(FileFlags.Archive)) {
var win = new MainWindow {
InitialPath = oi.FileSystemPath
};
win.Show();
}
break;
}
break;
//case ObservablePair<string, string> op:
// Helpers.Run(op.Item1, Helpers.CustomCmdArgsReplace(op.Item2, tn.ObjectInfo));
// break;
}
}
private void CTM_Opened(object sender, RoutedEventArgs e) {
//var ctm = (ContextMenu)sender;
//var tn = (Thumbnail)ctm.PlacementTarget;
//ctm.Tag = tn.ObjectInfo.FileSystemPath;
//foreach (MenuItem item in mi.Items) {
// var op = (ObservablePair<string, string>)item.DataContext;
// item.DataContext = new ObservablePair<string, string>(op.Item1, op.Item2.Replace(@"%FileSystemPath%", tn.ObjectInfo.FileSystemPath));
//}
}
}
}