Use services instead of putting all the logic in Application.cs

This commit is contained in:
Adrien Allard committed 2018-11-09 19:05:31 +01:00
1 parent 8e649ebe42
commit 40e637a3f6
15 files changed
+703 -266

No files matched your search

+11 -1
View File
@@ -1,11 +1,21 @@
<Application x:Class="FileConverter.Application"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:xaml="clr-namespace:Markdown.Xaml;assembly=Markdown.Xaml"
xmlns:valueConverters="clr-namespace:FileConverter.ValueConverters"
xmlns:generic="clr-namespace:FileConverter.ValueConverters.Generic"
StartupUri="Windows/MainWindow.xaml" ShutdownMode="OnMainWindowClose">
xmlns:viewModels="clr-namespace:FileConverter.ViewModels"
xmlns:services="clr-namespace:FileConverter.Services"
ShutdownMode="OnLastWindowClose">
<Application.Resources>
<!--Global View Model Locator-->
<viewModels:ViewModelLocator x:Key="Locator" />
<services:NavigationService x:Key="Navigation" />
<services:ConversionService x:Key="Conversions" />
<services:SettingsService x:Key="Settings" />
<services:UpgradeService x:Key="Upgrade" />
<!-- Converters -->
<valueConverters:ApplicationVersionToApplicationName x:Key="ApplicationVersionToApplicationName"/>
<generic:BoolToVisibility x:Key="BoolToVisibility"/>
+150 -257
View File
@@ -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<ConversionJob> conversionJobs = new List<ConversionJob>();
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<ApplicationTerminateArgs> OnApplicationTerminate;
public static Version ApplicationVersion
{
get
{
return Application.Version;
}
}
public ReadOnlyCollection<ConversionJob> 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<INavigationService>();
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<IConversionService>();
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<IUpgradeService>();
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<INavigationService>();
navigationService.RegisterPage<HelpWindow>(Pages.Help, false);
navigationService.RegisterPage<MainWindow>(Pages.Main, false);
navigationService.RegisterPage<SettingsWindow>(Pages.Settings, true);
navigationService.RegisterPage<DiagnosticsWindow>(Pages.Diagnostics, true);
navigationService.RegisterPage<UpgradeWindow>(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<ISettingsService>();
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<UpgradeVersionDescription> task = Upgrade.Helpers.GetLatestVersionDescriptionAsync(this.OnGetLatestVersionDescription);
#else
long fileTime = Registry.GetValue<long>(Registry.Keys.LastUpdateCheckDate);
DateTime lastUpdateDateTime = DateTime.FromFileTime(fileTime);
TimeSpan durationSinceLastUpdate = DateTime.Now.Subtract(lastUpdateDateTime);
if (durationSinceLastUpdate > new TimeSpan(1, 0, 0, 0))
{
Task<UpgradeVersionDescription> task = Upgrade.Helpers.GetLatestVersionDescriptionAsync(this.OnGetLatestVersionDescription);
}
#endif
IUpgradeService upgradeService = SimpleIoc.Default.GetInstance<IUpgradeService>();
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<IConversionService>();
// 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<INavigationService>().NavigateTo(Pages.Upgrade);
IUpgradeService upgradeService = SimpleIoc.Default.GetInstance<IUpgradeService>();
upgradeService.NewVersionAvailable -= this.UpgradeService_NewVersionAvailable;
}
private void ConversionService_ConversionJobsTerminated(object sender, ConversionJobsTerminatedEventArgs e)
{
IConversionService conversionService = SimpleIoc.Default.GetInstance<IConversionService>();
conversionService.ConversionJobsTerminated -= this.ConversionService_ConversionJobsTerminated;
ISettingsService settingsService = SimpleIoc.Default.GetInstance<ISettingsService>();
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);
}
}
}
@@ -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<ISettingsService>();
int? count = settingsService.Settings?.ConversionPresets?.Count(match => match?.name == this.Name);
if (count > 1)
{
return "The preset name is already used.";
@@ -167,6 +167,13 @@
<Compile Include="Helpers.cs" />
<Compile Include="InputPostConversionAction.cs" />
<Compile Include="IXmlSerializable.cs" />
<Compile Include="Services\ConversionJobsTerminatedEventArgs.cs" />
<Compile Include="Services\ConversionService.cs" />
<Compile Include="Services\IConversionService.cs" />
<Compile Include="Services\INavigationService.cs" />
<Compile Include="Services\ISettingsService.cs" />
<Compile Include="Services\IUpgradeService.cs" />
<Compile Include="Services\NavigationService.cs" />
<Compile Include="PathHelpers.cs" />
<Compile Include="Properties\Resources.fr.Designer.cs">
<DependentUpon>Resources.fr.resx</DependentUpon>
@@ -181,6 +188,9 @@
<ExcludeFromStyleCop>True</ExcludeFromStyleCop>
</Compile>
<Compile Include="Registry.cs" />
<Compile Include="Pages.cs" />
<Compile Include="Services\SettingsService.cs" />
<Compile Include="Services\UpgradeService.cs" />
<Compile Include="Settings.Migration.cs" />
<Compile Include="Settings.Settings.cs" />
<Compile Include="Upgrade\Helpers.cs" />
+8 -4
View File
@@ -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<ISettingsService>();
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<ISettingsService>();
CultureInfo currentCulture = settingsService?.Settings?.ApplicationLanguage;
Thread thread = new Thread(parameterizedThreadStart);
thread.Name = name;
+13
View File
@@ -0,0 +1,13 @@
// <copyright file="Pages.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
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";
}
}
@@ -0,0 +1,20 @@
// <copyright file="ConversionJobsTerminatedEventArgs.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter.Services
{
using System;
public class ConversionJobsTerminatedEventArgs : EventArgs
{
public ConversionJobsTerminatedEventArgs(bool allConversionsSucceed)
{
this.AllConversionsSucceed = allConversionsSucceed;
}
public bool AllConversionsSucceed
{
get;
private set;
}
}
}
@@ -0,0 +1,164 @@
// <copyright file="ConversionService.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
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<ConversionJob> conversionJobs = new List<ConversionJob>();
private readonly int numberOfConversionThread = 1;
public ConversionService()
{
this.ConversionJobs = this.conversionJobs.AsReadOnly();
ISettingsService settingsService = SimpleIoc.Default.GetInstance<ISettingsService>();
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<IConversionService>(() => this);
}
public event System.EventHandler<ConversionJobsTerminatedEventArgs> ConversionJobsTerminated;
public ReadOnlyCollection<ConversionJob> 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());
}
}
}
}
@@ -0,0 +1,22 @@
// <copyright file="IConversionService.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter.Services
{
using System.Collections.ObjectModel;
using FileConverter.ConversionJobs;
public interface IConversionService
{
ReadOnlyCollection<ConversionJob> ConversionJobs
{
get;
}
event System.EventHandler<ConversionJobsTerminatedEventArgs> ConversionJobsTerminated;
void ConvertFilesAsync();
void RegisterConversionJob(ConversionJob conversionJob);
}
}
@@ -0,0 +1,11 @@
// <copyright file="INavigationService.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter.Services
{
using System.Windows;
public interface INavigationService : GalaSoft.MvvmLight.Views.INavigationService
{
void RegisterPage<T>(string pageKey, bool cancelAutoExit) where T : Window;
}
}
@@ -0,0 +1,14 @@
// <copyright file="ISettingsService.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter.Services
{
public interface ISettingsService
{
Settings Settings
{
get;
}
void RevertSettings();
}
}
@@ -0,0 +1,15 @@
namespace FileConverter.Services
{
public interface IUpgradeService
{
event System.EventHandler<UpgradeVersionDescription> NewVersionAvailable;
UpgradeVersionDescription UpgradeVersionDescription
{
get;
}
void CheckForUpgrade();
}
}
@@ -0,0 +1,161 @@
// <copyright file="NavigationService.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
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<string, PageInfo> pageInfoByType;
private readonly List<string> historic;
private string currentPageKey;
public NavigationService()
{
this.pageInfoByType = new Dictionary<string, PageInfo>();
this.historic = new List<string>();
SimpleIoc.Default.Register<INavigationService>(() => 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<T>(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;
}
}
}
}
@@ -0,0 +1,33 @@
// <copyright file="SettingsService.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
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<ISettingsService>(() => this);
}
public Settings Settings
{
get;
private set;
}
public void RevertSettings()
{
// Load previous preset in order to cancel changes.
this.Settings = Settings.Load();
}
}
}
@@ -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<IUpgradeService>(() => this);
}
public event System.EventHandler<UpgradeVersionDescription> NewVersionAvailable;
public UpgradeVersionDescription UpgradeVersionDescription
{
get => this.upgradeVersionDescription;
private set
{
this.upgradeVersionDescription = value;
this.RaisePropertyChanged();
}
}
public void CheckForUpgrade()
{
#if DEBUG
Task<UpgradeVersionDescription> task = Upgrade.Helpers.GetLatestVersionDescriptionAsync(this.OnGetLatestVersionDescription);
#else
long fileTime = Registry.GetValue<long>(Registry.Keys.LastUpdateCheckDate);
DateTime lastUpdateDateTime = DateTime.FromFileTime(fileTime);
TimeSpan durationSinceLastUpdate = DateTime.Now.Subtract(lastUpdateDateTime);
if (durationSinceLastUpdate > new TimeSpan(1, 0, 0, 0))
{
Task<UpgradeVersionDescription> 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);
}
}
}