From 8e4a9d4072ad66b67c6599f8fc3cec0fb7d965c8 Mon Sep 17 00:00:00 2001 From: Ruben Date: Sun, 1 Sep 2019 18:10:01 +0200 Subject: [PATCH] Numerous bug fixes, misc stuff --- PicView/App.config | 18 +- PicView/Configs/Configs.cs | 189 ++++++-- PicView/{Misc => }/Fields.cs | 15 +- PicView/File Logic/ArchiveExtraction.cs | 166 +++++-- PicView/File Logic/Copy_Paste.cs | 18 +- PicView/File Logic/DeleteFiles.cs | 6 + PicView/File Logic/FileFunctions.cs | 6 +- PicView/File Logic/FileLists.cs | 54 +-- PicView/File Logic/Open_Save.cs | 20 +- PicView/File Logic/Wallpaper.cs | 17 +- PicView/Image Logic/ImageDecoder.cs | 31 +- PicView/Image Logic/Resize_and_Zoom.cs | 41 +- PicView/Image Logic/Scroll.cs | 4 +- PicView/Image Logic/Thumbnails.cs | 9 +- .../{Drag and Drop => }/DragAndDrop.cs | 56 +-- ...faceUtilities.cs => HideInterfaceLogic.cs} | 77 ++-- .../Instantiate/ContextMenus.cs | 123 +++-- PicView/Interface Logic/Instantiate/Timers.cs | 2 +- PicView/Interface Logic/SlideShow.cs | 9 +- PicView/Interface Logic/WindowLogic.cs | 64 ++- PicView/MainWindow.xaml | 2 +- PicView/MainWindow.xaml.cs | 97 ++-- PicView/Misc/NativeMethods.cs | 21 +- PicView/Misc/{Helper.cs => Utilities.cs} | 0 PicView/Navigation/Error_Handling.cs | 77 ++-- PicView/Navigation/LoadFromWeb.cs | 93 ++++ PicView/Navigation/Navigation.cs | 209 ++++----- PicView/{Loading => Navigation}/Preloader.cs | 41 +- PicView/PicGallery/PicGalleryLoad.cs | 83 ++++ PicView/PicGallery/PicGalleryLogic.cs | 422 ++---------------- PicView/PicGallery/PicGalleryScroll.cs | 158 +++++++ PicView/PicGallery/PicGalleryToggle.cs | 173 +++++++ PicView/PicVIew.csproj | 14 +- PicView/Properties/AssemblyInfo.cs | 2 +- PicView/Shortcuts/Shortcuts.cs | 59 ++- .../CustomControls/PicGallery.xaml.cs | 3 +- .../CustomControls/PicGalleryItem.xaml.cs | 2 +- .../Menus/QuickSettingsMenu.xaml.cs | 10 +- PicView/Windows/FakeWindow.xaml | 3 +- PicView/Windows/FakeWindow.xaml.cs | 13 +- 40 files changed, 1430 insertions(+), 977 deletions(-) rename PicView/{Misc => }/Fields.cs (96%) rename PicView/Interface Logic/{Drag and Drop => }/DragAndDrop.cs (86%) rename PicView/Interface Logic/{InterfaceUtilities.cs => HideInterfaceLogic.cs} (73%) rename PicView/Misc/{Helper.cs => Utilities.cs} (100%) create mode 100644 PicView/Navigation/LoadFromWeb.cs rename PicView/{Loading => Navigation}/Preloader.cs (91%) create mode 100644 PicView/PicGallery/PicGalleryLoad.cs create mode 100644 PicView/PicGallery/PicGalleryScroll.cs create mode 100644 PicView/PicGallery/PicGalleryToggle.cs diff --git a/PicView/App.config b/PicView/App.config index db495dfc..e7693c06 100644 --- a/PicView/App.config +++ b/PicView/App.config @@ -1,12 +1,12 @@ - + -
+
- + @@ -138,16 +138,16 @@ - - + + - - + + - - + + diff --git a/PicView/Configs/Configs.cs b/PicView/Configs/Configs.cs index 5c23a2ee..cba750c2 100644 --- a/PicView/Configs/Configs.cs +++ b/PicView/Configs/Configs.cs @@ -1,11 +1,165 @@ -using System.Windows; +using System.IO; +using System.Windows; +using System.Windows.Controls; +using static PicView.Fields; +using static PicView.FileLists; +using static PicView.Navigation; using static PicView.Scroll; +using static PicView.Tooltip; namespace PicView { internal static class Configs { + internal static void ChangeSorting(short sorting) + { + if (Properties.Settings.Default.SortPreference == sorting) + return; + + Properties.Settings.Default.SortPreference = sorting; + var tmp = Pics[FolderIndex]; + if (!string.IsNullOrWhiteSpace(tmp)) + { + Pics = FileList(Path.GetDirectoryName(tmp)); + PreloadCount = 4; + Pic(Pics.IndexOf(tmp)); + } + var sortcm = cm.Items[5] as MenuItem; + + var sort0 = sortcm.Items[0] as MenuItem; + var sort0Header = sort0.Header as RadioButton; + + var sort1 = sortcm.Items[1] as MenuItem; + var sort1Header = sort1.Header as RadioButton; + + var sort2 = sortcm.Items[2] as MenuItem; + var sort2Header = sort2.Header as RadioButton; + + var sort3 = sortcm.Items[3] as MenuItem; + var sort3Header = sort3.Header as RadioButton; + + var sort4 = sortcm.Items[4] as MenuItem; + var sort4Header = sort4.Header as RadioButton; + + var sort5 = sortcm.Items[5] as MenuItem; + var sort5Header = sort5.Header as RadioButton; + + var sort6 = sortcm.Items[6] as MenuItem; + var sort6Header = sort6.Header as RadioButton; + + switch (sorting) + { + case 0: + sort0Header.IsChecked = true; + sort1Header.IsChecked = false; + sort2Header.IsChecked = false; + sort3Header.IsChecked = false; + sort4Header.IsChecked = false; + sort5Header.IsChecked = false; + sort6Header.IsChecked = false; + break; + case 1: + sort0Header.IsChecked = false; + sort1Header.IsChecked = true; + sort2Header.IsChecked = false; + sort3Header.IsChecked = false; + sort4Header.IsChecked = false; + sort5Header.IsChecked = false; + sort6Header.IsChecked = false; + break; + case 2: + sort0Header.IsChecked = false; + sort1Header.IsChecked = false; + sort2Header.IsChecked = true; + sort3Header.IsChecked = false; + sort4Header.IsChecked = false; + sort5Header.IsChecked = false; + sort6Header.IsChecked = false; + break; + case 3: + sort0Header.IsChecked = false; + sort1Header.IsChecked = false; + sort2Header.IsChecked = false; + sort3Header.IsChecked = true; + sort4Header.IsChecked = false; + sort5Header.IsChecked = false; + sort6Header.IsChecked = false; + break; + case 4: + sort0Header.IsChecked = false; + sort1Header.IsChecked = false; + sort2Header.IsChecked = false; + sort3Header.IsChecked = false; + sort4Header.IsChecked = true; + sort5Header.IsChecked = false; + sort6Header.IsChecked = false; + break; + case 5: + sort0Header.IsChecked = false; + sort1Header.IsChecked = false; + sort2Header.IsChecked = false; + sort3Header.IsChecked = false; + sort4Header.IsChecked = false; + sort5Header.IsChecked = true; + sort6Header.IsChecked = false; + break; + case 6: + sort0Header.IsChecked = false; + sort1Header.IsChecked = false; + sort2Header.IsChecked = false; + sort3Header.IsChecked = false; + sort4Header.IsChecked = false; + sort5Header.IsChecked = false; + sort6Header.IsChecked = true; + break; + } + } + + + internal static void SetScrolling(object sender, RoutedEventArgs e) + { + var settingscm = cm.Items[6] as MenuItem; + var scrollcm = settingscm.Items[1] as MenuItem; + var scrollcmHeader = scrollcm.Header as CheckBox; + + if (Properties.Settings.Default.ScrollEnabled) + { + IsScrollEnabled = false; + scrollcmHeader.IsChecked = false; + } + else + { + IsScrollEnabled = true; + scrollcmHeader.IsChecked = true; + } + } + + internal static void SetLooping(object sender, RoutedEventArgs e) + { + var settingscm = cm.Items[6] as MenuItem; + var loopcm = settingscm.Items[0] as MenuItem; + var loopcmHeader = loopcm.Header as CheckBox; + + if (Properties.Settings.Default.Looping) + { + Properties.Settings.Default.Looping = false; + loopcmHeader.IsChecked = false; + ToolTipStyle("Looping disabled"); + } + else + { + Properties.Settings.Default.Looping = true; + loopcmHeader.IsChecked = true; + ToolTipStyle("Looping enabled"); + } + } + + internal static void SetBgColorEnabled(object sender, RoutedEventArgs e) + { + Properties.Settings.Default.WindowBorderColorEnabled = Properties.Settings.Default.WindowBorderColorEnabled ? false : true; + } + internal static void SetSlidetimer() { switch (Properties.Settings.Default.Slidetimeren.ToString("0")) @@ -71,38 +225,5 @@ internal static void SetSlidetimer() break; } } - - - internal static void SetScrolling(object sender, RoutedEventArgs e) - { - if (Properties.Settings.Default.ScrollEnabled) - { - Properties.Settings.Default.ScrollEnabled = false; - - IsScrollEnabled = false; - } - else - { - Properties.Settings.Default.ScrollEnabled = true; - IsScrollEnabled = true; - } - } - - internal static void SetLooping(object sender, RoutedEventArgs e) - { - if (Properties.Settings.Default.Looping) - { - Properties.Settings.Default.Looping = false; - } - else - { - Properties.Settings.Default.Looping = true; - } - } - - internal static void SetBgColorEnabled(object sender, RoutedEventArgs e) - { - Properties.Settings.Default.WindowBorderColorEnabled = Properties.Settings.Default.WindowBorderColorEnabled ? false : true; - } } } diff --git a/PicView/Misc/Fields.cs b/PicView/Fields.cs similarity index 96% rename from PicView/Misc/Fields.cs rename to PicView/Fields.cs index 1aef01fb..a6159213 100644 --- a/PicView/Misc/Fields.cs +++ b/PicView/Fields.cs @@ -51,13 +51,13 @@ internal static class Fields internal static MainWindow mainWindow = ((MainWindow)Application.Current.MainWindow); - /// - /// File path of current image - /// - internal static string PicPath { get; set; } + ///// + ///// File path of current image + ///// + //internal static string Pics[FolderIndex] { get; set; } /// - /// Backup of PicPath + /// Backup of Previous file, if changed folder etc. /// internal static string xPicPath; @@ -66,6 +66,11 @@ internal static class Fields /// internal static string TempZipPath { get; set; } + /// + /// File path for the extracted zip file + /// + internal static string TempZipFile { get; set; } + /// /// Returns zoom percentage. if 100%, return empty string /// diff --git a/PicView/File Logic/ArchiveExtraction.cs b/PicView/File Logic/ArchiveExtraction.cs index 223dfe7e..dc65acff 100644 --- a/PicView/File Logic/ArchiveExtraction.cs +++ b/PicView/File Logic/ArchiveExtraction.cs @@ -6,6 +6,7 @@ using static PicView.Error_Handling; using static PicView.Fields; using static PicView.Tooltip; +using static PicView.FileLists; namespace PicView { @@ -19,15 +20,20 @@ internal static class ArchiveExtraction internal static bool Extract(string path) { if (!string.IsNullOrWhiteSpace(TempZipPath)) + { +#if DEBUG + Trace.WriteLine("Extract function delete temp files"); +#endif DeleteTempFiles(); + } + var Winrar = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\WinRAR\\WinRAR.exe"; if (!File.Exists(Winrar)) Winrar = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + "\\WinRAR\\WinRAR.exe"; if (File.Exists(Winrar)) { - Extract(path, Winrar, true); - return true; + return Extract(path, Winrar, true); } var sevenZip = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\7-Zip\\7z.exe"; @@ -35,8 +41,7 @@ internal static bool Extract(string path) sevenZip = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + "\\7-Zip\\7z.exe"; if (File.Exists(sevenZip)) { - Extract(path, sevenZip, false); - return true; + return Extract(path, sevenZip, false); } return false; @@ -48,10 +53,19 @@ internal static bool Extract(string path) /// The path to the archived file /// Full path of the executeable /// If WinRar or 7-Zip - private static void Extract(string path, string exe, bool winrar) + private static bool Extract(string path, string exe, bool winrar) { - TempZipPath = Path.GetTempPath() + Path.GetRandomFileName(); - Directory.CreateDirectory(TempZipPath); +#if DEBUG + if (CreateTempDirectory(path)) + { + Trace.WriteLine("Created temp dir: " + TempZipPath); + } + else + return false; +#else + if (!CreateTempDirectory(path)) + return false; +#endif var arguments = winrar ? // Add WinRAR specifics @@ -73,9 +87,68 @@ private static void Extract(string path, string exe, bool winrar) WindowStyle = ProcessWindowStyle.Hidden #endif }); + x.EnableRaisingEvents = true; + x.Exited += delegate { + SetDirectory(); + }; + + if (x == null) + return false; + if (!x.WaitForExit(500)) + return false; - if (x == null) return; - x.WaitForExit(750); + //return SetDirectory(path); + return true; + } + + private static bool CreateTempDirectory(string path) + { + TempZipFile = path; + TempZipPath = Path.GetTempPath() + Path.GetRandomFileName(); + Directory.CreateDirectory(TempZipPath); + + return Directory.Exists(TempZipPath); + } + + private static bool SetDirectory() + { + if (string.IsNullOrEmpty(TempZipPath)) + { +#if DEBUG + Trace.WriteLine("SetDirectory empty zip path"); +#endif + return false; + } + + // Set extracted files to Pics + if (Directory.Exists(TempZipPath)) + { + var directory = Directory.GetDirectories(TempZipPath); + if (directory.Length > 0) + { + TempZipPath = directory[0]; + } + + var extractedFiles = FileList(TempZipPath); + if (extractedFiles.Count > 0) + Pics = extractedFiles; + else + return false; + + //if (Pics.Count > 0) + // Pics[FolderIndex] = Pics[0]; + //else + // return false; + + // Start at first file + FolderIndex = 0; + + // Add zipped files as recent file + RecentFiles.SetZipped(TempZipFile); + + return true; + } + return false; } /// @@ -91,48 +164,51 @@ internal static async Task RecoverFailedArchiveAsync() if (Pics.Count > 0) return true; - if (string.IsNullOrWhiteSpace(TempZipPath)) - { - // Unexped result - Reload(true); - return false; - } + mainWindow.Bar.Text = "Unzipping..."; + mainWindow.Bar.ToolTip = mainWindow.Bar.Text; + await Task.Delay(25); // TempZipPath is not null = images being extracted short count = 0; - mainWindow.Bar.Text = "Unzipping..."; do { - var processed = false; - var getProcesses = Process.GetProcessesByName("7z"); - if (getProcesses.Length > 0) - processed = true; + if (SetDirectory()) + return true; - getProcesses = Process.GetProcessesByName("Zip"); - if (getProcesses.Length > 0) - processed = true; - - if (!processed) + if (count > 3) { - Reload(true); - return false; - } + var processed = false; + var getProcesses = Process.GetProcessesByName("7z"); + if (getProcesses.Length > 0) + processed = true; - // Kill it if it's asking for password - if (!getProcesses[0].HasExited) - if (getProcesses[0].Threads[0].ThreadState == ThreadState.Wait) + if (!processed) { - ToolTipStyle("Password protected archive not supported"); - Reload(true); - getProcesses[0].Kill(); - return false; + getProcesses = Process.GetProcessesByName("Zip"); + if (getProcesses.Length > 0) + processed = true; } - if (count > 3) - { - Reload(true); - return false; + if (processed) + { + // Kill it if it's asking for password + if (!getProcesses[0].HasExited) + if (getProcesses[0].Threads[0].ThreadState == ThreadState.Wait) + { +#if DEBUG + Trace.WriteLine("Process killed"); +#endif + ToolTipStyle("Password protected archive not supported"); + //Reload(true); + getProcesses[0].Kill(); + return false; + } + } + break; + //Reload(true); + //return false; } + switch (count) { case 0: @@ -144,17 +220,23 @@ internal static async Task RecoverFailedArchiveAsync() break; case 2: - await Task.Delay(750); + await Task.Delay(950); break; default: - await Task.Delay(2500); + await Task.Delay(1500); break; } count++; } while (Pics.Count < 1); - return Directory.Exists(TempZipPath); +#if DEBUG + Trace.WriteLine("RecoverFailedArchiveAsync processed"); +#endif + + if (SetDirectory()) + return true; + return false; } } } diff --git a/PicView/File Logic/Copy_Paste.cs b/PicView/File Logic/Copy_Paste.cs index d571946e..bc6f7148 100644 --- a/PicView/File Logic/Copy_Paste.cs +++ b/PicView/File Logic/Copy_Paste.cs @@ -23,7 +23,7 @@ internal static class Copy_Paste /// internal static void CopyText() { - Clipboard.SetText(PicPath); + Clipboard.SetText(Pics[FolderIndex]); ToolTipStyle(TxtCopy); } @@ -33,13 +33,13 @@ internal static void CopyText() internal static void CopyPic() { // Copy pic if from web - if (string.IsNullOrWhiteSpace(PicPath) || Uri.IsWellFormedUriString(PicPath, UriKind.Absolute)) + if (string.IsNullOrWhiteSpace(Pics[FolderIndex]) || Uri.IsWellFormedUriString(Pics[FolderIndex], UriKind.Absolute)) { CopyBitmap(); } else { - var paths = new System.Collections.Specialized.StringCollection { PicPath }; + var paths = new System.Collections.Specialized.StringCollection { Pics[FolderIndex] }; Clipboard.SetFileDropList(paths); ToolTipStyle(FileCopy); } @@ -47,8 +47,8 @@ internal static void CopyPic() internal static void CopyBitmap() { - if (Preloader.Contains(PicPath)) - Clipboard.SetImage(Preloader.Load(PicPath)); + if (Preloader.Contains(Pics[FolderIndex])) + Clipboard.SetImage(Preloader.Load(Pics[FolderIndex])); else if (mainWindow.img.Source != null) Clipboard.SetImage((BitmapSource)mainWindow.img.Source); else @@ -75,7 +75,7 @@ internal static void Paste() var x = files[0]; // If from same folder - if (!string.IsNullOrWhiteSpace(PicPath) && Path.GetDirectoryName(x) == Path.GetDirectoryName(PicPath)) + if (!string.IsNullOrWhiteSpace(Pics[FolderIndex]) && Path.GetDirectoryName(x) == Path.GetDirectoryName(Pics[FolderIndex])) { if (!Preloader.Contains(x)) { @@ -135,13 +135,13 @@ internal static void Paste() Pics = FileList(s); if (Pics.Count > 0) Pic(Pics[0]); - else if (!string.IsNullOrWhiteSpace(PicPath)) - Pic(PicPath); + else if (!string.IsNullOrWhiteSpace(Pics[FolderIndex])) + Pic(Pics[FolderIndex]); else Unload(); } else if (Uri.IsWellFormedUriString(s, UriKind.Absolute)) // Check if from web - PicWeb(s); + LoadFromWeb.PicWeb(s); else ToolTipStyle("An error occured while trying to paste file"); } diff --git a/PicView/File Logic/DeleteFiles.cs b/PicView/File Logic/DeleteFiles.cs index 6bd95360..bd46aee9 100644 --- a/PicView/File Logic/DeleteFiles.cs +++ b/PicView/File Logic/DeleteFiles.cs @@ -22,6 +22,9 @@ internal static void DeleteTempFiles() try { Array.ForEach(Directory.GetFiles(TempZipPath), File.Delete); +#if DEBUG + Trace.WriteLine("Temp zip files deleted"); +#endif } catch (Exception) { @@ -31,6 +34,9 @@ internal static void DeleteTempFiles() try { Directory.Delete(TempZipPath); +#if DEBUG + Trace.WriteLine("Temp zip folder " + TempZipPath + " deleted"); +#endif } catch (Exception) { diff --git a/PicView/File Logic/FileFunctions.cs b/PicView/File Logic/FileFunctions.cs index 22aa311c..9ea01a01 100644 --- a/PicView/File Logic/FileFunctions.cs +++ b/PicView/File Logic/FileFunctions.cs @@ -7,14 +7,14 @@ namespace PicView class FileFunctions { - internal static bool RenameFile(string PicPath, string PicNewPath) + internal static bool RenameFile(string path, string newPath) { - if (File.Exists(PicNewPath)) + if (File.Exists(path)) return false; try { - File.Move(PicPath, PicNewPath); + File.Move(path, newPath); } catch (Exception) { diff --git a/PicView/File Logic/FileLists.cs b/PicView/File Logic/FileLists.cs index 323b43fa..a389c9aa 100644 --- a/PicView/File Logic/FileLists.cs +++ b/PicView/File Logic/FileLists.cs @@ -1,12 +1,10 @@ -using PicView.Native; -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using static PicView.ArchiveExtraction; using static PicView.Fields; -using static PicView.Error_Handling; namespace PicView { @@ -85,7 +83,7 @@ internal static List FileList(string path, SortFilesBy sortFilesBy) || file.ToLower().EndsWith("arw", StringComparison.OrdinalIgnoreCase) || file.ToLower().EndsWith("webp", StringComparison.OrdinalIgnoreCase) || file.ToLower().EndsWith("aai", StringComparison.OrdinalIgnoreCase) - || file.ToLower().EndsWith("ai", StringComparison.OrdinalIgnoreCase) + //|| file.ToLower().EndsWith("ai", StringComparison.OrdinalIgnoreCase) || file.ToLower().EndsWith("art", StringComparison.OrdinalIgnoreCase) || file.ToLower().EndsWith("bgra", StringComparison.OrdinalIgnoreCase) || file.ToLower().EndsWith("bgro", StringComparison.OrdinalIgnoreCase) @@ -253,51 +251,17 @@ internal static Task GetValues(string path) { Pics = new List(); FolderIndex = -1; - TempZipPath = string.Empty; - return; } - break; + return; } - if (zipped) - { - // Make a backup of FolderIndex and PicPath - if (FolderIndex > -1) - xFolderIndex = FolderIndex; - - if (!string.IsNullOrWhiteSpace(PicPath)) - xPicPath = PicPath; - - // Set extracted files to Pics - if (Directory.Exists(TempZipPath)) - { - // Start at first file - FolderIndex = 0; - - // Add zipped files as recent file - RecentFiles.SetZipped(path); + // Set files to Pics and get index + Pics = FileList(Path.GetDirectoryName(path)); + if (Pics == null) + return; + FolderIndex = Pics.IndexOf(path); + Pics[FolderIndex] = path; - var directory = Directory.GetDirectories(TempZipPath); - if (directory.Length > 0) - TempZipPath = directory[0]; - - Pics = FileList(TempZipPath); - if (Pics.Count > 0) - PicPath = Pics[0]; - else - Reload(true); - } - else Reload(true); - } - else - { - // Set files to Pics and get index - Pics = FileList(Path.GetDirectoryName(path)); - if (Pics == null) - return; - FolderIndex = Pics.IndexOf(path); - PicPath = path; - } }); } } diff --git a/PicView/File Logic/Open_Save.cs b/PicView/File Logic/Open_Save.cs index d9663901..421d0563 100644 --- a/PicView/File Logic/Open_Save.cs +++ b/PicView/File Logic/Open_Save.cs @@ -17,7 +17,7 @@ internal static class Open_Save /// internal static void Open_In_Explorer() { - if (!File.Exists(PicPath) || mainWindow.img.Source == null) + if (!File.Exists(Pics[FolderIndex]) || mainWindow.img.Source == null) { ToolTipStyle("Error, File does not exist, or something went wrong..."); return; @@ -26,14 +26,16 @@ internal static void Open_In_Explorer() { Close_UserControls(); ToolTipStyle(ExpFind); - Process.Start("explorer.exe", "/select,\"" + PicPath + "\""); + Process.Start("explorer.exe", "/select,\"" + Pics[FolderIndex] + "\""); } +#if DEBUG catch (InvalidCastException e) { -#if DEBUG Trace.WriteLine("Open_In_Explorer exception \n" + e.Message); -#endif } +#else + catch (InvalidCastException) { } +#endif } /// @@ -48,11 +50,7 @@ internal static void Open() }; if (dlg.ShowDialog() == true) { - Pic(dlg.FileName); - - if (string.IsNullOrWhiteSpace(PicPath)) - PicPath = dlg.FileName; } else return; @@ -68,14 +66,14 @@ internal static void SaveFiles() { Filter = FilterFiles, Title = "Save image - PicView", - FileName = Path.GetFileName(PicPath) + FileName = Path.GetFileName(Pics[FolderIndex]) }; - if (!string.IsNullOrEmpty(PicPath)) + if (!string.IsNullOrEmpty(Pics[FolderIndex])) { if (Savedlg.ShowDialog() == true) { - if (!TrySaveImage(Rotateint, Flipped, PicPath, Savedlg.FileName)) + if (!TrySaveImage(Rotateint, Flipped, Pics[FolderIndex], Savedlg.FileName)) ToolTipStyle("Error, File didn't get saved"); } else return; diff --git a/PicView/File Logic/Wallpaper.cs b/PicView/File Logic/Wallpaper.cs index 99b84e9d..e18233a6 100644 --- a/PicView/File Logic/Wallpaper.cs +++ b/PicView/File Logic/Wallpaper.cs @@ -1,5 +1,4 @@ using Microsoft.Win32; -using PicView.Native; using System; using System.ComponentModel; using System.Diagnostics; @@ -31,13 +30,15 @@ internal static void SetWallpaper(string path, WallpaperStyle style) { Task.Run(() => SetDesktopWallpaper(path, style)); } +#if DEBUG catch (Exception e) { -#if DEBUG Trace.WriteLine("Wallpaper exception \n" + e.Message); -#endif - return; + return; } +#else + catch (Exception) { return; } +#endif } } else @@ -57,13 +58,15 @@ internal static void SetWallpaper(string path, WallpaperStyle style) var timer = new Timer(2000); timer.Elapsed += (s, x) => Directory.Delete(tempPath); } +#if DEBUG catch (Exception e) { -#if DEBUG Trace.WriteLine("Wallpaper download exception \n" + e.Message); -#endif - return; + return; } +#else + catch (Exception) { return; } +#endif }); } } diff --git a/PicView/Image Logic/ImageDecoder.cs b/PicView/Image Logic/ImageDecoder.cs index 13900e07..7bad2372 100644 --- a/PicView/Image Logic/ImageDecoder.cs +++ b/PicView/Image Logic/ImageDecoder.cs @@ -121,7 +121,36 @@ internal static bool TrySaveImage(int rotate, bool flipped, string path, string internal static Size? ImageSize (string file) { - using (MagickImage magick = new MagickImage()) + var magick = new MagickImage(); + var ext = Path.GetExtension(file).ToLower(); + switch (ext) + { + // Standards + case ".jpg": + case ".jpeg": + case ".jpe": + magick.Format = MagickFormat.Jpg; + break; + case ".png": + magick.Format = MagickFormat.Png; + break; + case ".bmp": + magick.Format = MagickFormat.Bmp; + break; + case ".tif": + case ".tiff": + magick.Format = MagickFormat.Tif; + break; + case ".gif": + magick.Format = MagickFormat.Gif; + break; + case ".ico": + magick.Format = MagickFormat.Ico; + break; + default: return null; + } + + using (magick) { try { diff --git a/PicView/Image Logic/Resize_and_Zoom.cs b/PicView/Image Logic/Resize_and_Zoom.cs index 43f7dcbb..3fe6b66c 100644 --- a/PicView/Image Logic/Resize_and_Zoom.cs +++ b/PicView/Image Logic/Resize_and_Zoom.cs @@ -13,7 +13,7 @@ namespace PicView { internal static class Resize_and_Zoom - { + { // Zoom /// /// Pan and Zoom, reset zoom and double click to reset @@ -186,14 +186,14 @@ internal static void ResetZoom() isZoomed = false; // Reset size - ZoomFit(xWidth, xHeight); + TryZoomFit(); // Display non-zoomed values if (canNavigate) SetTitleString((int)mainWindow.img.Source.Width, (int)mainWindow.img.Source.Height, FolderIndex); else // Display values from web - SetTitleString((int)mainWindow.img.Source.Width, (int)mainWindow.img.Source.Height, PicPath); + SetTitleString((int)mainWindow.img.Source.Width, (int)mainWindow.img.Source.Height, Pics[FolderIndex]); } /// @@ -270,7 +270,40 @@ internal static void Zoom(int i, bool zoomMode) SetTitleString((int)mainWindow.img.Source.Width, (int)mainWindow.img.Source.Height, FolderIndex); else /// Display values from web - SetTitleString((int)mainWindow.img.Source.Width, (int)mainWindow.img.Source.Height, PicPath); + SetTitleString((int)mainWindow.img.Source.Width, (int)mainWindow.img.Source.Height, Pics[FolderIndex]); + } + + /// + /// Tries to call Zoomfit with additional error checking + /// + internal static void TryZoomFit() + { + if (freshStartup) + return; + + if (Pics != null) + { + if (Pics.Count > FolderIndex) + { + var tmp = PreLoading.Preloader.Load(Pics[FolderIndex]); + if (tmp != null) + ZoomFit(tmp.PixelWidth, tmp.PixelHeight); + else + { + var size = ImageDecoder.ImageSize(Pics[FolderIndex]); + if (size.HasValue) + ZoomFit(size.Value.Width, size.Value.Height); + else if (mainWindow.img.Source != null) + ZoomFit(mainWindow.img.Source.Width, mainWindow.img.Source.Height); + else if (xWidth != 0 && xHeight != 0) + ZoomFit(xWidth, xHeight); + } + } + } + else if (mainWindow.img.Source != null) + ZoomFit(mainWindow.img.Source.Width, mainWindow.img.Source.Height); + else if (xWidth != 0 && xHeight != 0) + ZoomFit(xWidth, xHeight); } /// diff --git a/PicView/Image Logic/Scroll.cs b/PicView/Image Logic/Scroll.cs index a73dfe15..6be6e409 100644 --- a/PicView/Image Logic/Scroll.cs +++ b/PicView/Image Logic/Scroll.cs @@ -20,9 +20,9 @@ internal static bool IsScrollEnabled { Properties.Settings.Default.ScrollEnabled = value; mainWindow.Scroller.VerticalScrollBarVisibility = value ? ScrollBarVisibility.Auto : ScrollBarVisibility.Disabled; - if (!freshStartup && !string.IsNullOrEmpty(PicPath)) + if (Pics != null) { - ZoomFit(mainWindow.img.Source.Width, mainWindow.img.Source.Height); + TryZoomFit(); ToolTipStyle(value ? "Scrolling enabled" : "Scrolling disabled"); } } diff --git a/PicView/Image Logic/Thumbnails.cs b/PicView/Image Logic/Thumbnails.cs index 9ebd3ad9..3b4350b3 100644 --- a/PicView/Image Logic/Thumbnails.cs +++ b/PicView/Image Logic/Thumbnails.cs @@ -171,13 +171,16 @@ internal static BitmapSource GetMagickImage(string file, byte quality, short siz magick.AdaptiveResize(size, size); } +#if DEBUG catch (MagickException e) { -#if DEBUG + Trace.WriteLine("GetMagickImage returned " + file + " null, \n" + e.Message); -#endif return null; - } + } +#else + catch (MagickException) { return null; } +#endif pic = magick.ToBitmapSource(); pic.Freeze(); return pic; diff --git a/PicView/Interface Logic/Drag and Drop/DragAndDrop.cs b/PicView/Interface Logic/DragAndDrop.cs similarity index 86% rename from PicView/Interface Logic/Drag and Drop/DragAndDrop.cs rename to PicView/Interface Logic/DragAndDrop.cs index 6504ec61..eb53115c 100644 --- a/PicView/Interface Logic/Drag and Drop/DragAndDrop.cs +++ b/PicView/Interface Logic/DragAndDrop.cs @@ -189,59 +189,43 @@ internal static class DragAndDrop } /// - /// Determine if supported files for drag and drop operation + /// Show image or thumbnail preview on drag enter /// /// /// - internal static void Image_DraOver(object sender, DragEventArgs e) + internal static void Image_DragEnter(object sender, DragEventArgs e) { // Error handling if (!e.Data.GetDataPresent(DataFormats.FileDrop)) return; var files = e.Data.GetData(DataFormats.FileDrop, true) as string[]; + var check = Drag_Drop_Check(files); - if (!Drag_Drop_Check(files).HasValue) - { - // Tell user drop not supported - e.Effects = DragDropEffects.None; - e.Handled = true; + // Do nothing for invalid files + if (!check.HasValue) return; - } // Tell that it's succeeded e.Effects = DragDropEffects.Copy; isDraggedOver = e.Handled = true; ToolTipStyle(DragOverString, true); - } - - /// - /// Show image or thumbnail preview on drag enter - /// - /// - /// - internal static void Image_DragEnter(object sender, DragEventArgs e) - { - // Error handling - if (!e.Data.GetDataPresent(DataFormats.FileDrop)) return; - var files = e.Data.GetData(DataFormats.FileDrop, true) as string[]; - - // Do nothing for invalid files - if (!Drag_Drop_Check(files).HasValue) - return; - // If no image, fix it to container - if (mainWindow.img.Source == null) - { - mainWindow.img.Width = mainWindow.Scroller.ActualWidth; - mainWindow.img.Height = mainWindow.Scroller.ActualHeight; - } - else + if (check.Value) { - // Save our image so we can swap back to it later if neccesary - prevPicResource = mainWindow.img.Source; - } + // If no image, fix it to container + if (mainWindow.img.Source == null) + { + mainWindow.img.Width = mainWindow.Scroller.ActualWidth; + mainWindow.img.Height = mainWindow.Scroller.ActualHeight; + } + else + { + // Save our image so we can swap back to it later if neccesary + prevPicResource = mainWindow.img.Source; + } - // Load from preloader or thumbnails - mainWindow.img.Source = Preloader.Contains(files[0]) ? Preloader.Load(files[0]) : GetBitmapSourceThumb(files[0]); + // Load from preloader or thumbnails + mainWindow.img.Source = Preloader.Contains(files[0]) ? Preloader.Load(files[0]) : GetBitmapSourceThumb(files[0]); + } } /// diff --git a/PicView/Interface Logic/InterfaceUtilities.cs b/PicView/Interface Logic/HideInterfaceLogic.cs similarity index 73% rename from PicView/Interface Logic/InterfaceUtilities.cs rename to PicView/Interface Logic/HideInterfaceLogic.cs index fc8365ca..24b3a26d 100644 --- a/PicView/Interface Logic/InterfaceUtilities.cs +++ b/PicView/Interface Logic/HideInterfaceLogic.cs @@ -1,4 +1,5 @@ -using System.Windows; +using PicView.PreLoading; +using System.Windows; using System.Windows.Input; using System.Windows.Media; using static PicView.FadeControls; @@ -13,30 +14,18 @@ internal static class HideInterfaceLogic /// /// Toggle between hidden interface and default /// - internal static void HideInterface(bool slideshow = false, bool navigationButtons = true) + internal static void ToggleInterface() { + if (Properties.Settings.Default.PicGallery == 2) + return; + // Hide interface if (Properties.Settings.Default.ShowInterface) { - mainWindow.TitleBar.Visibility = - mainWindow.LowerBar.Visibility = - mainWindow.LeftBorderRectangle.Visibility = - mainWindow.RightBorderRectangle.Visibility - = Visibility.Collapsed; - - if (navigationButtons) - clickArrowLeft.Visibility = - clickArrowRight.Visibility = - x2.Visibility = - minus.Visibility = Visibility.Visible; - else - clickArrowLeft.Visibility = - clickArrowRight.Visibility = - x2.Visibility = - minus.Visibility = Visibility.Collapsed; - - if (!slideshow || !Properties.Settings.Default.Fullscreen) - Properties.Settings.Default.ShowInterface = false; + ShowTopandBottom(false); + ShowNavigation(true); + + Properties.Settings.Default.ShowInterface = false; if (activityTimer != null) activityTimer.Start(); @@ -46,23 +35,55 @@ internal static void HideInterface(bool slideshow = false, bool navigationButton { Properties.Settings.Default.ShowInterface = true; + ShowTopandBottom(true); + ShowNavigation(false); + + if (activityTimer != null) + activityTimer.Stop(); + } + + TryZoomFit(); + + ToggleMenus.Close_UserControls(); + } + + internal static void ShowTopandBottom(bool show) + { + if (show) + { mainWindow.TitleBar.Visibility = mainWindow.LowerBar.Visibility = mainWindow.LeftBorderRectangle.Visibility = mainWindow.RightBorderRectangle.Visibility = Visibility.Visible; + } + else + { + mainWindow.TitleBar.Visibility = + mainWindow.LowerBar.Visibility = + mainWindow.LeftBorderRectangle.Visibility = + mainWindow.RightBorderRectangle.Visibility = Visibility.Collapsed; + } + } + internal static void ShowNavigation(bool show) + { + if (clickArrowLeft == null && clickArrowRight == null && x2 == null && minus == null) + return; + + if (show) + { + clickArrowLeft.Visibility = + clickArrowRight.Visibility = + x2.Visibility = + minus.Visibility = Visibility.Visible; + } + else + { clickArrowLeft.Visibility = clickArrowRight.Visibility = x2.Visibility = minus.Visibility = Visibility.Collapsed; - - if (activityTimer != null) - activityTimer.Stop(); } - if (xWidth != 0 && xHeight != 0) - ZoomFit(xWidth, xHeight); - - ToggleMenus.Close_UserControls(); } diff --git a/PicView/Interface Logic/Instantiate/ContextMenus.cs b/PicView/Interface Logic/Instantiate/ContextMenus.cs index 30a40d4b..0e2ccd5b 100644 --- a/PicView/Interface Logic/Instantiate/ContextMenus.cs +++ b/PicView/Interface Logic/Instantiate/ContextMenus.cs @@ -1,12 +1,9 @@ -using PicView.Native; -using System.IO; -using System.Windows; +using System.Windows; using System.Windows.Controls; using System.Windows.Media; using static PicView.Copy_Paste; using static PicView.DeleteFiles; using static PicView.Fields; -using static PicView.FileLists; using static PicView.Helper; using static PicView.Open_Save; using static PicView.RecentFiles; @@ -87,7 +84,7 @@ internal static void AddContextMenus() printcmIcon.Width = printcmIcon.Height = 12; printcmIcon.Fill = scbf; printcm.Icon = printcmIcon; - printcm.Click += (s, x) => Print(PicPath); + printcm.Click += (s, x) => Print(Pics[FolderIndex]); cm.Items.Add(printcm); @@ -132,106 +129,100 @@ internal static void AddContextMenus() /////////////////////////// /// File Name \\\\ /////////////////////////// - var sortcmChild0 = new RadioButton + var sortcmChild0 = new MenuItem(); + var sortcmChild0Header = new RadioButton { - Content = "File name" - }; - sortcmChild0.Click += (s, x) => - { - Properties.Settings.Default.SortPreference = 0; - if (!string.IsNullOrWhiteSpace(PicPath)) - Pics = FileList(Path.GetDirectoryName(PicPath)); + Content = "File name", + IsChecked = Properties.Settings.Default.SortPreference == 0 }; + sortcmChild0Header.Click += delegate { Configs.ChangeSorting(0); }; + sortcmChild0.Click += delegate { Configs.ChangeSorting(0); }; + sortcmChild0.Header = sortcmChild0Header; sortcm.Items.Add(sortcmChild0); /////////////////////////// /// File Size \\\\ /////////////////////////// - var sortcmChild1 = new RadioButton - { - Content = "File Size" - }; - sortcmChild1.Click += (s, x) => + var sortcmChild1 = new MenuItem(); + var sortcmChild1Header = new RadioButton { - Properties.Settings.Default.SortPreference = 1; - if (!string.IsNullOrWhiteSpace(PicPath)) - Pics = FileList(Path.GetDirectoryName(PicPath)); + Content = "File Size", + IsChecked = Properties.Settings.Default.SortPreference == 1 }; + sortcmChild1Header.Click += delegate { Configs.ChangeSorting(1); }; + sortcmChild1.Click += delegate { Configs.ChangeSorting(1); }; + sortcmChild1.Header = sortcmChild1Header; sortcm.Items.Add(sortcmChild1); /////////////////////////// - /// Creatin Time \\\\ + /// Creation Time \\\\ /////////////////////////// - var sortcmChild2 = new RadioButton + var sortcmChild2 = new MenuItem(); + var sortcmChild2Header = new RadioButton { - Content = "Creation time" - }; - sortcmChild2.Click += (s, x) => - { - Properties.Settings.Default.SortPreference = 2; - if (!string.IsNullOrWhiteSpace(PicPath)) - Pics = FileList(Path.GetDirectoryName(PicPath)); + Content = "Creation time", + IsChecked = Properties.Settings.Default.SortPreference == 2 + }; + sortcmChild2Header.Click += delegate { Configs.ChangeSorting(2); }; + sortcmChild2.Click += delegate { Configs.ChangeSorting(2); }; + sortcmChild2.Header = sortcmChild2Header; sortcm.Items.Add(sortcmChild2); /////////////////////////// /// File extension \\\\ /////////////////////////// - var sortcmChild3 = new RadioButton + var sortcmChild3 = new MenuItem(); + var sortcmChild3Header = new RadioButton { - Content = "File extension" - }; - sortcmChild3.Click += (s, x) => - { - Properties.Settings.Default.SortPreference = 3; - if (!string.IsNullOrWhiteSpace(PicPath)) - Pics = FileList(Path.GetDirectoryName(PicPath)); + Content = "File extension", + IsChecked = Properties.Settings.Default.SortPreference == 3 }; + sortcmChild3Header.Click += delegate { Configs.ChangeSorting(3); }; + sortcmChild3.Click += delegate { Configs.ChangeSorting(3); }; + sortcmChild3.Header = sortcmChild3Header; sortcm.Items.Add(sortcmChild3); /////////////////////////// /// Last Access Time \\\\ /////////////////////////// - var sortcmChild4 = new RadioButton - { - Content = "Last access time" - }; - sortcmChild4.Click += (s, x) => + var sortcmChild4 = new MenuItem(); + var sortcmChild4Header = new RadioButton { - Properties.Settings.Default.SortPreference = 4; - if (!string.IsNullOrWhiteSpace(PicPath)) - Pics = FileList(Path.GetDirectoryName(PicPath)); + Content = "Last access time", + IsChecked = Properties.Settings.Default.SortPreference == 4 }; + sortcmChild4Header.Click += delegate { Configs.ChangeSorting(4); }; + sortcmChild4.Click += delegate { Configs.ChangeSorting(4); }; + sortcmChild4.Header = sortcmChild4Header; sortcm.Items.Add(sortcmChild4); /////////////////////////// /// Last Write Time \\\\ /////////////////////////// - var sortcmChild5 = new RadioButton + var sortcmChild5 = new MenuItem(); + var sortcmChild5Header = new RadioButton { - Content = "Last write time" - }; - sortcmChild5.Click += (s, x) => - { - Properties.Settings.Default.SortPreference = 5; - if (!string.IsNullOrWhiteSpace(PicPath)) - Pics = FileList(Path.GetDirectoryName(PicPath)); + Content = "Last write time", + IsChecked = Properties.Settings.Default.SortPreference == 5 }; + sortcmChild5Header.Click += delegate { Configs.ChangeSorting(5); }; + sortcmChild5.Click += delegate { Configs.ChangeSorting(5); }; + sortcmChild5.Header = sortcmChild5Header; sortcm.Items.Add(sortcmChild5); /////////////////////////// /// Random \\\\ /////////////////////////// - var sortcmChild6 = new RadioButton - { - Content = "Random" - }; - sortcmChild6.Click += (s, x) => + var sortcmChild6 = new MenuItem(); + var sortcmChild6Header = new RadioButton { - Properties.Settings.Default.SortPreference = 6; - if (!string.IsNullOrWhiteSpace(PicPath)) - Pics = FileList(Path.GetDirectoryName(PicPath)); + Content = "Random", + IsChecked = Properties.Settings.Default.SortPreference == 6 }; + sortcmChild6Header.Click += delegate { Configs.ChangeSorting(6); }; + sortcmChild6.Click += delegate { Configs.ChangeSorting(6); }; + sortcmChild6.Header = sortcmChild6Header; sortcm.Items.Add(sortcmChild6); cm.Items.Add(sortcm); @@ -318,7 +309,7 @@ internal static void AddContextMenus() { Header = "Set as wallpaper" }; - wallcm.Click += (s, x) => SetWallpaper(PicPath, WallpaperStyle.Fill); + wallcm.Click += (s, x) => SetWallpaper(Pics[FolderIndex], WallpaperStyle.Fill); var wallcmIcon = new System.Windows.Shapes.Path { Data = Geometry.Parse(SVGiconCamera), @@ -373,7 +364,7 @@ internal static void AddContextMenus() fildecmIcon.Width = fildecmIcon.Height = 12; fildecmIcon.Fill = scbf; fildecm.Icon = fildecmIcon; - fildecm.Click += (s, x) => NativeMethods.ShowFileProperties(PicPath); + fildecm.Click += (s, x) => NativeMethods.ShowFileProperties(Pics[FolderIndex]); cm.Items.Add(fildecm); cm.Items.Add(new Separator()); @@ -414,7 +405,7 @@ internal static void AddContextMenus() cpccmIcon.Width = cpccmIcon.Height = 12; cpccmIcon.Fill = scbf; cpccm.Icon = cpccmIcon; - cpccm.Click += (s, x) => Cut(PicPath); + cpccm.Click += (s, x) => Cut(Pics[FolderIndex]); cm.Items.Add(cpccm); /////////////////////////// @@ -452,7 +443,7 @@ internal static void AddContextMenus() MovetoRecycleBinIcon.Width = MovetoRecycleBinIcon.Height = 12; MovetoRecycleBinIcon.Fill = scbf; MovetoRecycleBin.Icon = MovetoRecycleBinIcon; - MovetoRecycleBin.Click += (s, x) => DeleteFile(PicPath, true); + MovetoRecycleBin.Click += (s, x) => DeleteFile(Pics[FolderIndex], true); cm.Items.Add(MovetoRecycleBin); diff --git a/PicView/Interface Logic/Instantiate/Timers.cs b/PicView/Interface Logic/Instantiate/Timers.cs index 8a8d09e3..f98286de 100644 --- a/PicView/Interface Logic/Instantiate/Timers.cs +++ b/PicView/Interface Logic/Instantiate/Timers.cs @@ -5,7 +5,7 @@ namespace PicView { - class Timers + internal static class Timers { #region Add Timers diff --git a/PicView/Interface Logic/SlideShow.cs b/PicView/Interface Logic/SlideShow.cs index 8edd7704..e8792ac3 100644 --- a/PicView/Interface Logic/SlideShow.cs +++ b/PicView/Interface Logic/SlideShow.cs @@ -1,5 +1,4 @@ -using PicView.Native; -using System; +using System; using System.IO; using System.Windows; using System.Windows.Input; @@ -19,7 +18,7 @@ internal static class SlideShow internal static void LoadSlideshow() { Slidetimer.Interval = Properties.Settings.Default.Slidetimeren; - if (!File.Exists(PicPath)) + if (!File.Exists(Pics[FolderIndex])) { ToolTipStyle("There was no image(s) to show."); return; @@ -28,7 +27,7 @@ internal static void LoadSlideshow() if (mainWindow.WindowState == WindowState.Maximized) Maximize_Restore(); - HideInterface(false); + ToggleInterface(); mainWindow.Topmost = true; FitToWindow = false; mainWindow.Width = mainWindow.bg.Width = SystemParameters.PrimaryScreenWidth; @@ -44,7 +43,7 @@ internal static void LoadSlideshow() internal static void UnloadSlideshow() { - HideInterface(); + ToggleInterface(); mainWindow.Topmost = false; FitToWindow = true; mainWindow.bg.Width = double.NaN; diff --git a/PicView/Interface Logic/WindowLogic.cs b/PicView/Interface Logic/WindowLogic.cs index 031fb857..c68dc429 100644 --- a/PicView/Interface Logic/WindowLogic.cs +++ b/PicView/Interface Logic/WindowLogic.cs @@ -30,10 +30,13 @@ internal static bool FitToWindow if (value) { mainWindow.SizeToContent = SizeToContent.WidthAndHeight; - mainWindow.ResizeMode = ResizeMode.NoResize; + mainWindow.ResizeMode = ResizeMode.CanMinimize; if (quickSettingsMenu != null) + { quickSettingsMenu.SetFit.IsChecked = true; + quickSettingsMenu.SetCenter.IsChecked = false; + } mainWindow.WindowState = WindowState.Normal; @@ -44,11 +47,14 @@ internal static bool FitToWindow mainWindow.ResizeMode = ResizeMode.CanResizeWithGrip; if (quickSettingsMenu != null) + { quickSettingsMenu.SetCenter.IsChecked = true; + quickSettingsMenu.SetFit.IsChecked = false; + } } - if (mainWindow.img.Source != null) - ZoomFit(mainWindow.img.Source.Width, mainWindow.img.Source.Height); + // Resize it + TryZoomFit(); } } @@ -143,19 +149,17 @@ internal static void Fullscreen_Restore(bool startup = false) { if (startup || !Properties.Settings.Default.Fullscreen) { + if (!FitToWindow) + Properties.Settings.Default.Save(); + Properties.Settings.Default.Fullscreen = true; // Update new setting and sizing //FitToWindow = false; - HideInterface(false, false); - - mainWindow.TitleBar.Visibility = - mainWindow.LowerBar.Visibility = - mainWindow.LeftBorderRectangle.Visibility = - mainWindow.RightBorderRectangle.Visibility = Visibility.Collapsed; - + ShowTopandBottom(false); + ShowNavigation(false); - mainWindow.ResizeMode = ResizeMode.NoResize; + mainWindow.ResizeMode = ResizeMode.CanMinimize; mainWindow.SizeToContent = SizeToContent.Manual; mainWindow.Width = mainWindow.bg.Width = SystemParameters.PrimaryScreenWidth + 2; mainWindow.Height = SystemParameters.PrimaryScreenHeight + 2; @@ -165,19 +169,45 @@ internal static void Fullscreen_Restore(bool startup = false) mainWindow.Topmost = true; - - RemoveBorderColor(); } else { + if (FitToWindow) + { + mainWindow.SizeToContent = SizeToContent.WidthAndHeight; + mainWindow.ResizeMode = ResizeMode.NoResize; + + if (quickSettingsMenu != null) + quickSettingsMenu.SetFit.IsChecked = true; + + mainWindow.WindowState = WindowState.Normal; + + mainWindow.Width = mainWindow.bg.Width = double.NaN; + mainWindow.Height = mainWindow.bg.Height = double.NaN; + } + else + { + mainWindow.SizeToContent = SizeToContent.Manual; + mainWindow.ResizeMode = ResizeMode.CanResizeWithGrip; + + if (quickSettingsMenu != null) + quickSettingsMenu.SetCenter.IsChecked = true; + + mainWindow.Top = Properties.Settings.Default.Top; + mainWindow.Left = Properties.Settings.Default.Left; + mainWindow.Height = Properties.Settings.Default.Height; + mainWindow.Width = Properties.Settings.Default.Width; + + mainWindow.bg.Width = double.NaN; + mainWindow.bg.Height = double.NaN; + } + Properties.Settings.Default.Fullscreen = false; - FitToWindow = FitToWindow; // Just run it... - HideInterface(); + if (!Properties.Settings.Default.ShowInterface) + ToggleInterface(); - mainWindow.Width = mainWindow.bg.Width = double.NaN; - mainWindow.Height = mainWindow.bg.Height = double.NaN; mainWindow.Topmost = false; UpdateColor(); // Regain border } diff --git a/PicView/MainWindow.xaml b/PicView/MainWindow.xaml index 910c4eb5..d7f16447 100644 --- a/PicView/MainWindow.xaml +++ b/PicView/MainWindow.xaml @@ -11,7 +11,7 @@ SizeToContent="WidthAndHeight" Style="{DynamicResource MyWindowStyle}" WindowStartupLocation="CenterScreen" - ResizeMode="NoResize"> + ResizeMode="CanMinimize"> (); - freshStartup = true; - DataContext = this; + Pics = new List(); + //DataContext = this; MonitorInfo = MonitorSize.GetMonitorSize(); - if (!Properties.Settings.Default.BgColorWhite) - imgBorder.Background = new SolidColorBrush(Colors.Transparent); - // Load image if possible if (Application.Current.Properties["ArbitraryArgName"] == null) + { Unload(); + UpdateColor(); + } else + { Pic(Application.Current.Properties["ArbitraryArgName"].ToString()); - UpdateColor(); - backgroundBorderColor = (Color)Application.Current.Resources["BackgroundColorAlt"]; + if (Properties.Settings.Default.Fullscreen) + Fullscreen_Restore(true); + else + UpdateColor(); + } - // Add UserControls :) - LoadTooltipStyle(); - LoadFileMenu(); - LoadImageSettingsMenu(); - LoadQuickSettingsMenu(); - LoadFunctionsMenu(); - LoadAutoScrollSign(); LoadClickArrow(true); LoadClickArrow(false); Loadx2(); @@ -126,24 +122,12 @@ private void MainWindow_ContentRendered(object sender, EventArgs e) minus.Visibility = Visibility.Visible; } - if (Properties.Settings.Default.Fullscreen) - Fullscreen_Restore(true); - // Update UserControl values mainColor = (Color)Application.Current.Resources["MainColor"]; - quickSettingsMenu.ToggleScroll.IsChecked = IsScrollEnabled; - if (FitToWindow) - { - quickSettingsMenu.SetFit.IsChecked = true; - quickSettingsMenu.SetCenter.IsChecked = false; - } + if (!Properties.Settings.Default.BgColorWhite) + imgBorder.Background = new SolidColorBrush(Colors.Transparent); - else - { - quickSettingsMenu.SetCenter.IsChecked = true; - quickSettingsMenu.SetFit.IsChecked = false; - } - + backgroundBorderColor = (Color)Application.Current.Resources["BackgroundColorAlt"]; // Load PicGallery, if needed if (Properties.Settings.Default.PicGallery > 0) @@ -158,7 +142,29 @@ private void MainWindow_ContentRendered(object sender, EventArgs e) Panel.SetZIndex(picGallery, 999); if (Properties.Settings.Default.PicGallery == 2 && freshStartup) - PicGalleryToggle(); + PicGalleryToggle.ToggleGallery(); + } + + // Add UserControls :) + LoadTooltipStyle(); + LoadFileMenu(); + LoadImageSettingsMenu(); + LoadQuickSettingsMenu(); + LoadFunctionsMenu(); + LoadAutoScrollSign(); + + // Update UserControl values + quickSettingsMenu.ToggleScroll.IsChecked = IsScrollEnabled; + if (FitToWindow) + { + quickSettingsMenu.SetFit.IsChecked = true; + quickSettingsMenu.SetCenter.IsChecked = false; + } + + else + { + quickSettingsMenu.SetCenter.IsChecked = true; + quickSettingsMenu.SetFit.IsChecked = false; } // Initilize Things! @@ -217,12 +223,12 @@ private void AddEvents() fileMenu.Open.Click += (s, x) => Open(); fileMenu.Open_File_Location.Click += (s, x) => Open_In_Explorer(); - fileMenu.Print.Click += (s, x) => Print(PicPath); + fileMenu.Print.Click += (s, x) => Print(Pics[FolderIndex]); fileMenu.Save_File.Click += (s, x) => SaveFiles(); fileMenu.Open_Border.MouseLeftButtonUp += (s, x) => Open(); fileMenu.Open_File_Location_Border.MouseLeftButtonUp += (s, x) => Open_In_Explorer(); - fileMenu.Print_Border.MouseLeftButtonUp += (s, x) => Print(PicPath); + fileMenu.Print_Border.MouseLeftButtonUp += (s, x) => Print(Pics[FolderIndex]); fileMenu.Save_File_Location_Border.MouseLeftButtonUp += (s, x) => SaveFiles(); fileMenu.CloseButton.Click += Close_UserControls; @@ -281,9 +287,9 @@ private void AddEvents() functionsMenu.CloseButton.Click += Toggle_Functions_menu; functionsMenu.Help.Click += (s, x) => HelpWindow(); functionsMenu.About.Click += (s, x) => AboutWindow(); - functionsMenu.FileDetailsButton.Click += (s, x) => NativeMethods.ShowFileProperties(PicPath); - functionsMenu.DeleteButton.Click += (s, x) => DeleteFile(PicPath, true); - functionsMenu.DeletePermButton.Click += (s, x) => DeleteFile(PicPath, false); + functionsMenu.FileDetailsButton.Click += (s, x) => NativeMethods.ShowFileProperties(Pics[FolderIndex]); + functionsMenu.DeleteButton.Click += (s, x) => DeleteFile(Pics[FolderIndex], true); + functionsMenu.DeletePermButton.Click += (s, x) => DeleteFile(Pics[FolderIndex], false); functionsMenu.ReloadButton.Click += (s, x) => Reload(); functionsMenu.ResetZoomButton.Click += (s, x) => ResetZoom(); functionsMenu.ClearButton.Click += (s, x) => Unload(); @@ -323,7 +329,6 @@ private void AddEvents() // bg bg.MouseLeftButtonDown += Bg_MouseLeftButtonDown; bg.Drop += Image_Drop; - bg.DragOver += Image_DraOver; bg.DragEnter += Image_DragEnter; bg.DragLeave += Image_DragLeave; @@ -406,13 +411,13 @@ protected override void OnRenderSizeChanged(SizeChangedInfo size) // Move cursor after resize when the button has been pressed if (RightbuttonClicked) { - Point p = RightButton.PointToScreen(new Point(50, 30)); //Points cursor to center of RighButton + Point p = RightButton.PointToScreen(new Point(50, 10)); //Points cursor to center of RighButton NativeMethods.SetCursorPos((int)p.X, (int)p.Y); RightbuttonClicked = false; } else if (LeftbuttonClicked) { - Point p = LeftButton.PointToScreen(new Point(50, 30)); + Point p = LeftButton.PointToScreen(new Point(50, 10)); NativeMethods.SetCursorPos((int)p.X, (int)p.Y); LeftbuttonClicked = false; } @@ -447,7 +452,7 @@ private void Window_Closing(object sender, CancelEventArgs e) Hide(); // Make it feel faster - if (!Properties.Settings.Default.FitToWindow) + if (!Properties.Settings.Default.FitToWindow && !Properties.Settings.Default.Fullscreen) { Properties.Settings.Default.Top = Top; Properties.Settings.Default.Left = Left; diff --git a/PicView/Misc/NativeMethods.cs b/PicView/Misc/NativeMethods.cs index eccf031c..38ca84c1 100644 --- a/PicView/Misc/NativeMethods.cs +++ b/PicView/Misc/NativeMethods.cs @@ -2,16 +2,17 @@ using System.Runtime.InteropServices; using System.Security; -namespace PicView.Native +namespace PicView { //https://msdn.microsoft.com/en-us/library/ms182161.aspx [SuppressUnmanagedCodeSecurity] internal static class NativeMethods { - + // Alphanumeric sort [DllImport("shlwapi.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] internal static extern int StrCmpLogicalW(string x, string y); + // Change cursor position [DllImport("User32.dll")] internal static extern bool SetCursorPos(int x, int y); @@ -67,13 +68,19 @@ internal struct SHELLEXECUTEINFO public IntPtr hProcess; } - [DllImport("shell32.dll", CharSet = CharSet.Auto, SetLastError = true)] - public static extern void SHChangeNotify(uint wEventId, uint uFlags, IntPtr dwItem1, IntPtr dwItem2); + //[DllImport("shell32.dll", CharSet = CharSet.Auto, SetLastError = true)] + //public static extern void SHChangeNotify(uint wEventId, uint uFlags, IntPtr dwItem1, IntPtr dwItem2); + + // Remove from Alt + tab + [DllImport("user32.dll", SetLastError = true)] + internal static extern int GetWindowLong(IntPtr hWnd, int nIndex); + [DllImport("user32.dll")] + internal static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); + internal const int GWL_EX_STYLE = -20; + internal const int WS_EX_APPWINDOW = 0x00040000, WS_EX_TOOLWINDOW = 0x00000080; - /// - /// Used to disable Screensaver and Power options. - /// + // Disable Screensaver and Power options. internal const uint ES_CONTINUOUS = 0x80000000; internal const uint ES_SYSTEM_REQUIRED = 0x00000001; internal const uint ES_DISPLAY_REQUIRED = 0x00000002; diff --git a/PicView/Misc/Helper.cs b/PicView/Misc/Utilities.cs similarity index 100% rename from PicView/Misc/Helper.cs rename to PicView/Misc/Utilities.cs diff --git a/PicView/Navigation/Error_Handling.cs b/PicView/Navigation/Error_Handling.cs index fecee371..1ed08f7d 100644 --- a/PicView/Navigation/Error_Handling.cs +++ b/PicView/Navigation/Error_Handling.cs @@ -2,6 +2,7 @@ using System; using System.Diagnostics; using System.IO; +using System.Threading.Tasks; using System.Windows.Media.Imaging; using static PicView.AjaxLoader; using static PicView.DeleteFiles; @@ -22,55 +23,56 @@ internal static class Error_Handling /// Attemps to fix erros and prevent crashes /// /// The index to start from - internal static bool PicErrorFix(int x) + internal static async Task PicErrorFix(int x) { + BitmapSource pic = null; #if DEBUG Trace.WriteLine("Entered PicErrorFix"); // We don't want to go in here #endif if (Pics == null) { Reload(true); - return false; + return null; } if (Pics.Count < 0) { ToolTipStyle("Unexpected error", true, TimeSpan.FromSeconds(3)); Unload(); - return false; + return null; } else if (x >= Pics.Count) { if (Pics.Count > 0) { - Pic(Pics[0]); - return true; + if (x < Pics.Count) + { + await Task.Run(() => pic = RenderToBitmapSource(Pics[x])); + if (pic != null) + return pic; + } } else { Unload(); - return false; + return null; } } else if (x < 0) { - var img = RenderToBitmapSource(PicPath); - if (img != null) - { - Pic(PicPath); - return true; - } - + await Task.Run(() => pic = RenderToBitmapSource(Pics[FolderIndex])); + if (pic != null) + return pic; else { - Pics = FileList(Path.GetDirectoryName(PicPath)); - Pics.Remove(PicPath); + Pics = FileList(Path.GetDirectoryName(Pics[FolderIndex])); + Pics.Remove(Pics[FolderIndex]); x--; if (x < 0) { Unload(); - return false; + return null; } } } @@ -81,20 +83,17 @@ internal static bool PicErrorFix(int x) { ToolTipStyle("Unexpected error", true, TimeSpan.FromSeconds(3)); Unload(); - return false; + return null; } // Retry if exists, fixes rare error if (File.Exists(file)) { - //Preloader.Add(file); - BitmapSource pic = Preloader.Load(file); + await Task.Run(() => pic = RenderToBitmapSource(file)); if (pic != null) - { - Pic(file); - return true; - } - return false; + return pic; + + return null; } // Continue to remove file if can't be rendered @@ -105,7 +104,8 @@ internal static bool PicErrorFix(int x) { ToolTipStyle("No images in folder", true, TimeSpan.FromSeconds(3)); Unload(); - return false; + + return null; } // Go to next image @@ -120,8 +120,8 @@ internal static bool PicErrorFix(int x) AjaxLoadingEnd(); // Repeat process if the next image was not found - PicErrorFix(FolderIndex); - return false; + await PicErrorFix(FolderIndex); + return null; } @@ -129,8 +129,18 @@ internal static bool PicErrorFix(int x) /// /// Clears data, to free objects no longer necessary to store in memory and allow changing folder without error. /// - internal static void ChangeFolder() + internal static void ChangeFolder(bool backup = false) { + if (backup) + { + // Make a backup of xPicPath and FolderIndex + if (!string.IsNullOrWhiteSpace(Pics[FolderIndex])) + xPicPath = Pics[FolderIndex]; + + if (FolderIndex > -1) + xFolderIndex = FolderIndex; + } + Pics.Clear(); Preloader.Clear(); DeleteTempFiles(); @@ -152,12 +162,20 @@ internal static void Reload(bool fromBackup = false) return; } - var x = fromBackup ? xPicPath : PicPath; + var x = fromBackup ? xPicPath : Pics[FolderIndex]; if (File.Exists(x)) { // Force reloading values by setting freshStartup to true freshStartup = true; + + // Clear Preloader, to avoid errors by FolderIndex changing location because of re-sorting + Preloader.Clear(); + + // Need a sort method instead + PicGalleryLogic.Clear(); + PicGalleryLoad.Load(); + Pic(x); // Reset @@ -189,7 +207,6 @@ internal static void Unload() Pics.Clear(); PreloadCount = 0; Preloader.Clear(); - PicPath = string.Empty; FolderIndex = 0; mainWindow.img.Width = mainWindow.Scroller.Width = mainWindow.Scroller.Height = mainWindow.img.Height = double.NaN; diff --git a/PicView/Navigation/LoadFromWeb.cs b/PicView/Navigation/LoadFromWeb.cs new file mode 100644 index 00000000..7b9db00e --- /dev/null +++ b/PicView/Navigation/LoadFromWeb.cs @@ -0,0 +1,93 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Net; +using System.Threading.Tasks; +using System.Windows.Media.Imaging; +using System.Windows.Threading; +using static PicView.AjaxLoader; +using static PicView.Error_Handling; +using static PicView.Fields; +using static PicView.ImageDecoder; +using static PicView.SetTitle; +using static PicView.Thumbnails; +using static PicView.Tooltip; +using static PicView.Navigation; + +namespace PicView +{ + internal static class LoadFromWeb + { + /// + /// Attemps to download image and display it + /// + /// + internal static async void PicWeb(string path) + { + if (ajaxLoading.Opacity != 1) + AjaxLoadingStart(); + + mainWindow.Bar.Text = Loading; + + BitmapSource pic; + try + { + pic = await LoadImageWebAsync(path); + } +#if DEBUG + catch (Exception e) + { + Trace.WriteLine("PicWeb caught exception, message = " + e.Message); + pic = null; + } +#else + catch (Exception) { pic = null; } +#endif + if (pic == null) + { + Reload(true); + ToolTipStyle("Unable to load image"); + AjaxLoadingEnd(); + return; + } + + Pic(pic, path); + Pics[FolderIndex] = path; + RecentFiles.Add(path); + canNavigate = false; + } + + /// + /// Downloads image from web and returns as BitmapSource + /// + /// + /// + internal static async Task LoadImageWebAsync(string address) + { + canNavigate = false; + BitmapSource pic = null; + await Task.Run(async () => + { + var client = new WebClient(); + client.DownloadProgressChanged += (sender, e) => + mainWindow.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => + { + mainWindow.Title = mainWindow.Bar.Text = e.BytesReceived + "/" + e.TotalBytesToReceive + ". " + e.ProgressPercentage + "% complete..."; + mainWindow.Bar.ToolTip = mainWindow.Title; + })); + client.DownloadDataCompleted += (sender, e) => + mainWindow.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => + { + if (pic != null) + SetTitleString(pic.PixelWidth, pic.PixelHeight, address); + canNavigate = false; + })); + + var bytes = await client.DownloadDataTaskAsync(new Uri(address)); + var stream = new MemoryStream(bytes); + pic = GetMagickImage(stream); + }); + return pic; + } + } +} diff --git a/PicView/Navigation/Navigation.cs b/PicView/Navigation/Navigation.cs index 5ba435fd..52657ece 100644 --- a/PicView/Navigation/Navigation.cs +++ b/PicView/Navigation/Navigation.cs @@ -1,14 +1,11 @@ using PicView.PreLoading; using System; using System.IO; -using System.Net; using System.Threading.Tasks; using System.Windows.Media; using System.Windows.Media.Imaging; -using System.Windows.Threading; using static PicView.AjaxLoader; using static PicView.ArchiveExtraction; -using static PicView.DeleteFiles; using static PicView.Error_Handling; using static PicView.Fields; using static PicView.FileLists; @@ -24,6 +21,7 @@ namespace PicView { internal static class Navigation { + #region Update Pic /// /// Loads a picture from a given file path and does extra error checking /// @@ -33,38 +31,36 @@ internal static async void Pic(string path) // Set Loading mainWindow.Title = mainWindow.Bar.Text = Loading; mainWindow.Bar.ToolTip = Loading; - if (mainWindow.img.Source == null) + //if (mainWindow.img.Source == null) AjaxLoadingStart(); // Handle if from web if (!File.Exists(path)) { if (Uri.IsWellFormedUriString(path, UriKind.Absolute)) - PicWeb(path); + LoadFromWeb.PicWeb(path); else Unload(); return; } // If count not correct or just started, get values - if (Pics == null) - await GetValues(path); - else if (Pics.Count <= FolderIndex || FolderIndex < 0 || freshStartup) + if (Pics.Count <= FolderIndex || FolderIndex < 0 || freshStartup) await GetValues(path); // If the file is in the same folder, navigate to it. If not, start manual loading procedure. - else if (!string.IsNullOrWhiteSpace(PicPath) && Path.GetDirectoryName(path) != Path.GetDirectoryName(PicPath)) + else if (!string.IsNullOrWhiteSpace(Pics[FolderIndex]) && Path.GetDirectoryName(path) != Path.GetDirectoryName(Pics[FolderIndex])) { - // Reset zipped values - if (!string.IsNullOrWhiteSpace(TempZipPath)) - { - DeleteTempFiles(); - TempZipPath = string.Empty; - RecentFiles.SetZipped(string.Empty, false); - } + //// Reset zipped values + //if (!string.IsNullOrWhiteSpace(TempZipPath)) + //{ + // DeleteTempFiles(); + // TempZipPath = string.Empty; + // RecentFiles.SetZipped(string.Empty, false); + //} // Reset old values and get new - ChangeFolder(); + ChangeFolder(true); await GetValues(path); } @@ -80,10 +76,13 @@ internal static async void Pic(string path) var recovery = await RecoverFailedArchiveAsync(); if (!recovery) { - ToolTipStyle("Archive could not be processed"); + if (sexyToolTip.Opacity == 0) + ToolTipStyle("Archive could not be processed"); + Reload(true); return; } + mainWindow.Focus(); } } else @@ -104,16 +103,13 @@ internal static async void Pic(string path) { Reload(true); return; - } - - - AjaxLoadingEnd(); + } // Load images for PicGallery if enabled if (Properties.Settings.Default.PicGallery > 0) { - if (!PicGalleryLogic.LoadComplete && !PicGalleryLogic.isLoading) - await PicGalleryLogic.Load(); + if (!PicGalleryLogic.IsLoading) + await PicGalleryLoad.Load(); } if (prevPicResource != null) @@ -122,13 +118,14 @@ internal static async void Pic(string path) /// /// Loads image based on overloaded int. - /// Possible out of range error if used inappropriately. /// - /// + /// The index of file to load from Pics internal static async void Pic(int x) { + BitmapSource pic; + // Additional error checking - if (Pics.Count < x) + if (Pics.Count <= x) { if (x == 0) { @@ -141,24 +138,32 @@ internal static async void Pic(int x) } } - else if (!File.Exists(Pics[x])) - PicErrorFix(x); - else + // Untested code + pic = await PicErrorFix(x); + if (pic == null) + { Reload(true); - return; + return; + } } if (x < 0) { - if (!PicErrorFix(x)) - return; + pic = await PicErrorFix(x); + } + //if (!canNavigate) + //{ + // Reload(true); + // return; + //} + else + { + // Add "pic" as local variable used for the image. + // Use the Load() function load image from memory if available + // if not, it will be null + pic = Preloader.Load(Pics[x]); } - // Add "pic" as local variable used for the image. - // Use the Load() function load image from memory if available - // if not, it will be null - BitmapSource pic = Preloader.Load(Pics[x]); - if (pic == null) { mainWindow.Title = mainWindow.Bar.Text = Loading; @@ -206,13 +211,19 @@ internal static async void Pic(int x) // If pic is still null, image can't be rendered if (pic == null) { - if (!PicErrorFix(x)) + // Attempt to load new image + pic = await PicErrorFix(x); + if (pic == null) { - // Fixes error when Skipping to last or first pic - await Task.Run(() => pic = RenderToBitmapSource(Pics[x])); - if (pic == null) - Reload(true); - //return; + Pics.RemoveAt(x); + if (Pics.Count <= 0) + { + Unload(); + return; + } + + Pic(reverse); + return; } } } @@ -233,40 +244,32 @@ internal static async void Pic(int x) // Update values canNavigate = true; SetTitleString(pic.PixelWidth, pic.PixelHeight, x); - PicPath = Pics[x]; - FolderIndex = x; - AjaxLoadingEnd(); - Progress(x, Pics.Count); + //Pics[FolderIndex] = Pics[x]; + FolderIndex = x; - if (picGallery != null) + // Preload images \\ + if (Preloader.StartPreload()) { - if (!freshStartup) - if (PicGalleryLogic.LoadComplete) - PicGalleryLogic.ScrollTo(); - - //if (x < picGallery.Container.Children.Count) - //{ - // var item = picGallery.Container.Children[x] as PicGalleryItem; - // item.Setselected(true); - - // var y = reverse ? x - 1 : x + 1; - // var previtem = picGallery.Container.Children[y] as PicGalleryItem; - // previtem.Setselected(false); - //} + Preloader.Add(pic, Pics[FolderIndex]); + await Preloader.PreLoad(x); + // Update if changed file list size + if (PreloadCount == 4 && FolderIndex == x) + SetTitleString(pic.PixelWidth, pic.PixelHeight, x); } - // Preload images \\ - if (Preloader.StartPreload()) + if (picGallery != null) { - Preloader.Add(pic, PicPath); - await Preloader.PreLoad(x); + if (!PicGalleryLogic.IsLoading) + PicGalleryScroll.ScrollTo(); } - + + Progress(x, Pics.Count); if (!freshStartup) RecentFiles.Add(Pics[x]); - + + AjaxLoadingEnd(); freshStartup = false; } @@ -290,11 +293,15 @@ internal static void Pic(BitmapSource pic, string imageName) SetTitleString(pic.PixelWidth, pic.PixelHeight, imageName); NoProgress(); - PicPath = string.Empty; + Pics[FolderIndex] = string.Empty; canNavigate = false; } + #endregion + + #region Change Image + /// /// Goes to next, previous, first or last file in folder /// @@ -320,10 +327,9 @@ internal static void Pic(bool next = true, bool end = false) { FolderIndex = next ? Pics.Count - 1 : 0; if (Pics.Count > 20) - { - PreloadCount = 4; Preloader.Clear(); - } + + PreloadCount = 4; } // Go to next or previous else @@ -418,63 +424,6 @@ internal static void FastPicUpdate() Pic(FolderIndex); } - /// - /// Attemps to download image and display it - /// - /// - internal static async void PicWeb(string path) - { - if (ajaxLoading.Opacity != 1) - AjaxLoadingStart(); - - mainWindow.Bar.Text = Loading; - - BitmapSource pic; - try - { - pic = await LoadImageWebAsync(path); - } - catch (Exception) - { - pic = null; - } - - if (pic == null) - { - Reload(true); - ToolTipStyle("Unable to load image"); - AjaxLoadingEnd(); - return; - } - - Pic(pic, path); - PicPath = path; - RecentFiles.Add(path); - } - - /// - /// Downloads image from web and returns as BitmapSource - /// - /// - /// - internal static async Task LoadImageWebAsync(string address) - { - BitmapSource pic = null; - await Task.Run(async () => - { - var client = new WebClient(); - client.DownloadProgressChanged += (sender, e) => - mainWindow.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => - { - mainWindow.Title = mainWindow.Bar.Text = e.BytesReceived + "/" + e.TotalBytesToReceive + ". " + e.ProgressPercentage + "% complete..."; - mainWindow.Bar.ToolTip = mainWindow.Title; - })); - - var bytes = await client.DownloadDataTaskAsync(new Uri(address)); - var stream = new MemoryStream(bytes); - pic = GetMagickImage(stream); - }); - return pic; - } + #endregion } } diff --git a/PicView/Loading/Preloader.cs b/PicView/Navigation/Preloader.cs similarity index 91% rename from PicView/Loading/Preloader.cs rename to PicView/Navigation/Preloader.cs index 521d51bf..56d3dbd3 100644 --- a/PicView/Loading/Preloader.cs +++ b/PicView/Navigation/Preloader.cs @@ -1,8 +1,6 @@ -using System; -using System.Collections.Concurrent; +using System.Collections.Concurrent; using System.Diagnostics; using System.IO; -using System.Linq; using System.Threading.Tasks; using System.Windows.Media.Imaging; using static PicView.Fields; @@ -100,14 +98,11 @@ internal static void Add(int i) else { Pics.Remove(Pics[i]); + IsLoading = false; #if DEBUG Trace.WriteLine("Preloader removed = " + Pics[i] + " from Pics, index " + i); #endif - IsLoading = false; } - - - } internal static void Add(BitmapSource bmp, string key) @@ -120,7 +115,15 @@ internal static void Add(BitmapSource bmp, string key) return; if (!bmp.IsFrozen) bmp.Freeze(); +#if DEBUG + if (Sources.TryAdd(key, bmp)) + Trace.WriteLine("Manually added = " + key + " to Preloader, index " + Pics.IndexOf(key)); + else + Trace.WriteLine("Preloader failed to add = " + key + " , index " + Pics.IndexOf(key)); +#else Sources.TryAdd(key, bmp); +#endif + } /// @@ -135,11 +138,15 @@ internal static void Remove(string key) return; _ = Sources[key]; - Sources.TryRemove(key, out _); - #if DEBUG - Trace.WriteLine("Removed = " + key + " from Preloader, index " + Pics.IndexOf(key)); + if (Sources.TryRemove(key, out _)) + Trace.WriteLine("Removed = " + key + " from Preloader, index " + Pics.IndexOf(key)); + else + Trace.WriteLine("Failed to Remove = " + key + " from Preloader, index " + Pics.IndexOf(key)); +#else + Sources.TryRemove(key, out _); #endif + //GC.Collect(); // Need to force this, else too high memory usage? } /// @@ -183,9 +190,7 @@ internal static void Clear(string[] array) { for (int i = 0; i < array.Length; i++) { - Remove(array[i]); - GC.Collect(); - + Remove(array[i]); #if DEBUG Trace.WriteLine("Removed = " + array[i] + " from Preloader"); #endif @@ -240,7 +245,6 @@ internal static Task PreLoad(int index) var extraToLoad = 3; var cleanUp = toLoad + extraToLoad; - // Not looping if (!Properties.Settings.Default.Looping) { @@ -374,9 +378,16 @@ internal static Task PreLoad(int index) IsLoading = false; // Fixes loading erros // Update Pics if needed - var tmp = FileList(Path.GetDirectoryName(PicPath)); + var tmp = FileList(Path.GetDirectoryName(Pics[index])); if (tmp.Count != Pics.Count) + { Pics = tmp; + PreloadCount = 4; // Prevent possible loading errors +#if DEBUG + Trace.WriteLine("Preloader changed Pics filelist."); +#endif + } + }); } } diff --git a/PicView/PicGallery/PicGalleryLoad.cs b/PicView/PicGallery/PicGalleryLoad.cs new file mode 100644 index 00000000..3c7a90c2 --- /dev/null +++ b/PicView/PicGallery/PicGalleryLoad.cs @@ -0,0 +1,83 @@ +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using static PicView.Fields; +using static PicView.HideInterfaceLogic; +using static PicView.PicGalleryLogic; +using static PicView.PicGalleryScroll; +using static PicView.Thumbnails; + + + +namespace PicView +{ + internal static class PicGalleryLoad + { + internal static void PicGallery_Loaded(object sender, RoutedEventArgs e) + { + picGallery.Scroller.PreviewMouseWheel += ScrollTo; + picGallery.Scroller.MouseDown += (s, x) => mainWindow.Focus(); + picGallery.grid.MouseLeftButtonDown += (s, x) => mainWindow.Focus(); + + IsLoading = IsOpen = false; + } + + internal static void LoadLayout() + { + if (Properties.Settings.Default.PicGallery == 1) + { + if (Properties.Settings.Default.ShowInterface) + { + picGallery.Width = mainWindow.Width - 15; + picGallery.Height = mainWindow.ActualHeight - 78; + } + else + { + picGallery.Width = mainWindow.Width - 2; + picGallery.Height = mainWindow.Height - 2; // 2px for borders + } + + picGallery.HorizontalAlignment = HorizontalAlignment.Stretch; + picGallery.Scroller.HorizontalScrollBarVisibility = ScrollBarVisibility.Visible; + picGallery.Scroller.VerticalScrollBarVisibility = ScrollBarVisibility.Disabled; + picGallery.x2.Visibility = Visibility.Visible; + picGallery.Container.Margin = new Thickness(0, 65, 0, 0); + } + else + { + picGallery.Width = picGalleryItem_Size + 19; // 17 for scrollbar width + 2 for borders + picGallery.Height = MonitorInfo.Height; + picGallery.HorizontalAlignment = HorizontalAlignment.Right; + picGallery.Scroller.HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; + picGallery.Scroller.VerticalScrollBarVisibility = ScrollBarVisibility.Visible; + picGallery.x2.Visibility = Visibility.Collapsed; + picGallery.Container.Margin = new Thickness(0, 0, 0, 0); + ShowNavigation(true); + ShowTopandBottom(false); + } + + picGallery.Visibility = Visibility.Visible; + picGallery.Opacity = 1; + picGallery.Container.Orientation = Orientation.Vertical; + } + + internal static Task Load() + { + IsLoading = true; + return Task.Run(() => + { + for (int i = 0; i < Pics.Count; i++) + { + var pic = GetBitmapSourceThumb(Pics[i]); + if (pic != null) + { + pic.Freeze(); + Add(pic, i); + } + } + IsLoading = false; + }); + } + + } +} diff --git a/PicView/PicGallery/PicGalleryLogic.cs b/PicView/PicGallery/PicGalleryLogic.cs index 2c27a99b..58961df5 100644 --- a/PicView/PicGallery/PicGalleryLogic.cs +++ b/PicView/PicGallery/PicGalleryLogic.cs @@ -1,375 +1,28 @@ using PicView.PreLoading; using PicView.UserControls; -using PicView.Windows; using System; -using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; -using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Imaging; using System.Windows.Threading; using static PicView.Fields; using static PicView.ImageDecoder; -using static PicView.HideInterfaceLogic; using static PicView.Navigation; +using static PicView.PicGalleryScroll; using static PicView.Thumbnails; -using static PicView.WindowLogic; namespace PicView { internal static class PicGalleryLogic { + internal static bool IsLoading; - #region Fields + internal static volatile bool IsOpen; - internal static bool LoadComplete, isLoading, IsOpen; - - internal const int picGalleryItem_Size = 230; - internal const int picGalleryItem_Size_s = 200; - - public static int Horizontal_items - { - get - { - if (picGallery == null) return 0; - return (int)Math.Floor(picGallery.Width / picGalleryItem_Size); - } - set { } - } - - public static int Vertical_items - { - get - { - if (picGallery == null) return 0; - return Properties.Settings.Default.PicGallery == 1 ? - (int)Math.Floor(picGallery.Height / picGalleryItem_Size) : - Pics.Count; - } - set { } - } - - public static int Items_per_page - { - get - { - if (picGallery == null) return 0; - return Properties.Settings.Default.PicGallery == 1 ? - Horizontal_items * Vertical_items : - (int)Math.Floor(picGallery.Height / picGalleryItem_Size); - } - set { } - } - - public static int Current_page - { - get - { - return (int)Math.Floor((double)FolderIndex / Items_per_page); - } - set { } - } - - public static int Total_pages - { - get - { - return (int)Math.Floor((double)Pics.Count / Items_per_page); - } - set { } - } - - #endregion - - #region Scroll - - /// - /// Scrolls to center of current item - /// - /// The index of picGalleryItem - internal static void ScrollTo() - { - if (Properties.Settings.Default.PicGallery == 1) - picGallery.Scroller.ScrollToHorizontalOffset((picGalleryItem_Size * Horizontal_items) * Current_page); - else - picGallery.Scroller.ScrollToVerticalOffset((picGalleryItem_Size * Items_per_page) * Current_page); - } - - private static void Scroller_MouseWheel(object sender, MouseWheelEventArgs e) - { - if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control) - ScrollTo(e.Delta > 0); - else - ScrollTo(e.Delta > 0, false); - } - - /// - /// Scrolls a page back or forth - /// - /// - /// - internal static void ScrollTo(bool next, bool end = false, bool speedUp = false, bool animate = false) - { - if (end) - { - if (next) - picGallery.Scroller.ScrollToRightEnd(); - else - picGallery.Scroller.ScrollToLeftEnd(); - } - else - { - var speed = speedUp ? picGalleryItem_Size * 4.7 : picGalleryItem_Size; - var direction = next ? picGallery.Scroller.HorizontalOffset - speed : picGallery.Scroller.HorizontalOffset + speed; - - if (Properties.Settings.Default.PicGallery == 1) - { - if (animate) - { - //var anim = new DoubleAnimation - //{ - // From = Scroller.HorizontalOffset, - // To = direction, - // Duration = TimeSpan.FromSeconds(.3), - // AccelerationRatio = 0.2, - // DecelerationRatio = 0.4 - //}; - - //var sb = new Storyboard(); - //sb.Children.Add(anim); - //Storyboard.SetTarget(anim, Scroller); - //Storyboard.SetTargetProperty(anim, new PropertyPath(ScrollAnimationBehavior.VerticalOffsetProperty)) - } - else - { - picGallery.Scroller.ScrollToHorizontalOffset(direction); - } - } - else - { - if (animate) - { - //DoubleAnimation verticalAnimation = new DoubleAnimation - //{ - // From = scrollViewer.VerticalOffset, - // To = some - //}; - //value; - //verticalAnimation.Duration = new Duration(some duration); - - //Storyboard storyboard = new Storyboard(); - - //storyboard.Children.Add(verticalAnimation); - //Storyboard.SetTarget(verticalAnimation, scrollViewer); - //Storyboard.SetTargetProperty(verticalAnimation, new PropertyPath(ScrollAnimationBehavior.VerticalOffsetProperty)); // Attached dependency property - //storyboard.Begin(); - } - else - { - if (next) - picGallery.Scroller.ScrollToVerticalOffset(picGallery.Scroller.VerticalOffset - speed); - else - picGallery.Scroller.ScrollToVerticalOffset(picGallery.Scroller.VerticalOffset + speed); - } - } - } - } - - #endregion Scroll - - #region Open/Close - - internal static void PicGalleryToggle(bool change = false) - { - /// Quit when not enabled - if (Properties.Settings.Default.PicGallery == 0) - return; - - /// Toggle PicGallery, when not changed - if (!change) - { - if (Properties.Settings.Default.PicGallery == 1) - { - var da = new DoubleAnimation { Duration = TimeSpan.FromSeconds(.5) }; - - if (!IsOpen) - { - LoadLayout(); - da.To = 1; - da.From = 0; - IsOpen = true; - ScrollTo(); - } - else - { - da.To = 0; - da.From = 1; - da.Completed += delegate - { - if (IsOpen && Properties.Settings.Default.PicGallery == 1) - { - picGallery.Visibility = Visibility.Collapsed; - IsOpen = false; - } - }; - } - - picGallery.BeginAnimation(UIElement.OpacityProperty, da); - } - else - { - if (!IsOpen) - { - LoadLayout(); - - if (Properties.Settings.Default.ShowInterface) - HideInterface(); - - if (fake != null) - { - if (!fake.grid.Children.Contains(picGallery)) - { - mainWindow.bg.Children.Remove(picGallery); - fake.grid.Children.Add(picGallery); - } - } - else - { - mainWindow.bg.Children.Remove(picGallery); - fake = new FakeWindow(); - fake.grid.Children.Add(picGallery); - } - - fake.Show(); - IsOpen = true; - ScrollTo(); - mainWindow.Focus(); - } - else - { - fake.Hide(); - IsOpen = false; - - // Don't show it on next startup - Properties.Settings.Default.PicGallery = 1; - } - - } - } - /// Toggle PicGallery, when changed - else - { - if (Properties.Settings.Default.PicGallery == 1) - { - Properties.Settings.Default.PicGallery = 2; - LoadLayout(); - - if (fake == null) - fake = new FakeWindow(); - - if (!fake.grid.Children.Contains(picGallery)) - { - mainWindow.bg.Children.Remove(picGallery); - fake.grid.Children.Add(picGallery); - } - - fake.Show(); - mainWindow.Focus(); - } - else - { - fake.grid.Children.Remove(picGallery); - fake.Hide(); - mainWindow.bg.Children.Add(picGallery); - - Properties.Settings.Default.PicGallery = 1; - LoadLayout(); - } - } - } - - #endregion - - #region Load PicGallery - - internal static void PicGallery_Loaded(object sender, RoutedEventArgs e) - { - picGallery.Scroller.PreviewMouseWheel += Scroller_MouseWheel; - picGallery.Scroller.MouseDown += (s, x) => mainWindow.Focus(); - picGallery.x2.MouseLeftButtonUp += (s, x) => - { - if (Properties.Settings.Default.PicGallery == 1) - FadeOut(); - }; - picGallery.grid.MouseLeftButtonDown += (s, x) => mainWindow.Focus(); - - LoadComplete = isLoading = IsOpen = false; - } - - internal static void LoadLayout() - { - if (Properties.Settings.Default.PicGallery == 1) - { - if (Properties.Settings.Default.ShowInterface) - { - picGallery.Width = Application.Current.MainWindow.Width - 15; - picGallery.Height = Application.Current.MainWindow.ActualHeight - 78; - } - else - { - picGallery.Width = Application.Current.MainWindow.Width - 2; - picGallery.Height = Application.Current.MainWindow.Height - 2; // 2px for borders - } - - picGallery.HorizontalAlignment = HorizontalAlignment.Stretch; - picGallery.Scroller.HorizontalScrollBarVisibility = ScrollBarVisibility.Visible; - picGallery.Scroller.VerticalScrollBarVisibility = ScrollBarVisibility.Disabled; - picGallery.x2.Visibility = Visibility.Visible; - picGallery.Container.Margin = new Thickness(0, 65, 0, 0); - } - else - { - picGallery.Width = picGalleryItem_Size + 19; // 17 for scrollbar width + 2 for borders - picGallery.Height = MonitorInfo.Height; - picGallery.HorizontalAlignment = HorizontalAlignment.Right; - picGallery.Scroller.HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; - picGallery.Scroller.VerticalScrollBarVisibility = ScrollBarVisibility.Visible; - picGallery.x2.Visibility = Visibility.Collapsed; - picGallery.Container.Margin = new Thickness(0, 0, 0, 0); - } - - picGallery.Visibility = Visibility.Visible; - picGallery.Opacity = 1; - picGallery.Container.Orientation = Orientation.Vertical; - } - - internal static Task Load() - { - isLoading = true; - return Task.Run(() => - { - for (int i = 0; i < Pics.Count; i++) - { - var pic = GetBitmapSourceThumb(Pics[i]); - if (pic != null) - { - pic.Freeze(); - Add(pic, i); - } - } - LoadComplete = true; - isLoading = false; - }); - } - - #endregion - - #region Main Functions - - private static async void Add(BitmapSource pic, int index) + internal static async void Add(BitmapSource pic, int index) { await mainWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(() => { @@ -377,15 +30,10 @@ private static async void Add(BitmapSource pic, int index) var item = new PicGalleryItem(pic, index, selected); item.MouseLeftButtonUp += (s, x) => { + var child = picGallery.Container.Children[FolderIndex] as PicGalleryItem; + child.SetSelected(false); Click(index); - - if (!selected && FolderIndex < picGallery.Container.Children.Count) - { - item.Setselected(true); - var child = picGallery.Container.Children[FolderIndex] as PicGalleryItem; - child.Setselected(false); - } - + item.SetSelected(true); }; picGallery.Container.Children.Add(item); })); @@ -393,34 +41,41 @@ private static async void Add(BitmapSource pic, int index) internal static void Clear() { - LoadComplete = isLoading = IsOpen = false; + IsLoading = IsOpen = false; picGallery.Container.Children.Clear(); } //internal static void Sort() //{ - // var x = picGallery.Container.Children.Cast(); + // var items = picGallery.Container.Children.Cast(); + // switch (Properties.Settings.Default.SortPreference) + // { + // // Alphanumeric sort + // case 0: + // var list = items.ToList(); + // list.Sort((x, y) => { return NativeMethods.StrCmpLogicalW(x, y); }); + // break; + // case 1: + // items = items.OrderBy(f => new FileInfo(f).Length); + // break; + // case 2: + // items = items.OrderBy(f => new FileInfo(f).Extension); + // break; + // case 3: + // items = items.OrderBy(f => new FileInfo(f).CreationTime); + // break; + // case 4: + // items = items.OrderBy(f => new FileInfo(f).LastAccessTime); + // break; + // case SortFilesBy.Lastwritetime: + // items = items.OrderBy(f => new FileInfo(f).LastWriteTime); + // break; + // case SortFilesBy.Random: + // items = items.OrderBy(f => Guid.NewGuid()); + // break; + // } //} - private static void FadeOut() - { - var da = new DoubleAnimation() - { - To = 0, - From = 1, - Duration = TimeSpan.FromSeconds(0.4) - }; - da.Completed += delegate - { - picGallery.Visibility = Visibility.Collapsed; - }; - picGallery.BeginAnimation(UIElement.OpacityProperty, da); - } - - #endregion - - #region Item Click - internal static void Click(int id) { mainWindow.Focus(); @@ -510,8 +165,7 @@ internal static void PreviewItemClick(ImageSource source, int id) PreloadCount = 4; Preloader.Clear(); Preloader.Add(Pics[id]); - } - + } mainWindow.img.Source = source; var size = ImageSize(Pics[id]); @@ -526,11 +180,9 @@ internal static void ItemClick(int id) if (Properties.Settings.Default.PicGallery == 1) picGallery.Visibility = Visibility.Collapsed; - /// Fix annoying bug + // Fix annoying bug ajaxLoading.Opacity = 0; } - #endregion - } } diff --git a/PicView/PicGallery/PicGalleryScroll.cs b/PicView/PicGallery/PicGalleryScroll.cs new file mode 100644 index 00000000..a1b42a1a --- /dev/null +++ b/PicView/PicGallery/PicGalleryScroll.cs @@ -0,0 +1,158 @@ +using System; +using System.Windows.Input; +using static PicView.Fields; + + +namespace PicView +{ + internal static class PicGalleryScroll + { + internal const int picGalleryItem_Size = 230; + internal const int picGalleryItem_Size_s = 200; + + public static int Horizontal_items + { + get + { + if (picGallery == null) return 0; + return (int)Math.Floor(picGallery.Width / picGalleryItem_Size); + } + set { } + } + + public static int Vertical_items + { + get + { + if (picGallery == null) return 0; + return Properties.Settings.Default.PicGallery == 1 ? + (int)Math.Floor(picGallery.Height / picGalleryItem_Size) : + Pics.Count; + } + set { } + } + + public static int Items_per_page + { + get + { + if (picGallery == null) return 0; + return Properties.Settings.Default.PicGallery == 1 ? + Horizontal_items * Vertical_items : + (int)Math.Floor(picGallery.Height / picGalleryItem_Size); + } + set { } + } + + public static int Current_page + { + get + { + return (int)Math.Floor((double)FolderIndex / Items_per_page); + } + set { } + } + + public static int Total_pages + { + get + { + return (int)Math.Floor((double)Pics.Count / Items_per_page); + } + set { } + } + + /// + /// Scrolls to center of current item + /// + /// The index of picGalleryItem + internal static void ScrollTo() + { + if (Properties.Settings.Default.PicGallery == 1) + picGallery.Scroller.ScrollToHorizontalOffset((picGalleryItem_Size * Horizontal_items) * Current_page); + else + picGallery.Scroller.ScrollToVerticalOffset((picGalleryItem_Size * Items_per_page) * Current_page); + } + + internal static void ScrollTo(object sender, MouseWheelEventArgs e) + { + if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control) + ScrollTo(e.Delta > 0); + else + ScrollTo(e.Delta > 0, false); + } + + /// + /// Scrolls a page back or forth + /// + /// + /// + internal static void ScrollTo(bool next, bool end = false, bool speedUp = false, bool animate = false) + { + if (end) + { + if (next) + picGallery.Scroller.ScrollToRightEnd(); + else + picGallery.Scroller.ScrollToLeftEnd(); + } + else + { + var speed = speedUp ? picGalleryItem_Size * 4.7 : picGalleryItem_Size; + var direction = next ? picGallery.Scroller.HorizontalOffset - speed : picGallery.Scroller.HorizontalOffset + speed; + + if (Properties.Settings.Default.PicGallery == 1) + { + if (animate) + { + //var anim = new DoubleAnimation + //{ + // From = Scroller.HorizontalOffset, + // To = direction, + // Duration = TimeSpan.FromSeconds(.3), + // AccelerationRatio = 0.2, + // DecelerationRatio = 0.4 + //}; + + //var sb = new Storyboard(); + //sb.Children.Add(anim); + //Storyboard.SetTarget(anim, Scroller); + //Storyboard.SetTargetProperty(anim, new PropertyPath(ScrollAnimationBehavior.VerticalOffsetProperty)) + } + else + { + picGallery.Scroller.ScrollToHorizontalOffset(direction); + } + } + else + { + if (animate) + { + //DoubleAnimation verticalAnimation = new DoubleAnimation + //{ + // From = scrollViewer.VerticalOffset, + // To = some + //}; + //value; + //verticalAnimation.Duration = new Duration(some duration); + + //Storyboard storyboard = new Storyboard(); + + //storyboard.Children.Add(verticalAnimation); + //Storyboard.SetTarget(verticalAnimation, scrollViewer); + //Storyboard.SetTargetProperty(verticalAnimation, new PropertyPath(ScrollAnimationBehavior.VerticalOffsetProperty)); // Attached dependency property + //storyboard.Begin(); + } + else + { + if (next) + picGallery.Scroller.ScrollToVerticalOffset(picGallery.Scroller.VerticalOffset - speed); + else + picGallery.Scroller.ScrollToVerticalOffset(picGallery.Scroller.VerticalOffset + speed); + } + } + } + } + + } +} diff --git a/PicView/PicGallery/PicGalleryToggle.cs b/PicView/PicGallery/PicGalleryToggle.cs new file mode 100644 index 00000000..231fd99c --- /dev/null +++ b/PicView/PicGallery/PicGalleryToggle.cs @@ -0,0 +1,173 @@ +using PicView.Windows; +using System; +using System.Diagnostics; +using System.Windows; +using System.Windows.Media.Animation; +using static PicView.Fields; +using static PicView.PicGalleryLoad; +using static PicView.PicGalleryLogic; +using static PicView.PicGalleryScroll; +using static PicView.WindowLogic; + +namespace PicView +{ + internal static class PicGalleryToggle + { + internal static void ToggleGallery(bool change = false) + { + /// Quit when not enabled + if (Properties.Settings.Default.PicGallery == 0) + return; + + /// Toggle PicGallery, when not changed + if (!change) + { + if (Properties.Settings.Default.PicGallery == 1) + { + if (!IsOpen) + OpenPicGalleryOne(); + else + ClosePicGalleryOne(); + } + else + { + if (!IsOpen) + OpenPicGalleryTwo(); + else + ClosePicGalleryTwo(); + } + } + /// Toggle PicGallery, when changed + else + { + if (Properties.Settings.Default.PicGallery == 1) + { + ChangeToPicGalleryTwo(); + } + else + { + ChangeToPicGalleryOne(); + } + } + +#if DEBUG + Trace.WriteLine("Picgallery IsOpen = " + IsOpen); +#endif + } + + // Open!!! + + static void OpenPicGalleryOne() + { + LoadLayout(); + + var da = new DoubleAnimation { + Duration = TimeSpan.FromSeconds(.5), + To = 1, + From = 0 + }; + + IsOpen = true; + + picGallery.BeginAnimation(UIElement.OpacityProperty, da); + ScrollTo(); + } + + static void OpenPicGalleryTwo() + { + LoadLayout(); + + if (fake != null) + { + if (!fake.grid.Children.Contains(picGallery)) + { + mainWindow.bg.Children.Remove(picGallery); + fake.grid.Children.Add(picGallery); + } + } + else + { + mainWindow.bg.Children.Remove(picGallery); + fake = new FakeWindow(); + fake.grid.Children.Add(picGallery); + } + + fake.Show(); + IsOpen = true; + ScrollTo(); + mainWindow.Focus(); + } + + // Close!!! + + static void ClosePicGalleryOne() + { + IsOpen = false; + var da = new DoubleAnimation { Duration = TimeSpan.FromSeconds(.5) }; + + da.To = 0; + da.From = 1; + da.Completed += delegate + { + if (IsOpen && Properties.Settings.Default.PicGallery == 1) + { + picGallery.Visibility = Visibility.Collapsed; + } + }; + + picGallery.BeginAnimation(UIElement.OpacityProperty, da); + } + + static void ClosePicGalleryTwo() + { + IsOpen = false; + fake.Hide(); + + // Don't show it on next startup + Properties.Settings.Default.PicGallery = 1; + } + + + // Change !! + + static void ChangeToPicGalleryOne() + { + Properties.Settings.Default.PicGallery = 1; + LoadLayout(); + + if (fake.grid.Children.Contains(picGallery)) + { + fake.grid.Children.Remove(picGallery); + mainWindow.bg.Children.Add(picGallery); + } + + fake.Hide(); + } + + static void ChangeToPicGalleryTwo() + { + Properties.Settings.Default.PicGallery = 2; + LoadLayout(); + + if (fake != null) + { + if (!fake.grid.Children.Contains(picGallery)) + { + mainWindow.bg.Children.Remove(picGallery); + fake.grid.Children.Add(picGallery); + } + } + else + { + mainWindow.bg.Children.Remove(picGallery); + fake = new FakeWindow(); + fake.grid.Children.Add(picGallery); + } + + fake.Show(); + ScrollTo(); + mainWindow.Focus(); + } + + } +} diff --git a/PicView/PicVIew.csproj b/PicView/PicVIew.csproj index 53b065a8..cd212b0f 100644 --- a/PicView/PicVIew.csproj +++ b/PicView/PicVIew.csproj @@ -140,7 +140,7 @@ MSBuild:Compile Designer - + @@ -156,17 +156,21 @@ + + + + - + @@ -193,7 +197,7 @@ AllSettings.xaml - + FakeWindow.xaml @@ -344,9 +348,9 @@ Code - + - + AjaxLoading.xaml diff --git a/PicView/Properties/AssemblyInfo.cs b/PicView/Properties/AssemblyInfo.cs index 5727e7ac..8a5c9553 100644 --- a/PicView/Properties/AssemblyInfo.cs +++ b/PicView/Properties/AssemblyInfo.cs @@ -52,6 +52,6 @@ // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("0.9.3.2")] +[assembly: AssemblyFileVersion("0.9.6.5")] [assembly: NeutralResourcesLanguage("en")] diff --git a/PicView/Shortcuts/Shortcuts.cs b/PicView/Shortcuts/Shortcuts.cs index 930e887b..a2b17059 100644 --- a/PicView/Shortcuts/Shortcuts.cs +++ b/PicView/Shortcuts/Shortcuts.cs @@ -1,5 +1,4 @@ -using PicView.Native; -using System.Windows; +using System.Windows; using System.Windows.Input; using static PicView.Copy_Paste; using static PicView.DeleteFiles; @@ -10,6 +9,8 @@ using static PicView.LoadWindows; using static PicView.Navigation; using static PicView.Open_Save; +using static PicView.PicGalleryScroll; +using static PicView.PicGalleryToggle; using static PicView.Resize_and_Zoom; using static PicView.Rotate_and_Flip; using static PicView.Scroll; @@ -45,6 +46,7 @@ internal static void MainWindow_KeysDown(object sender, KeyEventArgs e) Pic(true, true); else Pic(); + } else if (canNavigate) { @@ -72,7 +74,7 @@ internal static void MainWindow_KeysDown(object sender, KeyEventArgs e) } if (!e.IsRepeat) { - // Go to first if Ctrl held down + // Go to last if Ctrl held down if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control) Pic(false, true); else @@ -96,7 +98,7 @@ internal static void MainWindow_KeysDown(object sender, KeyEventArgs e) { if (PicGalleryLogic.IsOpen) { - PicGalleryLogic.ScrollTo(true, (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control); + ScrollTo(true, (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control); return; } } @@ -109,7 +111,7 @@ internal static void MainWindow_KeysDown(object sender, KeyEventArgs e) { if (PicGalleryLogic.IsOpen) { - PicGalleryLogic.ScrollTo(false, (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control); + ScrollTo(false, (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control); return; } } @@ -130,7 +132,7 @@ internal static void MainWindow_KeysDown(object sender, KeyEventArgs e) else if (picGallery != null) { if (PicGalleryLogic.IsOpen) - PicGalleryLogic.ScrollTo(false, (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control); + ScrollTo(false, (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control); else if (!e.IsRepeat && (Keyboard.Modifiers & ModifierKeys.Control) != ModifierKeys.Control) Rotate(false); } @@ -149,7 +151,7 @@ internal static void MainWindow_KeysDown(object sender, KeyEventArgs e) else if (picGallery != null) { if (PicGalleryLogic.IsOpen) - PicGalleryLogic.ScrollTo(true, (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control); + ScrollTo(true, (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control); else if (!e.IsRepeat && (Keyboard.Modifiers & ModifierKeys.Control) != ModifierKeys.Control) Rotate(true); } @@ -180,7 +182,7 @@ internal static void MainWindow_KeysDown(object sender, KeyEventArgs e) if (e.KeyboardDevice.Modifiers == ModifierKeys.Alt && (e.SystemKey == Key.Z)) { if (!e.IsRepeat) - HideInterface(); + ToggleInterface(); return; } @@ -220,7 +222,7 @@ internal static void MainWindow_KeysUp(object sender, KeyEventArgs e) else if (Properties.Settings.Default.PicGallery > 0) { if (PicGalleryLogic.IsOpen) - PicGalleryLogic.PicGalleryToggle(); + ToggleGallery(); else if (!cm.IsVisible) SystemCommands.CloseWindow(mainWindow); } @@ -241,9 +243,9 @@ internal static void MainWindow_KeysUp(object sender, KeyEventArgs e) // X, Ctrl + X case Key.X: if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control) - Cut(PicPath); + Cut(Pics[FolderIndex]); else - IsScrollEnabled = IsScrollEnabled ? false : true; + Configs.SetScrolling(sender, e); break; // F case Key.F: @@ -251,7 +253,7 @@ internal static void MainWindow_KeysUp(object sender, KeyEventArgs e) break; // Delete, Shift + Delete case Key.Delete: - DeleteFile(PicPath, e.KeyboardDevice.Modifiers != ModifierKeys.Shift); + DeleteFile(Pics[FolderIndex], e.KeyboardDevice.Modifiers != ModifierKeys.Shift); break; // Ctrl + C, Ctrl + Shift + C case Key.C: @@ -273,12 +275,12 @@ internal static void MainWindow_KeysUp(object sender, KeyEventArgs e) // Ctrl + I case Key.I: if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control) - NativeMethods.ShowFileProperties(PicPath); + NativeMethods.ShowFileProperties(Pics[FolderIndex]); break; // Ctrl + P case Key.P: if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control) - Print(PicPath); + Print(Pics[FolderIndex]); break; // Ctrl + R case Key.R: @@ -295,7 +297,7 @@ internal static void MainWindow_KeysUp(object sender, KeyEventArgs e) { if (PicGalleryLogic.IsOpen) { - PicGalleryLogic.ScrollTo(); + ScrollTo(); return; } } @@ -316,12 +318,34 @@ internal static void MainWindow_KeysUp(object sender, KeyEventArgs e) // F4 case Key.F4: if (picGallery != null) - PicGalleryLogic.PicGalleryToggle(Properties.Settings.Default.PicGallery == 2); + { + if (Properties.Settings.Default.PicGallery == 2) + ToggleGallery(true); + else + { + Properties.Settings.Default.PicGallery = 1; + ToggleGallery(); + } + } break; // F5 case Key.F5: if (picGallery != null) - PicGalleryLogic.PicGalleryToggle(Properties.Settings.Default.PicGallery == 1); + { + if (Properties.Settings.Default.PicGallery == 1) + if (PicGalleryLogic.IsOpen) + ToggleGallery(true); + else + { + Properties.Settings.Default.PicGallery = 2; + ToggleGallery(); + } + else + { + Properties.Settings.Default.PicGallery = 2; + ToggleGallery(); + } + } break; // F6 case Key.F6: @@ -347,7 +371,6 @@ internal static void MainWindow_KeysUp(object sender, KeyEventArgs e) mainWindow.Scroller.ScrollToEnd(); break; } - } internal static void MainWindow_MouseDown(object sender, MouseButtonEventArgs e) diff --git a/PicView/UserControls/CustomControls/PicGallery.xaml.cs b/PicView/UserControls/CustomControls/PicGallery.xaml.cs index 53993025..8870b44f 100644 --- a/PicView/UserControls/CustomControls/PicGallery.xaml.cs +++ b/PicView/UserControls/CustomControls/PicGallery.xaml.cs @@ -10,7 +10,8 @@ public partial class PicGallery : UserControl public PicGallery() { InitializeComponent(); - Loaded += PicView.PicGalleryLogic.PicGallery_Loaded; + //PicGalleryLogic.IsLoading = PicGalleryLogic.IsOpen = false; + Loaded += PicGalleryLoad.PicGallery_Loaded; } } diff --git a/PicView/UserControls/CustomControls/PicGalleryItem.xaml.cs b/PicView/UserControls/CustomControls/PicGalleryItem.xaml.cs index bab11934..dce776b4 100644 --- a/PicView/UserControls/CustomControls/PicGalleryItem.xaml.cs +++ b/PicView/UserControls/CustomControls/PicGalleryItem.xaml.cs @@ -47,7 +47,7 @@ private void PicGalleryItem_Loaded(object sender, RoutedEventArgs e) border.BorderBrush = new SolidColorBrush(AnimationHelper.GetPrefferedColorOverAlpha()); } - internal void Setselected(bool b) + internal void SetSelected(bool b) { if (b) { diff --git a/PicView/UserControls/Menus/QuickSettingsMenu.xaml.cs b/PicView/UserControls/Menus/QuickSettingsMenu.xaml.cs index 6e70aef9..ce873dd0 100644 --- a/PicView/UserControls/Menus/QuickSettingsMenu.xaml.cs +++ b/PicView/UserControls/Menus/QuickSettingsMenu.xaml.cs @@ -41,31 +41,31 @@ public QuickSettingsMenu() Fill.PreviewMouseLeftButtonDown += Fill_PreviewMouseLeftButtonDown; Fill.MouseEnter += Fill_MouseEnter; Fill.MouseLeave += Fill_MouseLeave; - Fill.Click += (s,x) => SetWallpaper(PicPath, WallpaperStyle.Fill); + Fill.Click += (s,x) => SetWallpaper(Pics[FolderIndex], WallpaperStyle.Fill); // Fit Fit.PreviewMouseLeftButtonDown += Fit_PreviewMouseLeftButtonDown; Fit.MouseEnter += Fit_MouseEnter; Fit.MouseLeave += Fit_MouseLeave; - Fit.Click += (s, x) => SetWallpaper(PicPath, WallpaperStyle.Fit); + Fit.Click += (s, x) => SetWallpaper(Pics[FolderIndex], WallpaperStyle.Fit); // Center Center.PreviewMouseLeftButtonDown += Center_PreviewMouseLeftButtonDown; Center.MouseEnter += Center_MouseEnter; Center.MouseLeave += Center_MouseLeave; - Center.Click += (s, x) => SetWallpaper(PicPath, WallpaperStyle.Center); + Center.Click += (s, x) => SetWallpaper(Pics[FolderIndex], WallpaperStyle.Center); // Tile Tile.PreviewMouseLeftButtonDown += Tile_PreviewMouseLeftButtonDown; Tile.MouseEnter += Tile_MouseEnter; Tile.MouseLeave += Tile_MouseLeave; - Tile.Click += (s, x) => SetWallpaper(PicPath, WallpaperStyle.Tile); + Tile.Click += (s, x) => SetWallpaper(Pics[FolderIndex], WallpaperStyle.Tile); // Stretch Stretch.PreviewMouseLeftButtonDown += Stretch_PreviewMouseLeftButtonDown; Stretch.MouseEnter += Stretch_MouseEnter; Stretch.MouseLeave += Stretch_MouseLeave; - Stretch.Click += (s, x) => SetWallpaper(PicPath, WallpaperStyle.Stretch); + Stretch.Click += (s, x) => SetWallpaper(Pics[FolderIndex], WallpaperStyle.Stretch); // Set Center SetCenter.PreviewMouseLeftButtonDown += SetCenter_PreviewMouseLeftButtonDown; diff --git a/PicView/Windows/FakeWindow.xaml b/PicView/Windows/FakeWindow.xaml index c1280476..f437bd18 100644 --- a/PicView/Windows/FakeWindow.xaml +++ b/PicView/Windows/FakeWindow.xaml @@ -4,7 +4,7 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="FakeWindow" AllowsTransparency="True" - Background="#72000000" + Background="{x:Null}" Focusable="False" ResizeMode="NoResize" ShowInTaskbar="False" @@ -16,6 +16,7 @@ \ No newline at end of file diff --git a/PicView/Windows/FakeWindow.xaml.cs b/PicView/Windows/FakeWindow.xaml.cs index a3d5fc90..46f8401f 100644 --- a/PicView/Windows/FakeWindow.xaml.cs +++ b/PicView/Windows/FakeWindow.xaml.cs @@ -2,6 +2,9 @@ using System.Windows; using System.Windows.Input; using static PicView.Fields; +using static PicView.PicGalleryScroll; +using static PicView.NativeMethods; +using System.Windows.Interop; namespace PicView.Windows { @@ -18,7 +21,6 @@ public FakeWindow() Width = MonitorInfo.Width; Height = MonitorInfo.Height; ContentRendered += FakeWindow_ContentRendered; - } private void FakeWindow_ContentRendered(object sender, EventArgs e) @@ -30,6 +32,11 @@ private void FakeWindow_ContentRendered(object sender, EventArgs e) MouseWheel += FakeWindow_MouseWheel; Application.Current.MainWindow.Focus(); LostFocus += FakeWindow_LostFocus; + GotFocus += FakeWindow_LostFocus; + + // Hide from alt tab + var helper = new WindowInteropHelper(this).Handle; + SetWindowLong(helper, GWL_EX_STYLE, (GetWindowLong(helper, GWL_EX_STYLE) | WS_EX_TOOLWINDOW) & ~WS_EX_APPWINDOW); } private void FakeWindow_LostFocus(object sender, RoutedEventArgs e) @@ -56,9 +63,9 @@ private void FakeWindow_StateChanged(object sender, EventArgs e) private void FakeWindow_MouseWheel(object sender, MouseWheelEventArgs e) { if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control) - PicGalleryLogic.ScrollTo(e.Delta > 0, true); + ScrollTo(e.Delta > 0, true); else - PicGalleryLogic.ScrollTo(e.Delta > 0, false, true); + ScrollTo(e.Delta > 0, false, true); } private void MainWindow_StateChanged(object sender, EventArgs e)