diff --git a/Application/FileConverter/Application.xaml.cs b/Application/FileConverter/Application.xaml.cs index 782ee0d..6994978 100644 --- a/Application/FileConverter/Application.xaml.cs +++ b/Application/FileConverter/Application.xaml.cs @@ -391,7 +391,7 @@ namespace FileConverter IConversionService conversionService = SimpleIoc.Default.GetInstance(); // Create conversion jobs. - Debug.Log("Create jobs for conversion preset: '{0}'", conversionPreset.Name); + Debug.Log("Create jobs for conversion preset: '{0}'", conversionPreset.FullName); try { for (int index = 0; index < filePaths.Count; index++) diff --git a/Application/FileConverter/ConversionJobs/ConversionJob.cs b/Application/FileConverter/ConversionJobs/ConversionJob.cs index 1523e82..5852a9f 100644 --- a/Application/FileConverter/ConversionJobs/ConversionJob.cs +++ b/Application/FileConverter/ConversionJobs/ConversionJob.cs @@ -319,7 +319,7 @@ namespace FileConverter.ConversionJobs this.State = ConversionState.Ready; } - Debug.Log("Job initialized: Preset: '{0}' Input: {1} Output: {2}", this.ConversionPreset.Name, this.InputFilePath, this.OutputFilePath); + Debug.Log("Job initialized: Preset: '{0}' Input: {1} Output: {2}", this.ConversionPreset.FullName, this.InputFilePath, this.OutputFilePath); if (this.State != ConversionState.Failed) { diff --git a/Application/FileConverter/ConversionPreset/ConversionPreset.cs b/Application/FileConverter/ConversionPreset/ConversionPreset.cs index ad0d330..669b287 100644 --- a/Application/FileConverter/ConversionPreset/ConversionPreset.cs +++ b/Application/FileConverter/ConversionPreset/ConversionPreset.cs @@ -7,20 +7,20 @@ namespace FileConverter using System.ComponentModel; using System.Globalization; using System.Linq; - using System.Runtime.CompilerServices; using System.Xml.Serialization; - using FileConverter.Annotations; using FileConverter.Controls; using FileConverter.Services; + using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Ioc; [XmlRoot] [XmlType] - public class ConversionPreset : INotifyPropertyChanged, IDataErrorInfo, IXmlSerializable + public class ConversionPreset : ObservableObject, IXmlSerializable { - private string name; + private string shortName; + private OutputType outputType; private List inputTypes; private InputPostConversionAction inputPostConversionAction; @@ -29,12 +29,12 @@ namespace FileConverter public ConversionPreset() { - this.Name = Properties.Resources.DefaultPresetName; + this.FullName = Properties.Resources.DefaultPresetName; } - public ConversionPreset(string name, OutputType outputType, params string[] inputTypes) + public ConversionPreset(string shortName, OutputType outputType, params string[] inputTypes) { - this.Name = name; + this.ShortName = shortName; this.OutputType = outputType; List inputTypeList = new List(); inputTypeList.AddRange(inputTypes); @@ -43,9 +43,10 @@ namespace FileConverter this.outputFileNameTemplate = "(p)(f)"; } - public ConversionPreset(string name, ConversionPreset source, params string[] additionalInputTypes) + public ConversionPreset(string shortName, ConversionPreset source, params string[] additionalInputTypes) { - this.Name = name; + this.ShortName = shortName; + this.ParentFoldersNames = source.ParentFoldersNames; this.OutputType = source.outputType; List inputTypeList = new List(); if (source.inputTypes != null) @@ -68,23 +69,61 @@ namespace FileConverter } } - public event PropertyChangedEventHandler PropertyChanged; - - [XmlAttribute] - public string Name + [XmlAttribute("Name")] + public string FullName { get { - return this.name; + string fullName = string.Empty; + if (this.ParentFoldersNames != null) + { + foreach (string folder in this.ParentFoldersNames) + { + fullName += $"{folder}/"; + } + } + + fullName += this.shortName; + + return fullName; } set { - this.name = value; - this.OnPropertyChanged(); + string[] folders = value.Split('/'); + if (folders.Length == 0) + { + Diagnostics.Debug.Log("Invalid full name."); + this.ShortName = value; + return; + } + + this.ShortName = folders[folders.Length - 1]; + Array.Resize(ref folders, folders.Length - 1); + + this.ParentFoldersNames = folders; } } + [XmlIgnore] + public string ShortName + { + get => this.shortName; + + set + { + this.shortName = value; + this.RaisePropertyChanged(); + } + } + + [XmlIgnore] + public string[] ParentFoldersNames + { + get; + set; + } + [XmlAttribute] public OutputType OutputType { @@ -97,7 +136,7 @@ namespace FileConverter { this.outputType = value; this.InitializeDefaultSettings(this.outputType); - this.OnPropertyChanged(); + this.RaisePropertyChanged(); this.CoerceInputTypes(); } } @@ -125,7 +164,7 @@ namespace FileConverter this.inputTypes[index] = this.inputTypes[index].ToLowerInvariant(); } - this.OnPropertyChanged(); + this.RaisePropertyChanged(); } } @@ -140,7 +179,7 @@ namespace FileConverter set { this.inputPostConversionAction = value; - this.OnPropertyChanged(); + this.RaisePropertyChanged(); } } @@ -184,7 +223,7 @@ namespace FileConverter } } - this.OnPropertyChanged(nameof(this.Settings)); + this.RaisePropertyChanged(nameof(this.Settings)); } } @@ -199,7 +238,7 @@ namespace FileConverter set { this.outputFileNameTemplate = value; - this.OnPropertyChanged(); + this.RaisePropertyChanged(); } } @@ -239,35 +278,7 @@ namespace FileConverter } } - this.OnPropertyChanged(); - } - } - - public string Error - { - get - { - string errorString = this.Validate("Name"); - if (!string.IsNullOrEmpty(errorString)) - { - return errorString; - } - - errorString = this.Validate("OutputFileNameTemplate"); - if (!string.IsNullOrEmpty(errorString)) - { - return errorString; - } - - return string.Empty; - } - } - - public string this[string columnName] - { - get - { - return this.Validate(columnName); + this.RaisePropertyChanged(); } } @@ -307,14 +318,14 @@ namespace FileConverter } this.inputTypes.Add(inputType); - this.OnPropertyChanged(nameof(this.InputTypes)); + this.RaisePropertyChanged(nameof(this.InputTypes)); } public void RemoveInputType(string inputType) { if (this.inputTypes.Remove(inputType)) { - this.OnPropertyChanged(nameof(this.InputTypes)); + this.RaisePropertyChanged(nameof(this.InputTypes)); } } @@ -347,7 +358,7 @@ namespace FileConverter this.settings[settingsKey] = value; - this.OnPropertyChanged(nameof(this.Settings)); + this.RaisePropertyChanged(nameof(this.Settings)); } public string GetSettingsValue(string settingsKey) @@ -388,12 +399,6 @@ namespace FileConverter return this.Settings.ContainsKey(settingsKey); } - [NotifyPropertyChangedInvocator] - protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) - { - this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } - private void CoerceInputTypes() { if (this.inputTypes == null) @@ -529,7 +534,7 @@ namespace FileConverter throw new System.Exception("Missing default settings for type " + outputType); } - this.OnPropertyChanged(nameof(this.Settings)); + this.RaisePropertyChanged(nameof(this.Settings)); } private void InitializeSettingsValue(string settingsKey, string value, bool force = false) @@ -554,102 +559,6 @@ namespace FileConverter } } - private string Validate(string propertyName) - { - // Return error message if there is an error, else return empty or null string. - switch (propertyName) - { - case "Name": - { - if (string.IsNullOrEmpty(this.Name)) - { - return "The preset name can't be empty."; - } - - if (this.Name.Contains(";")) - { - return "The preset name can't contains the character ';'."; - } - - ISettingsService settingsService = SimpleIoc.Default.GetInstance(); - int? count = settingsService.Settings?.ConversionPresets?.Count(match => match?.name == this.Name); - if (count > 1) - { - return "The preset name is already used."; - } - } - - break; - - case "OutputFileNameTemplate": - { - string sampleOutputFilePath = this.GenerateOutputFilePath(FileConverter.Properties.Resources.OuputFileNameTemplateSample, 1, 3); - if (string.IsNullOrEmpty(sampleOutputFilePath)) - { - return "The output filename template must produce a non empty result."; - } - - if (!PathHelpers.IsPathValid(sampleOutputFilePath)) - { - // Diagnostic to feedback purpose. - // Drive letter. - if (!PathHelpers.IsPathDriveLetterValid(sampleOutputFilePath)) - { - return "The output filename template must define a root (for example c:\\, use (p) to use the input file path)."; - } - - // File name. - string filename = PathHelpers.GetFileName(sampleOutputFilePath); - if (filename == null) - { - return "The output file name must not be empty (use (f) to use the name of the input file)."; - } - - char[] invalidFileNameChars = System.IO.Path.GetInvalidFileNameChars(); - for (int index = 0; index < invalidFileNameChars.Length; index++) - { - if (filename.Contains(invalidFileNameChars[index])) - { - return "The output file name must not contains the character '" + invalidFileNameChars[index] + "'."; - } - } - - // Directory names. - string path = sampleOutputFilePath.Substring(3, sampleOutputFilePath.Length - 3 - filename.Length); - char[] invalidPathChars = System.IO.Path.GetInvalidPathChars(); - for (int index = 0; index < invalidPathChars.Length; index++) - { - if (string.IsNullOrEmpty(path)) - { - return "The output directory name must not be empty (use (d0), (d1), ... to use the name of the parent directories of the input file)."; - } - - if (path.Contains(invalidPathChars[index])) - { - return "The output directory name must not contains the character '" + invalidPathChars[index] + "'."; - } - } - - string[] directories = path.Split('\\'); - for (int index = 0; index < directories.Length; ++index) - { - string directoryName = directories[index]; - if (string.IsNullOrEmpty(directoryName)) - { - return "The output directory name must not be empty (use (d0), (d1), ... to use the name of the parent directories of the input file)."; - } - } - - return "The output filename template is invalid"; - } - } - - break; - } - - return string.Empty; - } - public struct ConversionSetting { public ConversionSetting(KeyValuePair keyValuePair) diff --git a/Application/FileConverter/FileConverter.csproj b/Application/FileConverter/FileConverter.csproj index b201df0..01038e7 100644 --- a/Application/FileConverter/FileConverter.csproj +++ b/Application/FileConverter/FileConverter.csproj @@ -222,11 +222,14 @@ + + + HelpWindow.xaml @@ -257,6 +260,10 @@ MSBuild:Compile Designer + + MSBuild:Compile + Designer + Designer MSBuild:Compile @@ -392,6 +399,9 @@ + + + copy /Y "$(SolutionDir)Middleware\ffmpeg\$(PlatformName)\ffmpeg.exe" "$(TargetDir)ffmpeg.exe" diff --git a/Application/FileConverter/Properties/Resources.Designer.cs b/Application/FileConverter/Properties/Resources.Designer.cs index a3b0a46..489b5af 100644 --- a/Application/FileConverter/Properties/Resources.Designer.cs +++ b/Application/FileConverter/Properties/Resources.Designer.cs @@ -303,6 +303,24 @@ namespace FileConverter.Properties { } } + /// + /// Looks up a localized string similar to Create a new folder.. + /// + public static string CreateANewFolder { + get { + return ResourceManager.GetString("CreateANewFolder", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to New folder. + /// + public static string DefaultFolderName { + get { + return ResourceManager.GetString("DefaultFolderName", resourceCulture); + } + } + /// /// Looks up a localized string similar to New preset. /// @@ -879,15 +897,6 @@ namespace FileConverter.Properties { } } - /// - /// Looks up a localized string similar to C:\Music\Artist\Album\Song.wav. - /// - public static string OuputFileNameTemplateSample { - get { - return ResourceManager.GetString("OuputFileNameTemplateSample", resourceCulture); - } - } - /// /// Looks up a localized string similar to Output. /// @@ -897,6 +906,15 @@ namespace FileConverter.Properties { } } + /// + /// Looks up a localized string similar to C:\Music\Artist\Album\Song.wav. + /// + public static string OutputFileNameTemplateSample { + get { + return ResourceManager.GetString("OutputFileNameTemplateSample", resourceCulture); + } + } + /// /// Looks up a localized string similar to (p): input file path ///(f): input filename @@ -940,6 +958,24 @@ namespace FileConverter.Properties { } } + /// + /// Looks up a localized string similar to Folder. + /// + public static string PresetFolder { + get { + return ResourceManager.GetString("PresetFolder", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Folder Name. + /// + public static string PresetFolderName { + get { + return ResourceManager.GetString("PresetFolderName", resourceCulture); + } + } + /// /// Looks up a localized string similar to Preset Name. /// diff --git a/Application/FileConverter/Properties/Resources.en.resx b/Application/FileConverter/Properties/Resources.en.resx index edd1dba..722acb6 100644 --- a/Application/FileConverter/Properties/Resources.en.resx +++ b/Application/FileConverter/Properties/Resources.en.resx @@ -252,7 +252,7 @@ 180° rotation - + C:\Music\Artist\Album\Song.wav diff --git a/Application/FileConverter/Properties/Resources.es-ES.resx b/Application/FileConverter/Properties/Resources.es-ES.resx index d80f195..c34f10b 100644 --- a/Application/FileConverter/Properties/Resources.es-ES.resx +++ b/Application/FileConverter/Properties/Resources.es-ES.resx @@ -255,7 +255,7 @@ Rotación de 180° en el sentido del reloj - + C:\Música\Artista\Album\Canción.wav diff --git a/Application/FileConverter/Properties/Resources.fr.resx b/Application/FileConverter/Properties/Resources.fr.resx index 63a9433..9e93ac2 100644 --- a/Application/FileConverter/Properties/Resources.fr.resx +++ b/Application/FileConverter/Properties/Resources.fr.resx @@ -263,7 +263,7 @@ rotation de 180° - + C:\Musique\Artiste\Album\Chanson.wav diff --git a/Application/FileConverter/Properties/Resources.it-IT.resx b/Application/FileConverter/Properties/Resources.it-IT.resx index 3d61d51..4271bfe 100644 --- a/Application/FileConverter/Properties/Resources.it-IT.resx +++ b/Application/FileConverter/Properties/Resources.it-IT.resx @@ -301,7 +301,7 @@ Rotazione di 180° 180° rotation - + C:\Musica\Artista\Album\Canzone.wav C:\Music\Artist\Album\Song.wav @@ -705,4 +705,4 @@ use maj for uppercase version Errore durante l'inizializzazione del processo di conversione. Error during conversion job initialization. - + \ No newline at end of file diff --git a/Application/FileConverter/Properties/Resources.pt-BR.resx b/Application/FileConverter/Properties/Resources.pt-BR.resx index c02de13..abf93f3 100644 --- a/Application/FileConverter/Properties/Resources.pt-BR.resx +++ b/Application/FileConverter/Properties/Resources.pt-BR.resx @@ -255,7 +255,7 @@ Rotacionar 180° - + C:\Música\Artista\Álbum\música.wav diff --git a/Application/FileConverter/Properties/Resources.pt.resx b/Application/FileConverter/Properties/Resources.pt.resx index 1ddaa2b..213bc9a 100644 --- a/Application/FileConverter/Properties/Resources.pt.resx +++ b/Application/FileConverter/Properties/Resources.pt.resx @@ -255,7 +255,7 @@ Rotacionar 180° - + C:\Música\Artista\Álbum\música.wav diff --git a/Application/FileConverter/Properties/Resources.resx b/Application/FileConverter/Properties/Resources.resx index 12f4b04..359b577 100644 --- a/Application/FileConverter/Properties/Resources.resx +++ b/Application/FileConverter/Properties/Resources.resx @@ -255,7 +255,7 @@ 180° rotation - + C:\Music\Artist\Album\Song.wav @@ -550,4 +550,16 @@ use maj for uppercase version Error during conversion job initialization. + + Create a new folder. + + + New folder + + + Folder + + + Folder Name + \ No newline at end of file diff --git a/Application/FileConverter/Resources/FolderIcon.ico b/Application/FileConverter/Resources/FolderIcon.ico new file mode 100644 index 0000000..5f6e3a0 Binary files /dev/null and b/Application/FileConverter/Resources/FolderIcon.ico differ diff --git a/Application/FileConverter/SampleData/ConversionJobSampleData.xaml b/Application/FileConverter/SampleData/ConversionJobSampleData.xaml index a18a557..2a5267e 100644 --- a/Application/FileConverter/SampleData/ConversionJobSampleData.xaml +++ b/Application/FileConverter/SampleData/ConversionJobSampleData.xaml @@ -3,7 +3,6 @@ ErrorMessage="There is no error for now" InputFilePath="C:\Path\To\AVery\Long\Location\WithAVeryNiceFile.png" OutputFilePath="C:\Path\To\AVery\Long\Location\WithAVeryNiceFile.jpg" - IsCancelable="False" StartTime="08/07/2018 22:10:55" State="InProgress" StateFlags="None" diff --git a/Application/FileConverter/SampleData/SettingsSampleData.xaml b/Application/FileConverter/SampleData/SettingsSampleData.xaml new file mode 100644 index 0000000..49693e1 --- /dev/null +++ b/Application/FileConverter/SampleData/SettingsSampleData.xaml @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Application/FileConverter/Services/SettingsService.cs b/Application/FileConverter/Services/SettingsService.cs index de4b0eb..c2d63e5 100644 --- a/Application/FileConverter/Services/SettingsService.cs +++ b/Application/FileConverter/Services/SettingsService.cs @@ -451,7 +451,7 @@ namespace FileConverter.Services registryEntries.Add(inputType, new List()); } - registryEntries[inputType].Add(conversionPreset.Name); + registryEntries[inputType].Add(conversionPreset.FullName); } } diff --git a/Application/FileConverter/Settings.cs b/Application/FileConverter/Settings.cs index 48a6b56..de8c016 100644 --- a/Application/FileConverter/Settings.cs +++ b/Application/FileConverter/Settings.cs @@ -12,7 +12,7 @@ namespace FileConverter [XmlRoot] [XmlType] - public class Settings : ObservableObject, IDataErrorInfo, IXmlSerializable + public class Settings : ObservableObject, IXmlSerializable { public const int Version = 4; @@ -22,37 +22,10 @@ namespace FileConverter private bool checkUpgradeAtStartup = true; private CultureInfo applicationLanguage; private int maximumNumberOfSimultaneousConversions; - - [XmlIgnore] - public string Error - { - get - { - for (int index = 0; index < this.ConversionPresets.Count; index++) - { - string error = this.ConversionPresets[index].Error; - if (!string.IsNullOrEmpty(error)) - { - return error; - } - } - - return string.Empty; - } - } - - [XmlIgnore] - public string this[string columnName] - { - get - { - return this.Error; - } - } public ConversionPreset GetPresetFromName(string presetName) { - return this.conversionPresets.FirstOrDefault(match => match.Name == presetName); + return this.conversionPresets.FirstOrDefault(match => match.FullName == presetName); } public void Clean() @@ -73,7 +46,7 @@ namespace FileConverter for (int index = 0; index < settings.conversionPresets.Count; index++) { ConversionPreset conversionPreset = settings.conversionPresets[index]; - if (this.conversionPresets.Any(match => match.Name == conversionPreset.Name)) + if (this.conversionPresets.Any(match => match.FullName == conversionPreset.FullName)) { continue; } diff --git a/Application/FileConverter/Settings.default.xml b/Application/FileConverter/Settings.default.xml index 95aefde..7bf92f3 100644 --- a/Application/FileConverter/Settings.default.xml +++ b/Application/FileConverter/Settings.default.xml @@ -72,52 +72,6 @@ (p)(f) - - gif - 3gp - avi - bik - flv - m4v - mkv - mov - mp4 - mpeg - ogv - webm - wmv - None - - - - - - - (p)(f) - - - avi - bik - flv - mkv - mov - mp4 - 3gp - webm - wmv - m4v - mpeg - ogv - gif - None - - - - - - - (p)(f) - avi bik @@ -506,76 +460,6 @@ (p)(f) - - arw - bmp - cr2 - exr - ico - jpg - jpeg - raf - png - psd - svg - tga - tif - tiff - xcf - webp - None - - - - - (p)(f)-small - - - arw - bmp - cr2 - exr - ico - jpg - jpeg - raf - png - psd - svg - tga - tif - tiff - webp - None - - - - - (p)(f) - - - arw - bmp - cr2 - exr - ico - jpg - jpeg - raf - png - psd - svg - tga - tif - tiff - webp - None - - - - - (p)(f) - arw bmp @@ -647,5 +531,743 @@ None (p)(f) + + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + gif + None + + + + + + + (p)(f) + + + gif + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + None + + + + + + + (p)(f) + + + avi + bik + flv + mkv + mov + mp4 + 3gp + webm + wmv + m4v + mpeg + ogv + gif + None + + + + + + (p)(f) + + + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + gif + None + + + + + + (p)(f) + + + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + gif + None + + + + + + (p)(f) + + + arw + bmp + cr2 + exr + ico + jpg + jpeg + raf + png + psd + svg + tga + tif + tiff + xcf + webp + None + + + + + (p)(f)-small + + + arw + bmp + cr2 + exr + ico + jpg + jpeg + raf + png + psd + svg + tga + tif + tiff + xcf + webp + None + + + + + + (p)(f) + + + arw + bmp + cr2 + exr + ico + jpg + jpeg + raf + png + psd + svg + tga + tif + tiff + xcf + webp + None + + + + + + (p)(f) + + + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + gif + None + + + + + + + (p)(f) + + + gif + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + None + + + + + + + (p)(f) + + + avi + bik + flv + mkv + mov + mp4 + 3gp + webm + wmv + m4v + mpeg + ogv + gif + None + + + + + + (p)(f) + + + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + gif + None + + + + + + (p)(f) + + + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + gif + None + + + + + + (p)(f) + + + arw + bmp + cr2 + exr + ico + jpg + jpeg + raf + png + psd + svg + tga + tif + tiff + xcf + webp + None + + + + + (p)(f)-small + + + arw + bmp + cr2 + exr + ico + jpg + jpeg + raf + png + psd + svg + tga + tif + tiff + xcf + webp + None + + + + + + (p)(f) + + + arw + bmp + cr2 + exr + ico + jpg + jpeg + raf + png + psd + svg + tga + tif + tiff + xcf + webp + None + + + + + + (p)(f) + + + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + gif + None + + + + + + + (p)(f) + + + gif + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + None + + + + + + + (p)(f) + + + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + gif + None + + + + + + + (p)(f) + + + avi + bik + flv + mkv + mov + mp4 + 3gp + webm + wmv + m4v + mpeg + ogv + gif + None + + + + + + (p)(f) + + + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + gif + None + + + + + + (p)(f) + + + gif + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + None + + + + + + (p)(f) + + + arw + bmp + cr2 + exr + ico + jpg + jpeg + raf + png + psd + svg + tga + tif + tiff + webp + None + + + + + (p)(f) + + + arw + bmp + cr2 + exr + ico + jpg + jpeg + raf + png + psd + svg + tga + tif + tiff + xcf + webp + None + + + + + + (p)(f) + + + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + gif + None + + + + + + + (p)(f) + + + avi + bik + flv + mkv + mov + mp4 + 3gp + webm + wmv + m4v + mpeg + ogv + gif + None + + + + + + + (p)(f) + + + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + gif + None + + + + + + + (p)(f) + + + avi + bik + flv + mkv + mov + mp4 + 3gp + webm + wmv + m4v + mpeg + ogv + gif + None + + + + + + (p)(f) + + + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + gif + None + + + + + + (p)(f) + + + gif + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + None + + + + + + (p)(f) + + + arw + bmp + cr2 + exr + ico + jpg + jpeg + raf + png + psd + svg + tga + tif + tiff + webp + None + + + + + (p)(f) + + + arw + bmp + cr2 + exr + ico + jpg + jpeg + raf + png + psd + svg + tga + tif + tiff + xcf + webp + None + + + + + + (p)(f) + true \ No newline at end of file diff --git a/Application/FileConverter/ViewModels/InputExtensionCategory.cs b/Application/FileConverter/ViewModels/InputExtensionCategory.cs index be240a9..95c9842 100644 --- a/Application/FileConverter/ViewModels/InputExtensionCategory.cs +++ b/Application/FileConverter/ViewModels/InputExtensionCategory.cs @@ -3,12 +3,9 @@ namespace FileConverter.ViewModels { using System.Collections.Generic; - using System.ComponentModel; - using System.Runtime.CompilerServices; + using GalaSoft.MvvmLight; - using FileConverter.Annotations; - - public class InputExtensionCategory : INotifyPropertyChanged + public class InputExtensionCategory : ObservableObject { private string name; private List inputExtensions = new List(); @@ -18,8 +15,6 @@ namespace FileConverter.ViewModels this.Name = name; } - public event PropertyChangedEventHandler PropertyChanged; - public string Name { get @@ -30,7 +25,7 @@ namespace FileConverter.ViewModels set { this.name = value; - this.OnPropertyChanged(); + this.RaisePropertyChanged(); } } @@ -60,15 +55,9 @@ namespace FileConverter.ViewModels { inputExtension = new InputExtension(extension); this.inputExtensions.Add(inputExtension); - this.OnPropertyChanged("InputExtensions"); - this.OnPropertyChanged("InputExtensionNames"); + this.RaisePropertyChanged("InputExtensions"); + this.RaisePropertyChanged("InputExtensionNames"); } } - - [NotifyPropertyChangedInvocator] - protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) - { - this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } } } \ No newline at end of file diff --git a/Application/FileConverter/ViewModels/PresetNode.cs b/Application/FileConverter/ViewModels/PresetNode.cs new file mode 100644 index 0000000..a3d25e5 --- /dev/null +++ b/Application/FileConverter/ViewModels/PresetNode.cs @@ -0,0 +1,300 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +using System; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Linq; +using GalaSoft.MvvmLight; + +namespace FileConverter.ViewModels +{ + public abstract class AbstractTreeNode : ObservableObject, IDataErrorInfo + { + private PresetFolderNode parent; + + protected AbstractTreeNode(PresetFolderNode parent) + { + this.Parent = parent; + } + +#if DEBUG + protected AbstractTreeNode() + { + } +#endif + + public PresetFolderNode Parent + { + get => this.parent; + set + { + this.parent = value; + this.RaisePropertyChanged(); + } + } + + public abstract string Name + { + get; + set; + } + + public string this[string columnName] => this.Validate(columnName); + + public bool HasError => !string.IsNullOrEmpty(this.Error); + + public string Error + { + get + { + if (this.Parent == null) + { + // This is the root folder. Don't check rules on this specific folder. + return string.Empty; + } + + string errorString = this.Validate("Name"); + if (!string.IsNullOrEmpty(errorString)) + { + return errorString; + } + + errorString = this.Validate("OutputFileNameTemplate"); + if (!string.IsNullOrEmpty(errorString)) + { + return errorString; + } + + return string.Empty; + } + } + + protected virtual string Validate(string propertyName) + { + // Return error message if there is an error, else return empty or null string. + switch (propertyName) + { + case "Name": + { + if (string.IsNullOrEmpty(this.Name)) + { + return "The preset name can't be empty."; + } + + if (this.Name.Contains(";")) + { + return "The preset name can't contains the character ';'."; + } + + if (this.Name.Contains("/")) + { + return "The preset name can't contains the character '/'."; + } + + if (this.Parent != null) + { + int count = this.Parent.Children.Count(node => node.Name == this.Name); + if (count > 1) + { + return "The preset name is already used."; + } + } + } + + break; + } + + return string.Empty; + } + } + + public class PresetNode : AbstractTreeNode + { + public PresetNode(ConversionPreset preset, PresetFolderNode parent) : base(parent) + { + this.Preset = preset; + } + +#if DEBUG + public PresetNode() : base() + { + } +#endif + + public ConversionPreset Preset + { + get; +#if DEBUG + set; +#endif + } + + public override string Name + { + get => this.Preset.ShortName; + + set + { + this.Preset.ShortName = value; + this.RaisePropertyChanged(); + this.RaisePropertyChanged(nameof(this.HasError)); + } + } + + public string OutputFileNameTemplate + { + get + { + return this.Preset.OutputFileNameTemplate; + } + + set + { + this.Preset.OutputFileNameTemplate = value; + this.RaisePropertyChanged(); + } + } + + protected override string Validate(string propertyName) + { + string error = base.Validate(propertyName); + if (!string.IsNullOrEmpty(error)) + { + return error; + } + + // Return error message if there is an error, else return empty or null string. + switch (propertyName) + { + case "OutputFileNameTemplate": + { + string sampleOutputFilePath = this.Preset.GenerateOutputFilePath(FileConverter.Properties.Resources.OutputFileNameTemplateSample, 1, 3); + if (string.IsNullOrEmpty(sampleOutputFilePath)) + { + return "The output filename template must produce a non empty result."; + } + + if (!PathHelpers.IsPathValid(sampleOutputFilePath)) + { + // Diagnostic to feedback purpose. + // Drive letter. + if (!PathHelpers.IsPathDriveLetterValid(sampleOutputFilePath)) + { + return "The output filename template must define a root (for example c:\\, use (p) to use the input file path)."; + } + + // File name. + string filename = PathHelpers.GetFileName(sampleOutputFilePath); + if (filename == null) + { + return "The output file name must not be empty (use (f) to use the name of the input file)."; + } + + char[] invalidFileNameChars = System.IO.Path.GetInvalidFileNameChars(); + for (int index = 0; index < invalidFileNameChars.Length; index++) + { + if (filename.Contains(invalidFileNameChars[index])) + { + return "The output file name must not contains the character '" + invalidFileNameChars[index] + "'."; + } + } + + // Directory names. + string path = sampleOutputFilePath.Substring(3, sampleOutputFilePath.Length - 3 - filename.Length); + char[] invalidPathChars = System.IO.Path.GetInvalidPathChars(); + for (int index = 0; index < invalidPathChars.Length; index++) + { + if (string.IsNullOrEmpty(path)) + { + return "The output directory name must not be empty (use (d0), (d1), ... to use the name of the parent directories of the input file)."; + } + + if (path.Contains(invalidPathChars[index])) + { + return "The output directory name must not contains the character '" + invalidPathChars[index] + "'."; + } + } + + string[] directories = path.Split('\\'); + for (int index = 0; index < directories.Length; ++index) + { + string directoryName = directories[index]; + if (string.IsNullOrEmpty(directoryName)) + { + return "The output directory name must not be empty (use (d0), (d1), ... to use the name of the parent directories of the input file)."; + } + } + + return "The output filename template is invalid"; + } + } + + break; + } + + return string.Empty; + } + } + + public class PresetFolderNode : AbstractTreeNode + { + private string name; + private ObservableCollection children = new ObservableCollection(); + + public PresetFolderNode(string name, PresetFolderNode parent) : base(parent) + { + this.Name = name; + } + +#if DEBUG + public PresetFolderNode() : base() + { + } +#endif + + public override string Name + { + get => this.name; + + set + { + this.name = value; + this.RaisePropertyChanged(); + this.RaisePropertyChanged(nameof(this.HasError)); + } + } + + public ObservableCollection Children + { + get => this.children; + + set + { + this.children = value; + this.RaisePropertyChanged(); + } + } + + public bool IsNodeInHierarchy(AbstractTreeNode node, bool recurse) + { + Diagnostics.Debug.Assert(node != null, "node != null"); + foreach (ObservableObject child in this.Children) + { + if (child == node) + { + return true; + } + + if (recurse && child is PresetFolderNode subFolder) + { + if (subFolder.IsNodeInHierarchy(node, true)) + { + return true; + } + } + } + + return false; + } + } +} diff --git a/Application/FileConverter/ViewModels/SettingsViewModel.cs b/Application/FileConverter/ViewModels/SettingsViewModel.cs index a930e20..62f2b47 100644 --- a/Application/FileConverter/ViewModels/SettingsViewModel.cs +++ b/Application/FileConverter/ViewModels/SettingsViewModel.cs @@ -12,6 +12,7 @@ namespace FileConverter.ViewModels using System.Windows.Input; using FileConverter.Services; + using FileConverter.Views; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; @@ -32,15 +33,18 @@ namespace FileConverter.ViewModels /// See http://www.galasoft.ch/mvvm /// /// - public class SettingsViewModel : ViewModelBase + public class SettingsViewModel : ViewModelBase, IDataErrorInfo { private InputExtensionCategory[] inputCategories; - private ConversionPreset selectedPreset; + private PresetFolderNode presetsRootFolder; + private PresetFolderNode selectedFolder; + private PresetNode selectedPreset; private Settings settings; private bool displaySeeChangeLogLink = true; private RelayCommand openUrlCommand; private RelayCommand getChangeLogContentCommand; + private RelayCommand createFolderCommand; private RelayCommand movePresetUpCommand; private RelayCommand movePresetDownCommand; private RelayCommand addNewPresetCommand; @@ -56,12 +60,21 @@ namespace FileConverter.ViewModels /// public SettingsViewModel() { + this.getChangeLogContentCommand = new RelayCommand(this.DownloadChangeLogAction); + this.openUrlCommand = new RelayCommand((url) => Process.Start(url)); + this.createFolderCommand = new RelayCommand(this.CreateFolder); + this.movePresetUpCommand = new RelayCommand(this.MoveSelectedPresetUp, this.CanMoveSelectedPresetUp); + this.movePresetDownCommand = new RelayCommand(this.MoveSelectedPresetDown, this.CanMoveSelectedPresetDown); + this.addNewPresetCommand = new RelayCommand(this.AddNewPreset); + this.removePresetCommand = new RelayCommand(this.RemoveSelectedPreset, this.CanRemoveSelectedPreset); + this.saveCommand = new RelayCommand(this.SaveSettings, this.CanSaveSettings); + this.closeCommand = new RelayCommand(this.CloseSettings); + if (this.IsInDesignMode) { // Code runs in Blend --> create design time data. this.Settings = new Settings(); this.Settings.ConversionPresets.Add(new ConversionPreset("Test", OutputType.Mp3)); - this.SelectedPreset = new ConversionPreset("Test", OutputType.Mp3); } else { @@ -91,6 +104,7 @@ namespace FileConverter.ViewModels this.SupportedCultures = Helpers.GetSupportedCultures().ToArray(); this.InitializeCompatibleInputExtensions(); + this.InitializePresetFolders(); } } @@ -106,7 +120,7 @@ namespace FileConverter.ViewModels for (int index = 0; index < this.inputCategories.Length; index++) { InputExtensionCategory category = this.inputCategories[index]; - if (this.SelectedPreset == null || Helpers.IsOutputTypeCompatibleWithCategory(this.SelectedPreset.OutputType, category.Name)) + if (this.SelectedPreset == null || Helpers.IsOutputTypeCompatibleWithCategory(this.SelectedPreset.Preset.OutputType, category.Name)) { yield return category; } @@ -121,7 +135,68 @@ namespace FileConverter.ViewModels InputPostConversionAction.Delete, }; - public ConversionPreset SelectedPreset + public PresetFolderNode PresetsRootFolder + { + get => this.presetsRootFolder; + + set + { + this.presetsRootFolder = value; + this.RaisePropertyChanged(); + } + } + + public AbstractTreeNode SelectedItem + { + get + { + if (this.SelectedFolder != null) + { + return this.SelectedFolder; + } + + return this.SelectedPreset; + } + + set + { + if (value is PresetNode preset) + { + this.SelectedPreset = preset; + this.SelectedFolder = null; + } + else if (value is PresetFolderNode folder) + { + this.SelectedFolder = folder; + this.SelectedPreset = null; + } + else + { + this.SelectedPreset = null; + this.SelectedFolder = null; + } + + this.RaisePropertyChanged(); + } + } + + public PresetFolderNode SelectedFolder + { + get => this.selectedFolder; + + set + { + this.selectedFolder = value; + + this.RaisePropertyChanged(); + this.RaisePropertyChanged(nameof(this.SelectedItem)); + this.movePresetUpCommand?.RaiseCanExecuteChanged(); + this.movePresetDownCommand?.RaiseCanExecuteChanged(); + this.removePresetCommand?.RaiseCanExecuteChanged(); + } + } + + public PresetNode SelectedPreset { get => this.selectedPreset; @@ -129,20 +204,22 @@ namespace FileConverter.ViewModels { if (this.selectedPreset != null) { - this.selectedPreset.PropertyChanged -= this.SelectedPresetPropertyChanged; + this.selectedPreset.Preset.PropertyChanged -= this.SelectedPresetPropertyChanged; } this.selectedPreset = value; if (this.selectedPreset != null) { - this.selectedPreset.PropertyChanged += this.SelectedPresetPropertyChanged; + this.selectedPreset.Preset.PropertyChanged += this.SelectedPresetPropertyChanged; } this.RaisePropertyChanged(); + this.RaisePropertyChanged(nameof(this.SelectedItem)); this.RaisePropertyChanged(nameof(this.InputCategories)); this.movePresetUpCommand?.RaiseCanExecuteChanged(); this.movePresetDownCommand?.RaiseCanExecuteChanged(); + this.removePresetCommand?.RaiseCanExecuteChanged(); } } @@ -192,108 +269,74 @@ namespace FileConverter.ViewModels } } - public ICommand GetChangeLogContentCommand + public ICommand GetChangeLogContentCommand => this.getChangeLogContentCommand; + + public ICommand OpenUrlCommand => this.openUrlCommand; + + public ICommand CreateFolderCommand => this.createFolderCommand; + + public ICommand MovePresetUpCommand => this.movePresetUpCommand; + + public ICommand MovePresetDownCommand => this.movePresetDownCommand; + + public ICommand AddNewPresetCommand => this.addNewPresetCommand; + + public ICommand RemoveSelectedPresetCommand => this.removePresetCommand; + + public ICommand SaveCommand => this.saveCommand; + + public ICommand CloseCommand => this.closeCommand; + + public TreeViewSelectionBehavior.IsChildOfPredicate PresetsHierarchyPredicate => (object nodeA, object nodeB) => + { + if (nodeA is PresetNode) + { + return false; + } + + PresetFolderNode parentFolder = nodeA as PresetFolderNode; + Diagnostics.Debug.Assert(parentFolder != null, "Node should be a preset folder."); + + return parentFolder.IsNodeInHierarchy(nodeB as AbstractTreeNode, true); + }; + + public string Error { get { - if (this.getChangeLogContentCommand == null) + string nodeError = this.CheckErrorRecursively(this.presetsRootFolder); + if (!string.IsNullOrEmpty(nodeError)) { - this.getChangeLogContentCommand = new RelayCommand(this.DownloadChangeLogAction); + return nodeError; } - return this.getChangeLogContentCommand; + return string.Empty; } } - public ICommand OpenUrlCommand + public string this[string columnName] => this.Error; + + private string CheckErrorRecursively(AbstractTreeNode node) { - get + string nodeError = node.Error; + if (!string.IsNullOrEmpty(nodeError)) { - if (this.openUrlCommand == null) - { - this.openUrlCommand = new RelayCommand((url) => Process.Start(url)); - } - - return this.openUrlCommand; + return nodeError; } - } - public ICommand MovePresetUpCommand - { - get + if (node is PresetFolderNode folder) { - if (this.movePresetUpCommand == null) + foreach (AbstractTreeNode child in folder.Children) { - this.movePresetUpCommand = new RelayCommand(this.MoveSelectedPresetUp, this.CanMoveSelectedPresetUp); + nodeError = this.CheckErrorRecursively(child); + if (!string.IsNullOrEmpty(nodeError)) + { + return nodeError; + } } - - return this.movePresetUpCommand; } - } - public ICommand MovePresetDownCommand - { - get - { - if (this.movePresetDownCommand == null) - { - this.movePresetDownCommand = new RelayCommand(this.MoveSelectedPresetDown, this.CanMoveSelectedPresetDown); - } - - return this.movePresetDownCommand; - } - } - - public ICommand AddNewPresetCommand - { - get - { - if (this.addNewPresetCommand == null) - { - this.addNewPresetCommand = new RelayCommand(this.AddNewPreset); - } - - return this.addNewPresetCommand; - } - } - - public ICommand RemoveSelectedPresetCommand - { - get - { - if (this.removePresetCommand == null) - { - this.removePresetCommand = new RelayCommand(this.RemoveSelectedPreset, this.CanRemoveSelectedPreset); - } - - return this.removePresetCommand; - } - } - - public ICommand SaveCommand - { - get - { - if (this.saveCommand == null) - { - this.saveCommand = new RelayCommand(this.SaveSettings, this.CanSaveSettings); - } - - return this.saveCommand; - } - } - - public ICommand CloseCommand - { - get - { - if (this.closeCommand == null) - { - this.closeCommand = new RelayCommand(this.CloseSettings); - } - - return this.closeCommand; - } + return string.Empty; } private void SelectedPresetPropertyChanged(object sender, PropertyChangedEventArgs eventArgs) @@ -306,6 +349,11 @@ namespace FileConverter.ViewModels this.saveCommand.RaiseCanExecuteChanged(); } + private void NodePropertyChanged(object sender, PropertyChangedEventArgs eventArgs) + { + this.saveCommand.RaiseCanExecuteChanged(); + } + private void DownloadChangeLogAction() { IUpgradeService upgradeService = SimpleIoc.Default.GetInstance(); @@ -349,7 +397,62 @@ namespace FileConverter.ViewModels this.inputCategories = categories.ToArray(); this.RaisePropertyChanged(nameof(this.InputCategories)); } - + + private void InitializePresetFolders() + { + this.presetsRootFolder = new PresetFolderNode(null, null); + foreach (ConversionPreset preset in this.Settings.ConversionPresets) + { + PresetFolderNode parent = this.presetsRootFolder; + foreach (string folderName in preset.ParentFoldersNames) + { + PresetFolderNode subFolder = parent.Children.FirstOrDefault(match => match is PresetFolderNode && ((PresetFolderNode)match).Name == folderName) as PresetFolderNode; + if (subFolder == null) + { + subFolder = new PresetFolderNode(folderName, parent); + parent.Children.Add(subFolder); + + subFolder.PropertyChanged += this.NodePropertyChanged; + } + + parent = subFolder; + } + + PresetNode presetNode = new PresetNode(preset, parent); + parent.Children.Add(presetNode); + + presetNode.PropertyChanged += this.NodePropertyChanged; + } + + this.RaisePropertyChanged(nameof(this.PresetsRootFolder)); + } + + private void ComputePresetsParentFoldersNamesAndFillSettings(AbstractTreeNode node, List folderNamesCache) + { + if (node is PresetFolderNode folder) + { + if (!string.IsNullOrEmpty(folder.Name)) + { + folderNamesCache.Add(folder.Name); + } + + foreach (var child in folder.Children) + { + this.ComputePresetsParentFoldersNamesAndFillSettings(child, folderNamesCache); + } + + if (!string.IsNullOrEmpty(folder.Name)) + { + folderNamesCache.RemoveAt(folderNamesCache.Count - 1); + } + } + else if (node is PresetNode preset) + { + preset.Preset.ParentFoldersNames = folderNamesCache.ToArray(); + this.settings.ConversionPresets.Add(preset.Preset); + } + } + private void CloseSettings(CancelEventArgs args) { ISettingsService settingsService = SimpleIoc.Default.GetInstance(); @@ -361,11 +464,15 @@ namespace FileConverter.ViewModels private bool CanSaveSettings() { - return this.settings != null && string.IsNullOrEmpty(this.settings.Error); + return string.IsNullOrEmpty(this.Error); } private void SaveSettings() { + // Compute parent folder names. + this.settings.ConversionPresets.Clear(); + this.ComputePresetsParentFoldersNamesAndFillSettings(this.presetsRootFolder, new List()); + // Save changes. ISettingsService settingsService = SimpleIoc.Default.GetInstance(); settingsService.SaveSettings(); @@ -373,108 +480,255 @@ namespace FileConverter.ViewModels INavigationService navigationService = SimpleIoc.Default.GetInstance(); navigationService.Close(Pages.Settings, false); } - + + private void CreateFolder() + { + PresetFolderNode parent; + if (this.SelectedFolder != null) + { + parent = this.SelectedFolder; + } + else if (this.SelectedItem != null) + { + parent = this.SelectedItem.Parent; + } + else + { + parent = this.presetsRootFolder; + } + + int insertIndex = parent.Children.IndexOf(this.SelectedItem) + 1; + if (insertIndex < 0) + { + insertIndex = parent.Children.Count; + } + + // Generate a unique folder name. + string folderName = Properties.Resources.DefaultFolderName; + int index = 1; + while (parent.Children.Any(match => match is PresetFolderNode folder && folder.Name == folderName)) + { + index++; + folderName = $"{Properties.Resources.DefaultFolderName} ({index})"; + } + + PresetFolderNode newFolder = new PresetFolderNode(folderName, parent); + + parent.Children.Insert(insertIndex, newFolder); + + newFolder.PropertyChanged += this.NodePropertyChanged; + + this.SelectedItem = newFolder; + + this.saveCommand.RaiseCanExecuteChanged(); + + Messenger.Default.Send("FolderName", "DoFocus"); + } + private bool CanMoveSelectedPresetUp() { - ConversionPreset presetToMove = this.SelectedPreset; - if (presetToMove == null) + if (this.SelectedItem == null) { + // no preset selected. return false; } - int indexOfSelectedPreset = this.settings.ConversionPresets.IndexOf(presetToMove); + if (this.SelectedItem.Parent != this.presetsRootFolder) + { + // The parent is not the root, we can move the preset up. + return true; + } + + int indexOfSelectedPreset = this.SelectedItem.Parent.Children.IndexOf(this.SelectedItem); return indexOfSelectedPreset > 0; } private void MoveSelectedPresetUp() { - ConversionPreset presetToMove = this.SelectedPreset; - if (presetToMove == null) + Diagnostics.Debug.Assert(this.SelectedItem != null, "this.SelectedItem != null"); + + AbstractTreeNode itemToMoveUp = this.SelectedItem; + PresetFolderNode currentParent = itemToMoveUp.Parent; + int indexOfSelectedPreset = currentParent.Children.IndexOf(itemToMoveUp); + if (indexOfSelectedPreset == 0) { - return; + // Move to the parent folder. + int indexOfFolder = currentParent.Parent.Children.IndexOf(currentParent); + currentParent.Children.RemoveAt(indexOfSelectedPreset); + currentParent.Parent.Children.Insert(indexOfFolder, itemToMoveUp); + itemToMoveUp.Parent = currentParent.Parent; + } + else + { + int newIndexOfSelectedPreset = System.Math.Max(0, indexOfSelectedPreset - 1); + if (currentParent.Children[newIndexOfSelectedPreset] is PresetFolderNode newParent) + { + // Move to child folder. + currentParent.Children.RemoveAt(indexOfSelectedPreset); + newParent.Children.Add(itemToMoveUp); + itemToMoveUp.Parent = newParent; + } + else + { + // Swap nodes. + currentParent.Children.Move(indexOfSelectedPreset, newIndexOfSelectedPreset); + } } - int indexOfSelectedPreset = this.settings.ConversionPresets.IndexOf(presetToMove); - int newIndexOfSelectedPreset = System.Math.Max(0, indexOfSelectedPreset - 1); - - this.settings.ConversionPresets.Move(indexOfSelectedPreset, newIndexOfSelectedPreset); - this.movePresetUpCommand?.RaiseCanExecuteChanged(); - this.movePresetDownCommand?.RaiseCanExecuteChanged(); + this.SelectedItem = itemToMoveUp; + this.movePresetUpCommand.RaiseCanExecuteChanged(); + this.movePresetDownCommand.RaiseCanExecuteChanged(); + this.saveCommand.RaiseCanExecuteChanged(); } private bool CanMoveSelectedPresetDown() { - ConversionPreset presetToMove = this.SelectedPreset; - if (presetToMove == null) + if (this.SelectedItem == null) { + // no preset selected. return false; } - int indexOfSelectedPreset = this.settings.ConversionPresets.IndexOf(presetToMove); - return indexOfSelectedPreset < this.settings.ConversionPresets.Count - 1; + if (this.SelectedItem.Parent != this.presetsRootFolder) + { + // The parent is not the root, we can move the preset down. + return true; + } + + int indexOfSelectedPreset = this.SelectedItem.Parent.Children.IndexOf(this.SelectedItem); + return indexOfSelectedPreset < this.SelectedItem.Parent.Children.Count - 1; } private void MoveSelectedPresetDown() { - ConversionPreset presetToMove = this.SelectedPreset; - if (presetToMove == null) + Diagnostics.Debug.Assert(this.SelectedItem != null, "this.SelectedItem != null"); + + AbstractTreeNode itemToMoveDown = this.SelectedItem; + PresetFolderNode currentParent = itemToMoveDown.Parent; + int indexOfSelectedPreset = currentParent.Children.IndexOf(itemToMoveDown); + if (indexOfSelectedPreset == currentParent.Children.Count - 1) { - return; + // Move to the parent folder. + int indexOfFolder = currentParent.Parent.Children.IndexOf(currentParent); + currentParent.Children.RemoveAt(indexOfSelectedPreset); + currentParent.Parent.Children.Insert(indexOfFolder + 1, itemToMoveDown); + itemToMoveDown.Parent = currentParent.Parent; + } + else + { + int newIndexOfSelectedPreset = System.Math.Min(this.SelectedItem.Parent.Children.Count - 1, indexOfSelectedPreset + 1); + if (currentParent.Children[newIndexOfSelectedPreset] is PresetFolderNode newParent) + { + // Move to child folder. + currentParent.Children.RemoveAt(indexOfSelectedPreset); + newParent.Children.Insert(0, itemToMoveDown); + itemToMoveDown.Parent = newParent; + } + else + { + // Swap nodes. + currentParent.Children.Move(indexOfSelectedPreset, newIndexOfSelectedPreset); + } } - int indexOfSelectedPreset = this.settings.ConversionPresets.IndexOf(presetToMove); - int newIndexOfSelectedPreset = System.Math.Min(this.settings.ConversionPresets.Count - 1, indexOfSelectedPreset + 1); + this.SelectedItem = itemToMoveDown; - this.settings.ConversionPresets.Move(indexOfSelectedPreset, newIndexOfSelectedPreset); - this.movePresetUpCommand?.RaiseCanExecuteChanged(); - this.movePresetDownCommand?.RaiseCanExecuteChanged(); + this.movePresetUpCommand.RaiseCanExecuteChanged(); + this.movePresetDownCommand.RaiseCanExecuteChanged(); + this.saveCommand.RaiseCanExecuteChanged(); } private void AddNewPreset() { + PresetFolderNode parent; + if (this.SelectedFolder != null) + { + parent = this.SelectedFolder; + } + else if (this.SelectedItem != null) + { + parent = this.SelectedItem.Parent; + } + else + { + parent = this.presetsRootFolder; + } + + int insertIndex = parent.Children.IndexOf(this.SelectedItem) + 1; + if (insertIndex < 0) + { + insertIndex = parent.Children.Count; + } + // Generate a unique preset name. - ISettingsService settingsService = SimpleIoc.Default.GetInstance(); string presetName = Properties.Resources.DefaultPresetName; int index = 1; - while (settingsService.Settings.ConversionPresets.Any(match => match.Name == presetName)) + while (parent.Children.Any(match => match is PresetNode folder && folder.Preset.ShortName == presetName)) { index++; presetName = $"{Properties.Resources.DefaultPresetName} ({index})"; } - // Create preset by coping the selected one. - int insertIndex = 0; + // Create preset by copying the selected one. ConversionPreset newPreset = null; if (this.SelectedPreset != null) { - newPreset = new ConversionPreset(presetName, this.SelectedPreset); - insertIndex = this.settings.ConversionPresets.IndexOf(this.SelectedPreset) + 1; + newPreset = new ConversionPreset(presetName, this.SelectedPreset.Preset); } else { newPreset = new ConversionPreset(presetName, OutputType.Mkv, new string[0]); - insertIndex = this.settings.ConversionPresets.Count; } - settingsService.Settings.ConversionPresets.Insert(insertIndex, newPreset); - this.SelectedPreset = newPreset; + PresetNode node = new PresetNode(newPreset, parent); + + parent.Children.Insert(insertIndex, node); + + node.PropertyChanged += this.NodePropertyChanged; + + this.SelectedItem = node; Messenger.Default.Send("PresetName", "DoFocus"); this.removePresetCommand.RaiseCanExecuteChanged(); + this.saveCommand.RaiseCanExecuteChanged(); } private void RemoveSelectedPreset() { - ISettingsService settingsService = SimpleIoc.Default.GetInstance(); - settingsService.Settings.ConversionPresets.Remove(this.selectedPreset); + this.SelectedItem.PropertyChanged -= this.NodePropertyChanged; + + this.SelectedItem.Parent.Children.Remove(this.SelectedItem); + + this.SelectedItem = null; this.removePresetCommand.RaiseCanExecuteChanged(); + this.saveCommand.RaiseCanExecuteChanged(); } private bool CanRemoveSelectedPreset() { - return this.SelectedPreset != null; + return this.SelectedItem != null; + } + + public override void Cleanup() + { + base.Cleanup(); + + this.UnbindNode(this.presetsRootFolder); + } + + private void UnbindNode(AbstractTreeNode node) + { + node.PropertyChanged -= this.NodePropertyChanged; + + if (node is PresetFolderNode folder) + { + foreach (AbstractTreeNode child in folder.Children) + { + this.UnbindNode(child); + } + } } } } diff --git a/Application/FileConverter/Views/BindableSelectedItemBehavior.cs b/Application/FileConverter/Views/BindableSelectedItemBehavior.cs new file mode 100644 index 0000000..8204034 --- /dev/null +++ b/Application/FileConverter/Views/BindableSelectedItemBehavior.cs @@ -0,0 +1,199 @@ +// Source: https://tyrrrz.me/Blog/WPF-TreeView-SelectedItem-TwoWay-binding + +using System.Collections.Specialized; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Interactivity; + +namespace FileConverter.Views +{ + public class TreeViewSelectionBehavior : Behavior + { + public delegate bool IsChildOfPredicate(object nodeA, object nodeB); + + public static readonly DependencyProperty SelectedItemProperty = + DependencyProperty.Register(nameof(SelectedItem), typeof(object), + typeof(TreeViewSelectionBehavior), + new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, + OnSelectedItemChanged)); + + public static readonly DependencyProperty HierarchyPredicateProperty = + DependencyProperty.Register(nameof(HierarchyPredicate), typeof(IsChildOfPredicate), + typeof(TreeViewSelectionBehavior), + new FrameworkPropertyMetadata(null)); + + public static readonly DependencyProperty ExpandSelectedProperty = + DependencyProperty.Register(nameof(ExpandSelected), typeof(bool), + typeof(TreeViewSelectionBehavior), + new FrameworkPropertyMetadata(false)); + + private readonly EventSetter treeViewItemEventSetter; + private bool modelHandled; + + public TreeViewSelectionBehavior() + { + this.treeViewItemEventSetter = new EventSetter(FrameworkElement.LoadedEvent, new RoutedEventHandler(this.OnTreeViewItemLoaded)); + } + + // Bindable selected item + public object SelectedItem + { + get => this.GetValue(SelectedItemProperty); + set => this.SetValue(SelectedItemProperty, value); + } + + // Predicate that checks if two items are hierarchically related + public IsChildOfPredicate HierarchyPredicate + { + get => (IsChildOfPredicate)this.GetValue(HierarchyPredicateProperty); + set => this.SetValue(HierarchyPredicateProperty, value); + } + + // Should expand selected? + public bool ExpandSelected + { + get => (bool)this.GetValue(ExpandSelectedProperty); + set => this.SetValue(ExpandSelectedProperty, value); + } + + protected override void OnAttached() + { + base.OnAttached(); + + this.AssociatedObject.SelectedItemChanged += this.OnTreeViewSelectedItemChanged; + ((INotifyCollectionChanged)this.AssociatedObject.Items).CollectionChanged += this.OnTreeViewItemsChanged; + + this.UpdateTreeViewItemStyle(); + this.modelHandled = true; + this.UpdateAllTreeViewItems(); + this.modelHandled = false; + } + + protected override void OnDetaching() + { + base.OnDetaching(); + + if (this.AssociatedObject != null) + { + this.AssociatedObject.ItemContainerStyle?.Setters?.Remove(this.treeViewItemEventSetter); + this.AssociatedObject.SelectedItemChanged -= this.OnTreeViewSelectedItemChanged; + ((INotifyCollectionChanged)this.AssociatedObject.Items).CollectionChanged -= this.OnTreeViewItemsChanged; + } + } + + private static void OnSelectedItemChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) + { + var behavior = (TreeViewSelectionBehavior)sender; + if (behavior.modelHandled) + { + return; + } + + if (behavior.AssociatedObject == null) + { + return; + } + + behavior.modelHandled = true; + behavior.UpdateAllTreeViewItems(); + behavior.modelHandled = false; + } + + // Update state of all items starting with given, with optional recursion + private void UpdateTreeViewItem(TreeViewItem item, bool recurse) + { + if (this.SelectedItem == null) + { + return; + } + + var model = item.DataContext; + + // If the selected item is this model and is not yet selected - select and return + if (this.SelectedItem == model && !item.IsSelected) + { + item.IsSelected = true; + } + // If the selected item is a parent of this model - expand + else + { + bool isParentOfModel = this.HierarchyPredicate?.Invoke(this.SelectedItem, model) ?? true; + if (isParentOfModel) + { + item.IsExpanded = true; + } + } + + if (item.IsSelected && this.ExpandSelected) + { + item.IsExpanded = true; + } + + // Recurse into children + if (recurse) + { + foreach (var subitem in item.Items) + { + if (item.ItemContainerGenerator.ContainerFromItem(subitem) is TreeViewItem tvi) + { + this.UpdateTreeViewItem(tvi, true); + } + } + } + } + + // Update state of all items + private void UpdateAllTreeViewItems() + { + var treeView = this.AssociatedObject; + foreach (var item in treeView.Items) + { + if (treeView.ItemContainerGenerator.ContainerFromItem(item) is TreeViewItem tvi) + { + this.UpdateTreeViewItem(tvi, true); + } + } + } + + // Inject Loaded event handler into ItemContainerStyle + private void UpdateTreeViewItemStyle() + { + if (this.AssociatedObject.ItemContainerStyle == null) + { + this.AssociatedObject.ItemContainerStyle = new Style( + typeof(TreeViewItem), + Application.Current.TryFindResource(typeof(TreeViewItem)) as Style); + } + + if (!this.AssociatedObject.ItemContainerStyle.Setters.Contains(this.treeViewItemEventSetter)) + { + this.AssociatedObject.ItemContainerStyle.Setters.Add(this.treeViewItemEventSetter); + } + } + + private void OnTreeViewItemsChanged(object sender, + NotifyCollectionChangedEventArgs args) + { + this.UpdateAllTreeViewItems(); + } + + private void OnTreeViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs args) + { + if (this.modelHandled) + { + return; + } + if (this.AssociatedObject.Items.SourceCollection == null) + { + return; + } + + this.SelectedItem = args.NewValue; + } + + private void OnTreeViewItemLoaded(object sender, RoutedEventArgs args) + { + this.UpdateTreeViewItem((TreeViewItem)sender, false); + } + } +} diff --git a/Application/FileConverter/Views/DragDropExtension.cs b/Application/FileConverter/Views/DragDropExtension.cs new file mode 100644 index 0000000..0608ccb --- /dev/null +++ b/Application/FileConverter/Views/DragDropExtension.cs @@ -0,0 +1,117 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.Views +{ + using System; + using System.Windows; + using System.Windows.Controls; + using System.Windows.Media; + + /// + /// Provides extended support for drag drop operation + /// + public static class DragDropExtension + { + public static readonly DependencyProperty ScrollOnDragDropProperty = DependencyProperty.RegisterAttached("ScrollOnDragDrop", typeof(bool), typeof(DragDropExtension), new PropertyMetadata(false, HandleScrollOnDragDropChanged)); + + public static bool GetScrollOnDragDrop(DependencyObject element) + { + if (element == null) + { + throw new ArgumentNullException(nameof(element)); + } + + return (bool)element.GetValue(ScrollOnDragDropProperty); + } + + public static void SetScrollOnDragDrop(DependencyObject element, bool value) + { + if (element == null) + { + throw new ArgumentNullException(nameof(element)); + } + + element.SetValue(ScrollOnDragDropProperty, value); + } + + private static void HandleScrollOnDragDropChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args) + { + if (dependencyObject == null) + { + Diagnostics.Debug.LogError("Invalid types!"); + return; + } + + FrameworkElement container = dependencyObject as FrameworkElement; + + Unsubscribe(container); + + if (true.Equals(args.NewValue)) + { + Subscribe(container); + } + } + + private static void Subscribe(FrameworkElement container) + { + container.PreviewDragOver += OnContainerPreviewDragOver; + } + + private static void OnContainerPreviewDragOver(object sender, DragEventArgs args) + { + const double Tolerance = 60; + const double Offset = 20; + + FrameworkElement container = sender as FrameworkElement; + if (container == null) + { + return; + } + + ScrollViewer scrollViewer = GetFirstVisualChild(container); + if (scrollViewer == null) + { + return; + } + + double verticalPos = args.GetPosition(container).Y; + + if (verticalPos < Tolerance) // Top of visible list? + { + scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset - Offset); //Scroll up. + } + else if (verticalPos > container.ActualHeight - Tolerance) // Bottom of visible list? + { + scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset + Offset); //Scroll down. + } + } + + private static void Unsubscribe(FrameworkElement container) + { + container.PreviewDragOver -= OnContainerPreviewDragOver; + } + + public static T GetFirstVisualChild(DependencyObject dependencyObject) where T : DependencyObject + { + if (dependencyObject != null) + { + for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dependencyObject); i++) + { + DependencyObject child = VisualTreeHelper.GetChild(dependencyObject, i); + if (child is T visualChild) + { + return visualChild; + } + + T childItem = GetFirstVisualChild(child); + if (childItem != null) + { + return childItem; + } + } + } + + return null; + } + } +} diff --git a/Application/FileConverter/Views/Resources/ConversionPresets.xaml b/Application/FileConverter/Views/Resources/ConversionPresets.xaml index b824e63..0dfa7d0 100644 --- a/Application/FileConverter/Views/Resources/ConversionPresets.xaml +++ b/Application/FileConverter/Views/Resources/ConversionPresets.xaml @@ -89,13 +89,13 @@