diff --git a/Application/FileConverter/Application.xaml b/Application/FileConverter/Application.xaml index 95caf71..67f9e09 100644 --- a/Application/FileConverter/Application.xaml +++ b/Application/FileConverter/Application.xaml @@ -1,11 +1,21 @@  + 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 30efb2b..997d56c 100644 --- a/Application/FileConverter/Application.xaml.cs +++ b/Application/FileConverter/Application.xaml.cs @@ -17,82 +17,37 @@ namespace FileConverter { using System; using System.Collections.Generic; - using System.Collections.ObjectModel; + using System.Diagnostics; using System.Threading; - using System.Threading.Tasks; using System.Windows; using FileConverter.ConversionJobs; - using FileConverter.Diagnostics; - using FileConverter.Windows; + using FileConverter.Services; + using FileConverter.Views; + + using GalaSoft.MvvmLight.Ioc; + + 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 = 1, + Minor = 2, + Patch = 3, + }; 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 - { - get - { - return Application.Version; - } - } - - 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 static Version ApplicationVersion => Application.Version; public void CancelAutoExit() { @@ -108,12 +63,36 @@ namespace FileConverter { base.OnStartup(e); + this.RegisterServices(); + this.Initialize(); + // Navigate to the wanted view. + INavigationService navigationService = SimpleIoc.Default.GetInstance(); + + if (this.showHelp) + { + navigationService.NavigateTo(Pages.Help); + return; + } + if (this.needToRunConversionThread) { - Thread fileConvertionThread = Helpers.InstantiateThread("ConversionQueueThread", this.ConvertFiles); - fileConvertionThread.Start(); + navigationService.NavigateTo(Pages.Main); + + IConversionService conversionService = SimpleIoc.Default.GetInstance(); + conversionService.ConversionJobsTerminated += this.ConversionService_ConversionJobsTerminated; + conversionService.ConvertFilesAsync(); + } + + if (this.showSettings) + { + navigationService.NavigateTo(Pages.Settings); + } + + if (this.verbose) + { + navigationService.NavigateTo(Pages.Diagnostics); } } @@ -122,24 +101,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 = SimpleIoc.Default.GetInstance(); + + 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 +128,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 +150,47 @@ namespace FileConverter this.Shutdown(); } + private void RegisterServices() + { + if (this.TryFindResource("Settings") == null) + { + Debug.LogError("Can't retrieve conversion service."); + this.Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown())); + } + + if (this.TryFindResource("Locator") == null) + { + Debug.LogError("Can't retrieve view model locator."); + this.Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown())); + } + + if (this.TryFindResource("Conversions") == null) + { + Debug.LogError("Can't retrieve conversion service."); + this.Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown())); + } + + if (this.TryFindResource("Navigation") == null) + { + Debug.LogError("Can't retrieve navigation service."); + this.Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown())); + } + + if (this.TryFindResource("Upgrade") == null) + { + Debug.LogError("Can't retrieve navigation service."); + this.Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown())); + } + + INavigationService navigationService = SimpleIoc.Default.GetInstance(); + + navigationService.RegisterPage(Pages.Help, false); + navigationService.RegisterPage(Pages.Main, false); + navigationService.RegisterPage(Pages.Settings, true); + navigationService.RegisterPage(Pages.Diagnostics, true); + navigationService.RegisterPage(Pages.Upgrade, true); + } + private void Initialize() { #if BUILD32 @@ -189,12 +205,11 @@ namespace FileConverter #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"; + System.Array.Resize(ref args, 3); + args[1] = "--settings"; + args[2] = "--verbose"; } + #endif // Log arguments. @@ -208,10 +223,8 @@ 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; } @@ -244,8 +257,7 @@ namespace FileConverter return; case "settings": - this.ShowSettings = true; - this.HideMainWindow = true; + this.showSettings = true; break; case "apply-settings": @@ -267,7 +279,7 @@ namespace FileConverter case "verbose": { - this.Verbose = true; + this.verbose = true; } break; @@ -283,46 +295,26 @@ namespace FileConverter } } - // Load settigns. - Debug.Log("Load settings..."); - this.Settings = Settings.Load(); - if (this.Settings == null) + ISettingsService settingsService = SimpleIoc.Default.GetInstance(); + 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())); return; } - - if (this.Settings.MaximumNumberOfSimultaneousConversions <= 0) + + // 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 = SimpleIoc.Default.GetInstance(); + 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,7 +325,9 @@ namespace FileConverter if (conversionPreset != null) { - // Create convertion jobs. + IConversionService conversionService = SimpleIoc.Default.GetInstance(); + + // Create conversion jobs. Debug.Log("Create jobs for conversion preset: '{0}'", conversionPreset.Name); try { @@ -341,8 +335,8 @@ namespace FileConverter { string inputFilePath = filePaths[index]; ConversionJob conversionJob = ConversionJobFactory.Create(conversionPreset, inputFilePath); - - this.conversionJobs.Add(conversionJob); + + conversionService.RegisterConversionJob(conversionJob); } } catch (Exception exception) @@ -355,158 +349,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++) + SimpleIoc.Default.GetInstance().NavigateTo(Pages.Upgrade); + + IUpgradeService upgradeService = SimpleIoc.Default.GetInstance(); + upgradeService.NewVersionAvailable -= this.UpgradeService_NewVersionAvailable; + } + + private void ConversionService_ConversionJobsTerminated(object sender, ConversionJobsTerminatedEventArgs e) + { + IConversionService conversionService = SimpleIoc.Default.GetInstance(); + conversionService.ConversionJobsTerminated -= this.ConversionService_ConversionJobsTerminated; + + ISettingsService settingsService = SimpleIoc.Default.GetInstance(); + + 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 == 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); - } - } - - 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 == 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.", nameof(parameter)); - } + if (this.OnApplicationTerminate != null) + { + this.OnApplicationTerminate.Invoke(this, new ApplicationTerminateArgs(remainingTime)); + } - if (conversionJob.State != ConversionState.Ready) - { - Debug.LogError("Fail to execute conversion job."); - return; + this.Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown())); } - - try - { - conversionJob.StartConversion(); - } - 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/ConversionPreset/ConversionPreset.cs b/Application/FileConverter/ConversionPreset/ConversionPreset.cs index 37223a5..ad0d330 100644 --- a/Application/FileConverter/ConversionPreset/ConversionPreset.cs +++ b/Application/FileConverter/ConversionPreset/ConversionPreset.cs @@ -12,8 +12,9 @@ namespace FileConverter using FileConverter.Annotations; using FileConverter.Controls; - using FileConverter.Diagnostics; - using FileConverter.ValueConverters; + using FileConverter.Services; + + using GalaSoft.MvvmLight.Ioc; [XmlRoot] [XmlType] @@ -570,8 +571,8 @@ namespace FileConverter 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); + ISettingsService settingsService = SimpleIoc.Default.GetInstance(); + int? count = settingsService.Settings?.ConversionPresets?.Count(match => match?.name == this.Name); if (count > 1) { return "The preset name is already used."; diff --git a/Application/FileConverter/FileConverter.csproj b/Application/FileConverter/FileConverter.csproj index 9995bd4..e6427fa 100644 --- a/Application/FileConverter/FileConverter.csproj +++ b/Application/FileConverter/FileConverter.csproj @@ -167,6 +167,13 @@ + + + + + + + Resources.fr.resx @@ -181,6 +188,9 @@ True + + + diff --git a/Application/FileConverter/Helpers.cs b/Application/FileConverter/Helpers.cs index 3646925..4549209 100644 --- a/Application/FileConverter/Helpers.cs +++ b/Application/FileConverter/Helpers.cs @@ -11,6 +11,10 @@ namespace FileConverter using System.Threading; using FileConverter.ConversionJobs; + using FileConverter.Services; + + using GalaSoft.MvvmLight.Ioc; + using Microsoft.Win32; public static class Helpers @@ -142,8 +146,8 @@ namespace FileConverter public static Thread InstantiateThread(string name, ThreadStart threadStart) { - Application application = Application.Current as Application; - CultureInfo currentCulture = application?.Settings?.ApplicationLanguage; + ISettingsService settingsService = SimpleIoc.Default.GetInstance(); + CultureInfo currentCulture = settingsService?.Settings?.ApplicationLanguage; Thread thread = new Thread(threadStart); thread.Name = name; @@ -159,8 +163,8 @@ namespace FileConverter public static Thread InstantiateThread(string name, ParameterizedThreadStart parameterizedThreadStart) { - Application application = Application.Current as Application; - CultureInfo currentCulture = application?.Settings?.ApplicationLanguage; + ISettingsService settingsService = SimpleIoc.Default.GetInstance(); + CultureInfo currentCulture = settingsService?.Settings?.ApplicationLanguage; Thread thread = new Thread(parameterizedThreadStart); thread.Name = name; diff --git a/Application/FileConverter/Pages.cs b/Application/FileConverter/Pages.cs new file mode 100644 index 0000000..6fe6112 --- /dev/null +++ b/Application/FileConverter/Pages.cs @@ -0,0 +1,13 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter +{ + public static class Pages + { + public const string Help = "Help"; + public const string Main = "Main"; + public const string Settings = "Settings"; + public const string Diagnostics = "Diagnostics"; + public const string Upgrade = "Upgrade"; + } +} 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..49812bd --- /dev/null +++ b/Application/FileConverter/Services/ConversionService.cs @@ -0,0 +1,164 @@ +// 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 FileConverter.ConversionJobs; + using FileConverter.Diagnostics; + + using GalaSoft.MvvmLight; + using GalaSoft.MvvmLight.Ioc; + + public class ConversionService : ObservableObject, IConversionService + { + private readonly List conversionJobs = new List(); + + private readonly int numberOfConversionThread = 1; + + public ConversionService() + { + this.ConversionJobs = this.conversionJobs.AsReadOnly(); + + ISettingsService settingsService = SimpleIoc.Default.GetInstance(); + + this.numberOfConversionThread = 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); + } + + SimpleIoc.Default.Register(() => this); + } + + public event System.EventHandler ConversionJobsTerminated; + + public ReadOnlyCollection ConversionJobs + { + get; + private set; + } + + public void RegisterConversionJob(ConversionJob conversionJob) + { + this.conversionJobs.Add(conversionJob); + this.RaisePropertyChanged(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(); + } + + // 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); + } + } + + break; + } + } + + Thread.Sleep(50); + } + + 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()); + } + } + } +} diff --git a/Application/FileConverter/Services/IConversionService.cs b/Application/FileConverter/Services/IConversionService.cs new file mode 100644 index 0000000..9a1f29c --- /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 + { + ReadOnlyCollection ConversionJobs + { + get; + } + + event System.EventHandler ConversionJobsTerminated; + + 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..59dccea --- /dev/null +++ b/Application/FileConverter/Services/INavigationService.cs @@ -0,0 +1,11 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.Services +{ + using System.Windows; + + public interface INavigationService : GalaSoft.MvvmLight.Views.INavigationService + { + void RegisterPage(string pageKey, bool cancelAutoExit) where T : Window; + } +} \ 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..84ed632 --- /dev/null +++ b/Application/FileConverter/Services/ISettingsService.cs @@ -0,0 +1,14 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.Services +{ + public interface ISettingsService + { + Settings Settings + { + get; + } + + void RevertSettings(); + } +} diff --git a/Application/FileConverter/Services/IUpgradeService.cs b/Application/FileConverter/Services/IUpgradeService.cs new file mode 100644 index 0000000..5bcca07 --- /dev/null +++ b/Application/FileConverter/Services/IUpgradeService.cs @@ -0,0 +1,15 @@ + +namespace FileConverter.Services +{ + public interface IUpgradeService + { + event System.EventHandler NewVersionAvailable; + + UpgradeVersionDescription UpgradeVersionDescription + { + get; + } + + void CheckForUpgrade(); + } +} diff --git a/Application/FileConverter/Services/NavigationService.cs b/Application/FileConverter/Services/NavigationService.cs new file mode 100644 index 0000000..e1260ab --- /dev/null +++ b/Application/FileConverter/Services/NavigationService.cs @@ -0,0 +1,161 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.Services +{ + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.Linq; + using System.Runtime.CompilerServices; + using System.Windows; + + using GalaSoft.MvvmLight; + using GalaSoft.MvvmLight.Ioc; + + using Application = FileConverter.Application; + + public class NavigationService : ObservableObject, INavigationService + { + private readonly Dictionary pageInfoByType; + private readonly List historic; + private string currentPageKey; + + public NavigationService() + { + this.pageInfoByType = new Dictionary(); + this.historic = new List(); + + SimpleIoc.Default.Register(() => this); + } + + public string CurrentPageKey + { + get => this.currentPageKey; + + private set + { + if (this.currentPageKey == value) + { + return; + } + + this.currentPageKey = value; + this.RaisePropertyChanged(); + } + } + + public object Parameter { get; private set; } + + public void GoBack() + { + lock (this.pageInfoByType) + { + if (this.historic.Count <= 0) + { + return; + } + + string pageKey = this.historic.Last(); + PageInfo pageInfo; + if (!this.pageInfoByType.TryGetValue(pageKey, out pageInfo)) + { + throw new ArgumentException($"No such page: {pageKey} ", nameof(pageKey)); + } + + this.historic.RemoveAt(this.historic.Count - 1); + this.CurrentPageKey = this.historic.LastOrDefault(); + + Diagnostics.Debug.Log($"Go back from {pageKey ?? "null"} to {this.CurrentPageKey ?? "null"}."); + + this.pageInfoByType[pageKey] = pageInfo; + + if (pageInfo.Instance.IsVisible) + { + pageInfo.Instance.Close(); + } + + if (string.IsNullOrEmpty(this.CurrentPageKey)) + { + Application.Current.Shutdown(); + } + } + } + + public void NavigateTo(string pageKey) + { + this.NavigateTo(pageKey, null); + } + + public virtual void NavigateTo(string pageKey, object parameter) + { + lock (this.pageInfoByType) + { + PageInfo pageInfo; + if (!this.pageInfoByType.TryGetValue(pageKey, out pageInfo)) + { + throw new ArgumentException($"No such page: {pageKey}.", nameof(pageKey)); + } + + if (pageInfo.Instance == null || !pageInfo.Instance.IsLoaded) + { + pageInfo.Instance = Activator.CreateInstance(pageInfo.Type) as Window; + } + + this.Parameter = parameter; + this.historic.Add(pageKey); + this.CurrentPageKey = pageKey; + + Diagnostics.Debug.Log($"Navigate to {this.CurrentPageKey ?? "null"}."); + + this.pageInfoByType[pageKey] = pageInfo; + + if (pageInfo.Instance.IsVisible) + { + return; + } + + if (pageInfo.CancelAutoExit) + { + Application application = Application.Current as Application; + application?.CancelAutoExit(); + } + + pageInfo.Instance.Show(); + } + } + + public void RegisterPage(string pageKey, bool cancelAutoExit) 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)); + } + else + { + throw new Exception($"Page {pageKey} already registered."); + } + } + } + + private struct PageInfo + { + public Window Instance; + public Type Type; + public bool CancelAutoExit; + + public PageInfo(Type type, bool cancelAutoExit) + { + this.Instance = null; + this.Type = type; + this.CancelAutoExit = cancelAutoExit; + } + } + } +} diff --git a/Application/FileConverter/Services/SettingsService.cs b/Application/FileConverter/Services/SettingsService.cs new file mode 100644 index 0000000..8040aec --- /dev/null +++ b/Application/FileConverter/Services/SettingsService.cs @@ -0,0 +1,33 @@ +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. + +namespace FileConverter.Services +{ + using FileConverter.Diagnostics; + + using GalaSoft.MvvmLight; + using GalaSoft.MvvmLight.Ioc; + + public class SettingsService : ObservableObject, ISettingsService + { + public SettingsService() + { + // Load settigns. + Debug.Log("Load settings..."); + this.Settings = Settings.Load(); + + SimpleIoc.Default.Register(() => this); + } + + public Settings Settings + { + get; + private set; + } + + public void RevertSettings() + { + // Load previous preset in order to cancel changes. + this.Settings = Settings.Load(); + } + } +} diff --git a/Application/FileConverter/Services/UpgradeService.cs b/Application/FileConverter/Services/UpgradeService.cs new file mode 100644 index 0000000..3fb45fe --- /dev/null +++ b/Application/FileConverter/Services/UpgradeService.cs @@ -0,0 +1,66 @@ + +namespace FileConverter.Services +{ + using System; + using System.Threading.Tasks; + + using GalaSoft.MvvmLight; + using GalaSoft.MvvmLight.Ioc; + + public class UpgradeService : ObservableObject, IUpgradeService + { + private UpgradeVersionDescription upgradeVersionDescription; + + public UpgradeService() + { + SimpleIoc.Default.Register(() => this); + } + + public event System.EventHandler NewVersionAvailable; + + public UpgradeVersionDescription UpgradeVersionDescription + { + get => this.upgradeVersionDescription; + private set + { + this.upgradeVersionDescription = value; + this.RaisePropertyChanged(); + } + } + + public void CheckForUpgrade() + { +#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 + } + + private void OnGetLatestVersionDescription(UpgradeVersionDescription description) + { + if (description == null) + { + return; + } + + Registry.SetValue(Registry.Keys.LastUpdateCheckDate, DateTime.Now.ToFileTime()); + + if (description.LatestVersion <= Application.ApplicationVersion) + { + return; + } + + this.UpgradeVersionDescription = description; + + this.NewVersionAvailable?.Invoke(this, description); + } + } +}