diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..b14b2ea --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,36 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots and Logs** +If applicable, add the following informations to help explain your problem. +- Registry.xml +- Settings.user.xml +- The Diagnostics folder of the session that encountered the issue. +- A screenshot (if possible) + +You will find the xml files and diagnostics folder in `%localappdata%\FileConverter`. + +**Desktop (please complete the following information):** + - OS: [e.g. Windows 11 64bits] + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..bbcbbe7 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.gitignore b/.gitignore index d656489..879242a 100644 --- a/.gitignore +++ b/.gitignore @@ -26,6 +26,7 @@ bld/ # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* +TestData/* # NUNIT *.VisualState.xml @@ -195,6 +196,3 @@ FakesAssemblies/ # Ignore the installer signing commands file Installer/Installer.sign - -# Ignore the installer languages file because it is automatically generated -Installer/Languages.wxs diff --git a/Application/FileConverter/App.config b/Application/FileConverter/App.config index 397afee..4165a81 100644 --- a/Application/FileConverter/App.config +++ b/Application/FileConverter/App.config @@ -1,11 +1,27 @@ - + - + - + + + + + + + + + + + + + + + + + - \ No newline at end of file + diff --git a/Application/FileConverter/Application.xaml b/Application/FileConverter/Application.xaml index c817139..41d9604 100644 --- a/Application/FileConverter/Application.xaml +++ b/Application/FileConverter/Application.xaml @@ -1,57 +1,76 @@  + xmlns:viewModels="clr-namespace:FileConverter.ViewModels" + xmlns:services="clr-namespace:FileConverter.Services" + ShutdownMode="OnLastWindowClose"> - - - + + + + + - - - - + + + - - + + + + + - + + + - + + + - + + + + - + + + - + + + + + + + + + + + + + + diff --git a/Application/FileConverter/Application.xaml.cs b/Application/FileConverter/Application.xaml.cs index b2c4b6b..35ffbcf 100644 --- a/Application/FileConverter/Application.xaml.cs +++ b/Application/FileConverter/Application.xaml.cs @@ -1,7 +1,7 @@ // License: http://www.gnu.org/licenses/gpl.html GPL version 3. /* File Converter - This program allow you to convert file format to another. - Copyright (C) 2017 Adrien Allard + Copyright (C) 2024 Adrien Allard email: adrien.allard.pro@gmail.com This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -17,83 +17,49 @@ namespace FileConverter { using System; using System.Collections.Generic; - using System.Collections.ObjectModel; + using System.Diagnostics; + using System.IO; + using System.Security.Principal; using System.Threading; - using System.Threading.Tasks; using System.Windows; + using CommunityToolkit.Mvvm.DependencyInjection; + using FileConverter.ConversionJobs; - using FileConverter.Diagnostics; - using FileConverter.Windows; + using FileConverter.Services; + using FileConverter.ViewModels; + using FileConverter.Views; + using Microsoft.Extensions.DependencyInjection; + using Debug = FileConverter.Diagnostics.Debug; public partial class Application : System.Windows.Application { private static readonly Version Version = new Version() - { - Major = 1, - Minor = 2, - Patch = 3, - }; - - private readonly List conversionJobs = new List(); - - private int numberOfConversionThread = 1; + { + Major = 2, + Minor = 0, + Patch = 0, + }; private bool needToRunConversionThread; private bool cancelAutoExit; private bool isSessionEnding; + private bool verbose; + private bool showSettings; + private bool showHelp; - public Application() - { - this.ConvertionJobs = this.conversionJobs.AsReadOnly(); - } - public event EventHandler OnApplicationTerminate; - public static Version ApplicationVersion + public static Version ApplicationVersion => Application.Version; + + public static bool IsInAdmininstratorPrivileges { get { - return Application.Version; + return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); } } - public ReadOnlyCollection ConvertionJobs - { - get; - private set; - } - - public Settings Settings - { - get; - set; - } - - public bool ShowSettings - { - get; - set; - } - - public bool HideMainWindow - { - get; - set; - } - - public UpgradeVersionDescription UpgradeVersionDescription - { - get; - private set; - } - - public bool Verbose - { - get; - set; - } - public void CancelAutoExit() { this.cancelAutoExit = true; @@ -108,12 +74,36 @@ namespace FileConverter { base.OnStartup(e); + this.RegisterServices(); + this.Initialize(); + // Navigate to the wanted view. + INavigationService navigationService = Ioc.Default.GetRequiredService(); + + if (this.showHelp) + { + navigationService.Show(Pages.Help); + return; + } + if (this.needToRunConversionThread) { - Thread fileConvertionThread = Helpers.InstantiateThread("ConversionQueueThread", this.ConvertFiles); - fileConvertionThread.Start(); + navigationService.Show(Pages.Main); + + IConversionService conversionService = Ioc.Default.GetRequiredService(); + conversionService.ConversionJobsTerminated += this.ConversionService_ConversionJobsTerminated; + conversionService.ConvertFilesAsync(); + } + + if (this.showSettings) + { + navigationService.Show(Pages.Settings); + } + + if (this.verbose) + { + navigationService.Show(Pages.Diagnostics); } } @@ -122,24 +112,26 @@ namespace FileConverter base.OnExit(e); Debug.Log("Exit application."); - - if (!this.isSessionEnding && this.UpgradeVersionDescription != null && this.UpgradeVersionDescription.NeedToUpgrade) - { - Debug.Log("A new version of file converter has been found: {0}.", this.UpgradeVersionDescription.LatestVersion); - if (string.IsNullOrEmpty(this.UpgradeVersionDescription.InstallerPath)) + IUpgradeService upgradeService = Ioc.Default.GetRequiredService(); + + if (!this.isSessionEnding && upgradeService.UpgradeVersionDescription != null && upgradeService.UpgradeVersionDescription.NeedToUpgrade) + { + Debug.Log("A new version of file converter has been found: {0}.", upgradeService.UpgradeVersionDescription.LatestVersion); + + if (string.IsNullOrEmpty(upgradeService.UpgradeVersionDescription.InstallerPath)) { Debug.LogError("Invalid installer path."); } else { Debug.Log("Wait for the end of the installer download."); - while (this.UpgradeVersionDescription.InstallerDownloadInProgress) + while (upgradeService.UpgradeVersionDescription.InstallerDownloadInProgress) { Thread.Sleep(1000); } - string installerPath = this.UpgradeVersionDescription.InstallerPath; + string installerPath = upgradeService.UpgradeVersionDescription.InstallerPath; if (!System.IO.File.Exists(installerPath)) { Debug.LogError("Can't find upgrade installer ({0}). Try to restart the application.", installerPath); @@ -147,18 +139,12 @@ namespace FileConverter } // Start process. - Debug.Log("Start file converter upgrade from version {0} to {1}.", ApplicationVersion, this.UpgradeVersionDescription.LatestVersion); + Debug.Log("Start file converter upgrade from version {0} to {1}.", ApplicationVersion, upgradeService.UpgradeVersionDescription.LatestVersion); - System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(installerPath) - { - UseShellExecute = true, - }; + ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(installerPath) { UseShellExecute = true, }; Debug.Log("Start upgrade process: {0}{1}.", System.IO.Path.GetFileName(startInfo.FileName), startInfo.Arguments); - System.Diagnostics.Process process = new System.Diagnostics.Process - { - StartInfo = startInfo - }; + Process process = new System.Diagnostics.Process { StartInfo = startInfo }; process.Start(); } @@ -175,6 +161,46 @@ namespace FileConverter this.Shutdown(); } + private void RegisterServices() + { + var services = new ServiceCollection(); + + if (this.TryFindResource("Locator") is ViewModelLocator viewModelLocator) + { + viewModelLocator.RegisterViewModels(services); + } + else + { + Debug.LogError("Can't retrieve view model locator."); + this.Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown())); + } + + if (this.TryFindResource("Upgrade") is UpgradeService upgradeService) + { + services.AddSingleton(upgradeService); + } + else + { + Debug.LogError("Can't retrieve Upgrade service."); + this.Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown())); + } + + services + .AddSingleton() + .AddSingleton() + .AddSingleton(); + + Ioc.Default.ConfigureServices(services.BuildServiceProvider()); + + INavigationService navigationService = Ioc.Default.GetRequiredService(); + + navigationService.RegisterPage(Pages.Help, false, true); + navigationService.RegisterPage(Pages.Main, false, true); + navigationService.RegisterPage(Pages.Settings, true, true); + navigationService.RegisterPage(Pages.Diagnostics, true, false); + navigationService.RegisterPage(Pages.Upgrade, true, false); + } + private void Initialize() { #if BUILD32 @@ -186,17 +212,7 @@ namespace FileConverter // Retrieve arguments. Debug.Log("Retrieve arguments..."); string[] args = Environment.GetCommandLineArgs(); - -#if (DEBUG) - { - ////System.Array.Resize(ref args, 5); - ////args[1] = "--conversion-preset"; - ////args[2] = "To Png"; - ////args[3] = "--verbose"; - ////args[4] = @"D:\Test\images\Mario Big.png"; - } -#endif - + // Log arguments. for (int index = 0; index < args.Length; index++) { @@ -208,14 +224,16 @@ namespace FileConverter if (args.Length == 1) { - // Diplay help windows to explain that this application is a context menu extension. - ApplicationStartHelp applicationStartHelp = new ApplicationStartHelp(); - applicationStartHelp.Show(); - this.HideMainWindow = true; + // Display help windows to explain that this application is a context menu extension. + this.showHelp = true; return; } + ISettingsService settingsService = Ioc.Default.GetRequiredService(); + // Parse arguments. + bool quitAfterStartup = false; + int quitExitCode = 0; List filePaths = new List(); string conversionPresetName = null; for (int index = 1; index < args.Length; index++) @@ -234,40 +252,117 @@ namespace FileConverter switch (parameterTitle) { case "post-install-init": - Settings.PostInstallationInitialization(); - Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown())); - return; + if (!settingsService.PostInstallationInitialization()) + { + quitExitCode = 0x0F; + Debug.LogError(quitExitCode, $"Failed to execute post install initialization."); + } - case "version": - Console.Write(ApplicationVersion.ToString()); - Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown())); - return; - - case "settings": - this.ShowSettings = true; - this.HideMainWindow = true; + quitAfterStartup = true; break; - case "apply-settings": - Settings.ApplyTemporarySettings(); - Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown())); - return; + case "register-shell-extension": + { + quitAfterStartup = true; + + if (index >= args.Length - 1) + { + quitExitCode = 0x0B; + Debug.LogError(quitExitCode, $"Invalid format."); + break; + } + + string shellExtensionPath = args[index + 1]; + index++; + + if (!Helpers.RegisterShellExtension(shellExtensionPath)) + { + quitExitCode = 0x0C; + Debug.LogError(quitExitCode, $"Failed to register shell extension {shellExtensionPath}."); + } + + break; + } + + case "unregister-shell-extension": + { + quitAfterStartup = true; + + if (index >= args.Length - 1) + { + quitExitCode = 0x0D; + Debug.LogError(quitExitCode, $"Invalid format."); + break; + } + + string shellExtensionPath = args[index + 1]; + index++; + + if (!Helpers.UnregisterExtension(shellExtensionPath)) + { + quitExitCode = 0x0E; + Debug.LogError(quitExitCode, $"Failed to unregister shell extension {shellExtensionPath}."); + } + + break; + } + + case "version": + Console.WriteLine(ApplicationVersion.ToString()); + quitAfterStartup = true; + break; + + case "settings": + this.showSettings = true; + break; case "conversion-preset": if (index >= args.Length - 1) { - Debug.LogError("Invalid format. (code 0x01)"); - Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown())); - return; + quitAfterStartup = true; + quitExitCode = 0x01; + Debug.LogError(quitExitCode, $"Invalid format."); + break; } conversionPresetName = args[index + 1]; index++; - continue; + break; + + case "input-files": + if (index >= args.Length - 1) + { + quitAfterStartup = true; + quitExitCode = 0x02; + Debug.LogError(quitExitCode, $"Invalid format."); + break; + } + + string fileListPath = args[index + 1]; + try + { + using (FileStream file = File.OpenRead(fileListPath)) + using (StreamReader reader = new StreamReader(file)) + { + while (!reader.EndOfStream) + { + filePaths.Add(reader.ReadLine()); + } + } + } + catch (Exception exception) + { + quitAfterStartup = true; + quitExitCode = 0x03; + Debug.LogError(quitExitCode, $"Can't read input files list: {exception}"); + } + + index++; + break; case "verbose": { - this.Verbose = true; + this.verbose = true; } break; @@ -283,46 +378,33 @@ namespace FileConverter } } - // Load settigns. - Debug.Log("Load settings..."); - this.Settings = Settings.Load(); - if (this.Settings == null) + if (settingsService.Settings == null) { - Diagnostics.Debug.LogError("The application will now shutdown. If you want to fix the problem yourself please edit or delete the file: C:\\Users\\UserName\\AppData\\Local\\FileConverter\\Settings.user.xml."); - Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown())); + Debug.LogError("Can't load File Converter settings. The application will now shutdown, if you want to fix the problem yourself please edit or delete the file: C:\\Users\\UserName\\AppData\\Local\\FileConverter\\Settings.user.xml."); + quitAfterStartup = true; + quitExitCode = 13; + } + + if (quitAfterStartup) + { + Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown(quitExitCode))); return; } - if (this.Settings.MaximumNumberOfSimultaneousConversions <= 0) + Debug.Assert(quitExitCode == 0, "An error happened during the initialization."); + + // Check for upgrade. + if (settingsService.Settings.CheckUpgradeAtStartup) { - this.Settings.MaximumNumberOfSimultaneousConversions = System.Math.Max(1, Environment.ProcessorCount / 2); - Diagnostics.Debug.Log("The number of processors on this computer is {0}. Set the default number of conversion threads to {0}", this.Settings.MaximumNumberOfSimultaneousConversions); - } - - this.numberOfConversionThread = this.Settings.MaximumNumberOfSimultaneousConversions; - Diagnostics.Debug.Log("Maximum number of conversion threads: {0}", this.numberOfConversionThread); - - // Check upgrade. - if (this.Settings.CheckUpgradeAtStartup) - { -#if DEBUG - Task task = Upgrade.Helpers.GetLatestVersionDescriptionAsync(this.OnGetLatestVersionDescription); -#else - long fileTime = Registry.GetValue(Registry.Keys.LastUpdateCheckDate); - DateTime lastUpdateDateTime = DateTime.FromFileTime(fileTime); - - TimeSpan durationSinceLastUpdate = DateTime.Now.Subtract(lastUpdateDateTime); - if (durationSinceLastUpdate > new TimeSpan(1, 0, 0, 0)) - { - Task task = Upgrade.Helpers.GetLatestVersionDescriptionAsync(this.OnGetLatestVersionDescription); - } -#endif + IUpgradeService upgradeService = Ioc.Default.GetRequiredService(); + upgradeService.NewVersionAvailable += this.UpgradeService_NewVersionAvailable; + upgradeService.CheckForUpgrade(); } ConversionPreset conversionPreset = null; if (!string.IsNullOrEmpty(conversionPresetName)) { - conversionPreset = this.Settings.GetPresetFromName(conversionPresetName); + conversionPreset = settingsService.Settings.GetPresetFromName(conversionPresetName); if (conversionPreset == null) { Debug.LogError("Invalid conversion preset '{0}'. (code 0x02)", conversionPresetName); @@ -333,16 +415,18 @@ namespace FileConverter if (conversionPreset != null) { - // Create convertion jobs. - Debug.Log("Create jobs for conversion preset: '{0}'", conversionPreset.Name); + IConversionService conversionService = Ioc.Default.GetRequiredService(); + + // Create conversion jobs. + Debug.Log("Create jobs for conversion preset: '{0}'", conversionPreset.FullName); try { for (int index = 0; index < filePaths.Count; index++) { string inputFilePath = filePaths[index]; ConversionJob conversionJob = ConversionJobFactory.Create(conversionPreset, inputFilePath); - - this.conversionJobs.Add(conversionJob); + + conversionService.RegisterConversionJob(conversionJob); } } catch (Exception exception) @@ -355,158 +439,57 @@ namespace FileConverter } } - private void ConvertFiles() + private void UpgradeService_NewVersionAvailable(object sender, UpgradeVersionDescription e) { - // Prepare conversions. - for (int index = 0; index < this.ConvertionJobs.Count; index++) + Ioc.Default.GetRequiredService().Show(Pages.Upgrade); + + IUpgradeService upgradeService = Ioc.Default.GetRequiredService(); + upgradeService.NewVersionAvailable -= this.UpgradeService_NewVersionAvailable; + } + + private void ConversionService_ConversionJobsTerminated(object sender, ConversionJobsTerminatedEventArgs e) + { + IConversionService conversionService = Ioc.Default.GetRequiredService(); + conversionService.ConversionJobsTerminated -= this.ConversionService_ConversionJobsTerminated; + + ISettingsService settingsService = Ioc.Default.GetRequiredService(); + + if (!settingsService.Settings.ExitApplicationWhenConversionsFinished) { - this.ConvertionJobs[index].PrepareConversion(); + return; } - // Convert! - Thread[] jobThreads = new Thread[this.numberOfConversionThread]; - while (true) + if (this.cancelAutoExit) { - // Compute conversion flags. - ConversionFlags conversionFlags = ConversionFlags.None; - bool allJobAreFinished = true; - for (int jobIndex = 0; jobIndex < this.conversionJobs.Count; jobIndex++) - { - ConversionJob conversionJob = this.conversionJobs[jobIndex]; - allJobAreFinished &= !(conversionJob.State == ConversionJob.ConversionState.Ready || - conversionJob.State == ConversionJob.ConversionState.InProgress); - - if (conversionJob.State == ConversionJob.ConversionState.InProgress) - { - conversionFlags |= conversionJob.StateFlags; - } - } - - if (allJobAreFinished) - { - break; - } - - // Start job if possible. - for (int jobIndex = 0; jobIndex < this.conversionJobs.Count; jobIndex++) - { - ConversionJob conversionJob = this.conversionJobs[jobIndex]; - if (conversionJob.State == ConversionJob.ConversionState.Ready && - conversionJob.CanStartConversion(conversionFlags)) - { - // Find a thread to execute the job. - Thread jobThread = null; - for (int threadIndex = 0; threadIndex < jobThreads.Length; threadIndex++) - { - Thread thread = jobThreads[threadIndex]; - if (thread == null || !thread.IsAlive) - { - jobThread = Helpers.InstantiateThread(conversionJob.GetType().Name, this.ExecuteConversionJob); - jobThreads[threadIndex] = jobThread; - break; - } - } - - if (jobThread != null) - { - jobThread.Start(conversionJob); - - while (conversionJob.State == ConversionJob.ConversionState.Ready) - { - Debug.Log("Wait the launch of the conversion thread before launching any other thread."); - Thread.Sleep(20); - } - } - - break; - } - } - - Thread.Sleep(50); + return; } - if (this.Settings.ExitApplicationWhenConversionsFinished) + if (e.AllConversionsSucceed) { - bool allConversionsSucceed = true; - for (int index = 0; index < this.conversionJobs.Count; index++) + float remainingTime = settingsService.Settings.DurationBetweenEndOfConversionsAndApplicationExit; + while (remainingTime > 0f) { - allConversionsSucceed &= this.conversionJobs[index].State == ConversionJob.ConversionState.Done; - } - - if (this.cancelAutoExit) - { - return; - } - - if (allConversionsSucceed) - { - float remainingTime = this.Settings.DurationBetweenEndOfConversionsAndApplicationExit; - while (remainingTime > 0f) - { - if (this.OnApplicationTerminate != null) - { - this.OnApplicationTerminate.Invoke(this, new ApplicationTerminateArgs(remainingTime)); - } - - System.Threading.Thread.Sleep(1000); - remainingTime--; - - if (this.cancelAutoExit) - { - return; - } - } - if (this.OnApplicationTerminate != null) { this.OnApplicationTerminate.Invoke(this, new ApplicationTerminateArgs(remainingTime)); } - Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown())); + Thread.Sleep(1000); + remainingTime--; + + if (this.cancelAutoExit) + { + return; + } } - } - } - private void ExecuteConversionJob(object parameter) - { - ConversionJob conversionJob = parameter as ConversionJob; - if (conversionJob == null) - { - throw new System.ArgumentException("The parameter must be a conversion job.", "parameter"); - } + if (this.OnApplicationTerminate != null) + { + this.OnApplicationTerminate.Invoke(this, new ApplicationTerminateArgs(remainingTime)); + } - if (conversionJob.State != ConversionJob.ConversionState.Ready) - { - Debug.LogError("Fail to execute conversion job."); - return; + this.Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown())); } - - try - { - conversionJob.StartConvertion(); - } - catch (Exception exception) - { - Debug.LogError("Failure during conversion: {0}", exception.ToString()); - } - } - - private void OnGetLatestVersionDescription(UpgradeVersionDescription upgradeVersionDescription) - { - if (upgradeVersionDescription == null) - { - return; - } - - Registry.SetValue(Registry.Keys.LastUpdateCheckDate, DateTime.Now.ToFileTime()); - - if (upgradeVersionDescription.LatestVersion <= ApplicationVersion) - { - return; - } - - this.UpgradeVersionDescription = upgradeVersionDescription; - (this.MainWindow as MainWindow).OnNewVersionReleased(upgradeVersionDescription); } } } diff --git a/Application/FileConverter/Commands/CancelConversionJobCommand.cs b/Application/FileConverter/Commands/CancelConversionJobCommand.cs deleted file mode 100644 index 1244ea9..0000000 --- a/Application/FileConverter/Commands/CancelConversionJobCommand.cs +++ /dev/null @@ -1,35 +0,0 @@ -// License: http://www.gnu.org/licenses/gpl.html GPL version 3. - -namespace FileConverter.Commands -{ - using System; - using System.Windows.Input; - using FileConverter.ConversionJobs; - - public class CancelConversionJobCommand : ICommand - { - private readonly ConversionJob conversionJob; - - public CancelConversionJobCommand(ConversionJob conversionJob) - { - this.conversionJob = conversionJob; - } - - public event EventHandler CanExecuteChanged; - - public bool CanExecute(object parameter) - { - if (this.conversionJob == null) - { - return false; - } - - return this.conversionJob.IsCancelable && this.conversionJob.State == ConversionJob.ConversionState.InProgress; - } - - public void Execute(object parameter) - { - this.conversionJob?.Cancel(); - } - } -} \ No newline at end of file diff --git a/Application/FileConverter/Commands/DelegateCommand.cs b/Application/FileConverter/Commands/DelegateCommand.cs deleted file mode 100644 index 31569ca..0000000 --- a/Application/FileConverter/Commands/DelegateCommand.cs +++ /dev/null @@ -1,46 +0,0 @@ -// License: http://www.gnu.org/licenses/gpl.html GPL version 3. - -namespace FileConverter.Commands -{ - using System; - using System.Windows.Input; - - public class DelegateCommand : ICommand - { - private Action executeMethod; - private Func canExecuteMethod; - - public DelegateCommand(Action executeMethod) - { - if (executeMethod == null) - { - throw new ArgumentNullException(nameof(executeMethod)); - } - - this.executeMethod = executeMethod; - } - - public DelegateCommand(Action executeMethod, Func canExecuteMethod) - { - this.executeMethod = executeMethod; - this.canExecuteMethod = canExecuteMethod; - } - - public event EventHandler CanExecuteChanged; - - public bool CanExecute(object parameter) - { - if (this.canExecuteMethod != null) - { - return this.canExecuteMethod.Invoke(); - } - - return true; - } - - public void Execute(object parameter) - { - this.executeMethod.Invoke(); - } - } -} \ No newline at end of file diff --git a/Application/FileConverter/Commands/OpenUrlCommand.cs b/Application/FileConverter/Commands/OpenUrlCommand.cs deleted file mode 100644 index 4c8fe92..0000000 --- a/Application/FileConverter/Commands/OpenUrlCommand.cs +++ /dev/null @@ -1,33 +0,0 @@ -// License: http://www.gnu.org/licenses/gpl.html GPL version 3. - -namespace FileConverter.Commands -{ - using System; - using System.Diagnostics; - using System.Windows.Input; - - public class OpenUrlCommand : ICommand - { - public OpenUrlCommand() - { - } - - public event EventHandler CanExecuteChanged; - - public bool CanExecute(object parameter) - { - return true; - } - - public void Execute(object parameter) - { - string url = parameter as string; - if (string.IsNullOrEmpty(url)) - { - return; - } - - Process.Start(url); - } - } -} \ No newline at end of file diff --git a/Application/FileConverter/Controls/ConversionJobControl.xaml b/Application/FileConverter/Controls/ConversionJobControl.xaml new file mode 100644 index 0000000..caed4eb --- /dev/null +++ b/Application/FileConverter/Controls/ConversionJobControl.xaml @@ -0,0 +1,68 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Application/FileConverter/Controls/ConversionJobControl.xaml.cs b/Application/FileConverter/Controls/ConversionJobControl.xaml.cs new file mode 100644 index 0000000..54365eb --- /dev/null +++ b/Application/FileConverter/Controls/ConversionJobControl.xaml.cs @@ -0,0 +1,17 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.Controls +{ + using System.Windows.Controls; + + /// + /// Interaction logic for ConversionJobControl.xaml + /// + public partial class ConversionJobControl : UserControl + { + public ConversionJobControl() + { + this.InitializeComponent(); + } + } +} diff --git a/Application/FileConverter/Controls/EncodingQualitySliderControl.xaml b/Application/FileConverter/Controls/EncodingQualitySliderControl.xaml index f78ef4c..de6684d 100644 --- a/Application/FileConverter/Controls/EncodingQualitySliderControl.xaml +++ b/Application/FileConverter/Controls/EncodingQualitySliderControl.xaml @@ -5,12 +5,12 @@ xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:valueConverters="clr-namespace:FileConverter.ValueConverters" xmlns:project="clr-namespace:FileConverter.Properties" - x:Name="userControl" x:Class="FileConverter.Controls.EncodingQualitySliderControl" mc:Ignorable="d" d:DesignWidth="300" Height="50"> + @@ -21,8 +21,10 @@ - - diff --git a/Application/FileConverter/Controls/EncodingQualitySliderControl.xaml.cs b/Application/FileConverter/Controls/EncodingQualitySliderControl.xaml.cs index ce790fd..d54a0b5 100644 --- a/Application/FileConverter/Controls/EncodingQualitySliderControl.xaml.cs +++ b/Application/FileConverter/Controls/EncodingQualitySliderControl.xaml.cs @@ -2,7 +2,6 @@ namespace FileConverter.Controls { - using System.Diagnostics; using System.Windows; using System.Windows.Controls; diff --git a/Application/FileConverter/Controls/IconButton.cs b/Application/FileConverter/Controls/IconButton.cs new file mode 100644 index 0000000..bdc3c17 --- /dev/null +++ b/Application/FileConverter/Controls/IconButton.cs @@ -0,0 +1,38 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.Controls +{ + using System.Windows; + using System.Windows.Controls; + using System.Windows.Media; + + public class IconButton : Button + { + public static readonly DependencyProperty IconSourceProperty = DependencyProperty.Register("IconSource", typeof(ImageSource), typeof(IconButton)); + public static readonly DependencyProperty MouseOverBrushProperty = DependencyProperty.Register("MouseOverBrush", typeof(Brush), typeof(IconButton)); + public static readonly DependencyProperty PressedBrushProperty = DependencyProperty.Register("PressedBrush", typeof(Brush), typeof(IconButton)); + + static IconButton() + { + FrameworkElement.DefaultStyleKeyProperty.OverrideMetadata(typeof(IconButton), new FrameworkPropertyMetadata(typeof(IconButton))); + } + + public ImageSource IconSource + { + get => (ImageSource)this.GetValue(IconButton.IconSourceProperty); + set => this.SetValue(IconButton.IconSourceProperty, value); + } + + public Brush MouseOverBrush + { + get => (Brush)this.GetValue(IconButton.MouseOverBrushProperty); + set => this.SetValue(IconButton.MouseOverBrushProperty, value); + } + + public Brush PressedBrush + { + get => (Brush)this.GetValue(IconButton.PressedBrushProperty); + set => this.SetValue(IconButton.PressedBrushProperty, value); + } + } +} diff --git a/Application/FileConverter/ConversionJobs/ConversionJob.cs b/Application/FileConverter/ConversionJobs/ConversionJob.cs index a2dbe7b..e7e7ab6 100644 --- a/Application/FileConverter/ConversionJobs/ConversionJob.cs +++ b/Application/FileConverter/ConversionJobs/ConversionJob.cs @@ -5,31 +5,39 @@ namespace FileConverter.ConversionJobs using System; using System.ComponentModel; using System.Runtime.CompilerServices; - using System.Text; + using System.Windows.Input; + + using CommunityToolkit.Mvvm.Input; - using FileConverter.Commands; using FileConverter.Diagnostics; public class ConversionJob : INotifyPropertyChanged { private float progress = 0f; + private DateTime startTime; private ConversionState state = ConversionState.Unknown; private string errorMessage = string.Empty; private string userState = string.Empty; - private CancelConversionJobCommand cancelCommand; + private RelayCommand cancelCommand; - private string initialInputPath = string.Empty; - private int currentOuputFilePathIndex; + private readonly string initialInputPath; + private int currentOutputFilePathIndex; public ConversionJob() { - this.State = ConversionState.Unknown; + this.UserState = "Design Mode"; + this.ConversionPreset = null; this.initialInputPath = string.Empty; - this.InputFilePath = string.Empty; + this.InputFilePath = @"C:\Path\To\AVery\Long\Location\WithAVeryNiceFile.png"; + this.OutputFilePaths = new[] { "C:\\Path\\To\\AVery\\Long\\Location\\WithAVeryNiceFile.jpg" }; + this.StartTime = DateTime.Now - TimeSpan.FromMinutes(1.2); + this.State = ConversionState.InProgress; + this.StateFlags = ConversionFlags.None; + this.Progress = 0.6f; } - public ConversionJob(ConversionPreset conversionPreset, string inputFilePath) : this() + public ConversionJob(ConversionPreset conversionPreset, string inputFilePath) { if (conversionPreset == null) { @@ -41,6 +49,7 @@ namespace FileConverter.ConversionJobs throw new ArgumentNullException(nameof(inputFilePath)); } + this.State = ConversionState.Unknown; this.initialInputPath = inputFilePath; this.InputFilePath = inputFilePath; this.ConversionPreset = conversionPreset; @@ -48,17 +57,7 @@ namespace FileConverter.ConversionJobs } public event PropertyChangedEventHandler PropertyChanged; - - public enum ConversionState - { - Unknown, - - Ready, - InProgress, - Done, - Failed, - } - + public ConversionPreset ConversionPreset { get; @@ -68,7 +67,7 @@ namespace FileConverter.ConversionJobs public string InputFilePath { get; - private set; + set; } public string OutputFilePath @@ -80,40 +79,35 @@ namespace FileConverter.ConversionJobs return string.Empty; } - if (this.CurrentOuputFilePathIndex < 0) + if (this.CurrentOutputFilePathIndex < 0) { return this.OutputFilePaths[0]; } - if (this.CurrentOuputFilePathIndex >= this.OutputFilePaths.Length) + if (this.CurrentOutputFilePathIndex >= this.OutputFilePaths.Length) { return this.OutputFilePaths[this.OutputFilePaths.Length - 1]; } - return this.OutputFilePaths[this.CurrentOuputFilePathIndex]; + return this.OutputFilePaths[this.CurrentOutputFilePathIndex]; } } public ConversionState State { - get - { - return this.state; - } + get => this.state; private set { this.state = value; this.NotifyPropertyChanged(); + Application.Current.Dispatcher.Invoke(() => this.cancelCommand?.NotifyCanExecuteChanged()); } } public string UserState { - get - { - return this.userState; - } + get => this.userState; protected set { @@ -124,10 +118,7 @@ namespace FileConverter.ConversionJobs public float Progress { - get - { - return this.progress; - } + get => this.progress; protected set { @@ -136,12 +127,20 @@ namespace FileConverter.ConversionJobs } } + public DateTime StartTime + { + get => this.startTime; + + protected set + { + this.startTime = value; + this.NotifyPropertyChanged(); + } + } + public string ErrorMessage { - get - { - return this.errorMessage; - } + get => this.errorMessage; private set { @@ -156,41 +155,32 @@ namespace FileConverter.ConversionJobs protected set; } - public CancelConversionJobCommand CancelCommand + public ICommand CancelCommand { get { if (this.cancelCommand == null) { - this.cancelCommand = new CancelConversionJobCommand(this); + this.cancelCommand = new RelayCommand(this.Cancel, this.IsCancelable); } return this.cancelCommand; } } - public bool IsCancelable - { - get; - protected set; - } - protected bool CancelIsRequested { get; private set; } - protected int CurrentOuputFilePathIndex + protected int CurrentOutputFilePathIndex { - get - { - return this.currentOuputFilePathIndex; - } + get => this.currentOutputFilePathIndex; set { - this.currentOuputFilePathIndex = value; + this.currentOutputFilePathIndex = value; this.NotifyPropertyChanged(nameof(this.OutputFilePath)); } } @@ -208,6 +198,8 @@ namespace FileConverter.ConversionJobs } } + protected virtual bool IsCancelable() => this.State == ConversionState.InProgress; + protected string[] OutputFilePaths { get; @@ -240,7 +232,7 @@ namespace FileConverter.ConversionJobs this.OutputFilePaths = outputFilePaths; if (this.OutputFilePaths.Length == 0) { - int outputFilesCount = this.GetOuputFilesCount(); + int outputFilesCount = this.GetOutputFilesCount(); this.OutputFilePaths = new string[outputFilesCount]; } @@ -296,7 +288,7 @@ namespace FileConverter.ConversionJobs this.OutputFilePaths[index] = path; } - this.CurrentOuputFilePathIndex = 0; + this.CurrentOutputFilePathIndex = 0; // Check if the input file is located on a cd drive. if (PathHelpers.IsOnCDDrive(this.InputFilePath)) @@ -304,14 +296,23 @@ namespace FileConverter.ConversionJobs this.StateFlags = ConversionFlags.CdDriveExtraction; } - this.Initialize(); + try + { + this.Initialize(); + } + catch (Exception exception) + { + this.ConversionFailed(Properties.Resources.ErrorDuringJobInitialization); + Debug.Log(exception.ToString()); + return; + } if (this.State == ConversionState.Unknown) { 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) { @@ -319,7 +320,7 @@ namespace FileConverter.ConversionJobs } } - public void StartConvertion() + public void StartConversion() { if (this.ConversionPreset == null) { @@ -333,6 +334,7 @@ namespace FileConverter.ConversionJobs Debug.Log("Convert file {0} to {1}.", this.InputFilePath, this.OutputFilePath); + this.StartTime = DateTime.Now; this.State = ConversionState.InProgress; try @@ -355,11 +357,11 @@ namespace FileConverter.ConversionJobs this.OnConversionSucceed(); } - if (this.State == ConversionJob.ConversionState.Done && !this.AllOuputFilesExists()) + if (this.State == ConversionState.Done && !this.AllOutputFilesExists()) { Debug.LogError(Properties.Resources.ErrorCantFindOutputFiles); } - else if (this.State == ConversionJob.ConversionState.Failed && this.AtLeastOneOuputFilesExists()) + else if (this.State == ConversionState.Failed && this.AtLeastOneOutputFilesExists()) { Debug.Log(Properties.Resources.ErrorConversionFailedWithOutput); } @@ -367,7 +369,7 @@ namespace FileConverter.ConversionJobs public virtual void Cancel() { - if (!this.IsCancelable || this.State != ConversionState.InProgress) + if (!this.IsCancelable()) { return; } @@ -376,7 +378,7 @@ namespace FileConverter.ConversionJobs this.ConversionFailed(Properties.Resources.ErrorCanceled); } - protected virtual int GetOuputFilesCount() + protected virtual int GetOutputFilesCount() { return 1; } @@ -415,6 +417,8 @@ namespace FileConverter.ConversionJobs { Debug.Log("Conversion Succeed!"); + this.ChangeOutputFileTimestampToMatchOriginal(); + // Apply the input post conversion action. switch (this.InputPostConversionAction) { @@ -456,7 +460,7 @@ namespace FileConverter.ConversionJobs if (this.State == ConversionState.Failed) { // Already failed, don't override informations. - return; + return; } this.State = ConversionState.Failed; @@ -472,7 +476,36 @@ namespace FileConverter.ConversionJobs } } - private bool AllOuputFilesExists() + private void ChangeOutputFileTimestampToMatchOriginal() + { + Debug.Log("Changing output files timestamp to match original timestamp ..."); + + var originalFileCreationTime = System.IO.File.GetCreationTimeUtc(this.InputFilePath); + var originalFileLastAccesTime = System.IO.File.GetLastAccessTimeUtc(this.InputFilePath); + var originalFileLastWriteTime = System.IO.File.GetLastWriteTimeUtc(this.InputFilePath); + Debug.Log(" original timestamp: {0}, {1}, {2}", originalFileCreationTime, originalFileLastAccesTime, originalFileLastWriteTime); + + for (int index = 0; index < this.OutputFilePaths.Length; index++) + { + string outputFilePath = this.OutputFilePaths[index]; + try + { + System.IO.File.SetCreationTimeUtc(outputFilePath, originalFileCreationTime); + System.IO.File.SetLastAccessTimeUtc(outputFilePath, originalFileLastAccesTime); + System.IO.File.SetLastWriteTimeUtc(outputFilePath, originalFileLastWriteTime); + Debug.Log(" output file '{0}' timestamp changed", outputFilePath); + } + catch (Exception exception) + { + Debug.Log("Can't change timestamp from file '{0}'", outputFilePath); + Debug.Log("An exception as been thrown: {0}.", exception.ToString()); + } + } + + Debug.Log("... timestamp matching finished."); + } + + private bool AllOutputFilesExists() { for (int index = 0; index < this.OutputFilePaths.Length; index++) { @@ -486,7 +519,7 @@ namespace FileConverter.ConversionJobs return true; } - private bool AtLeastOneOuputFilesExists() + private bool AtLeastOneOutputFilesExists() { for (int index = 0; index < this.OutputFilePaths.Length; index++) { diff --git a/Application/FileConverter/ConversionJobs/ConversionJob_Excel.cs b/Application/FileConverter/ConversionJobs/ConversionJob_Excel.cs index bd80a7b..f03886c 100644 --- a/Application/FileConverter/ConversionJobs/ConversionJob_Excel.cs +++ b/Application/FileConverter/ConversionJobs/ConversionJob_Excel.cs @@ -26,15 +26,11 @@ namespace FileConverter.ConversionJobs { } - protected override ApplicationName Application - { - get - { - return ApplicationName.Excel; - } - } + protected override ApplicationName Application => ApplicationName.Excel; - protected override int GetOuputFilesCount() + protected override bool IsCancelable() => false; + + protected override int GetOutputFilesCount() { if (this.ConversionPreset.OutputType == OutputType.Pdf) { @@ -132,7 +128,7 @@ namespace FileConverter.ConversionJobs Diagnostics.Debug.Log("Convert pdf to images."); - this.pdf2ImageConversionJob.StartConvertion(); + this.pdf2ImageConversionJob.StartConversion(); if (this.pdf2ImageConversionJob.State != ConversionState.Done) { diff --git a/Application/FileConverter/ConversionJobs/ConversionJob_ExtractCDA.cs b/Application/FileConverter/ConversionJobs/ConversionJob_ExtractCDA.cs index 187c0c1..2e51793 100644 --- a/Application/FileConverter/ConversionJobs/ConversionJob_ExtractCDA.cs +++ b/Application/FileConverter/ConversionJobs/ConversionJob_ExtractCDA.cs @@ -22,12 +22,10 @@ namespace FileConverter.ConversionJobs public ConversionJob_ExtractCDA() : base() { - this.IsCancelable = true; } public ConversionJob_ExtractCDA(ConversionPreset conversionPreset, string inputFilePath) : base(conversionPreset, inputFilePath) { - this.IsCancelable = true; } protected override InputPostConversionAction InputPostConversionAction @@ -220,7 +218,7 @@ namespace FileConverter.ConversionJobs private void CompressAsync() { - this.compressionConversionJob.StartConvertion(); + this.compressionConversionJob.StartConversion(); } } } diff --git a/Application/FileConverter/ConversionJobs/ConversionJob_FFMPEG.Converters.cs b/Application/FileConverter/ConversionJobs/ConversionJob_FFMPEG.Converters.cs index 4862d7e..934d102 100644 --- a/Application/FileConverter/ConversionJobs/ConversionJob_FFMPEG.Converters.cs +++ b/Application/FileConverter/ConversionJobs/ConversionJob_FFMPEG.Converters.cs @@ -16,7 +16,7 @@ namespace FileConverter.ConversionJobs return string.Empty; } - return string.Format("{0} \"{1}\"", optionName, args); + return $"{optionName} \"{args}\""; } /// @@ -96,6 +96,14 @@ namespace FileConverter.ConversionJobs transformArgs += rotationArgs; } + if (conversionPreset.OutputType == OutputType.Mkv || conversionPreset.OutputType == OutputType.Mp4) + { + // http://trac.ffmpeg.org/wiki/Encode/H.264#Encodingfordumbplayers + // YUV planar color space with 4:2:0 chroma subsampling + transformArgs += (transformArgs.Length > 0 ? "," : string.Empty) + "format=yuv420p"; + //// TODO: maybe there should be an option for this on the settings? + } + return transformArgs; } diff --git a/Application/FileConverter/ConversionJobs/ConversionJob_FFMPEG.cs b/Application/FileConverter/ConversionJobs/ConversionJob_FFMPEG.cs index 3a4305a..a935aad 100644 --- a/Application/FileConverter/ConversionJobs/ConversionJob_FFMPEG.cs +++ b/Application/FileConverter/ConversionJobs/ConversionJob_FFMPEG.cs @@ -21,18 +21,29 @@ namespace FileConverter.ConversionJobs private ProcessStartInfo ffmpegProcessStartInfo; - private List ffmpegArgumentStringByPass = new List(); + private readonly List ffmpegArgumentStringByPass = new List(); public ConversionJob_FFMPEG() : base() { - this.IsCancelable = true; } public ConversionJob_FFMPEG(ConversionPreset conversionPreset, string inputFilePath) : base(conversionPreset, inputFilePath) { - this.IsCancelable = true; } - + + public static VideoEncodingSpeed[] VideoEncodingSpeeds => new[] + { + VideoEncodingSpeed.UltraFast, + VideoEncodingSpeed.SuperFast, + VideoEncodingSpeed.VeryFast, + VideoEncodingSpeed.Faster, + VideoEncodingSpeed.Fast, + VideoEncodingSpeed.Medium, + VideoEncodingSpeed.Slow, + VideoEncodingSpeed.Slower, + VideoEncodingSpeed.VerySlow, + }; + protected virtual string FfmpegPath { get @@ -61,22 +72,36 @@ namespace FileConverter.ConversionJobs return; } - this.ffmpegProcessStartInfo = new ProcessStartInfo(ffmpegPath); - - this.ffmpegProcessStartInfo.CreateNoWindow = true; - this.ffmpegProcessStartInfo.UseShellExecute = false; - this.ffmpegProcessStartInfo.RedirectStandardOutput = true; - this.ffmpegProcessStartInfo.RedirectStandardError = true; + this.ffmpegProcessStartInfo = new ProcessStartInfo(ffmpegPath) + { + CreateNoWindow = true, + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true + }; this.FillFFMpegArgumentsList(); } protected virtual void FillFFMpegArgumentsList() { + bool customCommandEnabled = this.ConversionPreset.GetSettingsValue(ConversionPreset.ConversionSettingKeys.EnableFFMPEGCustomCommand); + if (customCommandEnabled) + { + // Custom command override other settings. + string customCommand = this.ConversionPreset.GetSettingsValue(ConversionPreset.ConversionSettingKeys.FFMPEGCustomCommand) ?? string.Empty; + + string arguments = string.Format("-n -stats -i \"{0}\" {2} \"{1}\"", this.InputFilePath, this.OutputFilePath, customCommand); + this.ffmpegArgumentStringByPass.Add(new FFMpegPass(arguments)); + + return; + } + // This option are necessary to be able to read metadata on Windows. src: http://jonhall.info/how_to/create_id3_tags_using_ffmpeg - const string mp3MetadataArgs = "-id3v2_version 3 -write_id3v1 1"; + const string MP3MetadataArgs = "-id3v2_version 3 -write_id3v1 1"; + // AAC have no standard tag system, use ApeV2 (that are compatible). src: http://eolindel.free.fr/foobar/tags.shtml - const string aacMetadataArgs = "-write_apetag 1"; + const string AACMetadataArgs = "-write_apetag 1"; switch (this.ConversionPreset.OutputType) { @@ -86,7 +111,7 @@ namespace FileConverter.ConversionJobs // https://trac.ffmpeg.org/wiki/Encode/AAC int audioEncodingBitrate = this.ConversionPreset.GetSettingsValue(ConversionPreset.ConversionSettingKeys.AudioBitrate); - string encoderArgs = $"-c:a aac -q:a {this.AACBitrateToQualityIndex(audioEncodingBitrate)} {channelArgs} {aacMetadataArgs}"; + string encoderArgs = $"-c:a aac -q:a {this.AACBitrateToQualityIndex(audioEncodingBitrate)} {channelArgs} {AACMetadataArgs}"; string arguments = string.Format("-n -stats -i \"{0}\" {2} \"{1}\"", this.InputFilePath, this.OutputFilePath, encoderArgs); @@ -111,7 +136,7 @@ namespace FileConverter.ConversionJobs // Compute final arguments. string videoFilteringArgs = ConversionJob_FFMPEG.Encapsulate("-vf", transformArgs); - string encoderArgs = $"-c:v mpeg4 -vtag xvid -qscale:v {this.MPEG4QualityToQualityIndex(videoEncodingQuality)} {audioArgs} {videoFilteringArgs} {mp3MetadataArgs}"; + string encoderArgs = $"-c:v mpeg4 -vtag xvid -qscale:v {this.MPEG4QualityToQualityIndex(videoEncodingQuality)} {audioArgs} {videoFilteringArgs} {MP3MetadataArgs}"; string arguments = string.Format("-n -stats -i \"{0}\" {2} \"{1}\"", this.InputFilePath, this.OutputFilePath, encoderArgs); this.ffmpegArgumentStringByPass.Add(new FFMpegPass(arguments)); @@ -203,11 +228,11 @@ namespace FileConverter.ConversionJobs switch (encodingMode) { case EncodingMode.Mp3VBR: - encoderArgs = $"-codec:a libmp3lame -q:a {this.MP3VBRBitrateToQualityIndex(encodingQuality)} {channelArgs} {mp3MetadataArgs}"; + encoderArgs = $"-codec:a libmp3lame -q:a {this.MP3VBRBitrateToQualityIndex(encodingQuality)} {channelArgs} {MP3MetadataArgs}"; break; case EncodingMode.Mp3CBR: - encoderArgs = $"-codec:a libmp3lame -b:a {encodingQuality}k {channelArgs} {mp3MetadataArgs}"; + encoderArgs = $"-codec:a libmp3lame -b:a {encodingQuality}k {channelArgs} {MP3MetadataArgs}"; break; default: @@ -480,9 +505,12 @@ namespace FileConverter.ConversionJobs } } - if (input.Contains("Exiting.") || input.Contains("Error") || input.Contains("Unsupported dimensions") || input.Contains("No such file or directory")) + // Remove file names from log to avoid false negative when some words like 'Error' are in file name (github issue #247). + string inputWithoutFileNames = input.Replace(this.InputFilePath, string.Empty).Replace(this.OutputFilePath, string.Empty); + + if (inputWithoutFileNames.Contains("Exiting.") || inputWithoutFileNames.Contains("Error") || inputWithoutFileNames.Contains("Unsupported dimensions") || inputWithoutFileNames.Contains("No such file or directory")) { - if (input.StartsWith("Error while decoding stream") && input.EndsWith("Invalid data found when processing input")) + if (inputWithoutFileNames.StartsWith("Error while decoding stream") && inputWithoutFileNames.EndsWith("Invalid data found when processing input")) { // It is normal for a transport stream to start with a broken frame. // https://trac.ffmpeg.org/ticket/1622 diff --git a/Application/FileConverter/ConversionJobs/ConversionJob_Gif.cs b/Application/FileConverter/ConversionJobs/ConversionJob_Gif.cs index 8035b12..34c383c 100644 --- a/Application/FileConverter/ConversionJobs/ConversionJob_Gif.cs +++ b/Application/FileConverter/ConversionJobs/ConversionJob_Gif.cs @@ -14,7 +14,6 @@ namespace FileConverter.ConversionJobs public ConversionJob_Gif(ConversionPreset conversionPreset, string inputFilePath) : base(conversionPreset, inputFilePath) { - this.IsCancelable = true; } public override void Cancel() @@ -79,7 +78,7 @@ namespace FileConverter.ConversionJobs Diagnostics.Debug.Log(string.Empty); Diagnostics.Debug.Log("Convert image to PNG (intermediate format)."); - this.pngConversionJob.StartConvertion(); + this.pngConversionJob.StartConversion(); if (this.pngConversionJob.State != ConversionState.Done) { @@ -90,7 +89,7 @@ namespace FileConverter.ConversionJobs Diagnostics.Debug.Log(string.Empty); Diagnostics.Debug.Log("Convert png intermediate image to gif."); - this.gifConversionJob.StartConvertion(); + this.gifConversionJob.StartConversion(); if (this.gifConversionJob.State != ConversionState.Done) { diff --git a/Application/FileConverter/ConversionJobs/ConversionJob_Ico.cs b/Application/FileConverter/ConversionJobs/ConversionJob_Ico.cs index 46f8b73..2659cd1 100644 --- a/Application/FileConverter/ConversionJobs/ConversionJob_Ico.cs +++ b/Application/FileConverter/ConversionJobs/ConversionJob_Ico.cs @@ -13,7 +13,6 @@ namespace FileConverter.ConversionJobs public ConversionJob_Ico(ConversionPreset conversionPreset, string inputFilePath) : base(conversionPreset, inputFilePath) { - this.IsCancelable = true; } public override void Cancel() @@ -59,7 +58,7 @@ namespace FileConverter.ConversionJobs Diagnostics.Debug.Log(string.Empty); Diagnostics.Debug.Log("Convert image to PNG (intermediate format)."); - this.pngConversionJob.StartConvertion(); + this.pngConversionJob.StartConversion(); if (this.pngConversionJob.State != ConversionState.Done) { @@ -69,7 +68,7 @@ namespace FileConverter.ConversionJobs Diagnostics.Debug.Log(string.Empty); Diagnostics.Debug.Log("Convert png intermediate image to ICO."); - this.icoConversionJob.StartConvertion(); + this.icoConversionJob.StartConversion(); if (this.icoConversionJob.State != ConversionState.Done) { diff --git a/Application/FileConverter/ConversionJobs/ConversionJob_ImageMagick.cs b/Application/FileConverter/ConversionJobs/ConversionJob_ImageMagick.cs index c3a100f..dd8a387 100644 --- a/Application/FileConverter/ConversionJobs/ConversionJob_ImageMagick.cs +++ b/Application/FileConverter/ConversionJobs/ConversionJob_ImageMagick.cs @@ -17,12 +17,10 @@ namespace FileConverter.ConversionJobs public ConversionJob_ImageMagick() : base() { - this.IsCancelable = true; } public ConversionJob_ImageMagick(ConversionPreset conversionPreset, string inputFilePath) : base(conversionPreset, inputFilePath) { - this.IsCancelable = true; } protected override void Initialize() @@ -40,7 +38,7 @@ namespace FileConverter.ConversionJobs } } - protected override int GetOuputFilesCount() + protected override int GetOutputFilesCount() { if (System.IO.Path.GetExtension(this.InputFilePath).ToLowerInvariant() == ".pdf") { @@ -64,7 +62,7 @@ namespace FileConverter.ConversionJobs throw new Exception("The conversion preset must be valid."); } - this.CurrentOuputFilePathIndex = 0; + this.CurrentOutputFilePathIndex = 0; if (this.isInputFilePdf) { @@ -73,10 +71,28 @@ namespace FileConverter.ConversionJobs else { this.pageCount = 1; - using (MagickImage image = new MagickImage(this.InputFilePath)) + MagickReadSettings readSettings = new MagickReadSettings(); + + string inputExtension = System.IO.Path.GetExtension(this.InputFilePath).ToLowerInvariant(); + switch (inputExtension) + { + case ".cr2": + // Requires an explicit image format otherwise the image is interpreted as a TIFF image. + readSettings.Format = MagickFormat.Cr2; + break; + + case ".dng": + // Requires an explicit image format otherwise the image is interpreted as a TIFF image. + readSettings.Format = MagickFormat.Dng; + break; + + default: + break; + } + + using (MagickImage image = new MagickImage(this.InputFilePath, readSettings)) { Debug.Log("Load image {0} succeed.", this.InputFilePath); - this.ConvertImage(image); } } @@ -112,16 +128,18 @@ namespace FileConverter.ConversionJobs foreach (MagickImage image in images) { - Debug.Log("Write page {0}/{1}.", this.CurrentOuputFilePathIndex + 1, this.pageCount); + Debug.Log("Write page {0}/{1}.", this.CurrentOutputFilePathIndex + 1, this.pageCount); if (PdfSuperSamplingRatio > 1) { +#pragma warning disable CS0162 // Unreachable code detected image.Scale(new Percentage(100 / PdfSuperSamplingRatio)); +#pragma warning restore CS0162 // Unreachable code detected } this.ConvertImage(image, true); - this.CurrentOuputFilePathIndex++; + this.CurrentOutputFilePathIndex++; } } } @@ -223,7 +241,7 @@ namespace FileConverter.ConversionJobs return; } - float alreadyCompletedPages = this.CurrentOuputFilePathIndex / (float)this.pageCount; + float alreadyCompletedPages = this.CurrentOutputFilePathIndex / (float)this.pageCount; this.Progress = alreadyCompletedPages + ((float)eventArgs.Progress.ToDouble() / (100f * this.pageCount)); } } diff --git a/Application/FileConverter/ConversionJobs/ConversionJob_Office.cs b/Application/FileConverter/ConversionJobs/ConversionJob_Office.cs index 1519302..c9ca3e2 100644 --- a/Application/FileConverter/ConversionJobs/ConversionJob_Office.cs +++ b/Application/FileConverter/ConversionJobs/ConversionJob_Office.cs @@ -25,7 +25,9 @@ namespace FileConverter.ConversionJobs { get; } - + + protected override bool IsCancelable() => false; + protected override void Initialize() { base.Initialize(); diff --git a/Application/FileConverter/ConversionJobs/ConversionJob_PowerPoint.cs b/Application/FileConverter/ConversionJobs/ConversionJob_PowerPoint.cs index 1c46344..3242284 100644 --- a/Application/FileConverter/ConversionJobs/ConversionJob_PowerPoint.cs +++ b/Application/FileConverter/ConversionJobs/ConversionJob_PowerPoint.cs @@ -27,15 +27,11 @@ namespace FileConverter.ConversionJobs { } - protected override ApplicationName Application - { - get - { - return ApplicationName.PowerPoint; - } - } + protected override ApplicationName Application => ApplicationName.PowerPoint; - protected override int GetOuputFilesCount() + protected override bool IsCancelable() => false; + + protected override int GetOutputFilesCount() { if (this.ConversionPreset.OutputType == OutputType.Pdf) { @@ -121,7 +117,7 @@ namespace FileConverter.ConversionJobs Diagnostics.Debug.Log("Convert pdf to images."); - this.pdf2ImageConversionJob.StartConvertion(); + this.pdf2ImageConversionJob.StartConversion(); if (this.pdf2ImageConversionJob.State != ConversionState.Done) { diff --git a/Application/FileConverter/ConversionJobs/ConversionJob_Word.cs b/Application/FileConverter/ConversionJobs/ConversionJob_Word.cs index c102c00..8442181 100644 --- a/Application/FileConverter/ConversionJobs/ConversionJob_Word.cs +++ b/Application/FileConverter/ConversionJobs/ConversionJob_Word.cs @@ -26,15 +26,11 @@ namespace FileConverter.ConversionJobs { } - protected override ApplicationName Application - { - get - { - return ApplicationName.Word; - } - } + protected override ApplicationName Application => ApplicationName.Word; - protected override int GetOuputFilesCount() + protected override bool IsCancelable() => false; + + protected override int GetOutputFilesCount() { if (this.ConversionPreset.OutputType == OutputType.Pdf) { @@ -104,7 +100,18 @@ namespace FileConverter.ConversionJobs this.UserState = Properties.Resources.ConversionStateConversion; Diagnostics.Debug.Log("Convert word document to pdf."); - this.document.ExportAsFixedFormat(this.intermediateFilePath, Word.WdExportFormat.wdExportFormatPDF); + // this.document.ExportAsFixedFormat(this.intermediateFilePath, Word.WdExportFormat.wdExportFormatPDF); + this.document.ExportAsFixedFormat(this.intermediateFilePath, + Word.WdExportFormat.wdExportFormatPDF, + false, + Word.WdExportOptimizeFor.wdExportOptimizeForPrint, + Word.WdExportRange.wdExportAllDocument, + 1, 1, + Word.WdExportItem.wdExportDocumentContent, + true, + true, + Word.WdExportCreateBookmarks.wdExportCreateHeadingBookmarks, + true); Diagnostics.Debug.Log("Close word document '{0}'.", this.InputFilePath); this.document.Close(Word.WdSaveOptions.wdDoNotSaveChanges); @@ -124,7 +131,7 @@ namespace FileConverter.ConversionJobs Diagnostics.Debug.Log("Convert pdf to images."); - this.pdf2ImageConversionJob.StartConvertion(); + this.pdf2ImageConversionJob.StartConversion(); if (this.pdf2ImageConversionJob.State != ConversionState.Done) { diff --git a/Application/FileConverter/ConversionJobs/ConversionState.cs b/Application/FileConverter/ConversionJobs/ConversionState.cs new file mode 100644 index 0000000..46dad73 --- /dev/null +++ b/Application/FileConverter/ConversionJobs/ConversionState.cs @@ -0,0 +1,14 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ConversionJobs +{ + public enum ConversionState + { + Unknown, + + Ready, + InProgress, + Done, + Failed, + } +} diff --git a/Application/FileConverter/ConversionPreset/ConversionPreset.cs b/Application/FileConverter/ConversionPreset/ConversionPreset.cs index 2ec5a9f..1204ea6 100644 --- a/Application/FileConverter/ConversionPreset/ConversionPreset.cs +++ b/Application/FileConverter/ConversionPreset/ConversionPreset.cs @@ -4,22 +4,19 @@ namespace FileConverter { using System; using System.Collections.Generic; - using System.ComponentModel; using System.Globalization; - using System.Linq; - using System.Runtime.CompilerServices; using System.Xml.Serialization; + + using CommunityToolkit.Mvvm.ComponentModel; - using FileConverter.Annotations; using FileConverter.Controls; - using FileConverter.Diagnostics; - using FileConverter.ValueConverters; [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; @@ -28,12 +25,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); @@ -42,9 +39,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) @@ -67,30 +65,65 @@ 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; + 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.OnPropertyChanged(); } } + [XmlIgnore] + public string[] ParentFoldersNames + { + get; + set; + } + [XmlAttribute] public OutputType OutputType { - get - { - return this.outputType; - } + get => this.outputType; set { @@ -106,7 +139,7 @@ namespace FileConverter { get; set; - } = false; + } [XmlElement] public List InputTypes @@ -214,10 +247,7 @@ namespace FileConverter [XmlIgnore] public IConversionSettings Settings { - get - { - return this.settings; - } + get => this.settings; set { @@ -242,34 +272,6 @@ namespace FileConverter } } - 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); - } - } - public void Clean() { // Remove unrelevant settings. @@ -326,12 +328,12 @@ namespace FileConverter { if (string.IsNullOrEmpty(settingsKey)) { - throw new ArgumentNullException("key"); + throw new ArgumentNullException(nameof(settingsKey)); } - if (string.IsNullOrEmpty(value)) + if (value == null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } if (!this.IsRelevantSetting(settingsKey)) @@ -353,7 +355,7 @@ namespace FileConverter { if (string.IsNullOrEmpty(settingsKey)) { - throw new ArgumentNullException("key"); + throw new ArgumentNullException(nameof(settingsKey)); } if (this.settings.ContainsKey(settingsKey)) @@ -376,10 +378,10 @@ namespace FileConverter Type type = typeof(T); if (type.IsEnum) { - return (T)System.Enum.Parse(type, settingsValue); + return (T)Enum.Parse(type, settingsValue); } - return (T)System.Convert.ChangeType(settingsValue, type, NumberFormatInfo.InvariantInfo); + return (T)Convert.ChangeType(settingsValue, type, NumberFormatInfo.InvariantInfo); } public bool IsRelevantSetting(string settingsKey) @@ -387,12 +389,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) @@ -422,26 +418,36 @@ namespace FileConverter case OutputType.Aac: this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.AudioBitrate, "128"); this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.AudioChannelCount, "0"); + this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.EnableFFMPEGCustomCommand, "False"); + this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.FFMPEGCustomCommand, string.Empty); break; case OutputType.Flac: this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.AudioChannelCount, "0"); + this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.EnableFFMPEGCustomCommand, "False"); + this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.FFMPEGCustomCommand, string.Empty); break; case OutputType.Ogg: this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.AudioBitrate, "160"); this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.AudioChannelCount, "0"); + this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.EnableFFMPEGCustomCommand, "False"); + this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.FFMPEGCustomCommand, string.Empty); break; case OutputType.Mp3: this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.AudioEncodingMode, EncodingMode.Mp3VBR.ToString(), true); this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.AudioBitrate, "190"); this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.AudioChannelCount, "0"); + this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.EnableFFMPEGCustomCommand, "False"); + this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.FFMPEGCustomCommand, string.Empty); break; case OutputType.Wav: this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.AudioEncodingMode, EncodingMode.Wav16.ToString(), true); this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.AudioChannelCount, "0"); + this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.EnableFFMPEGCustomCommand, "False"); + this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.FFMPEGCustomCommand, string.Empty); break; // Video @@ -451,6 +457,8 @@ namespace FileConverter this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.VideoScale, "1"); this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.VideoRotation, "0"); this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.AudioBitrate, "190"); + this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.EnableFFMPEGCustomCommand, "False"); + this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.FFMPEGCustomCommand, string.Empty); break; case OutputType.Mkv: @@ -460,6 +468,8 @@ namespace FileConverter this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.VideoScale, "1"); this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.VideoRotation, "0"); this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.AudioBitrate, "128"); + this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.EnableFFMPEGCustomCommand, "False"); + this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.FFMPEGCustomCommand, string.Empty); break; case OutputType.Mp4: @@ -469,6 +479,8 @@ namespace FileConverter this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.VideoScale, "1"); this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.VideoRotation, "0"); this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.AudioBitrate, "128"); + this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.EnableFFMPEGCustomCommand, "False"); + this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.FFMPEGCustomCommand, string.Empty); break; case OutputType.Ogv: @@ -477,6 +489,8 @@ namespace FileConverter this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.VideoScale, "1"); this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.VideoRotation, "0"); this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.AudioBitrate, "160"); + this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.EnableFFMPEGCustomCommand, "False"); + this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.FFMPEGCustomCommand, string.Empty); break; case OutputType.Webm: @@ -485,6 +499,8 @@ namespace FileConverter this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.VideoQuality, "40"); this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.VideoScale, "1"); this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.VideoRotation, "0"); + this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.EnableFFMPEGCustomCommand, "False"); + this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.FFMPEGCustomCommand, string.Empty); break; // Images @@ -538,9 +554,9 @@ namespace FileConverter throw new ArgumentNullException("key"); } - if (string.IsNullOrEmpty(value)) + if (value == null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } if (!this.settings.ContainsKey(settingsKey)) @@ -553,102 +569,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 ';'."; - } - - Application application = Application.Current as Application; - int? count = application?.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) @@ -687,9 +607,11 @@ namespace FileConverter public const string VideoScale = "VideoScale"; public const string VideoRotation = "VideoRotation"; public const string VideoFramesPerSecond = "VideoFramesPerSecond"; + public const string FFMPEGCustomCommand = "FFMPEGCustomCommand"; public const string EnableAudio = "EnableAudio"; public const string EnableVideo = "EnableVideo"; + public const string EnableFFMPEGCustomCommand = "EnableFFMPEGCustomCommand"; } } } diff --git a/Application/FileConverter/ConversionPreset/ConversionSettingsOverride.cs b/Application/FileConverter/ConversionPreset/ConversionSettingsOverride.cs index 22eb066..1c4b383 100644 --- a/Application/FileConverter/ConversionPreset/ConversionSettingsOverride.cs +++ b/Application/FileConverter/ConversionPreset/ConversionSettingsOverride.cs @@ -16,13 +16,7 @@ namespace FileConverter this.value = value; } - public int Count - { - get - { - return 1; - } - } + public int Count => 1; public IEnumerable Keys { diff --git a/Application/FileConverter/ConversionPreset/IConversionSettings.cs b/Application/FileConverter/ConversionPreset/IConversionSettings.cs index f1b1a33..8d7ca51 100644 --- a/Application/FileConverter/ConversionPreset/IConversionSettings.cs +++ b/Application/FileConverter/ConversionPreset/IConversionSettings.cs @@ -7,4 +7,4 @@ namespace FileConverter public interface IConversionSettings : IReadOnlyDictionary { } -} \ No newline at end of file +} diff --git a/Application/FileConverter/Diagnostics/Debug.cs b/Application/FileConverter/Diagnostics/Debug.cs index 350999c..6927c70 100644 --- a/Application/FileConverter/Diagnostics/Debug.cs +++ b/Application/FileConverter/Diagnostics/Debug.cs @@ -12,13 +12,16 @@ namespace FileConverter.Diagnostics public static class Debug { - private static string diagnosticsFolderPath; - private static Dictionary diagnosticsDataById = new Dictionary(); + private static readonly string diagnosticsFolderPath; + private static readonly Dictionary diagnosticsDataById = new Dictionary(); private static int threadCount = 0; + private static readonly int mainThreadId = 0; static Debug() { - string path = PathHelpers.GetUserDataFolderPath(); + Debug.mainThreadId = Thread.CurrentThread.ManagedThreadId; + + string path = FileConverterExtension.PathHelpers.GetUserDataFolderPath; // Delete old diagnostics folder (1 day). DateTime expirationDate = DateTime.Now.Subtract(new TimeSpan(1, 0, 0, 0)); @@ -42,20 +45,34 @@ namespace FileConverter.Diagnostics public static event EventHandler StaticPropertyChanged; - public static DiagnosticsData[] Data - { - get - { - return Debug.diagnosticsDataById.Values.ToArray(); - } - } + public static DiagnosticsData[] Data => Debug.diagnosticsDataById.Values.ToArray(); public static void Log(string message, params object[] arguments) { - DiagnosticsData diagnosticsData; + string log = arguments.Length > 0 ? string.Format(message, arguments) : message; + Debug.Log(log, ConsoleColor.White); + } - Thread currentThread = System.Threading.Thread.CurrentThread; + public static void Log(string message) + { + Debug.Log(message, ConsoleColor.White); + } + + public static void Log(string log, ConsoleColor color) + { + DiagnosticsData diagnosticsData; + + Thread currentThread = Thread.CurrentThread; int threadId = currentThread.ManagedThreadId; + + // Display main thread logs in standard output. + if (threadId == Debug.mainThreadId) + { + Console.ForegroundColor = color; + Console.WriteLine(log); + Console.ResetColor(); + } + lock (Debug.diagnosticsDataById) { if (!Debug.diagnosticsDataById.TryGetValue(threadId, out diagnosticsData)) @@ -70,7 +87,23 @@ namespace FileConverter.Diagnostics } } - diagnosticsData.Log(message, arguments); + diagnosticsData.Log(log); + } + + public static void Assert(bool condition) + { + if (!condition) + { + LogError("Assertion failed"); + } + } + + public static void Assert(bool condition, string message) + { + if (!condition) + { + LogError(message); + } } public static void LogError(string message, params object[] arguments) @@ -79,7 +112,12 @@ namespace FileConverter.Diagnostics MessageBox.Show(log, "Error", MessageBoxButton.OK, MessageBoxImage.Error); - Debug.Log("Error: " + message, arguments); + Debug.Log($"Error: {log}", ConsoleColor.Red); + } + + public static void LogError(int errorCode, string message) + { + Debug.LogError($"{message} (code 0x{errorCode:X})"); } public static void Release() diff --git a/Application/FileConverter/Diagnostics/DiagnosticsData.cs b/Application/FileConverter/Diagnostics/DiagnosticsData.cs index 1507bcb..5353367 100644 --- a/Application/FileConverter/Diagnostics/DiagnosticsData.cs +++ b/Application/FileConverter/Diagnostics/DiagnosticsData.cs @@ -13,8 +13,8 @@ namespace FileConverter.Diagnostics public class DiagnosticsData : INotifyPropertyChanged { - private List logMessages = new List(); - private StringBuilder stringBuilder = new StringBuilder(); + private readonly List logMessages = new List(); + private readonly StringBuilder stringBuilder = new StringBuilder(); private System.IO.TextWriter logFileWriter; private string name; @@ -28,10 +28,7 @@ namespace FileConverter.Diagnostics public string Name { - get - { - return this.name; - } + get => this.name; private set { @@ -62,11 +59,11 @@ namespace FileConverter.Diagnostics public void Initialize(string diagnosticsFolderPath, int id) { - string path = Path.Combine(diagnosticsFolderPath, string.Format("Diagnostics{0}.log", id)); + string path = Path.Combine(diagnosticsFolderPath, $"Diagnostics{id}.log"); path = PathHelpers.GenerateUniquePath(path); this.logFileWriter = new StreamWriter(File.Open(path, FileMode.Create)); - this.Log("{0} {1}\n", System.DateTime.Now.ToLongDateString(), System.DateTime.Now.ToLongTimeString()); + this.Log($"{System.DateTime.Now.ToLongDateString()} {System.DateTime.Now.ToLongTimeString()}\n"); } public void Release() @@ -75,15 +72,13 @@ namespace FileConverter.Diagnostics this.logFileWriter = null; } - public void Log(string message, params object[] arguments) + public void Log(string log) { - string log = arguments.Length > 0 ? string.Format(message, arguments) : message; - this.logMessages.Add(log); this.logFileWriter.WriteLine(log); this.logFileWriter.Flush(); - this.OnPropertyChanged("Content"); + this.OnPropertyChanged(nameof(this.Content)); } [NotifyPropertyChangedInvocator] diff --git a/Application/FileConverter/FileConverter.csproj b/Application/FileConverter/FileConverter.csproj index 58f2e0c..d29711b 100644 --- a/Application/FileConverter/FileConverter.csproj +++ b/Application/FileConverter/FileConverter.csproj @@ -1,5 +1,5 @@  - + Debug @@ -9,10 +9,13 @@ Properties FileConverter FileConverter - v4.5 + v4.8 512 {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 4 + + + AnyCPU @@ -66,13 +69,29 @@ true - - ..\..\packages\Magick.NET-Q16-AnyCPU.7.0.5.502\lib\net40-client\Magick.NET-Q16-AnyCPU.dll + + ..\..\packages\CommunityToolkit.Mvvm.8.2.2\lib\netstandard2.0\CommunityToolkit.Mvvm.dll + + + ..\..\packages\Magick.NET-Q16-AnyCPU.13.5.0\lib\netstandard20\Magick.NET-Q16-AnyCPU.dll + True + + + ..\..\packages\Magick.NET.Core.13.5.0\lib\netstandard20\Magick.NET.Core.dll True ..\..\Middleware\Markdown.Xaml.dll + + ..\..\packages\Microsoft.Bcl.AsyncInterfaces.8.0.0\lib\net462\Microsoft.Bcl.AsyncInterfaces.dll + + + ..\..\packages\Microsoft.Extensions.DependencyInjection.8.0.0\lib\net462\Microsoft.Extensions.DependencyInjection.dll + + + ..\..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.8.0.0\lib\net462\Microsoft.Extensions.DependencyInjection.Abstractions.dll + ..\..\packages\Microsoft.Office.Interop.Excel.15.0.4795.1000\lib\net20\Microsoft.Office.Interop.Excel.dll True @@ -85,6 +104,9 @@ ..\..\packages\Microsoft.Office.Interop.Word.15.0.4797.1003\lib\net20\Microsoft.Office.Interop.Word.dll True + + ..\..\packages\Microsoft.Xaml.Behaviors.Wpf.1.1.77\lib\net462\Microsoft.Xaml.Behaviors.dll + ..\..\packages\Office.12.0.0\lib\net40\Office.dll True @@ -94,8 +116,33 @@ False ..\..\Middleware\Ripper.dll + + ..\..\packages\SharpShell.2.7.2\lib\net40-client\SharpShell.dll + + + ..\..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll + + + ..\..\packages\System.ComponentModel.Annotations.5.0.0\lib\net461\System.ComponentModel.Annotations.dll + + + + + ..\..\packages\System.Memory.4.5.5\lib\net461\System.Memory.dll + + + + ..\..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll + + + ..\..\packages\System.Runtime.CompilerServices.Unsafe.6.0.0\lib\net461\System.Runtime.CompilerServices.Unsafe.dll + + + ..\..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + + @@ -107,9 +154,8 @@ - - ..\..\packages\WpfAnimatedGif.1.4.14\lib\net\WpfAnimatedGif.dll - True + + ..\..\packages\WpfAnimatedGif.2.0.2\lib\net40\WpfAnimatedGif.dll ..\..\Middleware\yeti.mmedia.dll @@ -121,12 +167,13 @@ Designer - - + + ConversionJobControl.xaml + + EncodingQualitySliderControl.xaml - @@ -139,6 +186,7 @@ + @@ -148,13 +196,14 @@ + + + + + + + - - Resources.fr.resx - True - True - True - Resources.en.resx True @@ -162,12 +211,19 @@ True - - - - + + + + + + + + + + + @@ -187,37 +243,49 @@ - - ApplicationStartHelp.xaml + + + + + + + + + + + HelpWindow.xaml - + DiagnosticsWindow.xaml - - - - - + + + + SettingsWindow.xaml - + UpgradeWindow.xaml + + Designer + MSBuild:Compile + Designer MSBuild:Compile - + Designer MSBuild:Compile - + Designer MSBuild:Compile - + MSBuild:Compile Designer @@ -228,15 +296,27 @@ - + MainWindow.xaml Code - + + MSBuild:Compile + Designer + + + MSBuild:Compile + Designer + + Designer MSBuild:Compile - + + Designer + MSBuild:Compile + + Designer MSBuild:Compile @@ -260,20 +340,27 @@ Settings.settings True - - PublicResXFileCodeGenerator - Resources.fr.Designer.cs - + + + + PublicResXFileCodeGenerator Resources.en.Designer.cs - + + + + PublicResXFileCodeGenerator Resources.Designer.cs Designer + + + + Designer @@ -284,10 +371,9 @@ - - - - + + Designer + @@ -313,29 +399,69 @@ - - - - - - + + + {0c44ca69-42d6-4357-bdfd-83069d1aba2f} + FileConverterExtension + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - copy /Y "$(SolutionDir)Middleware\ffmpeg\$(PlatformName)\ffmpeg.exe" "$(TargetDir)ffmpeg.exe" -copy /Y "$(SolutionDir)Middleware\gs\x86\gsdll32.dll" "$(TargetDir)gsdll32.dll" -copy /Y "$(SolutionDir)Middleware\gs\x86\gswin32c.exe" "$(TargetDir)gswin32c.exe" + copy /Y "$(SolutionDir)Middleware\ffmpeg\ffmpeg.exe" "$(TargetDir)ffmpeg.exe" +copy /Y "$(SolutionDir)Middleware\gs\gsdll64.dll" "$(TargetDir)gsdll64.dll" +copy /Y "$(SolutionDir)Middleware\gs\gswin64c.exe" "$(TargetDir)gswin64c.exe" copy /Y "$(ProjectDir)Settings.default.xml" "$(TargetDir)Settings.default.xml" robocopy $(TargetDir) $(TargetDir)\Languages "$(TargetName).resources.dll" /CREATE /S /XD Languages /IS /IT /NFL /NDL /NJH /NJS /NC /NS /NP if %25errorlevel%25 leq 1 exit 0 else exit %25errorlevel%25 robocopy $(TargetDir) $(TargetDir)\Languages "$(TargetName).resources.dll" /MOVE /S /XD Languages /XL /IS /IT /NFL /NDL /NJH /NJS /NC /NS /NP if %25errorlevel%25 leq 1 exit 0 else exit %25errorlevel%25 + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + حول البرنامج + about + + + السماح لك لاختيار ماذا تريد أن تفعل مع الملف المدخل عند انتهاء التحويل + Allow you to choose what you want to do with your input files if the conversion succeed + + + افعل عند انتهاء التحويل بنجاح + Action when conversion succeed + + + ضبط مسبق جديد + New preset + + + البرنامج + Application + + + الصوت + Audio + + + البحث عن التحديثات تلقائياً عند فتح البرنامج + Automatically check for updates when File Converter starts + + + الخروج من البرنامج عند انتهاء كل التحويلات + Automatically exit when all conversions finished + + + ثبت لأدنى طاقة بحجم 2 + Clamp to lowest power of 2 size + + + إغلاق + Close + + + أرشيف الضبط المسبق + Conversion Presets + + + ملفات للتحويل + Files to convert + + + محول من + Converted from + + + السجلات + Logs + + + السجلات + Logs + + + فتح الوثائق + Open documentation + + + تبرع + Donate + + + لا تنسي مكافأة عملي لو أعجبك + Don't forget to reward my work if you like it :) + + + التحديث سوف يقوم بالتنزيل في الخلفية و سوف يتم تثبيت التحديث عند غلق البرنامج + The update will be downloaded in background, and installed once you exit File Converter. + + + تثبيت عندما اقوم بإغلاق البرنامج + Install when I exit File Converter + + + الترميز: + Encoding : + + + سرعة الترميز: + Encoding speed : + + + shell يكون صيغة File Converter + File Converter is a shell extension. + + + Windows explorer. ذلك معناه انه مدمج مع + That means it is integrated into the Windows explorer. + + + لاستخدام File Converter قم بفتح explorer وقم بالضغط مرتين يمين علي الملف الذي تريد جلبة الي القائمة حيث سوف تجد اوامر البرنامج (انظر ملف readme لتري مجموعه الصيغ المتوافقة + To use File Converter please open the explorer and right-click on any file you like to bring up the context menu where you will find File Converter commands (see the readme file to see the list of compatible file formats). + + + نموذج اسم الملف + File name template + + + إطار لكل ثانية + Frames per second : + + + افتح صفحة مشاريع GitHub + Open GitHub project page + + + مساعدة ؟ + help ? + + + نموذج المدخلات + Input example + + + صيغ المدخلات + Input formats + + + حذف + Delete + + + نقل الي مجلد الارشيف + Move in an archive folder + + + فارغ + None + + + التحديث تم تنزيله.اغلق البرنامج و قم بتثبيت التحديث الان + The update has been downloaded. Exit File Converter and install the update now. + + + تثبيت عندما اقوم بغلق البرنامج + Install when I exit File Converter + + + تقرير عن مشكلة + Report an issue + + + تحرك لأسفل الإعداد المسبق المحدد + Move down selected preset + + + تحرك لأعلي الإعداد المسبق المحدد + Move up selected preset + + + ترميز معدل البت الثابت + Constant bitrate encoding + + + ترميز معدل البت المتغير + Variable bitrate encoding + + + 90° + + + 90 درجة دوران عقارب الساعة + 90° counter clockwise rotation + + + موافق + Ok + + + 180° + + + 180° دوران + 180° rotation + + + C:\Music\Artist\Album\Song.wav + + + الاخراج + Output + + + (p): مسار الملف المخل +(f): اسم الملف المدخل +(o): نوع صيغه الاخراج +(i): نوع صيغة المدخل +(d0): إدخال المجلد الأصل +(d1): إدخال المجلد الأصل الفرعي +... +(n:i): فهرس رقم الصفحة +(n:c): إجمالي عدد الصفحات + +مسارات خاصة: +(p:d): documents مسار +(p:m): music مسار +(p:v): videos مسار +(p:p): pictures مسار + +استخدم maj لإصدار الأحرف الكبيرة + (p): input file path +(f): input filename +(o): output extension type +(i): input extension type +(d0): input parent folder +(d1): input sub parent folder +... +(n:i): page number index +(n:c): total page count + +Special paths: +(p:d): my documents path +(p:m): my music path +(p:v): my videos path +(p:p): my pictures path + +use maj for uppercase version + + + صيغة الاخراج + Output format + + + ضبط + Preset + + + اسم الضبط + Preset Name + + + الجوده: + Quality : + + + نطاق معدل البت الموصى به باللون الأزرق + Recommended bitrate range in blue + + + حذف + Delete + + + دوران: + Rotate : + + + حفظ + Save + + + الحجم: + Scale : + + + انظر سجل التغيرات.. + See change log ... + + + الاعدادات + Settings + + + الاعدادات + Settings + + + 270° + + + 90 درجة دوران في اتجاه عقارب الساعة + 90° clockwise rotation + + + يتوفر تحديث للبرنامج. يوصى بشدة بتثبيته في أسرع وقت ممكن! + An update for File Converter is available. It is strongly recommended that you install it as soon as possible! + + + ترقية التنزيل قيد التقدم ... + Upgrade download in progress... + + + تحديثات File Converter + File Converter Updates + + + حدد نسبة "حجم الملف" مقابل "جودة الفيديو". ستمنحك القيمة الأقل ملفًا أصغر ، بينما تمنحك القيمة الأكبر جودة فيديو أفضل. + Define the ratio 'file size' versus 'video quality'. A lower value will give you a smaller file, a greater value give you a better video quality. + + + اسرع + Faster + + + سريع + Fast + + + متوسط + Medium + + + ابطئ + Slower + + + بطئ + Slow + + + خارق السرعه + Super Fast + + + حدد نسبة "حجم الملف" مقابل "مدة الضغط". يمنحك الضغط البطيء ملفًا أصغر (لنفس جودة الفيديو) من ضغط أسرع. + Define the ratio 'file size' versus 'compression duration'. A slow compression will give you a smaller file (for the same video quality) than a faster compression. + + + سريع للغاية + Ultra Fast + + + سريع جداً + Very Fast + + + بطئ جداً + Very Slow + + + فيديو + Video + + + PCM signed 16-bit little-endian + + + PCM signed 24-bit little-endian + + + PCM signed 32-bit little-endian + + + PCM signed 8-bit little-endian + + + فارغ + None + + + لا دوران + No rotation + + + التحويل + Conversion + + + أنتهي + Done + + + الاخراج + Extraction + + + فشل + Failed + + + في قائمة الانتظار + In queue + + + قرأت الصوره المدخلة + Read input image + + + قرأت الملف + Read document + + + صورة متحركة + Animated Image + + + الصوت + Audio + + + مستند + Document + + + صوره + Image + + + فيديو + Video + + + فترة انتظار قبل اغلاق البرنامج + Waiting duration before application exit + + + اللغة + Language + + + الحد الأقصى لعدد التحويلات المتزامنة + Maximum number of simultaneous conversions + + + ضبط مسبق جديد + New preset + + + ###تنزيل سجل التغييرات + ###Downloading change log ... + + + أرشيف التحويلات + Conversion Archives + + + ألغي + Canceled. + + + فشل في ايجاد ffmpeg executable ,يجب ان تحاول اعادة تثبيت البرنامج + Fail to find ffmpeg executable. You should try to reinstall the application. + + + فشل في اخراج صوت CD + Audio CD track extraction failed. + + + قرص CD غير جاهز + CD drive is not ready. + + + فشل في بدأ ffmpeg + Fail to launch ffmpeg. + + + فشل في انشاء مسار مجلد الاخراج + Fail to create output path folders. + + + فشل في انشاء مسار فريد لملف الاخراج + Fail to generate a unique output file path. + + + فشل في قرأت قرص CD '{0}'. + Fail to read cd drive '{0}'. + + + فشل في استعاده مسار القرص المدخل + Fail to retrieve input path drive letter. + + + فشل في استعاده رقم المسار من المسار المدخل لcda + Fail to retrieve track number from the cda input path. + + + فشل في استخدام قرص الCD بسبب انه مستخدم + Fail to use the CD drive because it is oppened. + + + نوع الملف المدخل لايتوافق مع نوع الملف المخرج المختار + The input file type is not compatible with the selected output file type. + + + مسار مخرج غير صحيح تم انشائه بواسطه قالب مسار الملف المخرج + Invalid output path generated by output file path template. + + + '{0}'.صيغة الاخراج غير مدعومة + Unsupported output format '{0}'. + + + عدد القنوات: + Channel count : + + + تغيير عدد قنوات الملف المدخل + Change the number of channels of the input file. + + + Mono + + + نفس ملف الإدخال + Same than input file + + + استيريو + Stereo + + + **هذا البرنامج مجاني**. + **This program is free software**. + + + يمكنك إعاده توزيعه او تعديلة تحت رخصة GNU General Public License. + You can redistribute it and/or modify it under the terms of the GNU General Public License. + + + هذا البرنامح موزع املاً ان يكون مفيد , بدون اي تحذير انظر GNU General Public License (متوافر في مجلد التثبيت LICENSE.md` لمزيد من التفاصيل + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. See the GNU General Public License (available in the installation folder: `LICENSE.md`) for more details. + + + البرنامج ينتهي + The application is terminating. + + + البرنامج سوف ينتهي تلقائيا في {0} ثانية + The application will automatically terminate in {0} seconds. + + + البرنامج سوف ينتهي تلقائيا في {1} ثانية + The application will automatically terminate in 1 second. + + + Misc + Misc + + + لا يمكن ايجاد الملف المخرج + Can't find the output file(s). + + + فشل عملية التحويل لكن هناك ملف مخرج ليس موجود + The conversion job failed but there is an output file that does exists. + + + تجهيز التحويل + Prepare conversion + + + لتحويل ملفات Microsoft Office يجب ان يتم تثبيت Office + Microsoft Office must be installed in order to convert Office documents. + + + فشل في فتح مستند بواسطه Microsoft Office (تحقق من تثبيت رخصة صالحة) + Fail to open document with Microsoft Office (check if your licence/installation is valid). + + + لتحويل ملفات Microsoft Excel يجب ان يتم تثبيت Excel + Microsoft Excel must be installed in order to convert Excel documents. + + + لتحويل ملفات Microsoft PowerPoint يجب ان يتم تثبيت PowerPoint + Microsoft PowerPoint must be installed in order to convert PowerPoint documents. + + + لتحويل ملفات Microsoft Word يجب ان يتم تثبيت Word + Microsoft Word must be installed in order to convert Word documents. + + + فتح موقع البرناج + Open File Converter website + + + خطأ اثناء عملية تثبيت التحويل + Error during conversion job initialization. + + + مجلد جديد + New folder + + + مجلد جديد + New folder + + + مجلد + Folder + + + اسم المجلد + Folder Name + + + الوضع المتقدم + Advanced mode + + + تخصيص وسائط + Custom Arguments + + + وسائط سطر الاومر FFMPEG تخصيص + Custom FFMPEG command line arguments + + + لم يتم اختيار إعداد مسبق + No preset selected + + + تصدير + Export + + + استيراد + Import + + + نسخ الضبط + Duplicate preset + + + إلغاء + Cancel + + + خطأ + Error + + + لا يمكن تحميل ملف الضبط ,هل تريد ان تعود الي الضبط الرئيسي + Can't load file converter user settings. Do you want to fall back to default settings ? + + diff --git a/Application/FileConverter/Properties/Resources.de-DE.resx b/Application/FileConverter/Properties/Resources.de-DE.resx new file mode 100644 index 0000000..efa6ca5 --- /dev/null +++ b/Application/FileConverter/Properties/Resources.de-DE.resx @@ -0,0 +1,568 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Über + + + + Erlaubt es die Aktion auszuwählen, die passiert, sobald die Dateien konvertiert sind. + + + + Aktion nach Umwandlungsschluss + + + Eine neues Preset hinzufügen (duplicate selected preset) + + + + Applikation + + + + Audio + + + + Bei Programmstart automatisch nach Updates suchen + + + + Automatisch schließen, wenn alle Dateien bereit sind + + + + Clamp to lowest power of 2 size + + + + Schließen + + + + Umwandlungs-Preset + + + Dateien zu konvertieren + + + + Umgewandelt von + + + Logs + + + + Logs + + + + Dokumentation öffnen + + + + Spenden + + + + Vergessen Sie nicht meine Arbeit zu belohnen, wenn sie Ihnen gefällt :) + + + + Das Update wird im Hintergrund heruntergeladen und installiert sobald sie File Converter schließen + + + + Installieren sobald ich File Converter schließe + + + + Codierung: + + + Codierungsgeschwindigkeit : + + + File Converter ist eine Shell-Erweiterung. + + + Das heißt, dass sie in den Windows Explorer integriert ist. + + + + Dateinamen-Vorlage + + + Bilder die Sekunde(FPS): + + + + GitHub Projektseite öffnen + + + Hilfe + + + + Eingabebeispiel + + + + Eingabeformate + + + + Löschen + + + + Ins Archiv verschieben + + + + Nichts + + + + Das Update wurde heruntergeladen. Schließe File Converter um es zu installieren + + + + Installieren sobald ich File Converter schließe + + + + Einen Fehler melden + + + + Ausgewähltes Preset nach unten verschieben + + + + Ausgewähltes Preset nach oben verschieben + + + + Codieren mit konstanter Bitrate + + + Codieren mit variabler Bitrate + + + 90° + + + + 90° gegen den Uhrzeigersinn rotieren + + + Ok + + + 180° + + + + 180° rotieren + + + C:\Musik\Künstler\Album\Song.wav + + + Ausgabe + + + (p): Eingabe Dateipfad(f): Eingabe Dateiname(o): Ausgabe Erweiterungstyp(i): Eingabe Erweiterungstyp(d0): Eingabe Oberordner(d1): Eingabe Unter-Oberordner...(n:i): Seitennummer(n:c): total page countSpecial paths:(p:d): Meine Dokumente Pfad(p:m): Meine Musik Pfad(p:v): Meine Videos Pfad(p:p): Meine Vilder Pfad + + + Ausgabeformat + + + Preset + + + Preset Name + + + Qualität: + + + Empfohlene Bitratenreichweite in Blau + + + Ausgewähltes Preset löschen + + + Rotieren: + + + Speichern + + + Größe: + + + Change log anschauen + + + File Converter Einstellungen + + + Einstellungen + + + 270° + + + + 90° im Uhrzeigersinn rotieren + + + Eine Aktualisierung für File Converter ist verfügbar. Es wird stark empfohlen, dass Sie dies so früh wie möglich installieren! + + + Aktualisierung wird heruntergeladen + + + File Converter Aktualisierungen + + + Definieren Sie das Verhältnis zwischen Dateigröße und Videoqualität. Ein niedrigerer Wert wird Ihnen eine kleinere Datei geben, ein größerer Wert wird Ihnen bessere Videoqualität geben. + + + Schneller + + + Schnell + + + Medium + + + + Langsamer + + + Langsam + + + Super schnell + + + Definieren Sie das Verhältnis zwischen Dateigröße und Komprimierungsdauer. Eine langasme Komprimierung wird Ihnen eine kleinere Datei(bei selber Qualität) geben als schnellere Komprimierung. + + + Ultra schnell + + + Sehr schnell + + + Sehr langsam + + + Video + + + + PCM signierter 16-bit little-endian + + + PCM signierter 24-bit little-endian + + + PCM signierter 32-bit little-endian + + + PCM signierter 8-bit little-endian + + + Keiner + + + Keine Rotation + + + Umwandlung + + + Fertig + + + Extraktion + + + Fehler + + + In Warteschlange + + + Eingabebild lesen + + + Dokument lesen + + + Animiertes Bild + + + Audio + + + + Dokument + + + Bild + + + Video + + + Wartezeit bevor das Programm sich schließt + + + Sprache + + + Maximale Anzahl an gleichzeitig verlaufenden Umwandlung + + + Neues Preset + + + Change log wird heruntergeladen... + + + Umwandlungsarchiv + + + Abgebrochen + + + Fehler beim Finden der ffmpeg executable. Sie sollten versuchen das Programm neu zu installieren. + + + Audio CD Spur Extraktion fehlgeschlagen + + + CD Laufwerk ist nicht bereit. + + + Fehler beim Ausführen der ffmpeg + + + Fehler beim Erstellen des Ausgabeordners. + + + Fehler beim Generieren eines einzigartigen Ausageordners. + + + Fehler beim Lesen des CD Laufwerks '{0}'. + + + Fehler beim Lesen des Laufwerksbuchstaben des Eingangspfades. + + + Fehler beim Lesen der Spurnummer vom cda Eingangspfad. + + + Fehler beim Lesen vom CD-Laufwerk, da es geöffnet ist. + + + Der Eingangsdateityp ist nicht mit dem gewählten Ausgangsdateityp kompatibel. + + + Ungültiger Ausgangspfad von der Ausgangspfad-Vorlage erstellt. + + + Nicht-untertütztes Ausgangsformat: '{0}'. + + + Kanal Anzahl: + + + Hier können Sie die Anazhl an Kanälen der Eingangsdatei ändern. + + + Mono + + + Der Eingangsdatei gleich + + + Stereo + + + Um File Converter zu benutzen, öffnen sie den Dateiexplorer und klicken Sie mit der rechten Maustaste auf die Datei, die Sie umwandeln möchten, um das Kontext-Menü zu öffnen, wo Sie File Converter Befehle finden( Sehen Sie sich die Online-Dokumentation für eine Liste der integrierten Dateitypen an) + + + **This program is free software**. + Apparently, this has to stay english in order for it to be legally binding... I'm not sure about that though. + + + You can redistribute it and/or modify it under the terms of the GNU General Public License. + + + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. See the GNU General Public License (available in the installation folder: `LICENSE.md`) for more details. + + + Das Programm wird sich schließen. + + + Das Programm wird sich in {0} Sekunden automatisch schließen. + + + Das Programm wird sich in einer Sekunde automatisch schließen. + + + Verschiedenes + + + Ausgangsdateien konnten nicht gefunden werden. + + + Die Umwandlung ist fehlgeschlagen, aber es gibt eine Ausgabedatei. + + + Umwandlung vorbereiten + + + Microsoft Office muss installiert sein, damit ein Office Dokument umgewandelt werden kann. + + + Öfnnen des Dokuments mit Microsoft Office fehlgeschlagen(Prüfen Sie, ob ihre Lizenz und Installation von Microsoft Office gültig sind). + + + Microsoft Excel muss installiert sein, damit ein Excel Dokument umgewandelt werden kann. + + + Microsoft PowerPoint muss installiert sein, damit ein PowerPoint Dokument umgewandelt werden kann. + + + Microsoft Word muss installiert sein, damit ein Word Dokument umgewandelt werden kann. + + + Die File Converter Internetseite öffnen + + diff --git a/Application/FileConverter/Properties/Resources.el-GR.resx b/Application/FileConverter/Properties/Resources.el-GR.resx new file mode 100644 index 0000000..521cf05 --- /dev/null +++ b/Application/FileConverter/Properties/Resources.el-GR.resx @@ -0,0 +1,598 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Σχετικά + + + Σας επιτρέπει να επιλέξετε τι θέλετε να κάνετε με τα αρχεία που επιλέξατε, αν η μετατροπή τους πετύχει + + + Ενέργεια που θα γίνει όταν η μετατροπή επιτύχει + + + Νέα προκαθορισμένη ρύθμιση + + + Εφαρμογή + + + Ήχος + + + Αυτόματος έλεγχος για ενημερώσεις κατά την εκκίνηση του μετατροπέα αρχείων + + + Αυτόματη έξοδος όταν ολοκληρωθούν όλες οι μετατροπές + + + Συμπίεση στη χαμηλότερη τιμή σε μέγεθος 2 + + + Κλείσιμο + + + Προκαθορισμένες ρυθμίσεις μετατροπής + + + Αρχεία για μετατροπή + + + Έγινε μετατροπή από + + + Αρχεία διάγνωσης + + + Αρχεία καταγραφής-διάγνωσης + + + Άνοιγμα εγγράφων τεκμηρίωσης + + + Δωρεά + + + Μην ξεχάσεις να ανταμείψεις τη δουλειά μου αν σου αρέσει η εφαρμογή :) + + + Η ενημέρωση θα ληφθεί στο παρασκήνιο και θα εγκατασταθεί μόλις πραγματοποιήσετε έξοδο από τον Μετατροπέα αρχείων. + + + Εγκατάσταση κατά την έξοδο από τον Μετατροπέα Αρχείων + + + Κωδικοποίηση : + + + Τχύτητα Κωδικοποίησης : + + + Ο μετατροπέας αρχείων είναι επέκταση shell-κελύφους. + + + Αυτό σημαίνει ότι είναι ενσωματωμένη στην εξερεύνηση των Windows. + + + Για να χρησιμοποιήσετε το μετατροπέα αρχείων ανοίξτε την εξερεύνηση και κάντε δεξί κλικ σε οποιοδήποτε αρχείο θέλετε να εμφανιστεί το μενού περιβάλλοντος όπου θα βρείτε τις εντολές του μετατροπέα αρχείων (δείτε το αρχείο readme για να δείτε τη λίστα με τις συμβατές μορφές αρχείων). + + + Πρότυπο ονόματος αρχείου + + + Καρέ ανά δευτερόλεπτο : + + + Άνοιγμα σελίδας της εφαρμογής στο GitHub + + + Βοήθεια + + + Παράδειγμα εισαγωγής + + + Μορφές εισόδου + + + Διαγραφή + + + Μετακίνηση σε φάκελο αρχειοθέτησης + + + Καμία + + + Έγινε λήψη της ενημέρωσης. Κλείστε τον Μετατροπέα Αρχείων και εγκαταστήστε την ενημέρωση τώρα. + + + Εγκατάσταση κατά την έξοδο από τον Μετατροπέα Αρχείων + + + Αναφορά προβλήματος + + + Μετακίνηση της επιλεγμένης προεπιλογής κάτω + + + Μετακίνηση της επιλεγμένης προεπιλογής επάνω + + + Κωδικοποίηση σταθερού ρυθμού bit + + + Κωδικοποίηση μεταβλητού ρυθμού bit + + + 90° + + + 90° αριστερόστροφη περιστροφή + + + Ok + + + 180° + + + 180° περιστροφή + + + C:\Music\Artist\Album\Song.wav + + + Έξοδος + + + (p): διαδρομή αρχείου εισόδου +(f): όνομα αρχείου εισόδου +(o): τύπος επέκτασης εξόδου +(i): τύπος επέκτασης εισόδου +(d0): γονικός φάκελος εισόδου +(d1): εισαγωγή δευτερεύοντος γονικού φακέλου +.. +(n:i): δείκτης αριθμού σελίδας +(n:c): συνολικός αριθμός σελίδων + +Ειδικές διαδρομές: +(p:d): διαδρομή εγγράφων +(p:m): η μουσική μου διαδρομή +(p:v): η διαδρομή των βίντεό μου +(p:p): διαδρομή εικόνων + +χρήση maj για έκδοση με κεφαλαία + + + Μορφή εξόδου + + + Προεπιλογή + + + Όνομα προεπιλογής + + + Ποιότητα : + + + Προτεινόμενο εύρος ρυθμού bit σε μπλε + + + Διαγραφή + + + Περιστροφή : + + + Αποθήκευση + + + Κλίμακα : + + + Έμφάνιση αλλαγών ... + + + Ρυθμίσεις μετατροπέα αρχείων + + + Ρυθμίσεις + + + 270° + + + 90° δεξιόστροφη περιστροφή + + + Υπάρχει διαθέσιμη ενημέρωση για το πρόγραμμα μετατροπής αρχείων. Συνιστάται η εγκατάστασή του το συντομότερο δυνατό! + + + Λήψη αναβάθμισης σε εξέλιξη... + + + Ενημερώσεις Μετατροπέα Αρχείων + + + Ορίστε την αναλογία "μέγεθος αρχείου" έναντι "ποιότητα βίντεο". Με χαμηλότερη τιμή έχετε μικρότερο μέγεθος αρχείου, με μεγαλύτερη τιμή έχετε καλύτερη ποιότητα βίντεο. + + + Πολύ γρήγορη + + + Γρήγορη + + + Μεσαία + + + Πολύ αργή + + + Αργή + + + Ταχύτερη + + + Ορίστε την αναλογία 'μέγεθος αρχείου' έναντι 'διάρκειας συμπίεσης'. Η αργή συμπίεση θα σας δώσει ένα μικρότερο αρχείο (για την ίδια ποιότητα βίντεο) σε σύγκριση με την ταχύτερη συμπίεση. + + + Εξαιρετικά γρήγορη + + + Πολύ γρήγορη + + + Πολύ αργή + + + Βίντεο + + + PCM υπογεγραμμένο με 16-bit little-endian + + + PCM υπογεγραμμένο με 24-bit little-endian + + + PCM υπογεγραμμένο με 32-bit little-endian + + + PCM υπογεγραμμένο με 8-bit little-endian + + + Καμία + + + Χωρίς περιστροφή + + + Μετατροπή + + + Έγινε + + + Εξαγωγή + + + Απέτυχε + + + Σε ουρά + + + Ανάγνωση Εικόνας εισόδου + + + Ανάγνωση εγγράφου + + + Κινούμενη εικόνα + + + Ήχος + + + Έγγραφο + + + Εικόνα + + + Βίντεο + + + Διάρκεια αναμονής πριν από την έξοδο της εφαρμογής + + + Γλώσσα + + + Μέγιστος αριθμός ταυτόχρονων μετατροπών + + + Νέα προκαθορισμένη ρύθμιση + + + ###Λήψη αρχείου καταγραφής αλλαγών ... + + + Αρχειοθήκες μετατροπής + + + Ακυρώθηκε. + + + Αποτυχία εύρεσης του εκτελέσιμου ffmpeg. Θα πρέπει να προσπαθήσετε να εγκαταστήσετε ξανά την εφαρμογή. + + + Η εξαγωγή κομματιού του CD ήχου απέτυχε + + + Η μονάδα CD/DVD δεν είναι έτοιμη. + + + Αποτυχία εκκίνησης του ffmpeg. + + + Αποτυχία δημιουργίας φακέλων διαδρομής εξόδου. + + + Αποτυχία δημιουργίας μιας μοναδικής διαδρομής του αρχείου εξόδου. + + + Αποτυχία ανάγνωσης μονάδας CD/DVD '{0}'. + + + Αποτυχία ανάκτησης του γράμματος της μονάδας διαδρομής εισόδου. + + + Αποτυχία ανάκτησης αριθμού κομματιού από τη διαδρομή εισόδου cda. + + + Αποτυχία χρήσης της μονάδας CD/DVD επειδή είναι ανοιχτή. + + + Ο τύπος αρχείου εισόδου δεν είναι συμβατός με τον επιλεγμένο τύπο αρχείου εξόδου. + + + Δημιουργήθηκε μη έγκυρη διαδρομή εξόδου από το πρότυπο διαδρομής αρχείου εξόδου. + + + Μη υποστηριζόμενη μορφή εξόδου '{0}'. + + + Πλήθος καναλιών : + + + Αλλαγή του αριθμού καναλιών του αρχείου εισόδου. + + + Μονοφωνικό + + + Ίδιο με το αρχείο εισόδου + + + Stereo + + + **Αυτό το πρόγραμμα είναι ελεύθερο λογισμικό**. + + + Μπορείτε να το αναδιανείμετε ή/και να το τροποποιήσετε σύμφωνα με τους όρους της Γενικής Δημόσιας Άδειας GNU. + + + Αυτό το πρόγραμμα διανέμεται με την ελπίδα ότι θα είναι χρήσιμο, αλλά ΧΩΡΙΣ ΚΑΜΙΑ ΕΓΓΥΗΣΗ. Δείτε την Γενική Δημόσια Άδεια GNU (διαθέσιμη στον φάκελο εγκατάστασης: `LICENSE.md`) για περισσότερες λεπτομέρειες. + + + Η εφαρμογή τερματίζεται. + + + Η εφαρμογή θα τερματιστεί αυτόματα σε {0} δευτερόλεπτα. + + + Η εφαρμογή θα τερματιστεί αυτόματα σε 1 δευτερόλεπτο. + + + Διάφορα + + + Δεν είναι δυνατή η εύρεση του αρχείου(ων) εξόδου. + + + Η εργασία μετατροπής απέτυχε αλλά υπάρχει ένα αρχείο εξόδου που δημιουργήθηκε. + + + Προετοιμασία μετατροπής + + + Το Microsoft Office πρέπει να εγκατασταθεί για να μετατρέψετε έγγραφα του Office. + + + Αποτυχία ανοίγματος εγγράφου με το Microsoft Office (ελέγξτε αν η άδεια χρήσης/εγκατάσταση είναι έγκυρη). + + + Το Microsoft Excel πρέπει να εγκατασταθεί για να μετατρέψετε έγγραφα του Excel. + + + Το Microsoft PowerPoint πρέπει να είναι εγκατεστημένο, για να μετατρέψετε έγγραφα του PowerPoint. + + + Το Microsoft Word πρέπει να εγκατασταθεί για να μετατρέψετε έγγραφα του Word. + + + Τοποθεσία Web του Open File Converter + + + Πείτε ένα ευχαριστώ! + + + Σφάλμα κατά την προετοιμασία της εργασίας μετατροπής. + + + Δημιουργία νέου φακέλου + + + Νέος φάκελος + + + Φάκελος + + + Όνομα φακέλου + + + Προηγμένη κατάσταση λειτουργίας + + + Προσαρμοσμένοι ορισμοί + + + Προσαρμοσμένοι ορισμοί γραμμής εντολών FFMPEG + + + Δεν έχει επιλεγεί προκαθορισμένη ρύθμιση + + + Εξαγωγή + + + Εισαγωγή + + + Προκαθορισμένο Διπλότυπο + + + Ακύρωση + + + Σφάλμα + + + Δεν είναι δυνατή η φόρτωση των ρυθμίσεων χρήστη του μετατροπέα αρχείων. Θέλετε να επιστρέψετε στις προεπιλεγμένες ρυθμίσεις? + + + Αντιγραφή αρχείων στο πρόχειρο μετά τη μετατροπή + + \ No newline at end of file diff --git a/Application/FileConverter/Properties/Resources.en.resx b/Application/FileConverter/Properties/Resources.en.resx index 00c47dd..51a721c 100644 --- a/Application/FileConverter/Properties/Resources.en.resx +++ b/Application/FileConverter/Properties/Resources.en.resx @@ -121,13 +121,13 @@ About - Allow you to chose what you want to do with your input files if the conversion succeed + Allow you to choose what you want to do with your input files if the conversion succeed Action when conversion succeed - Add new preset (duplicate selected preset) + New preset Application @@ -159,7 +159,7 @@ Logs - + Logs @@ -252,7 +252,7 @@ 180° rotation - + C:\Music\Artist\Album\Song.wav @@ -289,11 +289,11 @@ use maj for uppercase version Quality : - + Recommended bitrate range in blue - Remove selected preset + Delete Rotate : @@ -310,7 +310,7 @@ use maj for uppercase version File Converter Settings - + Settings @@ -544,4 +544,34 @@ use maj for uppercase version Open File Converter website + + Error during conversion job initialization. + + + Export + + + Import + + + Duplicate preset + + + Cancel + + + Advanced mode + + + Custom Arguments + + + Custom FFMPEG command line arguments + + + Error + + + Can't load file converter user settings. Do you want to fall back to default settings ? + \ No newline at end of file diff --git a/Application/FileConverter/Properties/Resources.es-ES.resx b/Application/FileConverter/Properties/Resources.es-ES.resx new file mode 100644 index 0000000..d96f71d --- /dev/null +++ b/Application/FileConverter/Properties/Resources.es-ES.resx @@ -0,0 +1,550 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Acerca de... + + + Le permite elegir qué hacer con los archivos origen si la conversión tiene éxito + + + Acción tras conversión: + + + Añadir preajuste (duplicando el actual) + + + Aplicación + + + Audio + + + Buscar actualizaciones de forma automática cuando File Converter se ejecuta + + + Salir automáticamente al concluir las conversiones + + + Redondear al tamaño de la potencia de dos más bajo + + + Cerrar + + + Preajustes de conversión + + + Archivos a convertir + + + Convertir de + + + Registros + + + Registros + + + Abrir documentación + + + Donar + + + No olvide recompensar mi trabajo si le ha gustado :) + + + La actualización se descargará en segundo plano y será instalada una vez salga de File Converter. + + + Instalar tras salir de File Converter + + + Codificación: + + + Vel. de codificación: + + + File Converter es una extensión de la "shell" de Windows. + + + Ello significa que está integrado en el Explorador de Windows. + + + Para usar File Converter, abra el Explorador de Windows y haga clic derecho en cualquier archivo. En el menú contextual, use directamente los comandos de File Converter (cfr. al archivo "readme" para una completa lista de formatos de archivo compatibles). + + + Plantilla de nombre de archivo + + + Fotogramas por segundo: + + + Abrir la página del proyecto en GitHub + + + ¿Ayuda? + + + Ejemplo de origen + + + Formatos de origen: + + + Eliminar + + + Mover a carpeta de archivos + + + No hacer nada + + + Actualización descargada. Se instalará cuando salga de File Converter. + + + Instalar al salir de File Converter + + + Informar de un problema + + + Mover abajo el preajuste seleccionado + + + Mover arriba el preajuste seleccionado + + + Codificación con tasa de bits constante + + + Codificación con tasa de bits variable + + + 90° + + + Rotación de 90° en el sentido del reloj + + + Aceptar + + + 180° + + + Rotación de 180° en el sentido del reloj + + + C:\Música\Artista\Album\Canción.wav + + + Resultado + + + (p): ruta de archivo origen +(f): nombre de archivo origen +(o): extensión de destino +(i): extensión de origen +(d0): carpeta contenedora de origen +(d1): subcarpeta contenedora de origen +... +(n:i): índice de número de página +(n:c): número de páginas totales + +Rutas especiales: +(p:d): ruta de Documentos +(p:m): ruta de Música +(p:v): ruta de Vídeos +(p:p): ruta de Imágenes + +Use May para versión en mayúsculas + + + Formato destino + + + Preajuste + + + Nombre de preajuste + + + Calidad: + + + Rango de tasa de bits recomendado en azul + + + Remover preajuste seleccionado + + + Rotar: + + + Guardar + + + Escala: + + + Ver registro de cambios... + + + Configuración + + + Configuración + + + 270° + + + Rotación de 270° en el sentido del reloj + + + Hay disponible una actualización para File Converter. ¡Se recomienda vivamente instalarla cuanto antes! + + + Descarga de actualización en curso... + + + Actualizaciones de File Converter + + + Define la relación entre tamaño de archivo y calidad de vídeo. Cuanto menor sea el valor, más pequeño y de peor calidad será el archivo resultante y viceversa. + + + Muy rápida + + + Rápida + + + Media + + + Muy lenta + + + Lenta + + + Superrápida + + + Define la relación entre tamaño de archivo y tiempo invertido en la compresión. Una compresión prolongada arroja un tamaño menor de archivo conservando la calidad. + + + Ultrarrápida + + + Muy rápida + + + Muy lenta + + + Vídeo + + + PCM firmado 16 bits little-endian + + + PCM firmado 24 bits little-endian + + + PCM firmado 32 bits little-endian + + + PCM firmado 8 bits little-endian + + + Cero + + + Sin rotación + + + Conversión + + + Hecho + + + Extracción + + + Error + + + En cola + + + Leer imagen origen + + + Leer documento + + + Imagen animada + + + Audio + + + Documento + + + Imagen + + + Vídeo + + + Tiempo de espera antes de cerrar la aplicación + + + Idioma + + + Número máximo de conversiones simultáneas + + + Nuevo preajuste + + + ###Descargando registro de cambios... + + + Archivos de conversión + + + Cancelado. + + + No se encuentra el ejecutable de ffmpeg. Debería reinstalar la aplicación. + + + Extracción de pista de audio CD fallida. + + + La unidad de CD no está lista. + + + Error al ejecutar ffmpeg. + + + Error al crear las carpetas destino. + + + Error al generar la ruta de un archivo destino único. + + + Error al leer la unidad de CD '{0}'. + + + Error al indagar la letra de unidad de la ruta origen. + + + Error al indagar el número de pista. + + + Error al gestionar la unidad de CD: Bandeja abierta. + + + El tipo de archivo origen no es compatible con el tipo de archivo destino seleccionado. + + + Ruta destino inválida causada por una plantilla de ruta de archivo destino incorrecta. + + + Formato destino '{0}' no soportado. + + + Número de canales: + + + Cambiar el número de canales del archivo origen. + + + Mono + + + Mismo que el archivo origen + + + Estéreo + + + **Este programa es software libre**. + + + Puede distribuirlo y modificarlo bajo los términos de la Licencia Pública General de GNU. + + + Este programa se distribuye con la esperanza de que le resulte útil, pero SIN NINGUNA GARANTÍA. Para más detalles, sírvase leer la Licencia Pública General de GNU (disponible en el directorio de instalación como "LICENSE.md"). + + + La aplicación está a punto de cerrarse. + + + La aplicación se cerrará automáticamente en {0} segundos. + + + La aplicación se cerrará automáticamente en 1 segundo. + + + Miscelánea + + + No pueden encontrarse el archivo o archivos destino. + + + El trabajo de conversión falló porque el archivo destino ya existe. + + + Preparar conversión + + + Debe tener instalado Microsoft Office para poder convertir documentos de Office. + + + Error al abrir el documento con Microsoft Office (compruebe que su licencia y su instalación son correctas). + + + Debe tener instalado Microsoft Excel para poder convertir documentos de Excel. + + + Debe tener instalado Microsoft PowerPoint para poder convertir documentos de PowerPoint. + + + Debe tener instalado Microsoft Word para poder convertir documentos de Word. + + + Abrir la web de File Converter + + + Error al iniciar el trabajo de conversión. + + \ No newline at end of file diff --git a/Application/FileConverter/Properties/Resources.fr.resx b/Application/FileConverter/Properties/Resources.fr-FR.resx similarity index 89% rename from Application/FileConverter/Properties/Resources.fr.resx rename to Application/FileConverter/Properties/Resources.fr-FR.resx index 6fc58d6..a171ec4 100644 --- a/Application/FileConverter/Properties/Resources.fr.resx +++ b/Application/FileConverter/Properties/Resources.fr-FR.resx @@ -122,13 +122,13 @@ Cette option vous permet de choisir ce que vous souhaitez faire du fichier d'origine après une conversion réussie - Allow you to chose what you want to do with your input files if the conversion succeed + Allow you to choose what you want to do with your input files if the conversion succeed Action après conversion réussie - Ajoute un nouveau preset (duplique le preset selectionné) + Ajoute un nouveau profil (duplique le profil selectionné) Application @@ -137,14 +137,14 @@ Audio - Vérifier automatiquement les mises à jour au démarage de File Converter + Vérifier automatiquement les mises à jour au démarrage de File Converter Automatically check for updates when File Converter starts - Terminer File Converter lorsque toutes les conversions ont réussies + Fermer File Converter après que toutes les conversions ont réussis - Ajuster à la taille en puissance de 2 la plus proche + Ajuster la taille à la puissance de 2 la plus proche Fermer @@ -161,7 +161,7 @@ Historique d'activité - + Historique d'activité @@ -174,7 +174,7 @@ N'oubliez pas de récompenser mon travail si vous l'apréciez :) - La mise à jour sera téléchargé en tache de fond et sera installé à la fermeture de File Converter. + La mise à jour sera téléchargée en tâche de fond et sera installée à la fermeture de File Converter. The update will be downloaded in background, and installed once you exit File Converter. @@ -195,7 +195,7 @@ That means it is integrated into the Windows explorer. - Pour utiliser File Converter, ouvrez l'explorateur et faites un clic droit sur le ou les fichier(s) que vous souhaitez convertir pour faire apparaitre le menu contextuel ou vous trouverez File Converter (visitez la documentation en ligne pour connaître la liste des extensions de fichiers compatibles). + Pour utiliser File Converter, ouvrez l'explorateur et faites un clic droit sur le ou les fichier(s) que vous souhaitez convertir pour faire apparaître le menu contextuel où vous trouverez File Converter (visitez la documentation en ligne pour connaître la liste des extensions de fichier compatibles). To use File Converter please open the explorer and right-click on any file you like to bring up the context menu where you will find File Converter commands (see the online documentation to see the list of compatible file formats). @@ -211,13 +211,13 @@ aide ? - Example de chemin d'origine + Exemple de chemin d'origine Formats compatibles - Supprimer + Supprimer l'original Déplacer dans un dossier d'archive @@ -226,7 +226,7 @@ Aucune - La mise à jour a été téléchargé. Quitte File Conveter et installe la mise à jour maintenant. + La mise à jour a été téléchargée. Quitte File Converter et installe la mise à jour maintenant. The update has been downloaded. Exit File Converter and install the update now. @@ -263,7 +263,7 @@ rotation de 180° - + C:\Musique\Artiste\Album\Chanson.wav @@ -280,13 +280,13 @@ (n:i): index du numéro de page (n:c): nombre total de pages -Chemin spéciaux: +Chemins spéciaux: (p:d): chemin vers mes documents (p:m): chemin vers ma musique (p:v): chemin vers mes vidéos (p:p): chemin vers mes images -utilisez maj pour une version en majuscules +utilisez MAJ pour une version en majuscules Format de destination @@ -300,11 +300,11 @@ utilisez maj pour une version en majuscules Qualité : - + Taux recommandés en bleu - Supprime le preset selectionné + Supprime le profil selectionné Rotation : @@ -313,7 +313,7 @@ utilisez maj pour une version en majuscules Enregistrer - Echelle : + Échelle : Voir les changements ... @@ -321,7 +321,7 @@ utilisez maj pour une version en majuscules Configuration de File Converter - + Configuration @@ -341,7 +341,7 @@ utilisez maj pour une version en majuscules Mise à jour de File Converter - Défini le rapport 'poid du fichier' contre 'qualité vidéo'. Une valeur basse donnera un fichier plus léger, une valeur haute une meilleur qualité vidéo. + Définit le rapport 'poids du fichier' contre 'qualité vidéo'. Une valeur basse donnera un fichier plus léger, une valeur haute une meilleure qualité vidéo. Define the ratio 'file size' versus 'video quality'. A lower value will give you a smaller file, a greater value give you a better video quality. @@ -363,7 +363,7 @@ utilisez maj pour une version en majuscules Super Rapide - Défini le ratio 'poid du fichier' contre 'temps de compression'. Une compression lente donnera un fichier plus léger (pour la même qualité vidéo) qu'une compression rapide. + Définit le ratio 'poids du fichier' contre 'temps de compression'. Une compression lente donnera un fichier plus léger (pour la même qualité vidéo) par rapport à une compression rapide. Define the ratio 'file size' versus 'compression duration'. A slow compression will give you a smaller file (for the same video quality) than a faster compression. @@ -433,7 +433,7 @@ utilisez maj pour une version en majuscules Vidéo - Temps d'attente avant l'arret de l'application + Temps d'attente avant l'arrêt de l'application Langue @@ -457,7 +457,7 @@ utilisez maj pour une version en majuscules L'exécutable ffmpeg n'a pas été trouvé. Vous pouvez essayer de réinstaller l'application pour corriger le problème. - Echec de l'extraction de la piste audio. + Échec de l'extraction de la piste audio. Le lecteur CD n'est pas prêt. @@ -536,7 +536,7 @@ utilisez maj pour une version en majuscules Autre - Les fichiers n'ont pas pu être converti. + Les fichiers n'ont pas pu être convertis. Des fichiers sont présents malgré l'echec de la conversion. @@ -562,4 +562,25 @@ utilisez maj pour une version en majuscules Ouvrir le site web de File Converter - \ No newline at end of file + + L'initialisation du processus de conversion a échoué. + + + Annuler + + + Mode avancé + + + Arguments personalisés + + + Arguments de ligne de commande FFMPEG personalisés + + + Erreur + + + Impossible de charger la configuration de File Converter. Voulez vous appliquer la configuration par défaut ? + + diff --git a/Application/FileConverter/Properties/Resources.fr.Designer.cs b/Application/FileConverter/Properties/Resources.fr.Designer.cs deleted file mode 100644 index e69de29..0000000 diff --git a/Application/FileConverter/Properties/Resources.hi-IN.resx b/Application/FileConverter/Properties/Resources.hi-IN.resx new file mode 100644 index 0000000..cfb5edd --- /dev/null +++ b/Application/FileConverter/Properties/Resources.hi-IN.resx @@ -0,0 +1,577 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + के बारे में + + + रूपांतरण सफल होने पर आपको अपनी इनपुट फ़ाइलों के साथ क्या करना है, यह चुनने की अनुमति दें + + + रूपांतरण सफल होने पर कार्रवाई + + + नया प्रीसेट + + + एप्लीकेशन + + + ऑडियो + + + फ़ाइल कनवर्टर शुरू होने पर स्वचालित रूप से अपडेट की जांच करें + + + सभी रूपांतरण समाप्त होने पर स्वचालित रूप से बाहर निकलें + + + 2 आकार की सबसे कम शक्ति के लिए दबाना + + + बंद करें + + + रूपांतरण प्रीसेट + + + कनवर्ट करने के लिए फ़ाइलें + + + से परिवर्तित + + + Logs + + + Logs + + + खुला दस्तावेज़ + + + दान + + + अगर आपको मेरा काम पसंद आया तो इनाम देना न भूलें :) + + + अपडेट को बैकग्राउंड में डाउनलोड किया जाएगा, और फाइल कन्वर्टर से बाहर निकलने के बाद इंस्टॉल किया जाएगा। + + + जब मैं फ़ाइल कनवर्टर से बाहर निकलूं तो इंस्टॉल करें + + + Encoding : + + + Encoding speed : + + + फाइल कन्वर्टर एक शेल एक्सटेंशन है। + + + इसका मतलब है कि यह विंडोज एक्सप्लोरर में एकीकृत है। + + + फ़ाइल का नाम टेम्पलेट + + + चित्र हर क्षण में : + + + GitHub प्रोजेक्ट पेज खोलें + + + मदद ? + + + इनपुट उदाहरण + + + इनपुट प्रारूप + + + मिटाए + + + एक संग्रह फ़ोल्डर में ले जाएँ + + + कुछ भी नहीं + + + अपडेट डाउनलोड कर लिया गया है। फ़ाइल कनवर्टर से बाहर निकलें और अभी अपडेट इंस्टॉल करें। + + + जब मैं फ़ाइल कनवर्टर से बाहर निकलूं तो इंस्टॉल करें + + + मामले की रिपोर्ट करें + + + चयनित प्रीसेट को नीचे ले जाएँ + + + चयनित प्रीसेट ऊपर ले जाएँ + + + लगातार बिटरेट एन्कोडिंग + + + परिवर्तनीय बिटरेट एन्कोडिंग + + + 90° + + + 90° वामावर्त रोटेशन + + + ठीक + + + 180° + + + 180° रोटेशन + + + C:\Music\Artist\Album\Song.wav + + + उत्पादन + + + (p): इनपुट फ़ाइल पथ +(f): इनपुट फ़ाइल नाम +(o): आउटपुट एक्सटेंशन प्रकार +(i): इनपुट एक्सटेंशन प्रकार +(d0): इनपुट पैरेंट फोल्डर +(d1): इनपुट उप मूल फ़ोल्डर +... +(n:i): पेज नंबर इंडेक्स +(n:c): कुल पृष्ठ संख्या + +विशेष पथ: +(p:d): मेरे दस्तावेज़ पथ +(p:m): मेरा संगीत पथ +(p:v): मेरे वीडियो पथ +(p:p): मेरे चित्र पथ + +अपरकेस संस्करण के लिए माज का प्रयोग करें + + + आउटपुट स्वरूप + + + प्रीसेट + + + प्रीसेट नाम + + + गुणवत्ता : + + + नीले रंग में अनुशंसित बिटरेट श्रेणी + + + मिटाए + + + घुमाएँ : + + + सहेजें + + + पैमाना : + + + परिवर्तन लॉग देखें ... + + + फ़ाइल कनवर्टर सेटिंग्स + + + समायोजन + + + 270° + + + 90° दक्षिणावर्त घुमाव + + + फ़ाइल कनवर्टर के लिए एक अद्यतन उपलब्ध है। यह दृढ़ता से अनुशंसा की जाती है कि आप इसे जल्द से जल्द स्थापित करें! + + + अपग्रेड डाउनलोड जारी है... + + + फ़ाइल कनवर्टर अपडेट + + + 'फ़ाइल आकार' बनाम 'वीडियो गुणवत्ता' के अनुपात को परिभाषित करें। कम मान आपको एक छोटी फ़ाइल देगा, अधिक मूल्य आपको बेहतर वीडियो गुणवत्ता देगा। + + + और तेज + + + तेज़ + + + मध्यम + + + और धीमा + + + धीमा + + + अत्यधिक तीव्र + + + 'फ़ाइल आकार' बनाम 'संपीड़न अवधि' के अनुपात को परिभाषित करें। एक धीमी गति से संपीड़न आपको तेज़ संपीड़न की तुलना में एक छोटी फ़ाइल (समान वीडियो गुणवत्ता के लिए) देगा। + + + अत्यंत तेजट + + + बहुत तेज + + + बहुत धीमा + + + वीडियो + + + PCM signed 16-bit little-endian + + + PCM signed 24-bit little-endian + + + PCM signed 32-bit little-endian + + + PCM signed 8-bit little-endian + + + None + + + कोई रोटेशन नहीं + + + परिवर्तन + + + पूर्ण + + + निष्कर्षण + + + असफल + + + क़तार में + + + इनपुट छवि पढ़ें + + + दस्तावेज़ पढ़ें + + + एनिमेटेड छवि + + + ऑडियो + + + दस्तावेज़ + + + छवि + + + वीडियो + + + आवेदन से बाहर निकलने से पहले प्रतीक्षा अवधि + + + भाषा + + + एक साथ रूपांतरणों की अधिकतम संख्या + + + नया प्रीसेट + + + ###परिवर्तन लॉग डाउनलोड कर रहा है ... + + + रूपांतरण अभिलेखागार + + + रद्द + + + Ffmpeg निष्पादन योग्य खोजने में विफल। आपको एप्लिकेशन को फिर से स्थापित करने का प्रयास करना चाहिए। + + + ऑडियो सीडी ट्रैक निष्कर्षण विफल + + + सीडी ड्राइव तैयार नहीं है। + + + Ffmpeg लॉन्च करने में विफल। + + + आउटपुट पथ फ़ोल्डर बनाने में विफल। + + + एक अद्वितीय आउटपुट फ़ाइल पथ उत्पन्न करने में विफल। + + + सीडी ड्राइव पढ़ने में विफल '{0}'. + + + इनपुट पथ ड्राइव अक्षर पुनर्प्राप्त करने में विफल। + + + सीडीए इनपुट पथ से ट्रैक नंबर प्राप्त करने में विफल। + + + सीडी ड्राइव का उपयोग करने में विफल क्योंकि इसे खोला गया है। + + + इनपुट फ़ाइल प्रकार चयनित आउटपुट फ़ाइल प्रकार के साथ संगत नहीं है। + + + आउटपुट फ़ाइल पथ टेम्पलेट द्वारा उत्पन्न अमान्य आउटपुट पथ। + + + असमर्थित आउटपुट स्वरूप '{0}'. + + + चैनल गिनती : + + + इनपुट फ़ाइल के चैनलों की संख्या बदलें। + + + मोनो + + + इनपुट फ़ाइल के समान + + + स्टीरियो + + + फ़ाइल कन्वर्टर का उपयोग करने के लिए कृपया एक्सप्लोरर खोलें और संदर्भ मेनू लाने के लिए किसी भी फ़ाइल पर राइट-क्लिक करें जहां आपको फ़ाइल कन्वर्टर कमांड मिलेंगे (संगत फ़ाइल स्वरूपों की सूची देखने के लिए ऑनलाइन दस्तावेज़ देखें)। + + + **यह प्रोग्राम फ्री सॉफ्टवेयर है**. + + + आप इसे GNU जनरल पब्लिक लाइसेंस की शर्तों के तहत पुनर्वितरित और/या संशोधित कर सकते हैं. + + + यह कार्यक्रम इस उम्मीद में वितरित किया जाता है कि यह उपयोगी होगा, लेकिन बिना किसी वारंटी के। अधिक विवरण के लिए जीएनयू जनरल पब्लिक लाइसेंस (स्थापना फ़ोल्डर में उपलब्ध: `LICENSE.md`) देखें। + + + आवेदन समाप्त हो रहा है। + + + एप्लिकेशन स्वचालित रूप से {0} सेकंड में समाप्त हो जाएगा। + + + आवेदन स्वचालित रूप से 1 सेकंड में समाप्त हो जाएगा। + + + विविध + + + आउटपुट फ़ाइल नहीं मिल रही है। + + + रूपांतरण कार्य विफल रहा लेकिन एक आउटपुट फ़ाइल मौजूद है जो मौजूद है। + + + रूपांतरण तैयार करें + + + Office दस्तावेज़ों को कनवर्ट करने के लिए Microsoft Office स्थापित होना चाहिए। + + + Microsoft Office के साथ दस्तावेज़ खोलने में विफल (जाँचें कि क्या आपका लाइसेंस/स्थापना मान्य है)। + + + Excel दस्तावेज़ों को कनवर्ट करने के लिए Microsoft Excel स्थापित होना चाहिए। + + + PowerPoint दस्तावेज़ों को कनवर्ट करने के लिए Microsoft PowerPoint स्थापित होना चाहिए। + + + Word दस्तावेज़ों को कनवर्ट करने के लिए Microsoft Word स्थापित होना चाहिए। + + + फ़ाइल कनवर्टर वेबसाइट खोलें + + + रूपांतरण कार्य प्रारंभ करने के दौरान त्रुटि। + + + निर्यात करना + + + आयात + + + डुप्लिकेट प्रीसेट + + + रद्द करना + + + उन्नत मोड + + + कस्टम तर्क + + + कस्टम FFMPEG कमांड लाइन तर्क + + + गलती + + + फ़ाइल कनवर्टर उपयोगकर्ता सेटिंग्स लोड नहीं कर सकता। क्या आप डिफ़ॉल्ट सेटिंग्स पर वापस आना चाहते हैं? + + diff --git a/Application/FileConverter/Properties/Resources.it-IT.resx b/Application/FileConverter/Properties/Resources.it-IT.resx new file mode 100644 index 0000000..e404ce2 --- /dev/null +++ b/Application/FileConverter/Properties/Resources.it-IT.resx @@ -0,0 +1,704 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Informazioni su + About + + + Permette di scegliere cosa vuoi fare con i tuoi file di input se la conversione ha successo + Allow you to choose what you want to do with your input files if the conversion succeed + + + Azione dopo la conversione + Action when conversion succeed + + + Aggiungi nuovo modello (duplica modello selezionato) + Add new preset (duplicate selected preset) + + + Applicazione + Application + + + Audio + Audio + + + Controlla automaticamente gli aggiornamenti all'avvio di File Converter + Automatically check for updates when File Converter starts + + + Esci automaticamente quando tutte le conversioni sono terminate + Automatically exit when all conversions finished + + + Aggancia alla potenza 2 volte più bassa + Clamp to lowest power of 2 size + + + Esci + Close + + + Modelli di conversione + Conversion Presets + + + File da convertire + Files to convert + + + Convertito da + Converted from + + + Log + Logs + + + Log + Logs + + + Apri documentazione + Open documentation + + + Dona + Donate + + + Non dimenticare di premiare il nostro lavoro se ti piace :) + Don't forget to reward my work if you like it :) + + + L'aggiornamento verrà scaricato in background e installato una volta uscito da File Converter. + The update will be downloaded in background, and installed once you exit File Converter. + + + Installa quando esco da File Converter + Install when I exit File Converter + + + Codifica : + Encoding : + + + Velocità di codifica : + Encoding speed : + + + File Converter è un'estensione della shell. + File Converter is a shell extension. + + + Ciò significa che è integrato in Windows Explorer. + That means it is integrated into the Windows explorer. + + + Per utilizzare File Converter, apri l'explorer e fai clic con il pulsante destro del mouse su qualsiasi file per visualizzare il menu di scelta rapida in cui troverai i comandi di File Converter (consulta il file readme per visualizzare l'elenco dei formati di file compatibili). + To use File Converter please open the explorer and right-click on any file you like to bring up the context menu where you will find File Converter commands (see the readme file to see the list of compatible file formats). + + + Template nome file + File name template + + + Fotogrammi per secondo : + Frames per second : + + + Apri la pagina del progetto su GitHub + Open GitHub project page + + + aiuto ? + help ? + + + Input di esempio + Input example + + + Formati di input + Input formats + + + Cancella + Delete + + + Sposta in una cartella di archivio + Move in an archive folder + + + Niente + None + + + L'aggiornamento è stato scaricato. Uscire da File Converter e installare l'aggiornamento ora. + The update has been downloaded. Exit File Converter and install the update now. + + + Installa quando esco da File Converter + Install when I exit File Converter + + + Segnala un problema + Report an issue + + + Sposta in basso il modello selezionato + Move down selected preset + + + Sposta in alto il modello selezionato + Move up selected preset + + + Codifica bitrate costante + Constant bitrate encoding + + + Codifica bitrate variabile + Variable bitrate encoding + + + 90° + 90° + + + Rotazione antioraria di 90° + 90° counter clockwise rotation + + + Ok + Ok + + + 180° + 180° + + + Rotazione di 180° + 180° rotation + + + C:\Musica\Artista\Album\Canzone.wav + C:\Music\Artist\Album\Song.wav + + + Output + Output + + + (p): percorso del file di input +(f): nome file di input +(o): tipo di estensione di output +(i): tipo di estensione di input +(d0): cartella superiore di input +(d1): cartella inferiore di input +... +(n:i): indice numero di pagina +(n:c): numero totale di pagine + +Percorsi speciali: +(p:d): Percorso documenti +(p:m): Percorso musica +(p:v): Percorso video +(p:p): Percorso immagini + +usa maj per il maiuscolo + (p): input file path +(f): input filename +(o): output extension type +(i): input extension type +(d0): input parent folder +(d1): input sub parent folder +... +(n:i): page number index +(n:c): total page count + +Special paths: +(p:d): my documents path +(p:m): my music path +(p:v): my videos path +(p:p): my pictures path + +use maj for uppercase version + + + Formato di output + Output format + + + Modello + Preset + + + Nome modello + Preset Name + + + Qualità : + Quality : + + + In blu l'intervallo di bitrate consigliato + Recommended bitrate range in blue + + + Rimuovi preset selezionato + Remove selected preset + + + Ruota : + Rotate : + + + Salva + Save + + + Scala : + Scale : + + + Guarda il registro delle modifiche... + See change log ... + + + Impostazioni + Settings + + + Impostazioni + Settings + + + 270° + 270° + + + Rotazione senso orario di 90° + 90° clockwise rotation + + + È disponibile un aggiornamento per File Converter. Si consiglia di installarlo il prima possibile! + An update for File Converter is available. It is strongly recommended that you install it as soon as possible! + + + Download aggiornamento in corso... + Upgrade download in progress... + + + Aggiornamenti File Converter + File Converter Updates + + + Definisci il rapporto "dimensione del file" rispetto a "qualità video". Un valore inferiore ti darà un file più piccolo, un valore maggiore ti darà una qualità video migliore. + Define the ratio 'file size' versus 'video quality'. A lower value will give you a smaller file, a greater value give you a better video quality. + + + Più veloce + Faster + + + Veloce + Fast + + + Media + Medium + + + Più lenta + Slower + + + Lenta + Slow + + + Super veloce + Super Fast + + + Definisci il rapporto "dimensione del file" rispetto a "durata della compressione". Una compressione lenta ti darà un file più piccolo (con la stessa qualità video) rispetto a una compressione più veloce. + Define the ratio 'file size' versus 'compression duration'. A slow compression will give you a smaller file (for the same video quality) than a faster compression. + + + Ultra veloce + Ultra Fast + + + Molto veloce + Very Fast + + + Molto lenta + Very Slow + + + Video + Video + + + PCM signed 16-bit little-endian + PCM signed 16-bit little-endian + + + PCM signed 24-bit little-endian + PCM signed 24-bit little-endian + + + PCM signed 32-bit little-endian + PCM signed 32-bit little-endian + + + PCM signed 8-bit little-endian + PCM signed 8-bit little-endian + + + Niente + None + + + Nessuna rotazione + No rotation + + + Conversione + Conversion + + + Fatto + Done + + + Estrazione + Extraction + + + Fallito + Failed + + + In coda + In queue + + + Leggi immagine di input + Read input image + + + Leggi documento + Read document + + + Immagine animata + Animated Image + + + Audio + Audio + + + Documento + Document + + + Immagine + Image + + + Video + Video + + + Tempo di attesa prima dell'uscita dall'applicazione + Waiting duration before application exit + + + Lingua + Language + + + Numero massimo di conversioni simultanee + Maximum number of simultaneous conversions + + + Nuovo modello + New preset + + + ###Download del registro delle modifiche ... + ###Downloading change log ... + + + Archivi di conversione + Conversion Archives + + + Cancellato. + Canceled. + + + Impossibile trovare l'eseguibile ffmpeg. Dovresti provare a reinstallare l'applicazione. + Fail to find ffmpeg executable. You should try to reinstall the application. + + + Estrazione della traccia audio del CD non riuscita. + Audio CD track extraction failed. + + + L'unità CD non è pronta. + CD drive is not ready. + + + Impossibile avviare ffmpeg. + Fail to launch ffmpeg. + + + Impossibile creare cartelle del percorso di output. + Fail to create output path folders. + + + Impossibile generare un percorso univoco dei file di output. + Fail to generate a unique output file path. + + + Impossibile leggere l'unità cd '{0}'. + Fail to read cd drive '{0}'. + + + Impossibile recuperare la lettera dell'unità del percorso di input. + Fail to retrieve input path drive letter. + + + Impossibile recuperare il numero di traccia dal percorso di input cda. + Fail to retrieve track number from the cda input path. + + + Impossibile utilizzare l'unità CD perché è aperta. + Fail to use the CD drive because it is oppened. + + + Il tipo di file di input non è compatibile con il tipo di file di output selezionato. + The input file type is not compatible with the selected output file type. + + + Percorso di output non valido generato dal modello. + Invalid output path generated by output file path template. + + + Formato di output non supportato '{0}'. + Unsupported output format '{0}'. + + + Numero di canali: + Channel count : + + + Cambia il numero di canali del file di input. + Change the number of channels of the input file. + + + Mono + Mono + + + Uguale al file di input + Same than input file + + + Stereo + Stereo + + + ** Questo programma è gratuito **. + **This program is free software**. + + + È possibile ridistribuirlo e / o modificarlo secondo i termini della GNU General Public License. + You can redistribute it and/or modify it under the terms of the GNU General Public License. + + + Questo programma è distribuito nella speranza che sia utile, ma SENZA ALCUNA GARANZIA. Vedi la GNU General Public License (disponibile nella cartella di installazione: `LICENSE.md`) per maggiori dettagli. + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. See the GNU General Public License (available in the installation folder: `LICENSE.md`) for more details. + + + L'applicazione si sta chiudendo. + The application is terminating. + + + L'applicazione si chiuderà automaticamente tra {0} secondi. + The application will automatically terminate in {0} seconds. + + + L'applicazione si chiuderà automaticamente tra 1 secondo. + The application will automatically terminate in 1 second. + + + Varie + Misc + + + Impossibile trovare il/i file di output. + Can't find the output file(s). + + + Il processo di conversione non è riuscito, ma esiste un file di output. + The conversion job failed but there is an output file that does exists. + + + Preparo la conversione + Prepare conversion + + + Per convertire i documenti Microsoft Office deve essere installato. + Microsoft Office must be installed in order to convert Office documents. + + + Impossibile aprire il documento con Microsoft Office (verificare se la propria licenza / installazione è valida). + Fail to open document with Microsoft Office (check if your licence/installation is valid). + + + Microsoft Excel deve essere installato per convertire i documenti Excel. + Microsoft Excel must be installed in order to convert Excel documents. + + + Microsoft PowerPoint deve essere installato per convertire i documenti PowerPoint. + Microsoft PowerPoint must be installed in order to convert PowerPoint documents. + + + Microsoft Word deve essere installato per convertire i documenti Word. + Microsoft Word must be installed in order to convert Word documents. + + + Apri il sito di File Converter + Open File Converter website + + + 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.resx b/Application/FileConverter/Properties/Resources.pt-BR.resx similarity index 84% rename from Application/FileConverter/Properties/Resources.pt.resx rename to Application/FileConverter/Properties/Resources.pt-BR.resx index f4348fd..8ac4866 100644 --- a/Application/FileConverter/Properties/Resources.pt.resx +++ b/Application/FileConverter/Properties/Resources.pt-BR.resx @@ -121,13 +121,13 @@ Sobre - Se a conversão for bem sucedida, o que pretende fazer com o ficheiro original? + Se a conversão for bem sucedida, o que pretende fazer com o arquivo original? - Ação a fazer aquando conversão bem sucedida + Ação a fazer quando a conversão for bem sucedida - Adicional nova predefinição (duplicar predefinição selecionada) + Adicionar nova predefinição (duplicar predefinição selecionada) Programa @@ -151,7 +151,7 @@ Predefinições de conversão - Ficheiros para converter + Arquivos para converter Convertidos de @@ -159,11 +159,11 @@ Logs - + Logs - Abrir documentação + Abrir a documentação Doar @@ -172,7 +172,7 @@ Não se esqueça de recompensar o meu trabalho se gostou :) - A atualização irá ser decarregada em background e instalada assim que fechar o File Converter. + A atualização será baixada em segundo plano e instalada assim que fechar o File Converter. instalar quando eu sair do File Converter @@ -187,13 +187,13 @@ O File Converter é uma extensão shell. - Isso quer dizer que está integrada no explorador de ficheiros. + Isso quer dizer que ele está integrado no Explorador de arquivos do Windows. - Para usar o File Converter abra o explorador de ficheiros e clique com o botão direito do rato em qualquer ficheiro que goste para mostrar o menu de contexto, onde encontrará os comandos do File Converter (veja o ficheiro readme para ver a lista de formatos de ficheiro compatíveis). + Para usar o File Converter abra o Explorador de arquivos do Windows e clique com o botão direito do mouse em qualquer arquivo para mostrar o menu de contexto, onde encontrará os comandos do File Converter (veja no arquivo readme do File-Converter a lista de formatos de arquivos compatíveis). - Nome do ficheiro de modelo + Nome do arquivo de modelo Quadros por segundo : @@ -214,7 +214,7 @@ Apagar - Mover-se para um ficheiro + Mover-se para um arquivo Nenhum @@ -223,7 +223,7 @@ A atualização foi transferida. Saia do File Converter e instale a atualização agora. - Instalar quando eu saia do File Converter + Instalar quando eu sair do File Converter Reportar um problema @@ -244,7 +244,7 @@ 90° - Rotacionar 90° sentido inverso aos ponteiros do relógio + Rotacionar 90° sentido inverso ao relógio Ok @@ -255,14 +255,14 @@ Rotacionar 180° - + C:\Música\Artista\Álbum\música.wav Destino - (P): caminho do ficheiro original + (P): caminho do arquivo original (F): nome do arquivo original (O): tipo de extensão de destino (I): tipo de extensão de entrada @@ -292,8 +292,8 @@ Use maj para a versão em maiúsculas Qualidade : - - O bitrate recomendado está representado a azul + + O bitrate recomendado está representado em azul Remover a predefinição selecionada @@ -302,7 +302,7 @@ Use maj para a versão em maiúsculas Rotacionar : - Guardar + Salvar Escala : @@ -311,16 +311,16 @@ Use maj para a versão em maiúsculas Ver log de alterações ... - Definições + Configurações - - Definições + + Configurações 270° - Rotacionar 90° na direção dos ponteiros do relógio + Rotacionar 90° na direção do relógio Uma atualização para o File Converter está disponível. É altamente recomendado instala-la assim que puder! @@ -332,7 +332,7 @@ Use maj para a versão em maiúsculas Atualizações do File Converter - Define a relação "tamanho x qualidade". Um valor mais baixo produz um ficheiro mais pequeno, um valor mais alto produz um ficheiro com mais qualidade. + Define a relação "tamanho x qualidade". Um valor mais baixo produz um arquivo menor, um valor mais alto produz um arquivo com mais qualidade. Mais rápido @@ -353,7 +353,7 @@ Use maj para a versão em maiúsculas Super rápido - Define a relação "tamanho x duração de compressão". Uma compressão lenta produz um ficheiro mais pequeno (pela mesma qualidade) do que uma compressão mais rapida. + Define a relação "tamanho x duração de compressão". Uma compressão lenta produz um arquivo menor (pela mesma qualidade) do que uma compressão mais rapida. Ultra rápido @@ -401,7 +401,7 @@ Use maj para a versão em maiúsculas Em espera - Ler a imagem de entradae + Ler a imagem de entrada Ler o documento @@ -434,7 +434,7 @@ Use maj para a versão em maiúsculas Nova predefinição - ###A transferir registo de alterações ... + ###Transferindo registro de alterações ... Arquivos de conversão @@ -452,31 +452,31 @@ Use maj para a versão em maiúsculas A unidade de CD não está pronta - Foi impossível abrir o ffmpeg. + Não foi possível abrir o ffmpeg. - Foi impossível criar as pastas no caminho de saída. + Não foi possível criar as pastas no caminho de saída. - Foi impossível criar um caminho único de saída. + Não foi possível criar um caminho único de saída. - Foi impossível ler a unidade de CD '{0}'. + Não foi possível ler a unidade de CD '{0}'. - Foi impossível conseguir a letra da unidade do ficheiro original. + Não foi possível conseguir a letra da unidade do arquivo original. - Foi impossível conseguir o número de faixa do caminho de entrada do CDA. + Não foi possível conseguir o número de faixa do caminho de entrada do CDA. - Foi impossível usar a unidade de CD porque não está aberta. + Não foi possível usar a unidade de CD porque não está aberta. - O ficheiro original é incompatível com o formato de ficheiro selecionado. + O arquivo original é incompatível com o formato de arquivo selecionado. - Caminho de saída inválido gerado pelo modelo de caminho do ficheiro de saída. + Caminho de saída inválido gerado pelo modelo de caminho do arquivo de saída. Formato de saída não suportado '{0}'. @@ -485,13 +485,13 @@ Use maj para a versão em maiúsculas Contagem de canais : - Mudar o número de canais do ficheiro original + Mudar o número de canais do arquivo original Mono - O mesmo que o ficheiro original + O mesmo que o arquivo original Stereo @@ -506,42 +506,45 @@ Use maj para a versão em maiúsculas Este programa é distribuído na esperança de que seja útil, mas SEM QUALQUER GARANTIA. Veja a GNU General Public License (disponível na pasta de instalação do programa: "LICENSE.md") para mais detalhes. - O programa está a terminar. + O programa está terminando. - O programa irá terminar automáticamente em {0} segundos. + O programa terminará automaticamente em {0} segundos. - O programa irá terminar automáticamente em 1 segundo. + O programa terminará automaticamente em 1 segundo. Variadoc - É impossivel encontrar o(s) ficheiro(s) de saída. + Não foi possivel encontrar o(s) arquivo(s) de saída. - A conversão falhou mas existem ficheiros presentes na localização. + A conversão falhou mas existem arquivos presentes na localização. Preparar conversão - O Microsoft Office deve estar instalado para sr possível converter documentos do Office. + O Microsoft Office deve estar instalado para que seja possível converter documentos do Office. - É impossível abrir o documento Microsoft Office (verifique se a sua licença/instalação é válida) + Não foi possível abrir o documento Microsoft Office (verifique se a sua licença/instalação é válida) - O Microsoft Excel tem de estar instalado para converter documentos Excel. + O Microsoft Excel tem que estar instalado para converter documentos do Excel. - O Microsoft PowerPoint tem de estar instalado para converter documentos PowerPoint. + O Microsoft PowerPoint tem que estar instalado para converter documentos do PowerPoint. - O Microsoft Word tem de estar instalado para converter documentos Word. + O Microsoft Word tem que estar instalado para converter documentos do Word. Abrir o site do File Converter + + Error during conversion job initialization. + \ No newline at end of file diff --git a/Application/FileConverter/Properties/Resources.pt-PT.resx b/Application/FileConverter/Properties/Resources.pt-PT.resx new file mode 100644 index 0000000..661e61f --- /dev/null +++ b/Application/FileConverter/Properties/Resources.pt-PT.resx @@ -0,0 +1,598 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Sobre + + + Se a conversão for bem sucedida, o que pretende fazer com o ficheiro original? + + + Ação a fazer aquando conversão bem sucedida + + + Adicional nova predefinição (duplicar predefinição selecionada) + + + Aplicação + + + Áudio + + + Verificar por atualizações automaticamente quando o File converter iniciar + + + Sair do programa automaticamente quando todas as conversões estiverem concluídas + + + Arredondar para a menor potência de 2 tamanhos + + + Fechar + + + Predefinições de conversão + + + Ficheiros a converter + + + Convertidos de + + + Registos + + + Registos + + + Abrir documentação + + + Doar + + + Não se esqueça de recompensar o meu trabalho se gostou dele :) + + + A atualização irá ser transferida em segundo plano e instalada assim que fechar o File Converter. + + + Instalar quando eu sair do File Converter + + + Codificação : + + + Velocidade de codificação : + + + O File Converter é uma extensão shell. + + + Isto significa que está integrado no explorador de ficheiros do Windows. + + + Para usar o File Converter abra o explorador de ficheiros e clique com o botão direito do rato em qualquer ficheiro que goste para mostrar o menu de contexto, onde encontrará os comandos do File Converter (veja o ficheiro readme para ver a lista de formatos de ficheiro compatíveis). + + + Nome do ficheiro de modelo + + + Quadros por segundo : + + + Abrir a página do projeto no GitHub + + + Ajuda ? + + + Exemplo de origem + + + Formatos de origem + + + Eliminar + + + Mover para uma pasta de arquivo + + + Nenhum + + + A atualização foi transferida. Sair do File Converter e instalar a atualização agora. + + + Instalar quando eu sair do File Converter + + + Reportar um problema + + + Mover a predefinição selecionada para baixo + + + Mover a predefinição selecionada para cima + + + Codificação de taxa de bits constante + + + Codificação de taxa de bits variável + + + 90° + + + Rodar 90° no sentido contrário aos ponteiros do relógio + + + Ok + + + 180° + + + Rodar 180° + + + C:\Música\Artista\Álbum\Música.wav + + + Destino + + + (p): caminho do ficheiro original +(f): nome do ficheiro original +(o): tipo de extensão de saída +(i): tipo de extensão de entrada +(d0): pasta principal de entrada +(d1): pasta principal secundária de entrada +... +(n:i): índice de número de página +(n:c): contagem total de páginas + +Caminhos especiais: +(p:d): localização para documentos +(p:m): localização para música +(p:v): localização para vídeos +(p:p): localização para imagens + +Use maj para a versão em maiúsculas + + + Formato de saída + + + Predefinição + + + Nome da predefinição + + + Qualidade : + + + A taxa de bits recomendada está representada a azul + + + Remover a predefinição selecionada + + + Rodar : + + + Guardar + + + Escala : + + + Ver registo de alterações ... + + + Definições + + + Definições + + + 270° + + + Rodar 90° no sentido dos ponteiros do relógio + + + Uma atualização para o File Converter está disponível. É altamente recomendado instalá-la assim que possível! + + + Transferência da atualização em curso... + + + Atualizações do File Converter + + + Define o rácio 'tamanho do ficheiro' versus 'qualidade do vídeo'. Um valor mais baixo dá-lhe um ficheiro mais pequeno, um valor mais alto dá-lhe uma melhor qualidade de vídeo. + + + Mais rápida + + + Rápida + + + Média + + + Mais lenta + + + Lenta + + + Super rápida + + + Define o rácio 'tamanho do ficheiro' versus 'duração da compressão'. Uma compressão lenta dá-lhe um ficheiro mais pequeno (para a mesma qualidade de vídeo) do que uma compressão mais rápida. + + + Ultra rápida + + + Muito rápida + + + Muito lenta + + + Vídeo + + + PCM signed 16-bit little-endian + + + PCM signed 24-bit little-endian + + + PCM signed 32-bit little-endian + + + PCM signed 8-bit little-endian + + + Não + + + Sem rotação + + + Conversão + + + Concluída + + + Extração + + + Ocorreu um erro + + + Em espera + + + Ler a imagem de entrada + + + Ler o documento + + + Imagem animada + + + Áudio + + + Documento + + + Imagem + + + Vídeo + + + Duração da espera antes da aplicação fechar + + + Idioma + + + Número máximo de conversões simultâneas + + + Nova predefinição + + + ###A transferir registo de alterações ... + + + Arquivos de conversão + + + Cancelado. + + + Ocorreu um erro ao localizar o executável ffmpeg. Deve tentar reinstalar a aplicação. + + + Ocrreu um erro ao extrair faixa de CD áudio. + + + A unidade de CD não está pronta. + + + Ocrreu um erro ao iniciar o ffmpeg. + + + Ocrreu um erro ao criar as pastas na localização de saída. + + + Ocrreu um erro ao gerar uma localização única do ficheiro de saída. + + + Ocrreu um erro ao ler a unidade de CD '{0}'. + + + Ocrreu um erro ao obter a letra da unidade do ficheiro original. + + + Ocrreu um erro ao obter o número de faixa da localização de entrada do cda. + + + Ocrreu um erro ao utilizar a unidade de CD porque não está aberta. + + + O ficheiro original é incompatível com o formato de ficheiro selecionado. + + + Localização de saída inválida gerada pelo modelo de localização do ficheiro de saída. + + + Formato de saída não suportado '{0}'. + + + Contagem de canais : + + + Mudar o número de canais do ficheiro original + + + Mono + + + O mesmo que o ficheiro original + + + Estéreo + + + **Este programa é gratuito**. + + + Pode redistribuí-lo e/ou modificá-lo sob os termos da GNU General Public License. + + + Este programa é distribuído na esperança de que seja útil, mas SEM QUALQUER GARANTIA. Veja a GNU General Public License (disponível na pasta de instalação do programa: "LICENSE.md") para mais detalhes. + + + A aplicação está a terminar. + + + A aplicação irá terminar automaticamente dentro de {0} segundos. + + + A aplicação irá terminar automaticamente dentro de 1 segundo. + + + Diversos + + + Não foi possivel localizar o(s) ficheiro(s) de saída. + + + Ocorreu um erro na tarefa de conversão mas existe um ficheiro presente na localização de saída. + + + Preparar conversão + + + O Microsoft Office deve estar instalado para ser possível converter documentos do Office. + + + Ocorreu um erro ao abrir o documento Microsoft Office (verifique se a sua licença/instalação é válida) + + + O Microsoft Excel tem de estar instalado para converter documentos Excel. + + + O Microsoft PowerPoint tem de estar instalado para converter documentos PowerPoint. + + + O Microsoft Word tem de estar instalado para converter documentos Word. + + + Abrir o website do File Converter + + + Obrigado! + + + Ocorreu um erro durante a inicialização da tarefa de conversão. + + + Nova pasta + + + Nova pasta + + + Pasta + + + Nome da pasta + + + Modo avançado + + + Argumentos personalizados + + + Argumentos personalizados da linha de comandos do FFMPEG + + + Nenhuma predefinição selecionada + + + Exportar + + + Importar + + + Predefinição duplicada + + + Cancelar + + + Erro + + + Não foi possível carregar as definições do utilizador do conversor de ficheiros. Pretende voltar às predefinições ? + + + Copiar ficheiros para a área de transferência após a conversão + + \ No newline at end of file diff --git a/Application/FileConverter/Properties/Resources.resx b/Application/FileConverter/Properties/Resources.resx index 51639a6..32ef5a5 100644 --- a/Application/FileConverter/Properties/Resources.resx +++ b/Application/FileConverter/Properties/Resources.resx @@ -121,13 +121,13 @@ About - Allow you to chose what you want to do with your input files if the conversion succeed + Allow you to choose what you want to do with your input files if the conversion succeed Action when conversion succeed - Add new preset (duplicate selected preset) + New preset Application @@ -159,7 +159,7 @@ Logs - + Logs @@ -255,7 +255,7 @@ 180° rotation - + C:\Music\Artist\Album\Song.wav @@ -292,11 +292,11 @@ use maj for uppercase version Quality : - + Recommended bitrate range in blue - Remove selected preset + Delete Rotate : @@ -313,7 +313,7 @@ use maj for uppercase version Settings - + Settings @@ -544,4 +544,52 @@ use maj for uppercase version Open File Converter website + + Error during conversion job initialization. + + + New folder + + + New folder + + + Folder + + + Folder Name + + + Advanced mode + + + Custom Arguments + + + Custom FFMPEG command line arguments + + + No preset selected + + + Export + + + Import + + + Duplicate preset + + + Cancel + + + Error + + + Can't load file converter user settings. Do you want to fall back to default settings ? + + + Copy files in clipboard after conversion + \ No newline at end of file diff --git a/Application/FileConverter/Properties/Resources.tr-TR.resx b/Application/FileConverter/Properties/Resources.tr-TR.resx new file mode 100644 index 0000000..584f0f2 --- /dev/null +++ b/Application/FileConverter/Properties/Resources.tr-TR.resx @@ -0,0 +1,592 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Hakkında + + + Dönüşüm başarılı olursa, giriş dosyasıyla ne yapmak istediğinize karar verir + + + Dönüşüm işlemi başarılı olduğunda yapılacak işlem + + + Yeni ön ayar + + + Uygulama + + + Ses + + + File Converter başladığında otomatik olarak güncellemeleri denetle + + + Tüm dönüşümler bittiğinde otomatik olarak çıkış yap + + + 2 boyutun en düşük kuvvetine sıkıştır (?) + + + Kapat + + + Dönüşüm Ön Ayarları + + + Dönüştürülecek dosyalar + + + 'den/'dan dönüştürüldü + + + kayıtlar + + + kayıtlar + + + Açık Belgeler + + + Bağış yap + + + Eğer beğendiysen işimde bana yardımcı olmayı unutma :) + + + Güncelleme arkaplanda iniyor olacak, ve File Converter'dan çıktığınızda kurulacak. + + + File Converter'dan çıktığımda kur + + + Şifreleniyor : + + + Şifreleme hızı : + + + File Converter bir kabuk uzantısıdır. + + + Bu, Windows gezgini ile birleşik çalıştığı anlamına geliyor. + + + File converter'ı kullanmak için lütfen dosya gezginini açın ve File Converter komutlarını bulacağınız bağlam menüsüne ulaşmak için istediğiniz herhangi bir dosyaya sağ tıklayın (tüm uyumlu dosya türleri için readme dosyasına bakın). + + + Dosya ismi şablonu + + + Saniyedeki kare sayısı : + + + GitHub proje sayfasını aç + + + yardım ? + + + Giriş örneği + + + Giriş türleri + + + Sil + + + Bir arşiv klasörüne taşı + + + Hiçbiri + + + Güncelleme indirildi. File Converter'dan çıkın ve şimdi kurun. + + + Ben File Converter'dan çıktığımda kur + + + Bir problem raporla + + + Seçilen ön ayarı aşağı kaydır + + + Seçilen ön ayarı yukarı kaydır + + + Sabit bithızı şifreleme + + + Değişken bithızı şifreleme + + + 90° + + + 90° saat yönünün tersi dönme + + + Tamam + + + 180° + + + 180° dönme + + + C:\Müzil\Sanatçı\Albüm\şarkı.wav + + + Çıktı + + + (p): giriş dosyası yolu +(f): giriş dosyası ismi +(o): çıktı dosyası türü +(i): girdi dosyası türü +(d0): girdi üst klasörü +(d1): input sub parent folder +... +(n:i): sayfa sayısı indeksi +(n:c): toplam sayfa sayısı + +Özel yollar: +(p:d): belgeler yolu +(p:m): müzikler yolu +(p:v): videolar yolu +(p:p): resimler yolu + + + + + Çıktı türü + + + Ön ayar + + + Ön ayar adı + + + Kalite : + + + Önerilen bithızı değeri mavi aralığında + + + Sil + + + Döndür : + + + Kaydet + + + Ölçek : + + + Kayıtlara bakın ... + + + Ayarlar + + + Ayarlar + + + 270° + + + 90° saat yönünün tersine dönme + + + File Converter için bir güncelleme mevcut. Mümkün olan en yakın zamanda kurmanız şiddetle tavsiye edilir! + + + Yükseltme indiriliyor... + + + File Converter Güncellemeleri + + + 'dosya boyutu' ve 'video kalitesi' arasındaki oranı tanımla. Düşük bir değer daha küçük dosya boyutu demek, Yüksek bir değer daha kaliteli video demek. + + + Daha hızlı + + + Hızlı + + + Orta + + + Daha yavaş + + + Yavaş + + + Çok hızlı + + + 'dosya boyutu' ve 'sıkıştırma süreci' arasındaki oranı tanımla. Yavaş bir sıkıştırma, daha hızlı sıkıştırmaya göre daha küçük bir dosya anlamına geliyor. (Aynı video kalitesi için geçerli) + + + Aşırı hızlı + + + Epey hızlı + + + Epey yavaş + + + Video + + + PCM imzalı 16-bit little-endian + + + PCM imzalı 24-bit little-endian + + + PCM imzalı 32-bit little-endian + + + PCM imzalı 8-bit little-endian + + + Hiç + + + Dönme yok + + + Dönüşüm + + + Bitti + + + Çıkartma + + + Başarısız + + + Sırada + + + Giriş görüntüsünü oku + + + Dökümanı oku + + + Canlı görüntü + + + Ses + + + Döküman + + + Görüntü + + + Video + + + Uygulamadan çıkılmadan önceki bekleme süresi + + + Dil + + + Azami eş zamanlı çevirme sayısı + + + Yeni ön ayar + + + ###Değişim kaydı indiriliyor ... + + + Dönüşüm Arşivleri + + + İptal edildi. + + + Çalıştırılabilir ffmpeg bulunamadı. Uygulamayı yeniden kurmayı deneyin. + + + Ses CD çıkarma işlemi başarısız. + + + CD sürücü hazır değil. + + + ffmpeg başlatılamadı. + + + Çıktı yolu klasörü oluşturması başarısız. + + + Özgün çıktı yolu klasörü oluşturması başarısız. + + + cd sürücü okuma başarısız '{0}'. + + + Giriş yolu sürücü harfi alınamadı. + + + cda giriş yolundan parça numarası alınamadı. + + + CD sürücüsü açık olduğu için kullanılamıyor.. + + + Giriş dosya türü seçilen çıktı dosya türü ile uyumlu değil. + + + Çıktı dosyası yolu şablonu tarafından oluşturulan geçersiz çıktı yolu. + + + Desteklenmeyen çıktı dosyası türü '{0}'. + + + Kanal sayısı : + + + Giriş dosyasının kanal sayısını değiştirin. + + + Mono + + + Giriş dosyası ile aynı + + + Stereo + + + **Bu ücretsiz bir yazılımdır**. + + + GNU Genel Kamu Lisansı koşulları altında yeniden dağıtabilir ve/veya değiştirebilirsiniz. + + + Bu program, yararlı olacağı ümidiyle dağıtılmıştır, ancak HİÇBİR GARANTİSİ YOKTUR. Daha fazla ayrıntı için GNU Genel Kamu Lisansına (kurulum klasöründe bulunur: `LICENSE.md`) bakın. + + + Uygulama sonlandırılıyor. + + + Uygulama {0} saniye içinde otomatik olarak sonlandırılacak. + + + Uygulama 1 saniye içinde otomatik olarak sonlandırılacaktır. + + + Diğer + + + Çıktı dosyası/dosyaları bulunamıyor. + + + Dönüştürme başarısız oldu, ancak var olan bir çıktı dosyası var. + + + Dönüştürmeyi hazırla + + + Office belgelerini dönüştürmek için Microsoft Office yüklü olmalıdır. + + + Belge Microsoft Office ile açılamadı (lisansınızın/kurulumunuzun geçerli olup olmadığını kontrol edin). + + + Excel belgelerini dönüştürmek için Microsoft Excel'in kurulu olması gerekir. + + + PowerPoint belgelerini dönüştürmek için Microsoft PowerPoint yüklü olmalıdır. + + + Word belgelerini dönüştürmek için Microsoft Word yüklü olmalıdır. + + + File Converter internet sitesini aç + + + Dönüştürme başlatma sırasında hata meydana geldi. + + + Yeni klasör + + + Yeni klasör + + + Klasör + + + Klasör ismi + + + Gelişmiş mod + + + Özel parametreler + + + Özel FFMPEG komut satırı parametreleri + + + Hiçbir ön ayar seçilmedi + + + Dışa aktar + + + İçeri aktar + + + Ön ayarı kopyala + + + İptal + + + Hata + + + Dosya dönüştürücü kullanıcı ayarları yüklenemiyor. Varsayılan ayarlara geri dönmek istiyor musunuz? + + \ No newline at end of file diff --git a/Application/FileConverter/Properties/Resources.zh-CN.resx b/Application/FileConverter/Properties/Resources.zh-CN.resx new file mode 100644 index 0000000..12fd057 --- /dev/null +++ b/Application/FileConverter/Properties/Resources.zh-CN.resx @@ -0,0 +1,592 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 关于 + + + 指定转换成功后对文件的操作 + + + 转换成功时的操作 + + + 新的预设 + + + 应用 + + + 音频 + + + File Converter 启动时自动检查更新 + + + 所有转换完成后自动退出 + + + Clamp to lowest power of 2 size + + + 关闭 + + + 转换设置 + + + 要转换的文件 + + + 转换自 + + + 日志 + + + 日志 + + + 打开文件 + + + 捐赠 + + + 如果你喜欢,别忘了鼓励我的工作^_^ + + + 此更新将在后台下载,并在 File Converter 退出后立即开始安装。 + + + 当我退出 File Converter 时安装 + + + 正在编码: + + + 编码速度: + + + File Converter 是一个 Shell 扩展。 + + + 这意味着它被集成在 Windows 资源管理器中。 + + + 要使用 File Converter,请打开资源管理器并右击任意文件显示上下文菜单,您可以找到 File Converter 的一些命令(请查阅 readme 文件中列出的可兼容的文件格式)。 + + + 文件名模板 + + + 每秒帧数: + + + 打开 GitHub 项目页面 + + + 帮助? + + + 输入示例 + + + 输入格式 + + + 删除 + + + 移动到压缩包中 + + + 无 + + + 更新下载完成。现在可退出 File Converter 并安装更新。 + + + 当我退出 File Converter 时安装 + + + 报告问题 + + + 将所选项下移 + + + 将所选项上移 + + + 恒定比特率编码 + + + 可变比特率编码 + + + 90° + + + 逆时针旋转 90° + + + Ok + + + 180° + + + 旋转 180° + + + C:\Music\Artist\Album\Song.wav + + + 输出 + + + (p): 输入文件路径 +(f): 输入文件名 +(o): 输出扩展名 +(i): 输入扩展名 +(d0): 输入父级文件夹 +(d1): 输入次父级文件夹 +... +(n:i): 页码索引 +(n:c): 总页数 + +特殊路径: +(p:d): 文档 +(p:m): 音乐 +(p:v): 视频 +(p:p): 图片 + +使用 maj 表示大写 + + + 输出格式 + + + 预设 + + + 预设名称 + + + 质量: + + + 建议蓝光比特率范围 + + + 删除 + + + 旋转: + + + 保存 + + + 范围: + + + 请参阅更改日志…… + + + 设置 + + + 设置 + + + 270° + + + 顺时针旋转 90° + + + File Converter 有可用更新。墙裂建议您尽快安装最新版本! + + + 正在下载升级包…… + + + File Converter 更新 + + + 定义“文件大小”与“视频质量”的比重。较小的比重可以让您的文件占用更小,较大的比重可以让您的视频质量更高。 + + + 更快 + + + 快 + + + 中等 + + + 更慢 + + + 慢 + + + 超快 + + + 定义“文件大小”与“压缩时间”的比重。对于相同的视频质量,与快速压缩相比,慢速压缩将为您提供更小的文件。 + + + 超快速 + + + 极快速 + + + 极慢速 + + + 视频 + + + 带符号的16位低位编址 PCM + + + 带符号的24位低位编址 PCM + + + 带符号的32位低位编址 PCM + + + 带符号的8位低位编址 PCM + + + 无 + + + 不旋转 + + + 转换 + + + 完成 + + + 提取 + + + 失败 + + + 在队列中 + + + 读取输入的图像 + + + 读取文档 + + + 动态图像 + + + 音频 + + + 文档 + + + 图像 + + + 视频 + + + 应用退出前的等待时间 + + + 语言 + + + 同时转换的最大数量 + + + 新预设 + + + ###正在下载更新日志…… + + + 转换压缩包 + + + 取消。 + + + 找不到 ffmpeg 可执行文件,您应该尝试重新安装应用程序。 + + + 音频CD轨道提取失败。 + + + CD 驱动器未准备好。 + + + 启动 ffmpeg 失败。 + + + 创建输出路径文件夹失败。 + + + 无法生成唯一的输出文件路径。 + + + 无法读取CD驱动器'{0}'. + + + 无法检索到输入路径的驱动器号。 + + + 无法中cda输入路径检索轨道编号。 + + + 无法使用 CD 驱动器,因为它已被打开。 + + + 输入文件的类型与所选择的输出文件类型不兼容。 + + + 输出文件路径模板生成的输出路径无效。 + + + 不支持的输出格式'{0}'。 + + + 通道计数: + + + 修改输入文件的通道数量。 + + + 单声道 + + + 与输入文件相同 + + + 立体声 + + + **该软件免费**. + + + 您可以根据GNU通用公共许可证的条款重新发布和(或)修改它。 + + + 本程序的发布是希望它有用,但不提供任何担保。有关更多详细信息,请参阅GNU通用公共许可证(可在安装文件夹中找到:License.md)。 + + + 应用程序正在关闭。The application is terminating. + + + 应用程序将在 {0} 秒后自动关闭。 + + + 应用程序将在 1 秒内自动关闭。 + + + 杂项 + + + 无法找到输出文件。 + + + 转换失败,但输出文件确实存在。 + + + 准备转换 + + + 要转换 Office 文档,必须安装 Microsoft Office。 + + + 使用 Microsoft Office 打开文档失败(检查您的许可证/安装是否有效)。 + + + 要转换 Excel 文档,必须安装 Microsoft Excel。 + + + 要转换 PowerPoint 文档,必须安装 Microsoft PowerPoint。 + + + 要转换 Word 文档,必须安装 Microsoft Word。 + + + 打开 File Converter 网址 + + + 转换任务初始化时出错。 + + + 新文件夹 + + + 新文件夹 + + + 文件夹 + + + 文件夹名称 + + + 高级模式 + + + 自定义参数 + + + 自定义 FFMPEG 命令行参数 + + + 未选择预设 + + + 导出 + + + 导入 + + + 复制预设 + + + 取消 + + + 错误 + + + 无法加载 File Converter 用户设置。您想恢复默认设置吗? + + diff --git a/Application/FileConverter/Properties/Resources.zh-TW.resx b/Application/FileConverter/Properties/Resources.zh-TW.resx new file mode 100644 index 0000000..cbff6d0 --- /dev/null +++ b/Application/FileConverter/Properties/Resources.zh-TW.resx @@ -0,0 +1,595 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 關於 + + + 指定轉換成功後對檔案的操作 + + + 轉換成功時的操作 + + + 新的預設 + + + 應用程式 + + + 音訊 + + + 當File Converter啟動時自動檢查更新 + + + 所有轉換完成後自動關閉 + + + 限制為最接近的2的次方大小 + + + 關閉 + + + 轉換預設 + + + 要轉換的文件 + + + 轉換自 + + + 日誌 + + + 日誌 + + + 開啟文件 + + + 贊助 + + + 如果您喜歡我的作品,別忘了給予一些獎勵:) + + + 此更新將在背景下載,並在 File Converter 退出後立即安裝。 + + + 當我退出 File Converter 時安裝 + + + 編碼中: + + + 編碼速度: + + + File Converter是一個Shell擴充功能。 + + + 這表示它已整合到Windows檔案總管中。 + + + 要使用File Converter,請開啟資檔案總管並右鍵點選任何檔案以顯示選單,您可以找到File Converter的一些命令(請參閱線上文件以查看可相容的檔案格式)。 + + + 檔案名稱模板 + + + 每秒影格數: + + + 開啟GitHub專案頁面 + + + 幫助 + + + 輸入範例 + + + 輸入格式 + + + 刪除 + + + 移到壓縮檔中 + + + 無 + + + 更新下載完成。現在可退出File Converter並安裝更新。 + + + 退出File Converter時安裝 + + + 問題回報 + + + 下移所選預設 + + + 上移所選預設 + + + 固定位元速率編碼 + + + 可變位元速率編碼 + + + 90° + + + 逆時針旋轉90° + + + Ok + + + 180° + + + 旋轉180° + + + C:\Music\Artist\Album\Song.wav + + + 輸出 + + + (p): 輸入檔案路徑 +(f): 輸入檔案名稱 +(o): 輸出檔案格式 +(i): 輸入檔案格式 +(d0): 輸入上層資料夾名稱 +(d1): 輸入資料夾名稱 +... +(n:i): 頁數 +(n:c): 總頁數 + +特殊路徑: +(p:d): 文件 +(p:m): 音樂 +(p:v): 影片 +(p:p): 圖片 + +使用 maj 表示大寫 + + + 輸出格式 + + + 預設 + + + 預設名稱 + + + 品質: + + + 建議的藍色位元速率範圍 + + + 刪除 + + + 旋轉: + + + 儲存 + + + 範圍: + + + 請參閱變更日誌…… + + + 設定 + + + 設定 + + + 270° + + + 順時針旋轉90° + + + File Converter有更新。 強烈建議您盡快安裝新版本! + + + 升級下載正在進行中…… + + + File Converter更新 + + + 定義「檔案大小」與「視訊品質」的比率。 較小的值可以讓您的檔案更小,較大的值可以讓您的影片品質更高。 + + + 更快 + + + 快 + + + 中等 + + + 稍慢 + + + 慢 + + + 超快 + + + 定義「檔案大小」與「壓縮時間」的比種。 對於相同的影片品質,與快速壓縮相比,慢速壓縮將為您提供更小的文件。 + + + 超快速 + + + 極快速 + + + 極慢速 + + + 影片 + + + PCM-有符號的16位小端序 + + + PCM-有符號的24位小端序 + + + PCM-有符號的32位小端序 + + + PCM-有符號的8位小端序 + + + 無 + + + 不旋轉 + + + 轉換 + + + 完成 + + + 提取 + + + 失敗 + + + 在佇列中 + + + 讀取輸入影像 + + + 讀取文件 + + + 動態圖片 + + + 音訊 + + + 文件 + + + 圖片 + + + 影片 + + + 應用程式退出前的等待時間 + + + 語言 + + + 同時轉換的最大數量 + + + 新預設 + + + ###正在下载更新日誌…… + + + 轉換壓縮檔 + + + 取消。 + + + 找不到ffmpeg執行檔。 您應該嘗試重新安裝該應用程式。 + + + 音訊CD軌道提取失敗。 + + + CD光碟機未準備好。 + + + 啟動ffmpeg失敗。 + + + 無法建立輸出路徑資料夾。 + + + 無法產生唯一的輸出檔案路徑。 + + + 無法讀取CD'{0}'. + + + 無法檢索輸入路徑磁碟機號。 + + + 無法從 cda 輸入路徑檢索軌道編號。 + + + CD光碟機已開啟,無法使用。 + + + 輸入檔案格式與所選輸出檔案格式不相容。 + + + 輸出檔案路徑範例產生的輸出路徑無效。 + + + 不支援的輸出格式'{0}'。 + + + 聲道數量: + + + 更改輸入檔的聲道數量。 + + + 單聲道 + + + 與輸入檔案相同 + + + 立體聲 + + + **此軟體免費**. + + + 您可以根據 GNU 通用公共授權的條款重新分發和(或)修改它。 + + + 分發此程序是希望它有幫助,但不提供任何保證。 有關更多詳細資訊,請參閱GNU通用公共許可證(可在安裝資料夾中找到:LICENSE.md)。 + + + 應用程式正在關閉。. + + + >應用程式將在 {0} 秒後自動關閉。 + + + 應用程式將在1秒後自動關閉。 + + + 雜項 + + + 無法找到輸出檔案。 + + + 轉換作業失敗,但輸出檔案確實存在。 + + + 準備轉換 + + + 要轉換Office文件,必須安裝Microsoft Office。 + + + 使用Microsoft Office開啟文件失敗(檢查您的授權/安裝是否有效)。 + + + 要轉換Excel文件,必須安裝Microsoft Excel。 + + + 要轉換PowerPoint文件,必須安裝Microsoft PowerPoint。 + + + 要轉換Word文件,必須安裝Microsoft Word。 + + + 打開File Converter網站 + + + 感謝! + + + 轉換作業初始化期間出錯。 + + + 新建資料夾 + + + 新建資料夾 + + + 資料夾 + + + 資料夾名稱 + + + 高級模式 + + + 自訂參數 + + + 自訂FFMPEG命令列參數 + + + 未選擇預設 + + + 輸出 + + + 輸入 + + + 複製預設 + + + 取消 + + + 錯誤 + + + 無法載入File Converter使用者設定。 您想恢復到預設設定嗎? + + diff --git a/Application/FileConverter/Properties/Settings.Designer.cs b/Application/FileConverter/Properties/Settings.Designer.cs index 285c711..7b4da8c 100644 --- a/Application/FileConverter/Properties/Settings.Designer.cs +++ b/Application/FileConverter/Properties/Settings.Designer.cs @@ -1,28 +1,24 @@ //------------------------------------------------------------------------------ // // This code was generated by a tool. -// Runtime Version:4.0.30319.18444 +// Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ -namespace FileConverter.Properties -{ - - +namespace FileConverter.Properties { + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] - internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase - { - + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.7.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); - - public static Settings Default - { - get - { + + public static Settings Default { + get { return defaultInstance; } } diff --git a/Application/FileConverter/Registry.cs b/Application/FileConverter/Registry.cs index 85d4a64..477248c 100644 --- a/Application/FileConverter/Registry.cs +++ b/Application/FileConverter/Registry.cs @@ -80,14 +80,23 @@ namespace FileConverter } } - public static T GetValue(string key) + private static string GetUserRegistryFilePath + { + get + { + string path = FileConverterExtension.PathHelpers.GetUserDataFolderPath; + path = Path.Combine(path, "Registry.xml"); + return path; + } + } + + public static T GetValue(string key, T defaultValue = default(T)) { Registry registry = Registry.Instance; - string stringValue; - if (!registry.registryEntries.TryGetValue(key, out stringValue)) + if (!registry.registryEntries.TryGetValue(key, out string stringValue)) { - return default(T); + return defaultValue; } try @@ -100,7 +109,7 @@ namespace FileConverter Diagnostics.Debug.LogError("Can't convert registry value: {0}.", exception.Message); } - return default(T); + return defaultValue; } public static void SetValue(string key, T value) @@ -126,7 +135,7 @@ namespace FileConverter public void Dispose() { // SAVE - string registryFilePath = Registry.GetUserRegistryFilePath(); + string registryFilePath = Registry.GetUserRegistryFilePath; try { @@ -140,7 +149,7 @@ namespace FileConverter private static void Load() { - string registryFilePath = Registry.GetUserRegistryFilePath(); + string registryFilePath = Registry.GetUserRegistryFilePath; if (!File.Exists(registryFilePath)) { Registry.instance = new Registry(); @@ -164,13 +173,6 @@ namespace FileConverter } } - private static string GetUserRegistryFilePath() - { - string path = PathHelpers.GetUserDataFolderPath(); - path = Path.Combine(path, "Registry.xml"); - return path; - } - [XmlRoot("Entry")] public struct Entry { @@ -198,6 +200,7 @@ namespace FileConverter public static class Keys { public static readonly string LastUpdateCheckDate = "LastUpdateCheckDate"; + public static readonly string ImportInitialFolder = "ImportInitialFolder"; } } } diff --git a/Application/FileConverter/Resources/ApplicationIcon.ico b/Application/FileConverter/Resources/ApplicationIcon.ico index 1b0191e..b2198dd 100644 Binary files a/Application/FileConverter/Resources/ApplicationIcon.ico and b/Application/FileConverter/Resources/ApplicationIcon.ico differ diff --git a/Application/FileConverter/Resources/CancelIcon.png b/Application/FileConverter/Resources/CancelIcon.png index 1f3948d..9c4340e 100644 Binary files a/Application/FileConverter/Resources/CancelIcon.png and b/Application/FileConverter/Resources/CancelIcon.png differ diff --git a/Application/FileConverter/Resources/DeleteIcon.ico b/Application/FileConverter/Resources/DeleteIcon.ico new file mode 100644 index 0000000..dbc7c3a Binary files /dev/null and b/Application/FileConverter/Resources/DeleteIcon.ico differ diff --git a/Application/FileConverter/Resources/DownIcon.ico b/Application/FileConverter/Resources/DownIcon.ico new file mode 100644 index 0000000..c9cec61 Binary files /dev/null and b/Application/FileConverter/Resources/DownIcon.ico differ diff --git a/Application/FileConverter/Resources/DuplicatePresetIcon.ico b/Application/FileConverter/Resources/DuplicatePresetIcon.ico new file mode 100644 index 0000000..e1f4f12 Binary files /dev/null and b/Application/FileConverter/Resources/DuplicatePresetIcon.ico differ diff --git a/Application/FileConverter/Resources/ExportIcon.ico b/Application/FileConverter/Resources/ExportIcon.ico new file mode 100644 index 0000000..b24fc0c Binary files /dev/null and b/Application/FileConverter/Resources/ExportIcon.ico differ diff --git a/Application/FileConverter/Resources/FailIcon.png b/Application/FileConverter/Resources/FailIcon.png index 6f9b86f..c10794f 100644 Binary files a/Application/FileConverter/Resources/FailIcon.png and b/Application/FileConverter/Resources/FailIcon.png differ diff --git a/Application/FileConverter/Resources/FileConverterUsage.gif b/Application/FileConverter/Resources/FileConverterUsage.gif index de4af49..626923a 100644 Binary files a/Application/FileConverter/Resources/FileConverterUsage.gif and b/Application/FileConverter/Resources/FileConverterUsage.gif differ 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/Resources/ImportIcon.ico b/Application/FileConverter/Resources/ImportIcon.ico new file mode 100644 index 0000000..d28c549 Binary files /dev/null and b/Application/FileConverter/Resources/ImportIcon.ico differ diff --git a/Application/FileConverter/Resources/LogIcon.png b/Application/FileConverter/Resources/LogIcon.png new file mode 100644 index 0000000..65187dd Binary files /dev/null and b/Application/FileConverter/Resources/LogIcon.png differ diff --git a/Application/FileConverter/Resources/PaypalIcon.png b/Application/FileConverter/Resources/PaypalIcon.png new file mode 100644 index 0000000..e54a9b0 Binary files /dev/null and b/Application/FileConverter/Resources/PaypalIcon.png differ diff --git a/Application/FileConverter/Resources/Pledge-icon.png b/Application/FileConverter/Resources/Pledge-icon.png deleted file mode 100644 index a032ffb..0000000 Binary files a/Application/FileConverter/Resources/Pledge-icon.png and /dev/null differ diff --git a/Application/FileConverter/Resources/PresetIcon.ico b/Application/FileConverter/Resources/PresetIcon.ico new file mode 100644 index 0000000..67df382 Binary files /dev/null and b/Application/FileConverter/Resources/PresetIcon.ico differ diff --git a/Application/FileConverter/Resources/Settings-Icon.png b/Application/FileConverter/Resources/Settings-Icon.png deleted file mode 100644 index 5b3f573..0000000 Binary files a/Application/FileConverter/Resources/Settings-Icon.png and /dev/null differ diff --git a/Application/FileConverter/Resources/SettingsIcon.ico b/Application/FileConverter/Resources/SettingsIcon.ico new file mode 100644 index 0000000..2b9d5e1 Binary files /dev/null and b/Application/FileConverter/Resources/SettingsIcon.ico differ diff --git a/Application/FileConverter/Resources/SuccessIcon.png b/Application/FileConverter/Resources/SuccessIcon.png index 00ce2bf..9c62222 100644 Binary files a/Application/FileConverter/Resources/SuccessIcon.png and b/Application/FileConverter/Resources/SuccessIcon.png differ diff --git a/Application/FileConverter/Resources/UpIcon.ico b/Application/FileConverter/Resources/UpIcon.ico new file mode 100644 index 0000000..5448080 Binary files /dev/null and b/Application/FileConverter/Resources/UpIcon.ico differ diff --git a/Application/FileConverter/Services/ConversionJobsTerminatedEventArgs.cs b/Application/FileConverter/Services/ConversionJobsTerminatedEventArgs.cs new file mode 100644 index 0000000..6a2fe81 --- /dev/null +++ b/Application/FileConverter/Services/ConversionJobsTerminatedEventArgs.cs @@ -0,0 +1,20 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.Services +{ + using System; + + public class ConversionJobsTerminatedEventArgs : EventArgs + { + public ConversionJobsTerminatedEventArgs(bool allConversionsSucceed) + { + this.AllConversionsSucceed = allConversionsSucceed; + } + + public bool AllConversionsSucceed + { + get; + private set; + } + } +} diff --git a/Application/FileConverter/Services/ConversionService.cs b/Application/FileConverter/Services/ConversionService.cs new file mode 100644 index 0000000..3445c54 --- /dev/null +++ b/Application/FileConverter/Services/ConversionService.cs @@ -0,0 +1,202 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.Services +{ + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.Threading; + + using CommunityToolkit.Mvvm.ComponentModel; + using CommunityToolkit.Mvvm.DependencyInjection; + + using FileConverter.ConversionJobs; + using FileConverter.Diagnostics; + + public class ConversionService : ObservableObject, IConversionService + { + private readonly List conversionJobs = new List(); + + private readonly int numberOfConversionThread = 1; + + private ISettingsService settingsService; + + public ConversionService(ISettingsService settingsService) + { + if (settingsService == null) + { + throw new ArgumentNullException(nameof(settingsService)); + } + + this.settingsService = settingsService; + + this.ConversionJobs = this.conversionJobs.AsReadOnly(); + + this.numberOfConversionThread = this.settingsService.Settings.MaximumNumberOfSimultaneousConversions; + Diagnostics.Debug.Log("Maximum number of conversion threads: {0}", this.numberOfConversionThread); + + if (this.numberOfConversionThread <= 0) + { + this.numberOfConversionThread = System.Math.Max(1, Environment.ProcessorCount / 2); + Diagnostics.Debug.Log("The number of processors on this computer is {0}. Set the default number of conversion threads to {0}", settingsService.Settings.MaximumNumberOfSimultaneousConversions); + } + } + + public event System.EventHandler ConversionJobsTerminated; + + public ReadOnlyCollection ConversionJobs + { + get; + private set; + } + + public void RegisterConversionJob(ConversionJob conversionJob) + { + this.conversionJobs.Add(conversionJob); + this.OnPropertyChanged(nameof(this.ConversionJobs)); + } + + public void ConvertFilesAsync() + { + Thread fileConvertionThread = Helpers.InstantiateThread("ConversionQueueThread", this.ConvertFiles); + fileConvertionThread.Start(); + } + + private void ConvertFiles() + { + // Prepare conversions. + for (int index = 0; index < this.ConversionJobs.Count; index++) + { + this.ConversionJobs[index].PrepareConversion(); + } + + System.Collections.Specialized.StringCollection files = new System.Collections.Specialized.StringCollection(); + // Convert! + Thread[] jobThreads = new Thread[this.numberOfConversionThread]; + while (true) + { + // Compute conversion flags. + ConversionFlags conversionFlags = ConversionFlags.None; + bool allJobAreFinished = true; + for (int jobIndex = 0; jobIndex < this.conversionJobs.Count; jobIndex++) + { + ConversionJob conversionJob = this.conversionJobs[jobIndex]; + allJobAreFinished &= !(conversionJob.State == ConversionState.Ready || conversionJob.State == ConversionState.InProgress); + + if (conversionJob.State == ConversionState.InProgress) + { + conversionFlags |= conversionJob.StateFlags; + } + } + + if (allJobAreFinished) + { + break; + } + + // Start job if possible. + for (int jobIndex = 0; jobIndex < this.conversionJobs.Count; jobIndex++) + { + ConversionJob conversionJob = this.conversionJobs[jobIndex]; + if (conversionJob.State == ConversionState.Ready && conversionJob.CanStartConversion(conversionFlags)) + { + // Find a thread to execute the job. + Thread jobThread = null; + for (int threadIndex = 0; threadIndex < jobThreads.Length; threadIndex++) + { + Thread thread = jobThreads[threadIndex]; + if (thread == null || !thread.IsAlive) + { + jobThread = Helpers.InstantiateThread(conversionJob.GetType().Name, this.ExecuteConversionJob); + jobThreads[threadIndex] = jobThread; + break; + } + } + + if (jobThread != null) + { + jobThread.Start(conversionJob); + + while (conversionJob.State == ConversionState.Ready) + { + Debug.Log("Wait the launch of the conversion thread before launching any other thread."); + Thread.Sleep(20); + } + } + + if (!files.Contains(conversionJob.OutputFilePath)) + { + files.Add(conversionJob.OutputFilePath); + } + + break; + } + } + + Thread.Sleep(50); + } + + // Copy the output files to the clipboard + if (this.settingsService.Settings.CopyFilesInClipboardAfterConversion && files.Count > 0) + { + Thread clipboardThread = Helpers.InstantiateThread("CopyFilesToClipboardThread", this.CopyFilesToClipboard); + clipboardThread.SetApartmentState(ApartmentState.STA); + clipboardThread.Start(files); + } + + bool allConversionsSucceed = true; + for (int index = 0; index < this.conversionJobs.Count; index++) + { + allConversionsSucceed &= this.conversionJobs[index].State == ConversionState.Done; + } + + if (this.ConversionJobsTerminated != null) + { + this.ConversionJobsTerminated.Invoke(this, new ConversionJobsTerminatedEventArgs(allConversionsSucceed)); + } + } + + private void ExecuteConversionJob(object parameter) + { + ConversionJob conversionJob = parameter as ConversionJob; + if (conversionJob == null) + { + throw new System.ArgumentException("The parameter must be a conversion job.", nameof(parameter)); + } + + if (conversionJob.State != ConversionState.Ready) + { + Debug.LogError("Fail to execute conversion job."); + return; + } + + try + { + conversionJob.StartConversion(); + } + catch (Exception exception) + { + Debug.LogError("Failure during conversion: {0}", exception.ToString()); + } + } + + private void CopyFilesToClipboard(object _filePaths) + { + try + { + System.Collections.Specialized.StringCollection FilePaths = _filePaths as System.Collections.Specialized.StringCollection; + System.Windows.Forms.Clipboard.SetFileDropList(FilePaths); + Debug.Log("Output files copied to the clipboard:"); + for (int index = 0; index < FilePaths.Count; index++) + { + Debug.Log(" {0}", FilePaths[index]); + } + } + catch (Exception exception) + { + Debug.Log("Can't copy files to the clipboard."); + Debug.Log("An exception has been thrown: {0}.", exception.ToString()); + } + } + } +} diff --git a/Application/FileConverter/Services/IConversionService.cs b/Application/FileConverter/Services/IConversionService.cs new file mode 100644 index 0000000..e5216b0 --- /dev/null +++ b/Application/FileConverter/Services/IConversionService.cs @@ -0,0 +1,22 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.Services +{ + using System.Collections.ObjectModel; + + using FileConverter.ConversionJobs; + + public interface IConversionService + { + event System.EventHandler ConversionJobsTerminated; + + ReadOnlyCollection ConversionJobs + { + get; + } + + void ConvertFilesAsync(); + + void RegisterConversionJob(ConversionJob conversionJob); + } +} diff --git a/Application/FileConverter/Services/INavigationService.cs b/Application/FileConverter/Services/INavigationService.cs new file mode 100644 index 0000000..2fe0524 --- /dev/null +++ b/Application/FileConverter/Services/INavigationService.cs @@ -0,0 +1,15 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.Services +{ + using System.Windows; + + public interface INavigationService + { + void RegisterPage(string pageKey, bool cancelAutoExit, bool mainWindow) where T : Window; + + void Show(string pageKey); + + void Close(string pageKey, bool alreadyClosing); + } +} \ No newline at end of file diff --git a/Application/FileConverter/Services/ISettingsService.cs b/Application/FileConverter/Services/ISettingsService.cs new file mode 100644 index 0000000..92fbd7f --- /dev/null +++ b/Application/FileConverter/Services/ISettingsService.cs @@ -0,0 +1,18 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.Services +{ + public interface ISettingsService + { + Settings Settings + { + get; + } + + bool PostInstallationInitialization(); + + void SaveSettings(); + + void RevertSettings(); + } +} diff --git a/Application/FileConverter/Services/IUpgradeService.cs b/Application/FileConverter/Services/IUpgradeService.cs new file mode 100644 index 0000000..c7b393e --- /dev/null +++ b/Application/FileConverter/Services/IUpgradeService.cs @@ -0,0 +1,24 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.Services +{ + using System.Threading.Tasks; + + public interface IUpgradeService + { + event System.EventHandler NewVersionAvailable; + + UpgradeVersionDescription UpgradeVersionDescription + { + get; + } + + Task CheckForUpgrade(); + + Task DownloadChangeLog(); + + Task StartUpgrade(); + + void CancelUpgrade(); + } +} diff --git a/Application/FileConverter/Services/NavigationService.cs b/Application/FileConverter/Services/NavigationService.cs new file mode 100644 index 0000000..8b53acd --- /dev/null +++ b/Application/FileConverter/Services/NavigationService.cs @@ -0,0 +1,195 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.Services +{ + using System; + using System.Collections.Generic; + using System.Windows; + + using CommunityToolkit.Mvvm.ComponentModel; + using CommunityToolkit.Mvvm.DependencyInjection; + + using FileConverter.Annotations; + + using Application = FileConverter.Application; + + public class NavigationService : ObservableObject, INavigationService + { + private readonly Dictionary pageInfoByType; + private int numberOfPageShowed = 0; + + public NavigationService() + { + this.pageInfoByType = new Dictionary(); + } + + public void Show([NotNull] string pageKey) + { + lock (this.pageInfoByType) + { + PageInfo pageInfo; + if (!this.pageInfoByType.TryGetValue(pageKey, out pageInfo)) + { + throw new ArgumentException($"No such page: {pageKey}.", nameof(pageKey)); + } + + if (pageInfo.Showed) + { + return; + } + + pageInfo.Showed = true; + + if (pageInfo.Instance == null || !pageInfo.Instance.IsLoaded) + { + pageInfo.Instance = Activator.CreateInstance(pageInfo.Type) as Window; + } + + Diagnostics.Debug.Log($"Show page {pageKey}."); + + this.pageInfoByType[pageKey] = pageInfo; + + this.numberOfPageShowed++; + + if (pageInfo.CancelAutoExit) + { + Application application = Application.Current as Application; + application?.CancelAutoExit(); + } + + pageInfo.Instance.Show(); + } + } + + public void Close([NotNull] string pageKey, bool alreadyClosing) + { + if (pageKey == null) + { + throw new ArgumentNullException(nameof(pageKey)); + } + + lock (this.pageInfoByType) + { + PageInfo pageInfo; + if (!this.pageInfoByType.TryGetValue(pageKey, out pageInfo)) + { + throw new ArgumentException($"No such page: {pageKey}.", nameof(pageKey)); + } + + if (!pageInfo.Showed) + { + return; + } + + pageInfo.Showed = false; + + Diagnostics.Debug.Log($"Close page {pageKey}."); + + this.pageInfoByType[pageKey] = pageInfo; + + if (pageInfo.MainWindow) + { + this.CloseSecondaryWindowsIfThereIsNoOtherMainWindowShowed(); + } + + if (!alreadyClosing) + { + pageInfo.Instance.Close(); + } + + this.numberOfPageShowed--; + + // If this is the last window. + if (this.numberOfPageShowed == 0) + { + IUpgradeService upgradeService = Ioc.Default.GetRequiredService(); + bool upgradeInProgress = upgradeService.UpgradeVersionDescription != null && + upgradeService.UpgradeVersionDescription.NeedToUpgrade && + !upgradeService.UpgradeVersionDescription.InstallerDownloadDone; + + if (upgradeInProgress) + { + if (pageKey == Pages.Upgrade) + { + upgradeService.CancelUpgrade(); + Application.Current.Shutdown(); + } + else + { + INavigationService navigationService = Ioc.Default.GetRequiredService(); + navigationService.Show(Pages.Upgrade); + Diagnostics.Debug.Log("There is an upgrade in progress, display the upgrade window."); + } + } + else + { + Application.Current.Shutdown(); + } + } + } + } + + public void RegisterPage(string pageKey, bool cancelAutoExit, bool mainWindow) where T : Window + { + if (string.IsNullOrEmpty(pageKey)) + { + throw new ArgumentNullException(nameof(pageKey)); + } + + lock (this.pageInfoByType) + { + if (!this.pageInfoByType.ContainsKey(pageKey)) + { + this.pageInfoByType.Add(pageKey, new PageInfo(typeof(T), cancelAutoExit, mainWindow)); + } + else + { + throw new Exception($"Page {pageKey} already registered."); + } + } + } + + private void CloseSecondaryWindowsIfThereIsNoOtherMainWindowShowed() + { + List windowsToClose = new List(); + foreach (KeyValuePair keyValuePair in this.pageInfoByType) + { + if (keyValuePair.Value.MainWindow && keyValuePair.Value.Showed) + { + // There is another main window showed. + return; + } + + if (keyValuePair.Value.Showed) + { + windowsToClose.Add(keyValuePair.Key); + } + } + + // Close all windows. + for (int index = 0; index < windowsToClose.Count; index++) + { + this.Close(windowsToClose[index], false); + } + } + + private struct PageInfo + { + public Window Instance; + public Type Type; + public bool CancelAutoExit; + public bool MainWindow; + + public bool Showed; + + public PageInfo(Type type, bool cancelAutoExit, bool mainWindow) + { + this.Instance = null; + this.Type = type; + this.CancelAutoExit = cancelAutoExit; + this.MainWindow = mainWindow; + this.Showed = false; + } + } + } +} diff --git a/Application/FileConverter/Settings.Migration.cs b/Application/FileConverter/Services/SettingsService.Migration.cs similarity index 84% rename from Application/FileConverter/Settings.Migration.cs rename to Application/FileConverter/Services/SettingsService.Migration.cs index 0bfb3e6..d993c2d 100644 --- a/Application/FileConverter/Settings.Migration.cs +++ b/Application/FileConverter/Services/SettingsService.Migration.cs @@ -1,14 +1,13 @@ -// // License: http://www.gnu.org/licenses/gpl.html GPL version 3. +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. -namespace FileConverter +namespace FileConverter.Services { using System; - using FileConverter.ConversionJobs; - public partial class Settings + public partial class SettingsService { - private static void MigrateSettingsToCurrentVersion(Settings settings) + private void MigrateSettingsToCurrentVersion(Settings settings) { int settingsVersion = settings.SerializationVersion; @@ -17,12 +16,12 @@ namespace FileConverter { foreach (ConversionPreset conversionPreset in settings.ConversionPresets) { - Settings.MigrateConversionPresetToCurrentVersion(conversionPreset, settingsVersion); + this.MigrateConversionPresetToCurrentVersion(conversionPreset, settingsVersion); } } } - private static void MigrateConversionPresetToCurrentVersion(ConversionPreset preset, int settingsVersion) + private void MigrateConversionPresetToCurrentVersion(ConversionPreset preset, int settingsVersion) { if (settingsVersion <= 2) { @@ -72,4 +71,4 @@ namespace FileConverter } } } -} \ No newline at end of file +} diff --git a/Application/FileConverter/Services/SettingsService.cs b/Application/FileConverter/Services/SettingsService.cs new file mode 100644 index 0000000..18c81bf --- /dev/null +++ b/Application/FileConverter/Services/SettingsService.cs @@ -0,0 +1,205 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +using FileConverter.Properties; + +namespace FileConverter.Services +{ + using System; + using System.Diagnostics; + using System.IO; + using System.Windows; + + using CommunityToolkit.Mvvm.ComponentModel; + + using Debug = FileConverter.Diagnostics.Debug; + + public partial class SettingsService : ObservableObject, ISettingsService + { + public SettingsService() + { + // Load settigns. + Debug.Log("Load settings..."); + this.Settings = this.Load(); + } + + public Settings Settings + { + get; + private set; + } + + private string UserSettingsTemporaryFilePath + { + get + { + string path = FileConverterExtension.PathHelpers.GetUserDataFolderPath; + path = Path.Combine(path, "Settings.temp.xml"); + return path; + } + } + + public bool PostInstallationInitialization() + { + Debug.Log("Execute post installation initialization."); + + Settings defaultSettings = null; + + // Load the default settings. + if (File.Exists(FileConverterExtension.PathHelpers.DefaultSettingsFilePath)) + { + try + { + XmlHelpers.LoadFromFile("Settings", FileConverterExtension.PathHelpers.DefaultSettingsFilePath, out defaultSettings); + } + catch (Exception exception) + { + Debug.LogError($"Fail to load file converter default settings. {exception.Message}"); + return false; + } + } + else + { + Debug.LogError("Default settings not found at path {0}. You should try to reinstall the application.", FileConverterExtension.PathHelpers.DefaultSettingsFilePath); + return false; + } + + // Load user settings if exists. + Settings userSettings = null; + if (File.Exists(FileConverterExtension.PathHelpers.UserSettingsFilePath)) + { + try + { + XmlHelpers.LoadFromFile("Settings", FileConverterExtension.PathHelpers.UserSettingsFilePath, out userSettings); + } + catch (Exception) + { + File.Delete(FileConverterExtension.PathHelpers.UserSettingsFilePath); + } + + if (userSettings != null) + { + if (userSettings.SerializationVersion != Settings.Version) + { + this.MigrateSettingsToCurrentVersion(userSettings); + + Debug.Log("File converter settings have been imported from version {0} to version {1}.", userSettings.SerializationVersion, Settings.Version); + userSettings.SerializationVersion = Settings.Version; + } + + // Remove default settings. + if (userSettings.ConversionPresets != null) + { + for (int index = userSettings.ConversionPresets.Count - 1; index >= 0; index--) + { + if (userSettings.ConversionPresets[index].IsDefaultSettings) + { + userSettings.ConversionPresets.RemoveAt(index); + } + } + } + } + } + + Settings settings = userSettings != null ? userSettings.Merge(defaultSettings) : defaultSettings; + return this.Save(settings); + } + + public void SaveSettings() + { + this.Save(this.Settings); + } + + public void RevertSettings() + { + // Load previous preset in order to cancel changes. + this.Settings = this.Load(); + } + + private Settings Load() + { + Settings settings = null; + if (File.Exists(FileConverterExtension.PathHelpers.UserSettingsFilePath)) + { + Settings userSettings = null; + try + { + var stopwatch = new Stopwatch(); + stopwatch.Start(); + XmlHelpers.LoadFromFile("Settings", FileConverterExtension.PathHelpers.UserSettingsFilePath, out userSettings); + stopwatch.Stop(); + Debug.Log($"Settings load time: {stopwatch.Elapsed.TotalMilliseconds}ms"); + + settings = userSettings; + } + catch (Exception) + { + MessageBoxResult messageBoxResult = + MessageBox.Show(Resources.ErrorCantLoadSettings, + Resources.Error, + MessageBoxButton.YesNo, + MessageBoxImage.Exclamation); + + if (messageBoxResult == MessageBoxResult.Yes) + { + File.Delete(FileConverterExtension.PathHelpers.UserSettingsFilePath); + return this.Load(); + } + else if (messageBoxResult == MessageBoxResult.No) + { + return null; + } + } + + if (userSettings != null && userSettings.SerializationVersion != Settings.Version) + { + this.MigrateSettingsToCurrentVersion(userSettings); + + Diagnostics.Debug.Log("File converter settings has been imported from version {0} to version {1}.", userSettings.SerializationVersion, Settings.Version); + userSettings.SerializationVersion = Settings.Version; + this.Save(userSettings); + } + } + else + { + // Load the default settings. + if (File.Exists(FileConverterExtension.PathHelpers.DefaultSettingsFilePath)) + { + try + { + XmlHelpers.LoadFromFile("Settings", FileConverterExtension.PathHelpers.DefaultSettingsFilePath, out Settings defaultSettings); + settings = defaultSettings; + } + catch (Exception exception) + { + Debug.LogError("Fail to load file converter default settings. {0}", exception.Message); + } + } + else + { + Debug.LogError("Default settings not found at path {0}. You should try to reinstall the application.", FileConverterExtension.PathHelpers.DefaultSettingsFilePath); + } + } + + return settings; + } + + private bool Save(Settings settings) + { + if (settings == null) + { + throw new ArgumentNullException(nameof(settings)); + } + + settings.Clean(); + + // Save the settings in a temporary files (we'll write the settings file when we'll succeed to write the registry keys). + XmlHelpers.SaveToFile("Settings", this.UserSettingsTemporaryFilePath, settings); + + // Copy temporary settings file to the real settings file. + File.Copy(this.UserSettingsTemporaryFilePath, FileConverterExtension.PathHelpers.UserSettingsFilePath, true); + File.Delete(this.UserSettingsTemporaryFilePath); + + return true; + } + } +} diff --git a/Application/FileConverter/Services/UpgradeService.cs b/Application/FileConverter/Services/UpgradeService.cs new file mode 100644 index 0000000..1ff083d --- /dev/null +++ b/Application/FileConverter/Services/UpgradeService.cs @@ -0,0 +1,256 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.Services +{ + using System; + using System.IO; + using System.Net; + using System.Text.RegularExpressions; + using System.Threading.Tasks; + using System.Xml; + using System.Xml.Serialization; + + using CommunityToolkit.Mvvm.ComponentModel; + + using FileConverter.Annotations; + using FileConverter.Diagnostics; + + public class UpgradeService : ObservableObject, IUpgradeService + { +#if DEBUG + private const string BaseURI = "https://raw.githubusercontent.com/Tichau/FileConverter/integration/"; +#else + private const string BaseURI = "https://raw.githubusercontent.com/Tichau/FileConverter/master/"; +#endif + + [NotNull] + private readonly WebClient webClient = new WebClient(); + + private UpgradeVersionDescription upgradeVersionDescription; + + public UpgradeService() + { + this.UpgradeVersionDescription = new UpgradeVersionDescription(); + } + + public event EventHandler NewVersionAvailable; + + public UpgradeVersionDescription UpgradeVersionDescription + { + get => this.upgradeVersionDescription; + private set + { + this.upgradeVersionDescription = value; + this.OnPropertyChanged(); + } + } + + public async Task CheckForUpgrade() + { + Task task = null; + try + { +#if DEBUG + task = this.DownloadLatestVersionDescription(); +#else + long fileTime = Registry.GetValue(Registry.Keys.LastUpdateCheckDate); + DateTime lastUpdateDateTime = DateTime.FromFileTime(fileTime); + + TimeSpan durationSinceLastUpdate = DateTime.Now.Subtract(lastUpdateDateTime); + if (durationSinceLastUpdate > new TimeSpan(1, 0, 0, 0)) + { + task = this.DownloadLatestVersionDescription(); + } +#endif + } + catch (Exception exception) + { + Diagnostics.Debug.Log($"Failed to check upgrade: {exception.Message}."); + } + + UpgradeVersionDescription versionDescription = await task; + + if (versionDescription == null) + { + return null; + } + + Registry.SetValue(Registry.Keys.LastUpdateCheckDate, DateTime.Now.ToFileTime()); + + if (versionDescription.LatestVersion <= Application.ApplicationVersion) + { + return null; + } + + this.UpgradeVersionDescription = versionDescription; + + this.NewVersionAvailable?.Invoke(this, versionDescription); + return versionDescription; + } + + public async Task DownloadChangeLog() + { + if (this.UpgradeVersionDescription == null) + { + throw new ArgumentNullException(nameof(this.UpgradeVersionDescription)); + } + + this.UpgradeVersionDescription.ChangeLog = Properties.Resources.DownloadingChangeLog; + + Uri uri = new Uri(UpgradeService.BaseURI + "CHANGELOG.md"); + try + { + Task openReadTaskAsync = this.webClient.OpenReadTaskAsync(uri); + if (openReadTaskAsync == null) + { + return null; + } + + Stream stream = await openReadTaskAsync; + using (StreamReader reader = new StreamReader(stream)) + { + this.UpgradeVersionDescription.ChangeLog = reader.ReadToEnd(); + } + } + catch (Exception) + { + Debug.LogError("Error while retrieving change log."); + return null; + } + + return this.UpgradeVersionDescription.ChangeLog; + } + + public async Task StartUpgrade() + { + if (this.UpgradeVersionDescription == null) + { + Debug.Log("Can't start upgrade because no check upgrade have been done."); + return; + } + + try + { + this.UpgradeVersionDescription.NeedToUpgrade = true; + await this.DownloadInstaller(); + } + catch (Exception exception) + { + Debug.Log($"Failed to download upgrade: {exception.Message}."); + } + } + + public void CancelUpgrade() + { + if (this.UpgradeVersionDescription == null) + { + Debug.Log("Can't cancel upgrade because there is no upgrade in progress."); + return; + } + + Debug.Log("Cancel application upgrade."); + this.UpgradeVersionDescription.NeedToUpgrade = false; + } + + private async Task DownloadLatestVersionDescription() + { +#if BUILD32 + Uri uri = new Uri(Helpers.BaseURI + "version (x86).xml"); +#else + Uri uri = new Uri(UpgradeService.BaseURI + "version.xml"); +#endif + + UpgradeVersionDescription description = null; + try + { + Stream stream = await this.webClient.OpenReadTaskAsync(uri); + + XmlRootAttribute xmlRoot = new XmlRootAttribute + { + ElementName = "Version" + }; + + XmlSerializer serializer = new XmlSerializer(typeof(UpgradeVersionDescription), xmlRoot); + + XmlReaderSettings xmlReaderSettings = new XmlReaderSettings + { + IgnoreWhitespace = true, + IgnoreComments = true + }; + + using (XmlReader xmlReader = XmlReader.Create(stream, xmlReaderSettings)) + { + description = (UpgradeVersionDescription)serializer.Deserialize(xmlReader); + } + } + catch (Exception) + { + Debug.Log("Error while retrieving change log."); + return null; + } + + return description; + } + + private async Task DownloadInstaller() + { + if (this.UpgradeVersionDescription == null) + { + throw new ArgumentNullException(nameof(this.UpgradeVersionDescription)); + } + + if (this.UpgradeVersionDescription.InstallerDownloadInProgress) + { + throw new Exception("The installer download is currently in progress."); + } + + Uri uri = new Uri(this.UpgradeVersionDescription.InstallerURL); + + string fileName = "FileConverter-setup.msi"; + Regex retrieveFileNameRegex = new Regex("/([^/]*)"); + MatchCollection matchCollection = retrieveFileNameRegex.Matches(this.UpgradeVersionDescription.InstallerURL); + if (matchCollection.Count > 0) + { + Match match = matchCollection[matchCollection.Count - 1]; + if (match.Groups.Count > 1) + { + fileName = match.Groups[1].Value; + } + } + + string tempPath = System.IO.Path.GetTempPath(); + string installerPath = System.IO.Path.Combine(tempPath, fileName); + + this.UpgradeVersionDescription.InstallerPath = installerPath; + this.UpgradeVersionDescription.InstallerDownloadInProgress = true; + this.UpgradeVersionDescription.InstallerDownloadProgress = 0; + + // Source: https://stackoverflow.com/questions/2859790/the-request-was-aborted-could-not-create-ssl-tls-secure-channel#2904963 + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + + this.webClient.DownloadProgressChanged += this.WebClient_DownloadProgressChanged; + + try + { + await this.webClient.DownloadFileTaskAsync(uri, installerPath); + + this.UpgradeVersionDescription.InstallerDownloadProgress = 100; + this.UpgradeVersionDescription.InstallerDownloadInProgress = false; + this.UpgradeVersionDescription = null; + } + catch (Exception exception) + { + Debug.LogError("Failed to download the new File Converter upgrade. You should try again or download it manually."); + Debug.Log(exception.ToString()); + this.UpgradeVersionDescription.NeedToUpgrade = false; + } + + this.webClient.DownloadProgressChanged -= this.WebClient_DownloadProgressChanged; + } + + private void WebClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs eventArgs) + { + this.UpgradeVersionDescription.InstallerDownloadProgress = eventArgs.ProgressPercentage; + } + } +} diff --git a/Application/FileConverter/Upgrade/UpgradeVersionDescription.cs b/Application/FileConverter/Services/UpgradeVersionDescription.cs similarity index 59% rename from Application/FileConverter/Upgrade/UpgradeVersionDescription.cs rename to Application/FileConverter/Services/UpgradeVersionDescription.cs index 844f0e9..1094b4a 100644 --- a/Application/FileConverter/Upgrade/UpgradeVersionDescription.cs +++ b/Application/FileConverter/Services/UpgradeVersionDescription.cs @@ -1,19 +1,17 @@ // License: http://www.gnu.org/licenses/gpl.html GPL version 3. -namespace FileConverter +namespace FileConverter.Services { - using System.ComponentModel; - using System.Runtime.CompilerServices; using System.Xml.Serialization; - using FileConverter.Annotations; + using CommunityToolkit.Mvvm.ComponentModel; - public class UpgradeVersionDescription : INotifyPropertyChanged + public class UpgradeVersionDescription : ObservableObject { private int installerDownloadProgress; private bool installerDownloadInProgress; - public event PropertyChangedEventHandler PropertyChanged; + private string changeLog; [XmlElement("Latest")] public Version LatestVersion @@ -28,12 +26,16 @@ namespace FileConverter get; set; } - + [XmlIgnore] public string ChangeLog { - get; - set; + get => this.changeLog; + set + { + this.changeLog = value; + this.OnPropertyChanged(); + } } [XmlIgnore] @@ -46,10 +48,7 @@ namespace FileConverter [XmlIgnore] public bool InstallerDownloadInProgress { - get - { - return this.installerDownloadInProgress; - } + get => this.installerDownloadInProgress; set { @@ -63,10 +62,7 @@ namespace FileConverter [XmlIgnore] public int InstallerDownloadProgress { - get - { - return this.installerDownloadProgress; - } + get => this.installerDownloadProgress; set { @@ -78,22 +74,10 @@ namespace FileConverter } [XmlIgnore] - public bool InstallerDownloadDone - { - get - { - return !this.InstallerDownloadInProgress && this.InstallerDownloadProgress == 100; - } - } + public bool InstallerDownloadDone => !this.InstallerDownloadInProgress && this.InstallerDownloadProgress == 100; [XmlIgnore] - public bool InstallerDownloadNotStarted - { - get - { - return !this.InstallerDownloadInProgress && this.InstallerDownloadProgress == 0; - } - } + public bool InstallerDownloadNotStarted => !this.InstallerDownloadInProgress && this.InstallerDownloadProgress == 0; [XmlIgnore] public bool NeedToUpgrade @@ -101,11 +85,5 @@ namespace FileConverter get; set; } - - [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/Settings.Settings.cs b/Application/FileConverter/Settings.Settings.cs deleted file mode 100644 index 74760f0..0000000 --- a/Application/FileConverter/Settings.Settings.cs +++ /dev/null @@ -1,210 +0,0 @@ -// License: http://www.gnu.org/licenses/gpl.html GPL version 3. - -namespace FileConverter -{ - using System.Collections.ObjectModel; - using System.Globalization; - using System.Linq; - using System.Xml.Serialization; - - public partial class Settings : IXmlSerializable - { - public const int Version = 4; - - private bool exitApplicationWhenConversionsFinished = true; - private float durationBetweenEndOfConversionsAndApplicationExit = 3f; - private ObservableCollection conversionPresets = new ObservableCollection(); - private bool checkUpgradeAtStartup = true; - private CultureInfo applicationLanguage; - private int maximumNumberOfSimultaneousConversions; - - [XmlAttribute] - public int SerializationVersion - { - get; - set; - } = Version; - - [XmlIgnore] - public CultureInfo ApplicationLanguage - { - get - { - return this.applicationLanguage; - } - - set - { - if (this.applicationLanguage != null && this.applicationLanguage.Equals(value)) - { - return; - } - - this.applicationLanguage = value; - if (this.applicationLanguage != null) - { - System.Threading.Thread.CurrentThread.CurrentCulture = this.applicationLanguage; - System.Threading.Thread.CurrentThread.CurrentUICulture = this.applicationLanguage; - } - - this.OnPropertyChanged(); - } - } - - [XmlElement] - public string ApplicationLanguageName - { - get - { - if (this.ApplicationLanguage == null) - { - return string.Empty; - } - - return this.ApplicationLanguage.Name; - } - - set - { - if (string.IsNullOrEmpty(value)) - { - this.ApplicationLanguage = null; - return; - } - - this.ApplicationLanguage = CultureInfo.GetCultureInfo(value); - } - } - - [XmlIgnore] - public ObservableCollection ConversionPresets - { - get - { - return this.conversionPresets; - } - - set - { - this.conversionPresets = value; - this.OnPropertyChanged(); - } - } - - [XmlElement] - public bool ExitApplicationWhenConversionsFinished - { - get - { - return this.exitApplicationWhenConversionsFinished; - } - - set - { - this.exitApplicationWhenConversionsFinished = value; - this.OnPropertyChanged(); - } - } - - [XmlElement] - public float DurationBetweenEndOfConversionsAndApplicationExit - { - get - { - return this.durationBetweenEndOfConversionsAndApplicationExit; - } - - set - { - this.durationBetweenEndOfConversionsAndApplicationExit = value; - this.OnPropertyChanged(); - } - } - - [XmlElement] - public int MaximumNumberOfSimultaneousConversions - { - get - { - return this.maximumNumberOfSimultaneousConversions; - } - - set - { - this.maximumNumberOfSimultaneousConversions = value; - this.OnPropertyChanged(); - } - } - - [XmlElement("ConversionPreset")] - public ConversionPreset[] SerializableConversionPresets - { - get - { - return this.ConversionPresets.ToArray(); - } - - set - { - for (int index = 0; index < value.Length; index++) - { - this.ConversionPresets.Add(value[index]); - } - } - } - - [XmlElement] - public bool CheckUpgradeAtStartup - { - get - { - return this.checkUpgradeAtStartup; - } - - set - { - this.checkUpgradeAtStartup = value; - this.OnPropertyChanged(); - } - } - - public void OnDeserializationComplete() - { - this.DurationBetweenEndOfConversionsAndApplicationExit = System.Math.Max(0, System.Math.Min(10, this.DurationBetweenEndOfConversionsAndApplicationExit)); - - for (int index = 0; index < this.ConversionPresets.Count; index++) - { - this.ConversionPresets[index].OnDeserializationComplete(); - } - - // Initialize application if it was not deserialized from the settings. - if (this.ApplicationLanguage == null) - { - CultureInfo bestCandidate = null; - CultureInfo currentUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; - foreach (CultureInfo culture in Helpers.GetSupportedCultures()) - { - if (culture.Equals(currentUICulture)) - { - bestCandidate = culture; - break; - } - else if (culture.Equals(currentUICulture.Parent)) - { - bestCandidate = culture; - } - } - - if (bestCandidate != null) - { - this.ApplicationLanguage = bestCandidate; - } - else - { - Diagnostics.Debug.Log("Can't find supported culture info for culture {0}. Fallback to default culture.", currentUICulture); - this.ApplicationLanguage = CultureInfo.GetCultureInfo("en"); - } - } - } - } -} diff --git a/Application/FileConverter/Settings.cs b/Application/FileConverter/Settings.cs index 33d4ba5..86076c9 100644 --- a/Application/FileConverter/Settings.cs +++ b/Application/FileConverter/Settings.cs @@ -2,275 +2,30 @@ namespace FileConverter { - using System; - using System.Collections.Generic; - using System.ComponentModel; - using System.Diagnostics; - using System.IO; using System.Linq; - using System.Reflection; - using System.Runtime.CompilerServices; - using System.Security.Principal; - using System.Windows; using System.Xml.Serialization; + using System.Collections.ObjectModel; + using System.Globalization; - using FileConverter.Annotations; - using Microsoft.Win32; + using CommunityToolkit.Mvvm.ComponentModel; [XmlRoot] [XmlType] - public partial class Settings : INotifyPropertyChanged, IDataErrorInfo + public class Settings : ObservableObject, IXmlSerializable { - private const char PresetSeparator = ';'; + public const int Version = 4; - public event PropertyChangedEventHandler PropertyChanged; - - [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; - } - } - - private static bool IsInAdmininstratorPrivileges - { - get - { - return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); - } - } - - [XmlIgnore] - public string this[string columnName] - { - get - { - return this.Error; - } - } - - public static void ApplyTemporarySettings() - { - // Load temporary settings. - string temporaryFilePath = Settings.GetUserSettingsTemporaryFilePath(); - if (!File.Exists(temporaryFilePath)) - { - return; - } - - Settings settings = null; - XmlHelpers.LoadFromFile("Settings", temporaryFilePath, out settings); - - RegistryKey registryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\FileConverter"); - if (registryKey == null) - { - Diagnostics.Debug.LogError("Can't apply settings in registry. (code 0x03)"); - return; - } - - // Compute the registry entries data from settings. - Dictionary> registryEntries = ComputeRegistryEntriesFromConvertionPresets(settings.ConversionPresets); - - bool succeed = Settings.ApplyRegistryModifications(registryEntries); - - if (succeed) - { - // Copy temporary settings file to the real settings file. - string userFilePath = Settings.GetUserSettingsFilePath(); - File.Copy(temporaryFilePath, userFilePath, true); - File.Delete(temporaryFilePath); - } - } - - public static void PostInstallationInitialization() - { - Settings defaultSettings = null; - - // Load the default settings. - string defaultFilePath = Settings.GetDefaultSettingsFilePath(); - if (File.Exists(defaultFilePath)) - { - try - { - XmlHelpers.LoadFromFile("Settings", defaultFilePath, out defaultSettings); - } - catch (Exception exception) - { - Diagnostics.Debug.LogError("Fail to load file converter default settings. {0}", exception.Message); - } - } - else - { - Diagnostics.Debug.LogError("Default settings not found at path {0}. You should try to reinstall the application.", defaultFilePath); - } - - // Load user settings if exists. - Settings userSettings = null; - string userFilePath = Settings.GetUserSettingsFilePath(); - if (File.Exists(userFilePath)) - { - try - { - XmlHelpers.LoadFromFile("Settings", userFilePath, out userSettings); - } - catch (Exception) - { - System.IO.File.Delete(userFilePath); - } - - if (userSettings != null) - { - if (userSettings.SerializationVersion != Version) - { - Settings.MigrateSettingsToCurrentVersion(userSettings); - - Diagnostics.Debug.Log("File converter settings have been imported from version {0} to version {1}.", userSettings.SerializationVersion, Version); - userSettings.SerializationVersion = Version; - } - - // Remove default settings. - if (userSettings.ConversionPresets != null) - { - for (int index = userSettings.ConversionPresets.Count - 1; index >= 0; index--) - { - if (userSettings.ConversionPresets[index].IsDefaultSettings) - { - userSettings.ConversionPresets.RemoveAt(index); - } - } - } - } - } - - Settings settings = userSettings != null ? userSettings.Merge(defaultSettings) : defaultSettings; - settings.Save(); - } - - public static Settings Load() - { - Settings settings = null; - string userFilePath = Settings.GetUserSettingsFilePath(); - if (File.Exists(userFilePath)) - { - Settings userSettings = null; - try - { - XmlHelpers.LoadFromFile("Settings", userFilePath, out userSettings); - settings = userSettings; - } - catch (Exception) - { - MessageBoxResult messageBoxResult = - MessageBox.Show( - "Can't load file converter user settings. Do you want to fall back to default settings ?", - "Error", - MessageBoxButton.YesNo, - MessageBoxImage.Exclamation); - - if (messageBoxResult == MessageBoxResult.Yes) - { - System.IO.File.Delete(userFilePath); - return Settings.Load(); - } - else if (messageBoxResult == MessageBoxResult.No) - { - return null; - } - } - - if (userSettings != null && userSettings.SerializationVersion != Version) - { - Settings.MigrateSettingsToCurrentVersion(userSettings); - - Diagnostics.Debug.Log("File converter settings has been imported from version {0} to version {1}.", userSettings.SerializationVersion, Version); - userSettings.SerializationVersion = Version; - userSettings.Save(); - } - } - else - { - // Load the default settings. - string defaultFilePath = Settings.GetDefaultSettingsFilePath(); - if (File.Exists(defaultFilePath)) - { - Settings defaultSettings = null; - try - { - XmlHelpers.LoadFromFile("Settings", defaultFilePath, out defaultSettings); - settings = defaultSettings; - } - catch (Exception exception) - { - Diagnostics.Debug.LogError("Fail to load file converter default settings. {0}", exception.Message); - } - } - else - { - Diagnostics.Debug.LogError("Default settings not found at path {0}. You should try to reinstall the application.", defaultFilePath); - } - } - - return settings; - } + private bool exitApplicationWhenConversionsFinished = false; + private float durationBetweenEndOfConversionsAndApplicationExit = 3f; + private ObservableCollection conversionPresets = new ObservableCollection(); + private bool checkUpgradeAtStartup = true; + private CultureInfo applicationLanguage; + private int maximumNumberOfSimultaneousConversions; + private bool copyFilesInClipboardAfterConversion = false; public ConversionPreset GetPresetFromName(string presetName) { - return this.conversionPresets.FirstOrDefault(match => match.Name == presetName); - } - - public void Save() - { - this.Clean(); - - // Save the settings in a temporary files (we'll write the settings file when we'll succeed to write the registry keys). - string temporaryFilePath = Settings.GetUserSettingsTemporaryFilePath(); - XmlHelpers.SaveToFile("Settings", temporaryFilePath, this); - - // Compute the registry entries data from settings. - Dictionary> registryEntries = Settings.ComputeRegistryEntriesFromConvertionPresets(this.ConversionPresets); - - // Detect if existing registry configuration need to be modified. - bool registryNeedModifications = Settings.IsRegistryNeedModifications(registryEntries); - - if (registryNeedModifications) - { - // Write the settings in registry. - if (Settings.IsInAdmininstratorPrivileges) - { - // We are in admin mode, write registry ... - bool succeed = Settings.ApplyRegistryModifications(registryEntries); - if (succeed) - { - // ... and copy temporary settings file to the real settings file. - string userFilePath = Settings.GetUserSettingsFilePath(); - File.Copy(temporaryFilePath, userFilePath, true); - File.Delete(temporaryFilePath); - } - } - else - { - // Run the application in admin mode in order to perform modifications. - Settings.RunSaveInAdminMode(); - } - } - else - { - // Copy temporary settings file to the real settings file. - string userFilePath = Settings.GetUserSettingsFilePath(); - File.Copy(temporaryFilePath, userFilePath, true); - File.Delete(temporaryFilePath); - } + return this.conversionPresets.FirstOrDefault(match => match.FullName == presetName); } public void Clean() @@ -280,208 +35,8 @@ namespace FileConverter this.ConversionPresets[index].Clean(); } } - - private static bool ApplyRegistryModifications(Dictionary> registryEntries) - { - if (!Settings.IsInAdmininstratorPrivileges) - { - MessageBox.Show("Can't apply settings in registry because the application is not in administrator privileges. (code 0x04)", "Error", MessageBoxButton.OK, MessageBoxImage.Error); - return false; - } - - RegistryKey registryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\FileConverter", RegistryKeyPermissionCheck.ReadWriteSubTree); - if (registryKey == null) - { - MessageBox.Show("Can't apply settings in registry. (code 0x05)", "Error", MessageBoxButton.OK, MessageBoxImage.Error); - return false; - } - - // Delete previous settings. - string[] subKeyNames = registryKey.GetSubKeyNames(); - for (int index = 0; index < subKeyNames.Length; index++) - { - try - { - registryKey.DeleteSubKey(subKeyNames[index]); - } - catch (Exception) - { - MessageBox.Show("Can't apply settings in registry. (code 0x06)", "Error", MessageBoxButton.OK, MessageBoxImage.Error); - return false; - } - } - - // Apply settings in registry. - foreach (KeyValuePair> registryEntry in registryEntries) - { - string presets = string.Empty; - for (int index = 0; index < registryEntry.Value.Count; index++) - { - if (index > 0) - { - presets += ";"; - } - - presets += registryEntry.Value[index]; - } - - RegistryKey subKey = null; - try - { - subKey = registryKey.CreateSubKey(registryEntry.Key); - } - catch (Exception exception) - { - Diagnostics.Debug.Log(exception.Message); - } - - if (subKey == null) - { - MessageBox.Show("Can't apply settings in registry. (code 0x07)", "Error", MessageBoxButton.OK, MessageBoxImage.Error); - return false; - } - - subKey.SetValue("Presets", presets); - } - - return true; - } - - private static Dictionary> ComputeRegistryEntriesFromConvertionPresets(ICollection conversionPresets) - { - Dictionary> registryEntries = new Dictionary>(); - - foreach (ConversionPreset conversionPreset in conversionPresets) - { - List inputTypes = conversionPreset.InputTypes; - for (int inputIndex = 0; inputIndex < inputTypes.Count; inputIndex++) - { - string inputType = inputTypes[inputIndex].ToLowerInvariant(); - if (!registryEntries.ContainsKey(inputType)) - { - registryEntries.Add(inputType, new List()); - } - - registryEntries[inputType].Add(conversionPreset.Name); - } - } - - return registryEntries; - } - - private static string GetDefaultSettingsFilePath() - { - string path = Assembly.GetEntryAssembly().Location; - path = Path.GetDirectoryName(path); - - if (!Directory.Exists(path)) - { - Directory.CreateDirectory(path); - } - - path = Path.Combine(path, "Settings.default.xml"); - return path; - } - - private static string GetUserSettingsFilePath() - { - string path = PathHelpers.GetUserDataFolderPath(); - path = Path.Combine(path, "Settings.user.xml"); - return path; - } - - private static string GetUserSettingsTemporaryFilePath() - { - string path = PathHelpers.GetUserDataFolderPath(); - path = Path.Combine(path, "Settings.temp.xml"); - return path; - } - - private static bool IsRegistryNeedModifications(Dictionary> registryEntries) - { - // Compare to registry entries. - RegistryKey registryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\FileConverter"); - if (registryKey == null) - { - return true; - } - - string[] subKeyNames = registryKey.GetSubKeyNames(); - if (subKeyNames.Length == registryEntries.Count) - { - for (int index = 0; index < subKeyNames.Length; index++) - { - string subKeyName = subKeyNames[index]; - if (!registryEntries.ContainsKey(subKeyName)) - { - return true; - } - - List presetsList = registryEntries[subKeyName]; - - RegistryKey subKey = registryKey.OpenSubKey(subKeyName); - if (subKey == null) - { - return true; - } - - string presetsString = subKey.GetValue("Presets", string.Empty) as string; - string[] presets = presetsString != null ? presetsString.Split(Settings.PresetSeparator) : new string[0]; - if (presets.Length != presetsList.Count) - { - return true; - } - - for (int presetIndex = 0; presetIndex < presets.Length; presetIndex++) - { - if (presetsList[presetIndex] != presets[presetIndex]) - { - return true; - } - } - } - } - else - { - return true; - } - - return false; - } - - private static void RunSaveInAdminMode() - { - ProcessStartInfo processStartInfo = new ProcessStartInfo(Assembly.GetEntryAssembly().Location, "--apply-settings") - { - UseShellExecute = true, - Verb = "runas", // indicates to elevate privileges - }; - - Process process = new Process - { - EnableRaisingEvents = true, // enable WaitForExit() - StartInfo = processStartInfo - }; - - try - { - process.Start(); - process.WaitForExit(); - } - catch (Exception) - { - MessageBox.Show("Can't apply settings in registry because the application has no administrator privileges. (code 0x08)", "Error", MessageBoxButton.OK, MessageBoxImage.Error); - return; - } - } - - [NotifyPropertyChangedInvocator] - private void OnPropertyChanged([CallerMemberName] string propertyName = null) - { - this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } - - private Settings Merge(Settings settings) + + public Settings Merge(Settings settings) { if (settings == null || settings.conversionPresets == null) { @@ -491,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; } @@ -501,5 +56,208 @@ namespace FileConverter return this; } + + [XmlAttribute] + public int SerializationVersion + { + get; + set; + } = Version; + + [XmlIgnore] + public CultureInfo ApplicationLanguage + { + get + { + return this.applicationLanguage; + } + + set + { + if (this.applicationLanguage != null && this.applicationLanguage.Equals(value)) + { + return; + } + + this.applicationLanguage = value; + if (this.applicationLanguage != null) + { + System.Threading.Thread.CurrentThread.CurrentCulture = this.applicationLanguage; + System.Threading.Thread.CurrentThread.CurrentUICulture = this.applicationLanguage; + } + + this.OnPropertyChanged(); + } + } + + [XmlElement] + public string ApplicationLanguageName + { + get + { + if (this.ApplicationLanguage == null) + { + return string.Empty; + } + + return this.ApplicationLanguage.Name; + } + + set + { + if (string.IsNullOrEmpty(value)) + { + this.ApplicationLanguage = null; + return; + } + + this.ApplicationLanguage = CultureInfo.GetCultureInfo(value); + } + } + + [XmlIgnore] + public ObservableCollection ConversionPresets + { + get + { + return this.conversionPresets; + } + + set + { + this.conversionPresets = value; + this.OnPropertyChanged(); + } + } + + [XmlElement] + public bool ExitApplicationWhenConversionsFinished + { + get + { + return this.exitApplicationWhenConversionsFinished; + } + + set + { + this.exitApplicationWhenConversionsFinished = value; + this.OnPropertyChanged(); + } + } + + [XmlElement] + public float DurationBetweenEndOfConversionsAndApplicationExit + { + get + { + return this.durationBetweenEndOfConversionsAndApplicationExit; + } + + set + { + this.durationBetweenEndOfConversionsAndApplicationExit = value; + this.OnPropertyChanged(); + } + } + + [XmlElement] + public int MaximumNumberOfSimultaneousConversions + { + get + { + return this.maximumNumberOfSimultaneousConversions; + } + + set + { + this.maximumNumberOfSimultaneousConversions = value; + this.OnPropertyChanged(); + } + } + + [XmlElement("ConversionPreset")] + public ConversionPreset[] SerializableConversionPresets + { + get + { + return this.ConversionPresets.ToArray(); + } + + set + { + for (int index = 0; index < value.Length; index++) + { + this.ConversionPresets.Add(value[index]); + } + } + } + + [XmlElement] + public bool CheckUpgradeAtStartup + { + get + { + return this.checkUpgradeAtStartup; + } + + set + { + this.checkUpgradeAtStartup = value; + this.OnPropertyChanged(); + } + } + + [XmlElement] + public bool CopyFilesInClipboardAfterConversion + { + get + { + return this.copyFilesInClipboardAfterConversion; + } + + set + { + this.copyFilesInClipboardAfterConversion = value; + this.OnPropertyChanged(); + } + } + public void OnDeserializationComplete() + { + this.DurationBetweenEndOfConversionsAndApplicationExit = System.Math.Max(0, System.Math.Min(10, this.DurationBetweenEndOfConversionsAndApplicationExit)); + + for (int index = 0; index < this.ConversionPresets.Count; index++) + { + this.ConversionPresets[index].OnDeserializationComplete(); + } + + // Initialize application if it was not deserialized from the settings. + if (this.ApplicationLanguage == null) + { + CultureInfo bestCandidate = null; + CultureInfo currentUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; + foreach (CultureInfo culture in Helpers.GetSupportedCultures()) + { + if (culture.Equals(currentUICulture)) + { + bestCandidate = culture; + break; + } + else if (culture.Equals(currentUICulture.Parent)) + { + bestCandidate = culture; + } + } + + if (bestCandidate != null) + { + this.ApplicationLanguage = bestCandidate; + } + else + { + Diagnostics.Debug.Log("Can't find supported culture info for culture {0}. Fallback to default culture.", currentUICulture); + this.ApplicationLanguage = CultureInfo.GetCultureInfo("en"); + } + } + } } } diff --git a/Application/FileConverter/Settings.default.xml b/Application/FileConverter/Settings.default.xml index 5c104e6..b73161f 100644 --- a/Application/FileConverter/Settings.default.xml +++ b/Application/FileConverter/Settings.default.xml @@ -1,7 +1,5 @@ - true - 3 2 3gp @@ -24,6 +22,8 @@ + + (p)(f) @@ -47,6 +47,8 @@ + + (p)(f) @@ -70,52 +72,8 @@ - (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) @@ -138,6 +96,8 @@ + + (p)(f) @@ -160,6 +120,8 @@ + + (p)(f) @@ -182,18 +144,24 @@ + + (p)(f) + arw bmp + cr2 exr ico jpg jpeg png psd + raf svg tga + tif tiff xcf 3gp @@ -217,15 +185,19 @@ (p)(f) + arw bmp + cr2 exr ico jpg jpeg + raf png psd svg tga + tif tiff xcf 3gp @@ -273,6 +245,8 @@ None + + (p)(f) @@ -282,6 +256,8 @@ aiff None + + (p)(f) @@ -309,6 +285,8 @@ None + + (p)(f) @@ -337,6 +315,8 @@ + + (p)(f) @@ -364,6 +344,8 @@ None + + (p)(f) @@ -375,6 +357,8 @@ + + (p:v)DVD Extraction\(f) @@ -386,12 +370,16 @@ + + (p:v)DVD Extraction\(f) vob None + + (p:m)DVD Extraction\(f) @@ -399,6 +387,8 @@ None + + (p:m)DVD Extraction\(f) @@ -407,12 +397,16 @@ + + (p:m)DVD Extraction\(f) cda None + + (p:m)CDA Extraction\(f) @@ -420,6 +414,8 @@ None + + (p:m)CDA Extraction\(f) @@ -428,21 +424,29 @@ + + (p:m)CDA Extraction\(f) + arw bmp + cr2 exr ico jpg jpeg + raf png psd svg tga + tif tiff xcf webp + dng + nef None @@ -470,18 +474,24 @@ (p)(f) (n:i) of (n:c) + arw bmp + cr2 exr ico jpg jpeg + raf png psd svg tga + tif tiff xcf webp + dng + nef None @@ -490,77 +500,25 @@ (p)(f) - - bmp - exr - ico - jpg - jpeg - png - psd - svg - tga - tiff - xcf - webp - None - - - - - (p)(f)-small - - - bmp - exr - ico - jpg - jpeg - png - psd - svg - tga - tiff - webp - None - - - - - (p)(f) - - - bmp - exr - ico - jpg - jpeg - png - psd - svg - tga - tiff - webp - None - - - - - (p)(f) - + arw bmp + cr2 exr ico jpg jpeg + raf png psd svg tga + tif tiff xcf webp + dng + nef None @@ -571,6 +529,7 @@ bmp + cr2 exr ico jpg @@ -579,6 +538,7 @@ psd svg tga + tif tiff xcf webp @@ -586,14 +546,18 @@ (p)(f) + arw + cr2 bmp exr jpg jpeg + raf png psd svg tga + tif tiff xcf webp @@ -606,8 +570,1110 @@ pptx xls xlsx + dng + nef 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 + dng + nef + None + + + + + (p)(f)-small + + + arw + bmp + cr2 + exr + ico + jpg + jpeg + raf + png + psd + svg + tga + tif + tiff + xcf + webp + dng + nef + None + + + + + + (p)(f) + + + arw + bmp + cr2 + exr + ico + jpg + jpeg + raf + png + psd + svg + tga + tif + tiff + xcf + webp + dng + nef + 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 + dng + nef + None + + + + + (p)(f)-small + + + arw + bmp + cr2 + exr + ico + jpg + jpeg + raf + png + psd + svg + tga + tif + tiff + xcf + webp + dng + nef + None + + + + + + (p)(f) + + + arw + bmp + cr2 + exr + ico + jpg + jpeg + raf + png + psd + svg + tga + tif + tiff + xcf + webp + dng + nef + None + + + + + + (p)(f) + + + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + gif + None + + + + + + + + + (p)(f) (720p) + + + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + gif + None + + + + + + + + + (p)(f) (720p) + + + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + gif + None + + + + + + + + (p)(f) (720p) + + + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + gif + None + + + + + + + + (p)(f) (720p) + + + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + gif + None + + + + + + + + (p)(f) (720p) + + + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + gif + None + + + + + + + + + (p)(f) (1080p) + + + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + gif + None + + + + + + + + + (p)(f) (1080p) + + + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + gif + None + + + + + + + + (p)(f) (1080p) + + + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + gif + None + + + + + + + + (p)(f) (1080p) + + + 3gp + avi + bik + flv + m4v + mkv + mov + mp4 + mpeg + ogv + webm + wmv + gif + None + + + + + + + + (p)(f) (1080p) + + + 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 + dng + nef + None + + + + + (p)(f) + + + arw + bmp + cr2 + exr + ico + jpg + jpeg + raf + png + psd + svg + tga + tif + tiff + xcf + webp + dng + nef + None + + + + + + (p)(f) + + + arw + bmp + cr2 + exr + ico + jpg + jpeg + raf + png + psd + svg + tga + tif + tiff + xcf + webp + dng + nef + 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 + dng + nef + None + + + + + (p)(f) + + + arw + bmp + cr2 + exr + ico + jpg + jpeg + raf + png + psd + svg + tga + tif + tiff + xcf + webp + dng + nef + None + + + + + + (p)(f) + + + arw + bmp + cr2 + exr + ico + jpg + jpeg + raf + png + psd + svg + tga + tif + tiff + xcf + webp + dng + nef + None + + + + + + (p)(f) + true \ No newline at end of file diff --git a/Application/FileConverter/Upgrade/Helpers.cs b/Application/FileConverter/Upgrade/Helpers.cs deleted file mode 100644 index fef9035..0000000 --- a/Application/FileConverter/Upgrade/Helpers.cs +++ /dev/null @@ -1,156 +0,0 @@ -// License: http://www.gnu.org/licenses/gpl.html GPL version 3. - -namespace FileConverter.Upgrade -{ - using System; - using System.IO; - using System.Net; - using System.Text.RegularExpressions; - using System.Threading.Tasks; - using System.Xml; - using System.Xml.Serialization; - - public static class Helpers - { -#if DEBUG - private const string BaseURI = "https://raw.githubusercontent.com/Tichau/FileConverter/development/"; -#else - private const string BaseURI = "https://raw.githubusercontent.com/Tichau/FileConverter/master/"; -#endif - - private static WebClient webClient = new WebClient(); - private static UpgradeVersionDescription currentlyDownloadedVersionDescription; - - public delegate void OnUpgradeOperationCompletedEventHandler(UpgradeVersionDescription upgradeVersionDescription); - - public static async Task GetLatestVersionDescriptionAsync(OnUpgradeOperationCompletedEventHandler onGetCompleteDelegate = null) - { -#if BUILD32 - Uri uri = new Uri(Helpers.BaseURI + "version (x86).xml"); -#else - Uri uri = new Uri(Helpers.BaseURI + "version.xml"); -#endif - - Stream stream = await Helpers.webClient.OpenReadTaskAsync(uri); - - UpgradeVersionDescription upgradeVersionDescription = null; - try - { - XmlRootAttribute xmlRoot = new XmlRootAttribute - { - ElementName = "Version" - }; - - XmlSerializer serializer = new XmlSerializer(typeof(UpgradeVersionDescription), xmlRoot); - - XmlReaderSettings xmlReaderSettings = new XmlReaderSettings - { - IgnoreWhitespace = true, - IgnoreComments = true - }; - - using (XmlReader xmlReader = XmlReader.Create(stream, xmlReaderSettings)) - { - upgradeVersionDescription = (UpgradeVersionDescription)serializer.Deserialize(xmlReader); - } - } - catch (Exception) - { - Diagnostics.Debug.LogError("Error while retrieving change log."); - return null; - } - - onGetCompleteDelegate?.Invoke(upgradeVersionDescription); - - return upgradeVersionDescription; - } - - public static async Task GetChangeLogAsync(UpgradeVersionDescription upgradeVersionDescription, OnUpgradeOperationCompletedEventHandler onGetCompleteDelegate = null) - { - if (upgradeVersionDescription == null) - { - throw new ArgumentNullException(nameof(upgradeVersionDescription)); - } - - Uri uri = new Uri(Helpers.BaseURI + "CHANGELOG.md"); - Stream stream = await Helpers.webClient.OpenReadTaskAsync(uri); - try - { - using (StreamReader reader = new StreamReader(stream)) - { - upgradeVersionDescription.ChangeLog = reader.ReadToEnd(); - } - } - catch (Exception) - { - Diagnostics.Debug.LogError("Error while retrieving change log."); - return null; - } - - onGetCompleteDelegate?.Invoke(upgradeVersionDescription); - - return upgradeVersionDescription.ChangeLog; - } - - public static async Task DownloadInstallerAsync(UpgradeVersionDescription upgradeVersionDescription) - { - if (upgradeVersionDescription == null) - { - throw new ArgumentNullException("upgradeVersionDescription"); - } - - if (Helpers.currentlyDownloadedVersionDescription != null) - { - throw new Exception("The installer download is currently in progress."); - } - - Uri uri = new Uri(upgradeVersionDescription.InstallerURL); - - string fileName = "FileConverter-setup.msi"; - Regex retrieveFileNameRegex = new Regex("/([^/]*)"); - MatchCollection matchCollection = retrieveFileNameRegex.Matches(upgradeVersionDescription.InstallerURL); - if (matchCollection.Count > 0) - { - Match match = matchCollection[matchCollection.Count - 1]; - if (match.Groups.Count > 1) - { - fileName = match.Groups[1].Value; - } - } - - string tempPath = System.IO.Path.GetTempPath(); - string installerPath = System.IO.Path.Combine(tempPath, fileName); - - upgradeVersionDescription.InstallerPath = installerPath; - upgradeVersionDescription.InstallerDownloadInProgress = true; - upgradeVersionDescription.InstallerDownloadProgress = 0; - - Helpers.currentlyDownloadedVersionDescription = upgradeVersionDescription; - - Helpers.webClient.DownloadProgressChanged += Helpers.WebClient_DownloadProgressChanged; - Helpers.webClient.DownloadFileCompleted += Helpers.WebClient_DownloadFileCompleted; - Task downloadTask = Helpers.webClient.DownloadFileTaskAsync(uri, installerPath); - } - - private static void WebClient_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) - { - Helpers.webClient.DownloadProgressChanged -= WebClient_DownloadProgressChanged; - Helpers.webClient.DownloadFileCompleted -= WebClient_DownloadFileCompleted; - - if (Helpers.currentlyDownloadedVersionDescription != null) - { - Helpers.currentlyDownloadedVersionDescription.InstallerDownloadProgress = 100; - Helpers.currentlyDownloadedVersionDescription.InstallerDownloadInProgress = false; - Helpers.currentlyDownloadedVersionDescription = null; - } - } - - private static void WebClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs eventArgs) - { - if (Helpers.currentlyDownloadedVersionDescription != null) - { - Helpers.currentlyDownloadedVersionDescription.InstallerDownloadProgress = eventArgs.ProgressPercentage; - } - } - } -} diff --git a/Application/FileConverter/ValueConverters/ApplicationVersionToApplicationName.cs b/Application/FileConverter/ValueConverters/ApplicationVersionToApplicationName.cs index 514c818..cc93d8c 100644 --- a/Application/FileConverter/ValueConverters/ApplicationVersionToApplicationName.cs +++ b/Application/FileConverter/ValueConverters/ApplicationVersionToApplicationName.cs @@ -17,7 +17,7 @@ namespace FileConverter.ValueConverters FileConverter.Version version = (FileConverter.Version)value; - return string.Format("File Converter v{0}", version.ToString()); + return $"File Converter v{version}"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) diff --git a/Application/FileConverter/ValueConverters/BitrateToString.cs b/Application/FileConverter/ValueConverters/BitrateToString.cs index 213b843..acea132 100644 --- a/Application/FileConverter/ValueConverters/BitrateToString.cs +++ b/Application/FileConverter/ValueConverters/BitrateToString.cs @@ -17,7 +17,7 @@ namespace FileConverter.ValueConverters double bitrate = (double)value; - return string.Format("{0} kbit/s", bitrate.ToString("0")); + return $"{bitrate:0} kbit/s"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) diff --git a/Application/FileConverter/ValueConverters/ChangelogConverter.cs b/Application/FileConverter/ValueConverters/ChangelogConverter.cs new file mode 100644 index 0000000..2b49938 --- /dev/null +++ b/Application/FileConverter/ValueConverters/ChangelogConverter.cs @@ -0,0 +1,59 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ValueConverters +{ + using System; + using System.Globalization; + using System.Windows.Data; + + using FileConverter.Diagnostics; + + public class ChangelogConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + bool header = false; + if (parameter != null) + { + switch (parameter) + { + case string s: + { + if (!bool.TryParse(s, out header)) + { + Debug.LogError($"Invalid parameter {s}"); + } + + break; + } + + case bool b: + header = b; + break; + + default: + Debug.LogError($"Invalid parameter {parameter}"); + break; + } + } + + string content = string.Empty; + if (header) + { + content += Properties.Resources.LicenceHeader1 + "\n"; + content += Properties.Resources.LicenceHeader2 + "\n\n"; + content += Properties.Resources.LicenceHeader3 + "\n\n"; + } + + string changelog = (string)value; + content += changelog; + + return content; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/Application/FileConverter/ValueConverters/ConversionJobToEstimatedRemainingDuration.cs b/Application/FileConverter/ValueConverters/ConversionJobToEstimatedRemainingDuration.cs new file mode 100644 index 0000000..117f9cd --- /dev/null +++ b/Application/FileConverter/ValueConverters/ConversionJobToEstimatedRemainingDuration.cs @@ -0,0 +1,52 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ValueConverters +{ + using System; + using System.Globalization; + using System.Windows.Data; + + using ConversionJobs; + + public class ConversionJobToEstimatedRemainingDuration : IMultiValueConverter + { + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) + { + if (values.Length != 3) + { + return string.Empty; + } + + ConversionState state = (ConversionState)values[0]; + DateTime startTime = (DateTime)values[1]; + float progress = (float)values[2]; + if (progress <= 0f) + { + return string.Empty; + } + + if (state == ConversionState.Unknown || + state == ConversionState.Ready || + state == ConversionState.Failed || + state == ConversionState.Done) + { + return string.Empty; + } + + TimeSpan elapsedTime = DateTime.Now - startTime; + if (elapsedTime.TotalSeconds < 10f) + { + return string.Empty; + } + + double remainingTimeInSeconds = (1 - progress) * elapsedTime.TotalSeconds / progress; + TimeSpan remainingTime = TimeSpan.FromSeconds(Math.Floor(remainingTimeInSeconds)); + return "~" + remainingTime.ToString("g"); + } + + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/Application/FileConverter/ValueConverters/ConversionJobsToProgressState.cs b/Application/FileConverter/ValueConverters/ConversionJobsToProgressState.cs new file mode 100644 index 0000000..dec5575 --- /dev/null +++ b/Application/FileConverter/ValueConverters/ConversionJobsToProgressState.cs @@ -0,0 +1,48 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ValueConverters +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Windows.Data; + using System.Windows.Shell; + + using FileConverter.ConversionJobs; + + public class ConversionJobsToProgressState : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (!(value is IEnumerable)) + { + return TaskbarItemProgressState.None; + } + + IEnumerable jobs = (IEnumerable)value; + + TaskbarItemProgressState progressState = TaskbarItemProgressState.None; + foreach (ConversionJob job in jobs) + { + if (job.State == ConversionState.Failed) + { + progressState = TaskbarItemProgressState.Error; + break; + } + + if (job.State == ConversionState.InProgress) + { + progressState = TaskbarItemProgressState.Normal; + break; + } + } + + return progressState; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/Application/FileConverter/ValueConverters/ConversionJobsToProgressValue.cs b/Application/FileConverter/ValueConverters/ConversionJobsToProgressValue.cs new file mode 100644 index 0000000..95c75a7 --- /dev/null +++ b/Application/FileConverter/ValueConverters/ConversionJobsToProgressValue.cs @@ -0,0 +1,40 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ValueConverters +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Windows.Data; + using System.Windows.Shell; + + using FileConverter.ConversionJobs; + + public class ConversionJobsToProgressValue : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (!(value is IEnumerable)) + { + return TaskbarItemProgressState.None; + } + + IEnumerable jobs = (IEnumerable)value; + + int jobCount = 0; + float progressValue = 0f; + foreach (ConversionJob job in jobs) + { + progressValue += job.Progress; + jobCount++; + } + + return jobCount > 0 ? progressValue / jobCount : 0f; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/Application/FileConverter/ValueConverters/ConversionSettingsRelevant.cs b/Application/FileConverter/ValueConverters/ConversionSettingsRelevant.cs new file mode 100644 index 0000000..4cf79a3 --- /dev/null +++ b/Application/FileConverter/ValueConverters/ConversionSettingsRelevant.cs @@ -0,0 +1,39 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ValueConverters +{ + using System; + using System.Globalization; + using System.Windows.Data; + + public class ConversionSettingsRelevant : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value == null) + { + return null; + } + + if (!(value is IConversionSettings)) + { + throw new ArgumentException("The value must be a conversion preset array."); + } + + IConversionSettings settings = (IConversionSettings)value; + + string key = parameter as string; + if (key == null) + { + throw new ArgumentException("The parameter must be a string value."); + } + + return settings.ContainsKey(key); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/Application/FileConverter/ValueConverters/ConversionStateToBrush.cs b/Application/FileConverter/ValueConverters/ConversionStateToBrush.cs index cdad1c0..3e8c10a 100644 --- a/Application/FileConverter/ValueConverters/ConversionStateToBrush.cs +++ b/Application/FileConverter/ValueConverters/ConversionStateToBrush.cs @@ -5,7 +5,6 @@ namespace FileConverter.ValueConverters using System; using System.Globalization; using System.Windows.Data; - using System.Windows.Media; using FileConverter.ConversionJobs; @@ -13,60 +12,15 @@ namespace FileConverter.ValueConverters { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - if (!(value is ConversionJob.ConversionState)) + if (!(value is ConversionState)) { throw new ArgumentException("The value must be a conversion state."); } - ConversionJob.ConversionState conversionState = (ConversionJob.ConversionState)value; + ConversionState conversionState = (ConversionState)value; string type = parameter as string; - if (type == "Background") - { - switch (conversionState) - { - case ConversionJob.ConversionState.Unknown: - return new SolidColorBrush(Color.FromRgb(230, 230, 230)); - - case ConversionJob.ConversionState.Ready: - return new SolidColorBrush(Color.FromRgb(230, 230, 230)); - - case ConversionJob.ConversionState.InProgress: - return new SolidColorBrush(Color.FromRgb(250, 236, 179)); - - case ConversionJob.ConversionState.Done: - return new SolidColorBrush(Color.FromRgb(200, 230, 201)); - - case ConversionJob.ConversionState.Failed: - return new SolidColorBrush(Color.FromRgb(255, 205, 210)); - } - } - else if (type == "Foreground") - { - switch (conversionState) - { - case ConversionJob.ConversionState.Unknown: - return new SolidColorBrush(Color.FromRgb(128, 128, 128)); - - case ConversionJob.ConversionState.Ready: - return new SolidColorBrush(Color.FromRgb(32, 32, 32)); - - case ConversionJob.ConversionState.InProgress: - return new SolidColorBrush(Color.FromRgb(255, 160, 0)); - - case ConversionJob.ConversionState.Done: - return new SolidColorBrush(Color.FromRgb(56, 142, 60)); - - case ConversionJob.ConversionState.Failed: - return new SolidColorBrush(Color.FromRgb(255, 82, 82)); - } - } - else - { - throw new SystemException("Unknown type."); - } - - throw new SystemException("Unknown state."); + return Application.Current.Resources[$"{conversionState}{type}Brush"]; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) diff --git a/Application/FileConverter/ValueConverters/Generic/BoolToVisibility.cs b/Application/FileConverter/ValueConverters/Generic/BoolToVisibility.cs index 5ecfbcc..5a6d03f 100644 --- a/Application/FileConverter/ValueConverters/Generic/BoolToVisibility.cs +++ b/Application/FileConverter/ValueConverters/Generic/BoolToVisibility.cs @@ -10,18 +10,35 @@ namespace FileConverter.ValueConverters.Generic { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - if (!(value is bool)) + if (value != null && !(value is bool)) { throw new ArgumentException("The value must be a boolean."); } + bool booleanValue = (bool?) value ?? false; + string stringParameter = parameter as string; - string falseResult = stringParameter ?? "Hidden"; + string trueResult = "Visible"; + string falseResult = "Hidden"; + if (!string.IsNullOrEmpty(stringParameter)) + { + string[] results = stringParameter.Split(';'); + Diagnostics.Debug.Assert(results.Length <= 2, "results.Length <= 2"); - bool booleanValue = (bool)value; + if (results.Length >= 1) + { + falseResult = results[0]; + } - return booleanValue ? "Visible" : falseResult; + if (results.Length >= 2) + { + trueResult = results[1]; + } + } + + + return booleanValue ? trueResult : falseResult; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) diff --git a/Application/FileConverter/ValueConverters/Generic/DoubleToTimeString.cs b/Application/FileConverter/ValueConverters/Generic/DoubleToTimeString.cs index 30d0800..d7e533b 100644 --- a/Application/FileConverter/ValueConverters/Generic/DoubleToTimeString.cs +++ b/Application/FileConverter/ValueConverters/Generic/DoubleToTimeString.cs @@ -17,7 +17,7 @@ namespace FileConverter.ValueConverters.Generic double doubleValue = (double)value; - return string.Format("{0} second{1}", doubleValue.ToString("0.#"), doubleValue >= 2 ? "s" : string.Empty); + return $"{doubleValue:0.#} second{(doubleValue >= 2 ? "s" : string.Empty)}"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) diff --git a/Application/FileConverter/ValueConverters/Generic/IcoFileSizeSelectorConverter.cs b/Application/FileConverter/ValueConverters/Generic/IcoFileSizeSelectorConverter.cs new file mode 100644 index 0000000..004fdcc --- /dev/null +++ b/Application/FileConverter/ValueConverters/Generic/IcoFileSizeSelectorConverter.cs @@ -0,0 +1,45 @@ +using System; +using System.Drawing; +using System.Linq; +using System.Reflection; +using System.Windows.Data; +using System.Windows.Media.Imaging; + +namespace FileConverter.ValueConverters.Generic +{ + /// + /// Forces the selection of a given size from the ICO file/resource. + /// If the exact size does not exists, selects the closest smaller if possible otherwise closest higher resolution. + /// If no parameter is given, the smallest frame available will be selected + /// + public class IcoFileSizeSelectorConverter : IValueConverter + { + public virtual object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) + { + var size = string.IsNullOrWhiteSpace(parameter?.ToString()) ? 0 : System.Convert.ToInt32(parameter); + + var uri = value?.ToString()?.Trim(); + if (string.IsNullOrWhiteSpace(uri)) + { + return null; + } + + if (!uri.StartsWith("pack:")) + { + uri = $"pack://application:,,,{uri}"; + } + + var decoder = BitmapDecoder.Create(new Uri(uri), BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnDemand); + + var result = decoder.Frames.Where(f => f.Width <= size).OrderByDescending(f => f.Width).FirstOrDefault() + ?? decoder.Frames.OrderBy(f => f.Width).FirstOrDefault(); + + return result; + } + + public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/Application/FileConverter/ValueConverters/Generic/ObjectToLocalizedString.cs b/Application/FileConverter/ValueConverters/Generic/ObjectToLocalizedString.cs index e7e6edd..5fae50d 100644 --- a/Application/FileConverter/ValueConverters/Generic/ObjectToLocalizedString.cs +++ b/Application/FileConverter/ValueConverters/Generic/ObjectToLocalizedString.cs @@ -12,7 +12,7 @@ namespace FileConverter.ValueConverters.Generic { if (value == null) { - throw new System.ArgumentNullException("value."); + throw new System.ArgumentNullException(nameof(value)); } string stringValue = value.ToString(); diff --git a/Application/FileConverter/ValueConverters/Generic/StringToEnum.cs b/Application/FileConverter/ValueConverters/Generic/StringToEnum.cs index d11984f..66b64ba 100644 --- a/Application/FileConverter/ValueConverters/Generic/StringToEnum.cs +++ b/Application/FileConverter/ValueConverters/Generic/StringToEnum.cs @@ -20,7 +20,7 @@ namespace FileConverter.ValueConverters.Generic string typeName = parameter as string; if (typeName == null) { - throw new ArgumentNullException("parameter", "The parameter must contains the enum type."); + throw new ArgumentNullException(nameof(parameter), "The parameter must contains the enum type."); } Type enumType = Type.GetType(typeName); diff --git a/Application/FileConverter/ValueConverters/Generic/StringToValueType.cs b/Application/FileConverter/ValueConverters/Generic/StringToValueType.cs index 650a959..2a29ba0 100644 --- a/Application/FileConverter/ValueConverters/Generic/StringToValueType.cs +++ b/Application/FileConverter/ValueConverters/Generic/StringToValueType.cs @@ -18,7 +18,7 @@ namespace FileConverter.ValueConverters.Generic string typeName = parameter as string; if (typeName == null) { - throw new ArgumentNullException("parameter", "The parameter must contains a convertible type."); + throw new ArgumentNullException(nameof(parameter), "The parameter must contains a convertible type."); } Type type = Type.GetType(typeName); diff --git a/Application/FileConverter/ValueConverters/OutputTypeEnumToViewModel.cs b/Application/FileConverter/ValueConverters/OutputTypeEnumToViewModel.cs index caa05ee..7d5f95d 100644 --- a/Application/FileConverter/ValueConverters/OutputTypeEnumToViewModel.cs +++ b/Application/FileConverter/ValueConverters/OutputTypeEnumToViewModel.cs @@ -7,7 +7,9 @@ namespace FileConverter.ValueConverters using System.Linq; using System.Windows.Data; - using FileConverter.Windows; + using CommunityToolkit.Mvvm.DependencyInjection; + + using FileConverter.ViewModels; public class OutputTypeEnumToViewModel : IValueConverter { @@ -20,7 +22,10 @@ namespace FileConverter.ValueConverters OutputType outputType = (OutputType)value; - return SettingsWindow.OutputTypeViewModels.FirstOrDefault(match => match.Type == outputType); + SettingsViewModel settingsViewModel = Ioc.Default.GetRequiredService(); + + return settingsViewModel.OutputTypes.Cast() + .FirstOrDefault(match => match.Type == outputType); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) diff --git a/Application/FileConverter/ValueConverters/OutputTypeToVisibility.cs b/Application/FileConverter/ValueConverters/OutputTypeToVisibility.cs index eded1f2..4e8b742 100644 --- a/Application/FileConverter/ValueConverters/OutputTypeToVisibility.cs +++ b/Application/FileConverter/ValueConverters/OutputTypeToVisibility.cs @@ -23,8 +23,7 @@ namespace FileConverter.ValueConverters return "Hidden"; } - OutputType referenceType; - if (!Enum.TryParse(referenceTypeName, out referenceType)) + if (!Enum.TryParse(referenceTypeName, out OutputType referenceType)) { return "Hidden"; } diff --git a/Application/FileConverter/Version.cs b/Application/FileConverter/Version.cs index 08b9f2d..97303bc 100644 --- a/Application/FileConverter/Version.cs +++ b/Application/FileConverter/Version.cs @@ -49,10 +49,10 @@ namespace FileConverter { if (this.Patch == 0) { - return string.Format("{0}.{1}", this.Major, this.Minor); + return $"{this.Major}.{this.Minor}"; } - return string.Format("{0}.{1}.{2}", this.Major, this.Minor, this.Patch); + return $"{this.Major}.{this.Minor}.{this.Patch}"; } public override bool Equals(object obj) diff --git a/Application/FileConverter/ViewModels/DiagnosticsViewModel.cs b/Application/FileConverter/ViewModels/DiagnosticsViewModel.cs new file mode 100644 index 0000000..c6552a0 --- /dev/null +++ b/Application/FileConverter/ViewModels/DiagnosticsViewModel.cs @@ -0,0 +1,47 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ViewModels +{ + using System.ComponentModel; + using System.Windows.Input; + + using CommunityToolkit.Mvvm.ComponentModel; + using CommunityToolkit.Mvvm.DependencyInjection; + using CommunityToolkit.Mvvm.Input; + + using FileConverter.Services; + + /// + /// This class contains properties that the diagnostics View can data bind to. + /// + public class DiagnosticsViewModel : ObservableRecipient + { + private RelayCommand closeCommand; + + /// + /// Initializes a new instance of the DiagnosticsViewModel class. + /// + public DiagnosticsViewModel() + { + } + + public ICommand CloseCommand + { + get + { + if (this.closeCommand == null) + { + this.closeCommand = new RelayCommand(this.Close); + } + + return this.closeCommand; + } + } + + private void Close(CancelEventArgs args) + { + INavigationService navigationService = Ioc.Default.GetRequiredService(); + navigationService.Close(Pages.Diagnostics, args != null); + } + } +} diff --git a/Application/FileConverter/ViewModels/HelpViewModel.cs b/Application/FileConverter/ViewModels/HelpViewModel.cs new file mode 100644 index 0000000..32ab7cb --- /dev/null +++ b/Application/FileConverter/ViewModels/HelpViewModel.cs @@ -0,0 +1,47 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ViewModels +{ + using System.ComponentModel; + using System.Windows.Input; + + using CommunityToolkit.Mvvm.ComponentModel; + using CommunityToolkit.Mvvm.DependencyInjection; + using CommunityToolkit.Mvvm.Input; + + using FileConverter.Services; + + /// + /// This class contains properties that the main View can data bind to. + /// + public class HelpViewModel : ObservableRecipient + { + private RelayCommand closeCommand; + + /// + /// Initializes a new instance of the HelpViewModel class. + /// + public HelpViewModel() + { + } + + public ICommand CloseCommand + { + get + { + if (this.closeCommand == null) + { + this.closeCommand = new RelayCommand(this.Close); + } + + return this.closeCommand; + } + } + + private void Close(CancelEventArgs args) + { + INavigationService navigationService = Ioc.Default.GetRequiredService(); + navigationService.Close(Pages.Help, args != null); + } + } +} diff --git a/Application/FileConverter/Windows/InputExtension.cs b/Application/FileConverter/ViewModels/InputExtension.cs similarity index 62% rename from Application/FileConverter/Windows/InputExtension.cs rename to Application/FileConverter/ViewModels/InputExtension.cs index fcebe97..43f538e 100644 --- a/Application/FileConverter/Windows/InputExtension.cs +++ b/Application/FileConverter/ViewModels/InputExtension.cs @@ -1,15 +1,15 @@ // License: http://www.gnu.org/licenses/gpl.html GPL version 3. -namespace FileConverter +namespace FileConverter.ViewModels { - using System.ComponentModel; - using System.Runtime.CompilerServices; using System.Windows.Media; - using FileConverter.Annotations; + using CommunityToolkit.Mvvm.ComponentModel; + using CommunityToolkit.Mvvm.DependencyInjection; + using FileConverter.ConversionJobs; - public class InputExtension : INotifyPropertyChanged + public class InputExtension : ObservableObject { private readonly Brush defaultBrush = new SolidColorBrush(Color.FromRgb(0, 0, 0)); private readonly Brush errorBrush = new SolidColorBrush(Color.FromRgb(255, 65, 0)); @@ -48,14 +48,9 @@ namespace FileConverter } } - public event PropertyChangedEventHandler PropertyChanged; - public string Name { - get - { - return this.name; - } + get => this.name; set { @@ -66,10 +61,7 @@ namespace FileConverter public Brush ForegroundBrush { - get - { - return this.foregroundBrush; - } + get => this.foregroundBrush; set { @@ -80,10 +72,7 @@ namespace FileConverter public string ToolTip { - get - { - return this.toolTip; - } + get => this.toolTip; set { @@ -92,10 +81,41 @@ namespace FileConverter } } - [NotifyPropertyChangedInvocator] - protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + public bool IsChecked { - this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + get + { + SettingsViewModel settingsViewModel = Ioc.Default.GetRequiredService(); + PresetNode selectedPreset = settingsViewModel.SelectedPreset; + if (selectedPreset == null) + { + return false; + } + + return selectedPreset.Preset.InputTypes.Contains(this.name.ToLowerInvariant()); + } + + set + { + SettingsViewModel settingsViewModel = Ioc.Default.GetRequiredService(); + PresetNode selectedPreset = settingsViewModel.SelectedPreset; + + if (value) + { + selectedPreset?.Preset.AddInputType(this.name.ToLowerInvariant()); + } + else + { + selectedPreset?.Preset.RemoveInputType(this.name.ToLowerInvariant()); + } + + this.OnPropertyChanged(nameof(this.IsChecked)); + } + } + + internal void OnCategoryChanged() + { + this.OnPropertyChanged(nameof(this.IsChecked)); } } } \ No newline at end of file diff --git a/Application/FileConverter/ViewModels/InputExtensionCategory.cs b/Application/FileConverter/ViewModels/InputExtensionCategory.cs new file mode 100644 index 0000000..3eaefcf --- /dev/null +++ b/Application/FileConverter/ViewModels/InputExtensionCategory.cs @@ -0,0 +1,125 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ViewModels +{ + using System.ComponentModel; + using System.Collections.Generic; + + using CommunityToolkit.Mvvm.ComponentModel; + using CommunityToolkit.Mvvm.DependencyInjection; + + public class InputExtensionCategory : ObservableObject + { + private readonly List inputExtensions = new List(); + private string name; + + public InputExtensionCategory(string name) + { + this.Name = name; + } + + public string Name + { + get => this.name; + + set + { + this.name = value; + this.OnPropertyChanged(); + } + } + + public IEnumerable InputExtensions => this.inputExtensions; + + public IEnumerable InputExtensionNames + { + get + { + foreach (InputExtension inputExtension in this.inputExtensions) + { + yield return inputExtension.Name; + } + } + } + + public void AddExtension(string extension) + { + InputExtension inputExtension = this.inputExtensions.Find(match => match.Name == extension); + if (inputExtension == null) + { + inputExtension = new InputExtension(extension); + this.inputExtensions.Add(inputExtension); + + inputExtension.PropertyChanged += this.OnExtensionPropertyChange; + + this.OnPropertyChanged(nameof(this.InputExtensions)); + this.OnPropertyChanged(nameof(this.InputExtensionNames)); + this.OnPropertyChanged(nameof(this.IsChecked)); + } + } + + public bool? IsChecked + { + get + { + SettingsViewModel settingsViewModel = Ioc.Default.GetRequiredService(); + PresetNode selectedPreset = settingsViewModel.SelectedPreset; + if (selectedPreset == null) + { + return false; + } + + bool all = true; + bool none = true; + foreach (string extension in this.InputExtensionNames) + { + bool contains = selectedPreset.Preset.InputTypes.Contains(extension); + all &= contains; + none &= !contains; + } + + if (all) + { + return true; + } + else if (none) + { + return false; + } + + return null; + } + + set + { + SettingsViewModel settingsViewModel = Ioc.Default.GetRequiredService(); + PresetNode selectedPreset = settingsViewModel.SelectedPreset; + + foreach (string extension in this.InputExtensionNames) + { + if (value == true) + { + selectedPreset?.Preset.AddInputType(extension); + } + else + { + selectedPreset?.Preset.RemoveInputType(extension); + } + } + + // Raise property change for extensions. + foreach (InputExtension inputExtension in this.InputExtensions) + { + inputExtension.OnCategoryChanged(); + } + + this.OnPropertyChanged(nameof(this.IsChecked)); + } + } + + private void OnExtensionPropertyChange(object sender, PropertyChangedEventArgs e) + { + this.OnPropertyChanged(nameof(this.IsChecked)); + } + } +} \ No newline at end of file diff --git a/Application/FileConverter/ViewModels/MainViewModel.cs b/Application/FileConverter/ViewModels/MainViewModel.cs new file mode 100644 index 0000000..e50a632 --- /dev/null +++ b/Application/FileConverter/ViewModels/MainViewModel.cs @@ -0,0 +1,145 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ViewModels +{ + using System.Collections.ObjectModel; + using System.ComponentModel; + using System.Windows.Input; + + using CommunityToolkit.Mvvm.ComponentModel; + using CommunityToolkit.Mvvm.DependencyInjection; + using CommunityToolkit.Mvvm.Input; + + using FileConverter.ConversionJobs; + using FileConverter.Services; + + /// + /// This class contains properties that the main View can data bind to. + /// + public class MainViewModel : ObservableRecipient + { + private string informationMessage; + private ObservableCollection conversionJobs; + + private RelayCommand showSettingsCommand; + private RelayCommand showDiagnosticsCommand; + private RelayCommand closeCommand; + + /// + /// Initializes a new instance of the MainViewModel class. + /// + public MainViewModel() + { + IConversionService settingsService = Ioc.Default.GetRequiredService(); + this.ConversionJobs = new ObservableCollection(settingsService.ConversionJobs); + + Application application = Application.Current as Application; + application.OnApplicationTerminate += this.Application_OnApplicationTerminate; + } + + public string InformationMessage + { + get => this.informationMessage; + + private set + { + this.SetProperty(ref this.informationMessage, value); + } + } + + public ObservableCollection ConversionJobs + { + get => this.conversionJobs; + + private set + { + this.SetProperty(ref this.conversionJobs, value); + + foreach (var job in this.conversionJobs) + { + job.PropertyChanged += this.ConversionJob_PropertyChanged; + } + } + } + + public ICommand ShowSettingsCommand + { + get + { + if (this.showSettingsCommand == null) + { + this.showSettingsCommand = new RelayCommand(() => Ioc.Default.GetRequiredService().Show(Pages.Settings)); + } + + return this.showSettingsCommand; + } + } + + public ICommand ShowDiagnosticsCommand + { + get + { + if (this.showDiagnosticsCommand == null) + { + this.showDiagnosticsCommand = new RelayCommand(() => Ioc.Default.GetRequiredService().Show(Pages.Diagnostics)); + } + + return this.showDiagnosticsCommand; + } + } + + public ICommand CloseCommand + { + get + { + if (this.closeCommand == null) + { + this.closeCommand = new RelayCommand(this.Close); + } + + return this.closeCommand; + } + } + + private void Close(CancelEventArgs args) + { + INavigationService navigationService = Ioc.Default.GetRequiredService(); + navigationService.Close(Pages.Main, args != null); + } + + private void ConversionJob_PropertyChanged(object sender, PropertyChangedEventArgs eventArgs) + { + if (eventArgs.PropertyName != "State" && eventArgs.PropertyName != "Progress") + { + return; + } + + this.OnPropertyChanged(nameof(this.ConversionJobs)); + } + + private void Application_OnApplicationTerminate(object sender, ApplicationTerminateArgs eventArgs) + { + if (float.IsNaN(eventArgs.RemainingTimeBeforeTermination)) + { + this.InformationMessage = string.Empty; + return; + } + + int remaingingSeconds = (int)eventArgs.RemainingTimeBeforeTermination; + + if (remaingingSeconds >= 2) + { + this.InformationMessage = string.Format(Properties.Resources.ApplicationWillTerminateInMultipleSeconds, remaingingSeconds); + } + else if (remaingingSeconds == 1) + { + this.InformationMessage = Properties.Resources.ApplicationWillTerminateInOneSecond; + } + + if (remaingingSeconds <= 0) + { + this.InformationMessage = Properties.Resources.ApplicationIsTerminating; + } + } + } +} \ No newline at end of file diff --git a/Application/FileConverter/Windows/OutputTypeViewModel.cs b/Application/FileConverter/ViewModels/OutputTypeViewModel.cs similarity index 96% rename from Application/FileConverter/Windows/OutputTypeViewModel.cs rename to Application/FileConverter/ViewModels/OutputTypeViewModel.cs index ffe7d01..936c977 100644 --- a/Application/FileConverter/Windows/OutputTypeViewModel.cs +++ b/Application/FileConverter/ViewModels/OutputTypeViewModel.cs @@ -1,6 +1,6 @@ // License: http://www.gnu.org/licenses/gpl.html GPL version 3. -namespace FileConverter.Windows +namespace FileConverter.ViewModels { public class OutputTypeViewModel { diff --git a/Application/FileConverter/ViewModels/PresetNode.cs b/Application/FileConverter/ViewModels/PresetNode.cs new file mode 100644 index 0000000..cf8ebd1 --- /dev/null +++ b/Application/FileConverter/ViewModels/PresetNode.cs @@ -0,0 +1,297 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ViewModels +{ + using System.Collections.ObjectModel; + using System.ComponentModel; + using System.Linq; + + using CommunityToolkit.Mvvm.ComponentModel; + + 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.OnPropertyChanged(); + } + } + + 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.OnPropertyChanged(); + this.OnPropertyChanged(nameof(this.HasError)); + } + } + + public string OutputFileNameTemplate + { + get => this.Preset.OutputFileNameTemplate; + + set + { + this.Preset.OutputFileNameTemplate = value; + this.OnPropertyChanged(); + } + } + + 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.OnPropertyChanged(); + this.OnPropertyChanged(nameof(this.HasError)); + } + } + + public ObservableCollection Children + { + get => this.children; + + set + { + this.children = value; + this.OnPropertyChanged(); + } + } + + 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 new file mode 100644 index 0000000..6e616a6 --- /dev/null +++ b/Application/FileConverter/ViewModels/SettingsViewModel.cs @@ -0,0 +1,747 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ViewModels +{ + using System; + using System.IO; + using System.Collections.Generic; + using System.ComponentModel; + using System.Diagnostics; + using System.Globalization; + using System.Linq; + using System.Windows.Data; + using System.Windows.Input; + + using Microsoft.Win32; + + using CommunityToolkit.Mvvm.ComponentModel; + using CommunityToolkit.Mvvm.DependencyInjection; + using CommunityToolkit.Mvvm.Input; + + using FileConverter.Annotations; + using FileConverter.Services; + using FileConverter.Views; + + /// + /// This class contains properties that the settings View can data bind to. + /// + public class SettingsViewModel : ObservableRecipient, IDataErrorInfo + { + private InputExtensionCategory[] inputCategories; + 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 newPresetCommand; + private RelayCommand duplicatePresetCommand; + private RelayCommand importPresetCommand; + private RelayCommand exportPresetCommand; + private RelayCommand removePresetCommand; + private RelayCommand saveCommand; + private RelayCommand closeCommand; + + private ListCollectionView outputTypes; + private CultureInfo[] supportedCultures; + + public event Action OnPresetCreated; + public event Action OnFolderCreated; + + /// + /// Initializes a new instance of the SettingsViewModel class. + /// + public SettingsViewModel() + { + this.getChangeLogContentCommand = new RelayCommand(this.DownloadChangeLogAction); + this.openUrlCommand = new RelayCommand((url) => Process.Start(url)); + this.createFolderCommand = new RelayCommand(this.CreateFolder); + this.newPresetCommand = new RelayCommand(() => this.AddNewPreset(false)); + this.duplicatePresetCommand = new RelayCommand(() => this.AddNewPreset(true), this.CanDuplicateSelectedPreset); + this.importPresetCommand = new RelayCommand(this.ImportPreset); + this.exportPresetCommand = new RelayCommand(this.ExportSelectedPreset, this.CanExportSelectedPreset); + this.removePresetCommand = new RelayCommand(this.RemoveSelectedPreset, this.CanRemoveSelectedPreset); + this.saveCommand = new RelayCommand(this.SaveSettings, this.CanSaveSettings); + this.closeCommand = new RelayCommand(this.CloseSettings); + + ISettingsService settingsService = Ioc.Default.GetRequiredService(); + this.Settings = settingsService.Settings; + + List outputTypeViewModels = new List(); + outputTypeViewModels.Add(new OutputTypeViewModel(OutputType.Ogg)); + outputTypeViewModels.Add(new OutputTypeViewModel(OutputType.Mp3)); + outputTypeViewModels.Add(new OutputTypeViewModel(OutputType.Aac)); + outputTypeViewModels.Add(new OutputTypeViewModel(OutputType.Flac)); + outputTypeViewModels.Add(new OutputTypeViewModel(OutputType.Wav)); + outputTypeViewModels.Add(new OutputTypeViewModel(OutputType.Mkv)); + outputTypeViewModels.Add(new OutputTypeViewModel(OutputType.Mp4)); + outputTypeViewModels.Add(new OutputTypeViewModel(OutputType.Ogv)); + outputTypeViewModels.Add(new OutputTypeViewModel(OutputType.Webm)); + outputTypeViewModels.Add(new OutputTypeViewModel(OutputType.Avi)); + outputTypeViewModels.Add(new OutputTypeViewModel(OutputType.Png)); + outputTypeViewModels.Add(new OutputTypeViewModel(OutputType.Jpg)); + outputTypeViewModels.Add(new OutputTypeViewModel(OutputType.Webp)); + outputTypeViewModels.Add(new OutputTypeViewModel(OutputType.Ico)); + outputTypeViewModels.Add(new OutputTypeViewModel(OutputType.Gif)); + outputTypeViewModels.Add(new OutputTypeViewModel(OutputType.Pdf)); + this.outputTypes = new ListCollectionView(outputTypeViewModels); + this.outputTypes.GroupDescriptions.Add(new PropertyGroupDescription("Category")); + + this.SupportedCultures = Helpers.GetSupportedCultures().ToArray(); + + this.InitializeCompatibleInputExtensions(); + this.InitializePresetFolders(); + } + + public IEnumerable InputCategories + { + get + { + if (this.inputCategories == null) + { + yield break; + } + + for (int index = 0; index < this.inputCategories.Length; index++) + { + InputExtensionCategory category = this.inputCategories[index]; + if (this.SelectedPreset == null || Helpers.IsOutputTypeCompatibleWithCategory(this.SelectedPreset.Preset.OutputType, category.Name)) + { + yield return category; + } + } + } + } + + public InputPostConversionAction[] InputPostConversionActions => new[] + { + InputPostConversionAction.None, + InputPostConversionAction.MoveInArchiveFolder, + InputPostConversionAction.Delete, + }; + + public PresetFolderNode PresetsRootFolder + { + get => this.presetsRootFolder; + + set + { + this.presetsRootFolder = value; + this.OnPropertyChanged(); + } + } + + 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.OnPropertyChanged(); + } + } + + public PresetFolderNode SelectedFolder + { + get => this.selectedFolder; + + set + { + this.selectedFolder = value; + + this.OnPropertyChanged(); + this.OnPropertyChanged(nameof(this.SelectedItem)); + this.removePresetCommand?.NotifyCanExecuteChanged(); + this.exportPresetCommand?.NotifyCanExecuteChanged(); + this.duplicatePresetCommand?.NotifyCanExecuteChanged(); + } + } + + public PresetNode SelectedPreset + { + get => this.selectedPreset; + + set + { + if (this.selectedPreset != null) + { + this.selectedPreset.Preset.PropertyChanged -= this.SelectedPresetPropertyChanged; + } + + this.selectedPreset = value; + + if (this.selectedPreset != null) + { + this.selectedPreset.Preset.PropertyChanged += this.SelectedPresetPropertyChanged; + } + + this.OnPropertyChanged(); + this.OnPropertyChanged(nameof(this.SelectedItem)); + this.OnPropertyChanged(nameof(this.InputCategories)); + this.removePresetCommand?.NotifyCanExecuteChanged(); + this.exportPresetCommand?.NotifyCanExecuteChanged(); + this.duplicatePresetCommand?.NotifyCanExecuteChanged(); + } + } + + public Settings Settings + { + get => this.settings; + + set + { + this.settings = value; + this.OnPropertyChanged(); + } + } + + public CultureInfo[] SupportedCultures + { + get => this.supportedCultures; + set + { + this.supportedCultures = value; + this.OnPropertyChanged(); + } + } + + public ListCollectionView OutputTypes + { + get => this.outputTypes; + set + { + this.outputTypes = value; + this.OnPropertyChanged(); + } + } + + public bool DisplaySeeChangeLogLink + { + get + { + return this.displaySeeChangeLogLink; + } + + private set + { + this.displaySeeChangeLogLink = value; + + this.OnPropertyChanged(); + } + } + + public ICommand GetChangeLogContentCommand => this.getChangeLogContentCommand; + + public ICommand OpenUrlCommand => this.openUrlCommand; + + public ICommand CreateFolderCommand => this.createFolderCommand; + + public ICommand AddNewPresetCommand => this.newPresetCommand; + + public ICommand DuplicatePresetCommand => this.duplicatePresetCommand; + + public ICommand ImportPresetCommand => this.importPresetCommand; + + public ICommand ExportPresetCommand => this.exportPresetCommand; + + 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 + { + string nodeError = this.CheckErrorRecursively(this.presetsRootFolder); + if (!string.IsNullOrEmpty(nodeError)) + { + return nodeError; + } + + return string.Empty; + } + } + + public string this[string columnName] => this.Error; + + [NotNull] + public string ImportDirectoryPath + { + get + { + string path = FileConverter.Registry.GetValue(FileConverter.Registry.Keys.ImportInitialFolder, Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)); + if (!Directory.Exists(path)) + { + path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); + } + + return path; + } + + set + { + if (!Directory.Exists(value)) + { + return; + } + + FileConverter.Registry.SetValue(FileConverter.Registry.Keys.ImportInitialFolder, value); + } + } + + private string CheckErrorRecursively(AbstractTreeNode node) + { + string nodeError = node.Error; + if (!string.IsNullOrEmpty(nodeError)) + { + return nodeError; + } + + if (node is PresetFolderNode folder) + { + foreach (AbstractTreeNode child in folder.Children) + { + nodeError = this.CheckErrorRecursively(child); + if (!string.IsNullOrEmpty(nodeError)) + { + return nodeError; + } + } + } + + return string.Empty; + } + + private void SelectedPresetPropertyChanged(object sender, PropertyChangedEventArgs eventArgs) + { + if (eventArgs.PropertyName == "OutputType") + { + this.OnPropertyChanged(nameof(this.InputCategories)); + } + + this.saveCommand.NotifyCanExecuteChanged(); + } + + private void NodePropertyChanged(object sender, PropertyChangedEventArgs eventArgs) + { + this.saveCommand.NotifyCanExecuteChanged(); + } + + private void DownloadChangeLogAction() + { + IUpgradeService upgradeService = Ioc.Default.GetRequiredService(); + upgradeService.DownloadChangeLog(); + this.DisplaySeeChangeLogLink = false; + } + + private void InitializeCompatibleInputExtensions() + { + List categories = new List(); + for (int index = 0; index < Helpers.CompatibleInputExtensions.Length; index++) + { + string compatibleInputExtension = Helpers.CompatibleInputExtensions[index]; + string extensionCategory = Helpers.GetExtensionCategory(compatibleInputExtension); + InputExtensionCategory category = categories.Find(match => match.Name == extensionCategory); + if (category == null) + { + category = new InputExtensionCategory(extensionCategory); + categories.Add(category); + } + + category.AddExtension(compatibleInputExtension); + } + + this.inputCategories = categories.ToArray(); + this.OnPropertyChanged(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 = this.CreateFolderNode(folderName, parent); + } + + parent = subFolder; + } + + this.CreatePresetNode(preset, parent); + } + + this.OnPropertyChanged(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 = Ioc.Default.GetRequiredService(); + settingsService.RevertSettings(); + + INavigationService navigationService = Ioc.Default.GetRequiredService(); + navigationService.Close(Pages.Settings, args != null); + } + + private bool CanSaveSettings() + { + 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 = Ioc.Default.GetRequiredService(); + settingsService.SaveSettings(); + + INavigationService navigationService = Ioc.Default.GetRequiredService(); + 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.NotifyCanExecuteChanged(); + + this.OnFolderCreated(); + } + + private bool CanDuplicateSelectedPreset() + { + return this.SelectedPreset != null; + } + + private void AddNewPreset(bool duplicate) + { + 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. + string presetName = Properties.Resources.DefaultPresetName; + int index = 1; + while (parent.Children.Any(match => match is PresetNode folder && folder.Preset.ShortName == presetName)) + { + index++; + presetName = $"{Properties.Resources.DefaultPresetName} ({index})"; + } + + // Create preset by copying the selected one. + ConversionPreset newPreset = null; + if (this.SelectedPreset != null && duplicate) + { + newPreset = new ConversionPreset(presetName, this.SelectedPreset.Preset); + } + else + { + newPreset = new ConversionPreset(presetName, OutputType.Mkv, new string[0]); + } + + PresetNode node = new PresetNode(newPreset, parent); + + parent.Children.Insert(insertIndex, node); + + node.PropertyChanged += this.NodePropertyChanged; + + this.SelectedItem = node; + + this.OnPresetCreated.Invoke(); + + this.removePresetCommand.NotifyCanExecuteChanged(); + this.saveCommand.NotifyCanExecuteChanged(); + } + + private void ImportPreset() + { + OpenFileDialog openFileDialog = new OpenFileDialog + { + Title = "Import presets", + Filter = "Preset file (*.xml)|*.xml", + InitialDirectory = this.ImportDirectoryPath, + }; + + if (openFileDialog.ShowDialog() == true) + { + if (!File.Exists(openFileDialog.FileName)) + { + Diagnostics.Debug.LogError("File does not exists."); + } + + string directoryPath = Path.GetDirectoryName(openFileDialog.FileName); + if (!string.IsNullOrEmpty(directoryPath)) + { + this.ImportDirectoryPath = directoryPath; + } + + List presetsToImport = new List(); + XmlHelpers.LoadFromFile("Presets", openFileDialog.FileName, out presetsToImport); + + // Add imported preset to preset tree. + bool itemSelected = false; + foreach (ConversionPreset conversionPreset in presetsToImport) + { + PresetFolderNode parent = this.PresetsRootFolder; + foreach (string folderName in conversionPreset.ParentFoldersNames) + { + PresetFolderNode folderNode = parent.Children.FirstOrDefault(match => match is PresetFolderNode && match.Name == folderName) as PresetFolderNode; + if (folderNode == null) + { + folderNode = this.CreateFolderNode(folderName, parent); + + if (!itemSelected) + { + this.SelectedItem = folderNode; + itemSelected = true; + } + } + + parent = folderNode; + } + + PresetNode node = this.CreatePresetNode(conversionPreset, parent); + if (!itemSelected) + { + this.SelectedItem = node; + itemSelected = true; + } + } + } + } + + private void ExportSelectedPreset() + { + SaveFileDialog saveFileDialog = new SaveFileDialog + { + Title = "Export selected preset or folder", + Filter = "Preset file (*.xml)|*.xml", + InitialDirectory = this.ImportDirectoryPath, + }; + + if (saveFileDialog.ShowDialog() == true) + { + string filePath = saveFileDialog.FileName; + string directoryPath = Path.GetDirectoryName(filePath); + if (!string.IsNullOrEmpty(directoryPath)) + { + this.ImportDirectoryPath = directoryPath; + } + + if (Path.GetExtension(filePath) != ".xml") + { + filePath += ".xml"; + } + + this.settings.ConversionPresets.Clear(); + this.ComputePresetsParentFoldersNamesAndFillSettings(this.presetsRootFolder, new List()); + + List presetsToExport = new List(); + this.FillWithPresetsRecursively(this.SelectedItem, presetsToExport); + + XmlHelpers.SaveToFile("Presets", filePath, presetsToExport); + } + } + + private bool CanExportSelectedPreset() + { + return this.SelectedItem != null; + } + + private void RemoveSelectedPreset() + { + this.SelectedItem.PropertyChanged -= this.NodePropertyChanged; + + this.SelectedItem.Parent.Children.Remove(this.SelectedItem); + + this.SelectedItem = null; + + this.removePresetCommand.NotifyCanExecuteChanged(); + this.saveCommand.NotifyCanExecuteChanged(); + } + + private bool CanRemoveSelectedPreset() + { + return this.SelectedItem != null; + } + + protected override void OnDeactivated() + { + base.OnDeactivated(); + + 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); + } + } + } + + private void FillWithPresetsRecursively(AbstractTreeNode node, List presets) + { + if (node is PresetNode presetNode) + { + presets.Add(presetNode.Preset); + } + else if (node is PresetFolderNode folder) + { + foreach (AbstractTreeNode childNode in folder.Children) + { + this.FillWithPresetsRecursively(childNode, presets); + } + } + } + + private PresetFolderNode CreateFolderNode(string folderName, PresetFolderNode parent) + { + PresetFolderNode subFolder = new PresetFolderNode(folderName, parent); + parent.Children.Add(subFolder); + + subFolder.PropertyChanged += this.NodePropertyChanged; + return subFolder; + } + + private PresetNode CreatePresetNode(ConversionPreset preset, PresetFolderNode parent) + { + PresetNode presetNode = new PresetNode(preset, parent); + parent.Children.Add(presetNode); + + presetNode.PropertyChanged += this.NodePropertyChanged; + return presetNode; + } + } +} diff --git a/Application/FileConverter/ViewModels/UpgradeViewModel.cs b/Application/FileConverter/ViewModels/UpgradeViewModel.cs new file mode 100644 index 0000000..2a9c00c --- /dev/null +++ b/Application/FileConverter/ViewModels/UpgradeViewModel.cs @@ -0,0 +1,93 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.ViewModels +{ + using System.ComponentModel; + using System.Windows.Input; + + using CommunityToolkit.Mvvm.ComponentModel; + using CommunityToolkit.Mvvm.DependencyInjection; + using CommunityToolkit.Mvvm.Input; + + using FileConverter.Services; + + /// + /// This class contains properties that the upgrade View can data bind to. + /// + public class UpgradeViewModel : ObservableRecipient + { + private readonly IUpgradeService upgradeService; + + private RelayCommand downloadInstallerCommand; + private RelayCommand launchInstallerCommand; + private RelayCommand closeCommand; + + /// + /// Initializes a new instance of the UpgradeViewModel class. + /// + public UpgradeViewModel() + { + this.upgradeService = Ioc.Default.GetRequiredService(); + this.upgradeService.DownloadChangeLog(); + } + + public ICommand DownloadInstallerCommand + { + get + { + if (this.downloadInstallerCommand == null) + { + this.downloadInstallerCommand = new RelayCommand(this.ExecuteDownloadInstallerCommand); + } + + return this.downloadInstallerCommand; + } + } + + public ICommand LaunchInstallerCommand + { + get + { + if (this.launchInstallerCommand == null) + { + this.launchInstallerCommand = new RelayCommand(this.ExecuteLaunchInstallerCommand); + } + + return this.launchInstallerCommand; + } + } + + public ICommand CloseCommand + { + get + { + if (this.closeCommand == null) + { + this.closeCommand = new RelayCommand(this.Close); + } + + return this.closeCommand; + } + } + + private void ExecuteDownloadInstallerCommand() + { + this.upgradeService.StartUpgrade(); + + INavigationService navigationService = Ioc.Default.GetRequiredService(); + navigationService.Close(Pages.Upgrade, false); + } + + private void ExecuteLaunchInstallerCommand() + { + INavigationService navigationService = Ioc.Default.GetRequiredService(); + navigationService.Close(Pages.Upgrade, false); + } + + private void Close(CancelEventArgs args) + { + INavigationService navigationService = Ioc.Default.GetRequiredService(); + navigationService.Close(Pages.Upgrade, args != null); + } + } +} diff --git a/Application/FileConverter/ViewModels/ViewModelLocator.cs b/Application/FileConverter/ViewModels/ViewModelLocator.cs new file mode 100644 index 0000000..24e2430 --- /dev/null +++ b/Application/FileConverter/ViewModels/ViewModelLocator.cs @@ -0,0 +1,52 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +/* + In App.xaml: + + + + + In the View: + DataContext="{Binding Source={StaticResource Locator}, Path=ViewModelName}" +*/ + +namespace FileConverter.ViewModels +{ + using CommunityToolkit.Mvvm.DependencyInjection; + using Microsoft.Extensions.DependencyInjection; + + /// + /// This class contains static references to all the view models in the + /// application and provides an entry point for the bindings. + /// + public class ViewModelLocator + { + /// + /// Initializes a new instance of the ViewModelLocator class. + /// + public ViewModelLocator() + { + } + + public HelpViewModel Help => Ioc.Default.GetRequiredService(); + + public MainViewModel Main => Ioc.Default.GetRequiredService(); + + public UpgradeViewModel Upgrade => Ioc.Default.GetRequiredService(); + + public SettingsViewModel Settings => Ioc.Default.GetRequiredService(); + + public DiagnosticsViewModel Diagnostics => Ioc.Default.GetRequiredService(); + + internal void RegisterViewModels(ServiceCollection services) + { + services + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton(); + } + } +} \ No newline at end of file diff --git a/Application/FileConverter/Views/BindableSelectedItemBehavior.cs b/Application/FileConverter/Views/BindableSelectedItemBehavior.cs new file mode 100644 index 0000000..b1ccc2f --- /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 Microsoft.Xaml.Behaviors; + +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/Windows/DiagnosticsWindow.xaml b/Application/FileConverter/Views/DiagnosticsWindow.xaml similarity index 50% rename from Application/FileConverter/Windows/DiagnosticsWindow.xaml rename to Application/FileConverter/Views/DiagnosticsWindow.xaml index de5d142..d0eb5eb 100644 --- a/Application/FileConverter/Windows/DiagnosticsWindow.xaml +++ b/Application/FileConverter/Views/DiagnosticsWindow.xaml @@ -1,4 +1,4 @@ - + Height="600" Width="800" Icon="/FileConverter;component/Resources/ApplicationIcon.ico" + DataContext="{Binding Diagnostics, Source={StaticResource Locator}}"> + + + + + - + - + + + + + + + + + + + + diff --git a/Application/FileConverter/Views/MainWindow.xaml.cs b/Application/FileConverter/Views/MainWindow.xaml.cs new file mode 100644 index 0000000..2328c7e --- /dev/null +++ b/Application/FileConverter/Views/MainWindow.xaml.cs @@ -0,0 +1,14 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.Views +{ + using System.Windows; + + public partial class MainWindow : Window + { + public MainWindow() + { + this.InitializeComponent(); + } + } +} diff --git a/Application/FileConverter/Views/Resources/Colors.xaml b/Application/FileConverter/Views/Resources/Colors.xaml new file mode 100644 index 0000000..06ccdb7 --- /dev/null +++ b/Application/FileConverter/Views/Resources/Colors.xaml @@ -0,0 +1,97 @@ + + + #00FFFFFF + + #CCE4F7 + #76C8FE + #0171BB + #004B82 + #074078 + + #808080 + #4D4D4D + #202020 + #BC0D01 + #E9AB01 + #0EAF80 + #E91101 + + #FFFFFF + #E0E0E0 + #FFA88C + #FFF3D1 + #BFFAE8 + #FFD4D1 + + #FCF8F6 + #D0D0D0 + #FDFDFD + #E0EEF9 + #F3EFED + #D3D0CE + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Application/FileConverter/Views/Resources/ConversionPresetTemplates.xaml b/Application/FileConverter/Views/Resources/ConversionPresetTemplates.xaml new file mode 100644 index 0000000..38f767a --- /dev/null +++ b/Application/FileConverter/Views/Resources/ConversionPresetTemplates.xaml @@ -0,0 +1,712 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Application/FileConverter/Views/Resources/CustomStyles.xaml b/Application/FileConverter/Views/Resources/CustomStyles.xaml new file mode 100644 index 0000000..d1d705c --- /dev/null +++ b/Application/FileConverter/Views/Resources/CustomStyles.xaml @@ -0,0 +1,175 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Application/FileConverter/Views/SettingsWindow.xaml b/Application/FileConverter/Views/SettingsWindow.xaml new file mode 100644 index 0000000..019b13b --- /dev/null +++ b/Application/FileConverter/Views/SettingsWindow.xaml @@ -0,0 +1,489 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - diff --git a/Application/FileConverter/Windows/MainWindow.xaml.cs b/Application/FileConverter/Windows/MainWindow.xaml.cs deleted file mode 100644 index 0e6fe95..0000000 --- a/Application/FileConverter/Windows/MainWindow.xaml.cs +++ /dev/null @@ -1,198 +0,0 @@ -// License: http://www.gnu.org/licenses/gpl.html GPL version 3. - -namespace FileConverter -{ - using System.ComponentModel; - using System.Runtime.CompilerServices; - using System.Windows; - - using FileConverter.Annotations; - using FileConverter.Windows; - - public partial class MainWindow : Window, INotifyPropertyChanged - { - private DiagnosticsWindow diagnosticsWindow; - private SettingsWindow settingsWindow; - private UpgradeWindow upgradeWindow; - - private string informationMessage; - - public MainWindow() - { - this.InitializeComponent(); - - Application application = Application.Current as Application; - - application.OnApplicationTerminate += this.Application_OnApplicationTerminate; - - this.ConverterJobsList.ItemsSource = application.ConvertionJobs; - - if (application.HideMainWindow) - { - this.Hide(); - } - - if (application.Verbose) - { - this.ShowDiagnosticsWindow(); - } - - if (application.ShowSettings) - { - this.ShowSettingsWindow(); - this.settingsWindow.OnSettingsWindowHide += this.SettingsWindow_Closed; - } - } - - public event PropertyChangedEventHandler PropertyChanged; - - public string InformationMessage - { - get - { - return this.informationMessage; - } - - private set - { - this.informationMessage = value; - this.OnPropertyChanged(); - } - } - - public void OnNewVersionReleased(UpgradeVersionDescription upgradeVersionDescription) - { - this.ShowUpgradeWindow(); - this.upgradeWindow.VersionDescription = upgradeVersionDescription; - } - - [NotifyPropertyChangedInvocator] - protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) - { - PropertyChangedEventHandler handler = this.PropertyChanged; - if (handler != null) - { - handler(this, new PropertyChangedEventArgs(propertyName)); - } - } - - protected override void OnClosing(CancelEventArgs eventArgs) - { - base.OnClosing(eventArgs); - - Application application = Application.Current as Application; - - if (application.UpgradeVersionDescription != null && application.UpgradeVersionDescription.NeedToUpgrade && !application.UpgradeVersionDescription.InstallerDownloadDone) - { - eventArgs.Cancel = true; - this.ShowUpgradeWindow(); - this.upgradeWindow.VersionDescription = application.UpgradeVersionDescription; - } - } - - private void SettingsButton_OnClick(object sender, RoutedEventArgs e) - { - this.ShowSettingsWindow(); - } - - private void SettingsWindow_Closed(object sender, System.EventArgs e) - { - this.settingsWindow.OnSettingsWindowHide -= this.SettingsWindow_Closed; - this.Close(); - } - - private void DiagnosticsButton_OnClick(object sender, RoutedEventArgs e) - { - this.ShowDiagnosticsWindow(); - } - - private void ShowDiagnosticsWindow() - { - if (this.diagnosticsWindow != null && this.diagnosticsWindow.IsVisible) - { - return; - } - else - { - this.diagnosticsWindow = new DiagnosticsWindow(); - } - - Application application = Application.Current as Application; - application?.CancelAutoExit(); - this.diagnosticsWindow.Show(); - } - - private void ShowSettingsWindow() - { - if (this.settingsWindow != null && this.settingsWindow.IsVisible) - { - return; - } - else - { - this.settingsWindow = new SettingsWindow(); - } - - Application application = Application.Current as Application; - application?.CancelAutoExit(); - this.settingsWindow.Show(); - } - - private void ShowUpgradeWindow() - { - if (this.upgradeWindow != null && this.upgradeWindow.IsVisible) - { - return; - } - else if (this.upgradeWindow == null) - { - this.upgradeWindow = new UpgradeWindow(); - this.upgradeWindow.Closed += this.UpgradeWindow_Closed; - } - - Application application = Application.Current as Application; - application?.CancelAutoExit(); - this.upgradeWindow.Show(); - } - - private void UpgradeWindow_Closed(object sender, System.EventArgs e) - { - Application application = Application.Current as Application; - - if (this.IsVisible) - { - return; - } - - if (application.UpgradeVersionDescription != null && application.UpgradeVersionDescription.NeedToUpgrade && application.UpgradeVersionDescription.InstallerDownloadDone) - { - this.Close(); - } - } - - private void Application_OnApplicationTerminate(object sender, ApplicationTerminateArgs eventArgs) - { - if (float.IsNaN(eventArgs.RemainingTimeBeforeTermination)) - { - this.InformationMessage = string.Empty; - return; - } - - int remaingingSeconds = (int)eventArgs.RemainingTimeBeforeTermination; - - if (remaingingSeconds >= 2) - { - this.InformationMessage = string.Format(Properties.Resources.ApplicationWillTerminateInMultipleSeconds, remaingingSeconds); - } - else if (remaingingSeconds == 1) - { - this.InformationMessage = Properties.Resources.ApplicationWillTerminateInOneSecond; - } - - if (remaingingSeconds <= 0) - { - this.InformationMessage = Properties.Resources.ApplicationIsTerminating; - } - } - } -} diff --git a/Application/FileConverter/Windows/SettingsWindow.xaml b/Application/FileConverter/Windows/SettingsWindow.xaml deleted file mode 100644 index da3a9f7..0000000 --- a/Application/FileConverter/Windows/SettingsWindow.xaml +++ /dev/null @@ -1,1046 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -