Compare commits

44 Commits
Author SHA1 Message Date
Adrien Allard e804355034 Merge remote-tracking branch 'refs/remotes/origin/development' 2015-11-07 17:19:26 +01:00
Adrien Allard 34a2990e9d Update screenshots 2015-11-07 17:17:52 +01:00
Adrien Allard 24f999d859 New readme with updated change log and help. 2015-11-07 17:06:07 +01:00
Adrien Allard bfa8fd7d4f Clean & stylecop 2015-11-07 11:30:10 +01:00
Tichau 3da4e0ea84 Change version number to 0.3 2015-11-07 11:05:40 +01:00
Tichau 28c9ae94b0 Change version number to 0.3 2015-11-07 11:00:27 +01:00
Tichau 1210637f59 Fix version number displaying 2015-11-07 10:59:49 +01:00
Tichau 509d47fb91 Change default settings 2015-11-07 10:25:35 +01:00
Tichau 1b4e39df45 Add AIFF file format 2015-11-06 18:32:41 +01:00
Tichau 8dbf692855 Add add/remove input type functions. 2015-11-06 18:19:54 +01:00
Tichau 7b0af841ab Add input type category checkbox 2015-11-06 18:16:23 +01:00
Tichau d66723d510 Refactor input types system. 2015-11-06 08:20:29 +01:00
Tichau 8963bdb6c0 Add 'OnDeserializationComplete' function 2015-11-06 08:19:13 +01:00
Tichau 4cd9a851e8 Clean 2015-11-06 08:18:47 +01:00
Tichau 77c5d94b74 Adapt default settings to new features. 2015-11-02 08:37:52 +01:00
Tichau 5f7b2911da Add multi resolution icon 2015-10-29 21:27:00 +01:00
Tichau 96a2d4f52f Add input post conversion actions implementation. 2015-10-29 08:52:22 +01:00
Tichau 12cfaaefc6 Added: InputPostConversionAction interface. 2015-10-28 19:28:05 +01:00
Tichau d4cf9d9649 Add move up/down preset. 2015-10-28 18:47:41 +01:00
Tichau e0d290306b Added: Create folders when necessary. 2015-10-27 19:23:00 +01:00
Tichau 1d66f9fef0 Add: handle path validity error check in conversion jobs. 2015-10-27 09:06:35 +01:00
Tichau 6f7b0386cd Fixed: output filename label doesn't display underscores 2015-10-27 08:05:21 +01:00
Tichau 228217e79b Add output file path template. 2015-10-26 19:05:14 +01:00
Tichau 06589d6cf8 Add output file path template UI 2015-10-21 22:00:00 +02:00
Tichau b88bdcb8be Add wav encoding modes (pcm 8, 16, 24 and 32 bits) 2015-10-20 18:50:52 +02:00
Tichau 06f5b818bb Add wav settings interface. 2015-10-20 08:43:06 +02:00
Tichau 8a7e8b0262 Take care of ogg bitrate setting. 2015-10-20 08:20:50 +02:00
Tichau a223ee1610 Fixed: Incorrect update of conversion settings du to dependency property update order.
Fixed using two binding instead of events.
2015-10-16 18:49:55 +02:00
Tichau 19e9e1d50a Fixed: Wrong bitrate changed events thrown when the dependency property update its value. 2015-10-13 08:50:17 +02:00
Tichau afe7c4048a Hide preset settings when no preset are selected. 2015-10-12 18:45:57 +02:00
Tichau a0fbf28e42 Add error codes on error messages. 2015-10-12 08:29:52 +02:00
Adrien Allard 915f93defd Added: Ogg conversion settings. 2015-08-26 08:52:32 +02:00
Adrien Allard 3e7c7a4a30 Fixed: Close window don't terminate application. 2015-08-22 15:55:30 +02:00
Adrien Allard 5db9c09cff Stylecop 2015-08-22 15:50:19 +02:00
Adrien Allard 82be95fb43 Implement ValueConverterGroup ConvertBack function. 2015-08-22 14:54:30 +02:00
Adrien Allard 132e254f25 Fixed: user control bindings 2015-08-22 14:49:14 +02:00
Adrien Allard 7352f2a0e3 Change resharper settings 2015-08-22 14:47:07 +02:00
Adrien Allard a3a930d44c Fixed: Conversion settings binding (for encoding type) 2015-08-21 20:15:16 +02:00
Adrien Allard ae3328b029 Take care of mp3 conversion settings 2015-08-19 08:31:45 +02:00
Adrien Allard c9d2c77340 Refactor conversion job system. 2015-08-18 23:06:51 +02:00
Adrien Allard 890ed87cf8 Move ConversionJob in a specific folder. 2015-08-18 20:46:11 +02:00
Adrien Allard f6547941bc Added: Quality slider for mp3 output type.
- Add quality slider.
- Fixed: application now don't quit when settings window lost focus.
- New generic converters.
2015-08-17 22:24:48 +02:00
Adrien Allard 00d380f92e Added: Encoding quality slider user control. 2015-08-17 22:21:47 +02:00
Tichau d7f25f6ab2 Resize screenshot. 2015-05-27 12:04:29 +02:00
66 changed files with 3284 additions and 773 deletions

No files matched your search

+17 -26
View File
@@ -21,12 +21,14 @@ namespace FileConverter
using System.Threading;
using System.Windows;
using FileConverter.ConversionJobs;
public partial class Application : System.Windows.Application
{
private static readonly Version Version = new Version()
{
Major = 0,
Minor = 2,
Minor = 3,
};
private readonly List<ConversionJob> conversionJobs = new List<ConversionJob>();
@@ -84,7 +86,7 @@ namespace FileConverter
{
this.cancelAutoExit = true;
}
private void Initialize()
{
// Load settigns.
@@ -100,17 +102,11 @@ namespace FileConverter
if (args.Length <= 1)
{
this.debugMode = true;
System.Array.Resize(ref args, 9);
System.Array.Resize(ref args, 5);
args[1] = "--conversion-preset";
args[2] = "To Mp3";
args[3] = @"D:\Projects\FileConverter\TestFiles\Herbie Hancock - Speak Like A Child [RVG Edition].flac";
args[3] = @"D:\Projects\FileConverter\TestFiles\01 - Le Bruit Du Bang.wma";
args[4] = @"D:\Projects\FileConverter\TestFiles\test\Toccata.wav";
args[5] = @"D:\Projects\FileConverter\TestFiles\test\Toccata - Copie (4).wav";
args[5] = "--verbose";
args[6] = @"D:\Projects\FileConverter\TestFiles\test\Toccata - Copie (3).wav";
args[7] = @"D:\Projects\FileConverter\TestFiles\test\Toccata - Copie (2).wav";
args[8] = @"D:\Projects\FileConverter\TestFiles\test\Toccata - Copie (5).wav";
args[3] = "--verbose";
args[4] = @"D:\Test\10 - Get around town (lp version).ogg";
System.Array.Resize(ref args, 2);
args[1] = "--settings";
@@ -151,7 +147,7 @@ namespace FileConverter
case "conversion-preset":
if (index >= args.Length - 1)
{
MessageBox.Show(string.Format("ERROR ! Invalid format."), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
MessageBox.Show(string.Format("Invalid format. (code 0x01)"), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown()));
return;
}
@@ -159,7 +155,7 @@ namespace FileConverter
conversionPreset = Settings.GetPresetFromName(args[index + 1]);
if (conversionPreset == null)
{
MessageBox.Show(string.Format("Invalid conversion preset '{0}'.", args[index + 1]), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
MessageBox.Show(string.Format("Invalid conversion preset '{0}'. (code 0x02)", args[index + 1]), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown()));
return;
}
@@ -195,7 +191,9 @@ namespace FileConverter
for (int index = 0; index < filePaths.Count; index++)
{
string inputFilePath = filePaths[index];
ConversionJob conversionJob = new ConversionJob(conversionPreset, inputFilePath);
ConversionJob conversionJob = ConversionJobFactory.Create(conversionPreset);
conversionJob.PrepareConversion(inputFilePath);
this.conversionJobs.Add(conversionJob);
}
@@ -207,23 +205,16 @@ namespace FileConverter
for (int index = 0; index < this.conversionJobs.Count; index++)
{
ConversionJob conversionJob = this.conversionJobs[index];
if (conversionJob.State != ConversionJob.ConversionState.Ready)
{
continue;
}
conversionJob.StartConvertion();
if (System.IO.File.Exists(conversionJob.OutputFilePath))
{
Diagnostics.Log("Success!");
if (this.debugMode)
{
Diagnostics.Log("Delete file {0}.", conversionJob.OutputFilePath);
try
{
System.IO.File.Delete(conversionJob.OutputFilePath);
}
catch
{
}
}
}
else
{
@@ -0,0 +1,26 @@
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:valueConverters="clr-namespace:FileConverter.ValueConverters" x:Name="userControl"
x:Class="FileConverter.Controls.EncodingQualitySliderControl"
mc:Ignorable="d" d:DesignWidth="300" Height="50">
<UserControl.Resources>
<valueConverters:BitrateToString x:Key="BitrateToString"/>
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="65"/>
</Grid.ColumnDefinitions>
<Slider Grid.Column="0" x:Name="slider" Margin="0,2,0,0" VerticalAlignment="Top" Maximum="245" AutoToolTipPlacement="TopLeft" SmallChange="8" IsSnapToTickEnabled="True" IsSelectionRangeEnabled="True" SelectionStart="115" SelectionEnd="245" Minimum="65" TickPlacement="BottomRight" LargeChange="32" TickFrequency="8" Ticks="65 85 100 115 130 165 175 190 225 245" Foreground="#004B82" />
<Label Grid.Column="1" Content="{Binding Value, Converter={StaticResource BitrateToString}, ElementName=slider, Mode=OneWay}" Width="65" />
<Label Grid.Column="0" Grid.Row="1" Content="Recommended bitrate range in blue" Foreground="#E5004B82" FontSize="11" />
</Grid>
</UserControl>
@@ -0,0 +1,181 @@
// <copyright file="EncodingQualitySliderControl.xaml.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter.Controls
{
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
/// <summary>
/// Interaction logic for EncodingQualitySliderControl.
/// </summary>
public partial class EncodingQualitySliderControl : UserControl
{
public static readonly DependencyProperty BitrateProperty = DependencyProperty.Register(
"Bitrate",
typeof(double),
typeof(EncodingQualitySliderControl),
new FrameworkPropertyMetadata(new PropertyChangedCallback(EncodingQualitySliderControl.OnBitrateValueChanged), new CoerceValueCallback(EncodingQualitySliderControl.CoerceBitrateValue)));
public static readonly DependencyProperty EncodingModeProperty = DependencyProperty.Register(
"EncodingMode",
typeof(EncodingMode),
typeof(EncodingQualitySliderControl),
new PropertyMetadata(new PropertyChangedCallback(EncodingQualitySliderControl.OnEncodingModeValueChanged)));
public EncodingQualitySliderControl()
{
this.InitializeComponent();
this.CoerceValue(EncodingQualitySliderControl.BitrateProperty);
this.slider.ValueChanged += this.Slider_ValueChanged;
}
public EncodingMode EncodingMode
{
get
{
return (EncodingMode)this.GetValue(EncodingQualitySliderControl.EncodingModeProperty);
}
set
{
this.SetCurrentValue(EncodingQualitySliderControl.EncodingModeProperty, value);
}
}
public double Bitrate
{
get
{
return (double)this.GetValue(EncodingQualitySliderControl.BitrateProperty);
}
set
{
this.SetCurrentValue(EncodingQualitySliderControl.BitrateProperty, this.GetNearestTickValue(value));
}
}
private static void OnBitrateValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs eventArgs)
{
EncodingQualitySliderControl encodingQualitySliderControl = sender as EncodingQualitySliderControl;
encodingQualitySliderControl.slider.Value = (double)eventArgs.NewValue;
}
private static object CoerceBitrateValue(DependencyObject sender, object basevalue)
{
EncodingQualitySliderControl encodingQualitySliderControl = sender as EncodingQualitySliderControl;
return encodingQualitySliderControl.GetNearestTickValue((double)basevalue);
}
private static void OnEncodingModeValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs eventArgs)
{
EncodingQualitySliderControl encodingQualitySliderControl = sender as EncodingQualitySliderControl;
Slider sliderControl = encodingQualitySliderControl.slider;
switch (encodingQualitySliderControl.EncodingMode)
{
case EncodingMode.Mp3VBR:
{
sliderControl.Minimum = 65;
sliderControl.Maximum = 245;
sliderControl.SelectionStart = 115;
sliderControl.SelectionEnd = 245;
sliderControl.Ticks.Clear();
sliderControl.Ticks.Add(65);
sliderControl.Ticks.Add(85);
sliderControl.Ticks.Add(100);
sliderControl.Ticks.Add(115);
sliderControl.Ticks.Add(130);
sliderControl.Ticks.Add(165);
sliderControl.Ticks.Add(175);
sliderControl.Ticks.Add(190);
sliderControl.Ticks.Add(225);
sliderControl.Ticks.Add(245);
break;
}
case EncodingMode.Mp3CBR:
{
sliderControl.Minimum = 8;
sliderControl.Maximum = 320;
sliderControl.SelectionStart = 128;
sliderControl.SelectionEnd = 256;
sliderControl.Ticks.Clear();
sliderControl.Ticks.Add(8);
sliderControl.Ticks.Add(16);
sliderControl.Ticks.Add(24);
sliderControl.Ticks.Add(32);
sliderControl.Ticks.Add(40);
sliderControl.Ticks.Add(48);
sliderControl.Ticks.Add(64);
sliderControl.Ticks.Add(80);
sliderControl.Ticks.Add(96);
sliderControl.Ticks.Add(112);
sliderControl.Ticks.Add(128);
sliderControl.Ticks.Add(160);
sliderControl.Ticks.Add(192);
sliderControl.Ticks.Add(224);
sliderControl.Ticks.Add(256);
sliderControl.Ticks.Add(320);
break;
}
case EncodingMode.OggVBR:
{
sliderControl.Minimum = 32;
sliderControl.Maximum = 500;
sliderControl.SelectionStart = 80;
sliderControl.SelectionEnd = 192;
sliderControl.Ticks.Clear();
sliderControl.Ticks.Add(32);
sliderControl.Ticks.Add(48);
sliderControl.Ticks.Add(64);
sliderControl.Ticks.Add(80);
sliderControl.Ticks.Add(96);
sliderControl.Ticks.Add(112);
sliderControl.Ticks.Add(128);
sliderControl.Ticks.Add(160);
sliderControl.Ticks.Add(192);
sliderControl.Ticks.Add(224);
sliderControl.Ticks.Add(256);
sliderControl.Ticks.Add(320);
sliderControl.Ticks.Add(500);
break;
}
}
encodingQualitySliderControl.CoerceValue(EncodingQualitySliderControl.BitrateProperty);
}
private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (this.Bitrate == e.NewValue)
{
return;
}
this.SetCurrentValue(EncodingQualitySliderControl.BitrateProperty, e.NewValue);
}
private double GetNearestTickValue(double value)
{
double minimumDifference = float.PositiveInfinity;
double nearestTick = value;
for (int index = 0; index < this.slider.Ticks.Count; index++)
{
double tick = this.slider.Ticks[index];
double difference = System.Math.Abs(value - tick);
if (difference < minimumDifference)
{
minimumDifference = difference;
nearestTick = tick;
}
}
return nearestTick;
}
}
}
-269
View File
@@ -1,269 +0,0 @@
// <copyright file="ConversionJob.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter
{
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
public class ConversionJob : INotifyPropertyChanged
{
private readonly Regex durationRegex = new Regex(@"Duration:\s*([0-9][0-9]):([0-9][0-9]):([0-9][0-9])\.([0-9][0-9]),.*bitrate:\s*([0-9]+) kb\/s");
private readonly Regex progressRegex = new Regex(@"size=\s*([0-9]+)kB\s+time=([0-9][0-9]):([0-9][0-9]):([0-9][0-9]).([0-9][0-9])\s+bitrate=\s*([0-9]+.[0-9])kbits\/s");
private TimeSpan fileDuration;
private TimeSpan actualConvertedDuration;
private ProcessStartInfo ffmpegProcessStartInfo;
private float progress;
private ConversionState state;
private string exitingMessage;
public ConversionJob()
{
this.ConversionPreset = null;
this.progress = 0f;
this.InputFilePath = string.Empty;
this.OutputFilePath = string.Empty;
this.State = ConversionState.Unknown;
this.ExitingMessage = string.Empty;
}
public ConversionJob(ConversionPreset conversionPreset, string inputFilePath)
{
this.ConversionPreset = conversionPreset;
this.InputFilePath = inputFilePath;
string extension = System.IO.Path.GetExtension(inputFilePath);
this.OutputFilePath = inputFilePath.Substring(0, inputFilePath.Length - extension.Length) + "." + this.ConversionPreset.OutputType.ToString().ToLowerInvariant();
this.Initialize();
}
public event PropertyChangedEventHandler PropertyChanged;
public enum ConversionState
{
Unknown,
Ready,
InProgress,
Done,
Failed,
}
public ConversionPreset ConversionPreset
{
get;
private set;
}
public string InputFilePath
{
get;
private set;
}
public string OutputFilePath
{
get;
private set;
}
public ConversionState State
{
get
{
return this.state;
}
private set
{
this.state = value;
this.NotifyPropertyChanged();
}
}
public float Progress
{
get
{
return this.progress;
}
private set
{
this.progress = value;
this.NotifyPropertyChanged();
}
}
public string ExitingMessage
{
get
{
return this.exitingMessage;
}
set
{
this.exitingMessage = value;
this.NotifyPropertyChanged();
}
}
public void StartConvertion()
{
if (this.ConversionPreset == null)
{
throw new Exception("The conversion preset must be valid.");
}
Diagnostics.Log("Convert file {0} to {1}.", this.InputFilePath, this.OutputFilePath);
string arguments = string.Empty;
switch (this.ConversionPreset.OutputType)
{
case OutputType.Mp3:
arguments = string.Format("-n -stats -i \"{0}\" -qscale:a 2 \"{1}\"", this.InputFilePath, this.OutputFilePath);
break;
case OutputType.Ogg:
arguments = string.Format("-n -stats -i \"{0}\" -acodec libvorbis -qscale:a 2 \"{1}\"", this.InputFilePath, this.OutputFilePath);
break;
case OutputType.Flac:
case OutputType.Wav:
arguments = string.Format("-n -stats -i \"{0}\" \"{1}\"", this.InputFilePath, this.OutputFilePath);
break;
default:
throw new NotImplementedException("Converter not implemented for output file type " + this.ConversionPreset.OutputType);
}
if (string.IsNullOrEmpty(arguments) || this.ffmpegProcessStartInfo == null)
{
return;
}
this.State = ConversionState.InProgress;
try
{
Diagnostics.Log(string.Empty);
this.ffmpegProcessStartInfo.Arguments = arguments;
Diagnostics.Log("Execute command: {0} {1}.", this.ffmpegProcessStartInfo.FileName, this.ffmpegProcessStartInfo.Arguments);
using (Process exeProcess = Process.Start(this.ffmpegProcessStartInfo))
{
using (StreamReader reader = exeProcess.StandardError)
{
while (!reader.EndOfStream)
{
string result = reader.ReadLine();
this.ParseFFMPEGOutput(result);
Diagnostics.Log("ffmpeg output: {0}", result);
}
}
exeProcess.WaitForExit();
}
}
catch
{
this.State = ConversionState.Failed;
throw;
}
if (!string.IsNullOrEmpty(this.ExitingMessage))
{
this.State = ConversionState.Failed;
return;
}
this.Progress = 1f;
this.State = ConversionState.Done;
Diagnostics.Log("\nDone!");
}
private void Initialize()
{
if (this.ConversionPreset == null)
{
throw new Exception("The conversion preset must be valid.");
}
this.ffmpegProcessStartInfo = null;
string applicationDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string ffmpegPath = string.Format("{0}\\ffmpeg.exe", applicationDirectory);
if (!System.IO.File.Exists(ffmpegPath))
{
Diagnostics.Log("Can't find ffmpeg executable ({0}). Try to reinstall the application.", ffmpegPath);
return;
}
this.ffmpegProcessStartInfo = new ProcessStartInfo(ffmpegPath);
this.ffmpegProcessStartInfo.CreateNoWindow = true;
this.ffmpegProcessStartInfo.UseShellExecute = false;
this.ffmpegProcessStartInfo.RedirectStandardOutput = true;
this.ffmpegProcessStartInfo.RedirectStandardError = true;
this.State = ConversionState.Ready;
}
private void ParseFFMPEGOutput(string input)
{
Match match = this.durationRegex.Match(input);
if (match.Success && match.Groups.Count >= 6)
{
int hours = int.Parse(match.Groups[1].Value);
int minutes = int.Parse(match.Groups[2].Value);
int seconds = int.Parse(match.Groups[3].Value);
int milliseconds = int.Parse(match.Groups[4].Value);
float bitrate = float.Parse(match.Groups[5].Value);
this.fileDuration = new TimeSpan(0, hours, minutes, seconds, milliseconds);
return;
}
match = this.progressRegex.Match(input);
if (match.Success && match.Groups.Count >= 7)
{
int size = int.Parse(match.Groups[1].Value);
int hours = int.Parse(match.Groups[2].Value);
int minutes = int.Parse(match.Groups[3].Value);
int seconds = int.Parse(match.Groups[4].Value);
int milliseconds = int.Parse(match.Groups[5].Value);
float bitrate = 0f;
float.TryParse(match.Groups[6].Value, out bitrate);
this.actualConvertedDuration = new TimeSpan(0, hours, minutes, seconds, milliseconds);
this.Progress = this.actualConvertedDuration.Ticks / (float)this.fileDuration.Ticks;
return;
}
if (input.Contains("Exiting."))
{
this.ExitingMessage = input;
}
}
private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
@@ -0,0 +1,269 @@
// <copyright file="ConversionJob.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter.ConversionJobs
{
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
public class ConversionJob : INotifyPropertyChanged
{
private float progress = 0f;
private ConversionState state = ConversionState.Unknown;
private string errorMessage = string.Empty;
private string initialInputPath = string.Empty;
public ConversionJob()
{
this.State = ConversionState.Unknown;
this.ConversionPreset = null;
this.InputFilePath = string.Empty;
}
public ConversionJob(ConversionPreset conversionPreset) : this()
{
if (conversionPreset == null)
{
throw new ArgumentNullException("conversionPreset");
}
this.ConversionPreset = conversionPreset;
}
public event PropertyChangedEventHandler PropertyChanged;
public enum ConversionState
{
Unknown,
Ready,
InProgress,
Done,
Failed,
}
public ConversionPreset ConversionPreset
{
get;
private set;
}
public string InputFilePath
{
get;
private set;
}
public string OutputFilePath
{
get;
private set;
}
public ConversionState State
{
get
{
return this.state;
}
private set
{
this.state = value;
this.NotifyPropertyChanged();
}
}
public float Progress
{
get
{
return this.progress;
}
protected set
{
this.progress = value;
this.NotifyPropertyChanged();
}
}
public string ErrorMessage
{
get
{
return this.errorMessage;
}
private set
{
this.errorMessage = value;
this.NotifyPropertyChanged();
}
}
public void PrepareConversion(string inputFilePath)
{
if (string.IsNullOrEmpty(inputFilePath))
{
throw new ArgumentNullException("inputFilePath");
}
if (this.ConversionPreset == null)
{
throw new Exception("The conversion preset must be valid.");
}
this.initialInputPath = inputFilePath;
this.InputFilePath = inputFilePath;
this.OutputFilePath = this.ConversionPreset.GenerateOutputFilePath(inputFilePath);
if (!PathHelpers.IsPathValid(this.OutputFilePath))
{
this.ConvertionFailed("Invalid output path generated by output file path template.");
Diagnostics.Log(string.Format("Invalid output path generated: {0} from input: {1}.", this.OutputFilePath, this.InputFilePath));
return;
}
if (this.OutputFilePath == this.InputFilePath)
{
// If the input post conversion action is to move or delete the input file, change its name in order to keep the output name intact.
if (this.ConversionPreset.InputPostConversionAction == InputPostConversionAction.MoveInArchiveFolder ||
this.ConversionPreset.InputPostConversionAction == InputPostConversionAction.Delete)
{
string inputExtension = System.IO.Path.GetExtension(this.InputFilePath);
string pathWithoutExtension = this.InputFilePath.Substring(0, this.InputFilePath.Length - inputExtension.Length);
this.InputFilePath = PathHelpers.GenerateUniquePath(pathWithoutExtension + "_TEMP" + inputExtension);
System.IO.File.Move(inputFilePath, this.InputFilePath);
}
}
// Create output folder that doesn't exist.
{
StringBuilder path = new StringBuilder(this.OutputFilePath.Length);
foreach (string directory in PathHelpers.GetDirectories(this.OutputFilePath))
{
path.Append(directory);
path.Append('\\');
if (!System.IO.Directory.Exists(path.ToString()))
{
try
{
System.IO.Directory.CreateDirectory(path.ToString());
}
catch (Exception)
{
this.ConvertionFailed("Invalid output path generated by output file path template.");
Diagnostics.Log(string.Format("Can't create directories for path {0}", this.OutputFilePath));
return;
}
}
}
}
// Make the output path valid.
try
{
this.OutputFilePath = PathHelpers.GenerateUniquePath(this.OutputFilePath);
}
catch (Exception exception)
{
this.ConvertionFailed("Can't generate a valid output filename.");
Diagnostics.Log(exception.Message);
return;
}
this.Initialize();
if (this.State == ConversionState.Unknown)
{
this.State = ConversionState.Ready;
}
}
public void StartConvertion()
{
if (this.ConversionPreset == null)
{
throw new Exception("The conversion preset must be valid.");
}
if (this.State != ConversionState.Ready)
{
throw new Exception("Invalid conversion state.");
}
Diagnostics.Log("Convert file {0} to {1}.", this.InputFilePath, this.OutputFilePath);
this.State = ConversionState.InProgress;
this.Convert();
if (this.State != ConversionState.Failed)
{
this.OnConversionSucceed();
}
}
protected virtual void Convert()
{
}
protected virtual void Initialize()
{
}
protected virtual void OnConversionSucceed()
{
Diagnostics.Log("Conversion Succeed!");
// Apply the input post conversion action.
switch (this.ConversionPreset.InputPostConversionAction)
{
case InputPostConversionAction.None:
break;
case InputPostConversionAction.MoveInArchiveFolder:
string basePath = System.IO.Path.GetDirectoryName(this.initialInputPath);
string inputFilename = System.IO.Path.GetFileName(this.initialInputPath);
string archivePath = basePath + "\\" + this.ConversionPreset.ConversionArchiveFolderName;
if (!System.IO.Directory.Exists(archivePath))
{
System.IO.Directory.CreateDirectory(archivePath);
}
string newPath = PathHelpers.GenerateUniquePath(archivePath + "\\" + inputFilename);
System.IO.File.Move(this.InputFilePath, newPath);
Diagnostics.Log("Input file moved in archive folder: '{0}'", newPath);
break;
case InputPostConversionAction.Delete:
System.IO.File.Delete(this.InputFilePath);
Diagnostics.Log("Input file deleted: '{0}'", this.initialInputPath);
break;
}
Diagnostics.Log(string.Empty);
this.Progress = 1f;
this.State = ConversionState.Done;
Diagnostics.Log("Conversion Done!");
}
protected void ConvertionFailed(string exitingMessage)
{
this.State = ConversionState.Failed;
this.ErrorMessage = exitingMessage;
}
protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
@@ -0,0 +1,14 @@
// <copyright file="ConversionJobFactory.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter.ConversionJobs
{
public static class ConversionJobFactory
{
public static ConversionJob Create(ConversionPreset conversionPreset)
{
ConversionJob conversionJob = new ConversionJob_FFMPEG(conversionPreset);
return conversionJob;
}
}
}
@@ -0,0 +1,307 @@
// <copyright file="ConversionJob_FFMPEG.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter.ConversionJobs
{
using System;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
public class ConversionJob_FFMPEG : ConversionJob
{
private readonly Regex durationRegex = new Regex(@"Duration:\s*([0-9][0-9]):([0-9][0-9]):([0-9][0-9])\.([0-9][0-9]),.*bitrate:\s*([0-9]+) kb\/s");
private readonly Regex progressRegex = new Regex(@"size=\s*([0-9]+)kB\s+time=([0-9][0-9]):([0-9][0-9]):([0-9][0-9]).([0-9][0-9])\s+bitrate=\s*([0-9]+.[0-9])kbits\/s");
private TimeSpan fileDuration;
private TimeSpan actualConvertedDuration;
private ProcessStartInfo ffmpegProcessStartInfo;
public ConversionJob_FFMPEG() : base()
{
}
public ConversionJob_FFMPEG(ConversionPreset conversionPreset) : base(conversionPreset)
{
}
protected override void Initialize()
{
base.Initialize();
if (this.ConversionPreset == null)
{
throw new Exception("The conversion preset must be valid.");
}
this.ffmpegProcessStartInfo = null;
string applicationDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string ffmpegPath = string.Format("{0}\\ffmpeg.exe", applicationDirectory);
if (!System.IO.File.Exists(ffmpegPath))
{
this.ConvertionFailed("Can't find ffmpeg executable. You should try to reinstall the application.");
Diagnostics.Log("Can't find ffmpeg executable ({0}). Try to reinstall the application.", ffmpegPath);
return;
}
this.ffmpegProcessStartInfo = new ProcessStartInfo(ffmpegPath);
this.ffmpegProcessStartInfo.CreateNoWindow = true;
this.ffmpegProcessStartInfo.UseShellExecute = false;
this.ffmpegProcessStartInfo.RedirectStandardOutput = true;
this.ffmpegProcessStartInfo.RedirectStandardError = true;
string arguments = string.Empty;
switch (this.ConversionPreset.OutputType)
{
case OutputType.Wav:
{
EncodingMode encodingMode = this.ConversionPreset.GetSettingsValue<EncodingMode>("Encoding");
string encoderArgs = string.Format("-acodec {0}", this.WAVEncodingToCodecArgument(encodingMode));
arguments = string.Format("-n -stats -i \"{0}\" {2} \"{1}\"", this.InputFilePath, this.OutputFilePath, encoderArgs);
}
break;
case OutputType.Mp3:
{
string encoderArgs = string.Empty;
EncodingMode encodingMode = this.ConversionPreset.GetSettingsValue<EncodingMode>("Encoding");
int encodingQuality = this.ConversionPreset.GetSettingsValue<int>("Bitrate");
switch (encodingMode)
{
case EncodingMode.Mp3VBR:
encoderArgs = string.Format("-codec:a libmp3lame -q:a {0}", this.MP3VBRBitrateToQualityIndex(encodingQuality));
break;
case EncodingMode.Mp3CBR:
encoderArgs = string.Format("-codec:a libmp3lame -b:a {0}k", encodingQuality);
break;
default:
break;
}
arguments = string.Format("-n -stats -i \"{0}\" {2} \"{1}\"", this.InputFilePath, this.OutputFilePath, encoderArgs);
}
break;
case OutputType.Ogg:
{
int encodingQuality = this.ConversionPreset.GetSettingsValue<int>("Bitrate");
string encoderArgs = string.Format("-codec:a libvorbis -qscale:a {0}", this.OGGVBRBitrateToQualityIndex(encodingQuality));
arguments = string.Format("-n -stats -i \"{0}\" {2} \"{1}\"", this.InputFilePath, this.OutputFilePath, encoderArgs);
}
break;
case OutputType.Flac:
arguments = string.Format("-n -stats -i \"{0}\" \"{1}\"", this.InputFilePath, this.OutputFilePath);
break;
default:
throw new NotImplementedException("Converter not implemented for output file type " + this.ConversionPreset.OutputType);
}
if (string.IsNullOrEmpty(arguments))
{
throw new Exception("Invalid ffmpeg process arguments.");
}
this.ffmpegProcessStartInfo.Arguments = arguments;
}
protected override void Convert()
{
if (this.ConversionPreset == null)
{
throw new Exception("The conversion preset must be valid.");
}
Diagnostics.Log("Convert file {0} to {1}.", this.InputFilePath, this.OutputFilePath);
Diagnostics.Log(string.Empty);
Diagnostics.Log("Execute command: {0} {1}.", this.ffmpegProcessStartInfo.FileName, this.ffmpegProcessStartInfo.Arguments);
try
{
using (Process exeProcess = Process.Start(this.ffmpegProcessStartInfo))
{
using (StreamReader reader = exeProcess.StandardError)
{
while (!reader.EndOfStream)
{
string result = reader.ReadLine();
this.ParseFFMPEGOutput(result);
Diagnostics.Log("ffmpeg output: {0}", result);
}
}
exeProcess.WaitForExit();
}
}
catch
{
this.ConvertionFailed("Failed to launch FFMPEG process.");
throw;
}
}
private int MP3VBRBitrateToQualityIndex(int bitrate)
{
switch (bitrate)
{
case 245:
return 0;
case 225:
return 1;
case 190:
return 2;
case 175:
return 3;
case 165:
return 4;
case 130:
return 5;
case 115:
return 6;
case 100:
return 7;
case 85:
return 8;
case 65:
return 9;
}
throw new Exception("Unknown VBR bitrate.");
}
/// <summary>
/// Convert bitrate in <c>vorbis</c> encoder quality index.
/// </summary>
/// <param name="bitrate">Wanted bitrate value.</param>
/// <returns>The <c>vorbis</c> encoder quality index associated to the given bitrate value.</returns>
/// http://wiki.hydrogenaud.io/index.php?title=Recommended_Ogg_Vorbis
private int OGGVBRBitrateToQualityIndex(int bitrate)
{
switch (bitrate)
{
case 500:
return 10;
case 320:
return 9;
case 256:
return 8;
case 224:
return 7;
case 192:
return 6;
case 160:
return 5;
case 128:
return 4;
case 112:
return 3;
case 96:
return 2;
case 80:
return 1;
case 64:
return 0;
case 48:
return -1;
case 32:
return -2;
}
throw new Exception("Unknown VBR bitrate.");
}
/// <summary>
/// Convert encoding mode setting to <c>ffmpeg</c> argument option.
/// </summary>
/// <param name="encoding">The encoding mode setting.</param>
/// <returns>Returns the <c>ffmpeg</c> argument corresponding to the given encoding mode.</returns>
/// https://trac.ffmpeg.org/wiki/audio%20types
private string WAVEncodingToCodecArgument(EncodingMode encoding)
{
switch (encoding)
{
case EncodingMode.Wav8:
return "pcm_s8le";
case EncodingMode.Wav16:
return "pcm_s16le";
case EncodingMode.Wav24:
return "pcm_s24le";
case EncodingMode.Wav32:
return "pcm_s32le";
}
throw new Exception("Unknown Wav encoding.");
}
private void ParseFFMPEGOutput(string input)
{
Match match = this.durationRegex.Match(input);
if (match.Success && match.Groups.Count >= 6)
{
int hours = int.Parse(match.Groups[1].Value);
int minutes = int.Parse(match.Groups[2].Value);
int seconds = int.Parse(match.Groups[3].Value);
int milliseconds = int.Parse(match.Groups[4].Value);
float bitrate = float.Parse(match.Groups[5].Value);
this.fileDuration = new TimeSpan(0, hours, minutes, seconds, milliseconds);
return;
}
match = this.progressRegex.Match(input);
if (match.Success && match.Groups.Count >= 7)
{
int size = int.Parse(match.Groups[1].Value);
int hours = int.Parse(match.Groups[2].Value);
int minutes = int.Parse(match.Groups[3].Value);
int seconds = int.Parse(match.Groups[4].Value);
int milliseconds = int.Parse(match.Groups[5].Value);
float bitrate = 0f;
float.TryParse(match.Groups[6].Value, out bitrate);
this.actualConvertedDuration = new TimeSpan(0, hours, minutes, seconds, milliseconds);
this.Progress = this.actualConvertedDuration.Ticks / (float)this.fileDuration.Ticks;
return;
}
if (input.Contains("Exiting."))
{
this.ConvertionFailed(input);
}
}
}
}
@@ -1,151 +0,0 @@
// <copyright file="FileConverter.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
using System.Collections.Generic;
namespace FileConverter
{
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Xml.Serialization;
using FileConverter.Annotations;
[XmlRoot]
[XmlType]
public class ConversionPreset : INotifyPropertyChanged, IDataErrorInfo
{
private string name;
private OutputType outputType;
private List<string> inputTypes;
public ConversionPreset()
{
this.Name = "New Preset";
}
public ConversionPreset(string name, OutputType outputType, string[] inputTypes)
{
this.Name = name;
this.OutputType = outputType;
this.InputTypes = new List<string>();
this.InputTypes.AddRange(inputTypes);
}
public event PropertyChangedEventHandler PropertyChanged;
[XmlAttribute]
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
this.OnPropertyChanged();
}
}
[XmlAttribute]
public OutputType OutputType
{
get
{
return outputType;
}
set
{
outputType = value;
this.OnPropertyChanged();
}
}
[XmlElement]
public List<string> InputTypes
{
get
{
return inputTypes;
}
set
{
inputTypes = value;
this.OnPropertyChanged();
}
}
[XmlIgnore]
public ConversionPreset.Setting[] Settings
{
get;
set;
}
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public class Setting
{
}
public string this[string columnName]
{
get
{
return this.Validate(columnName);
}
}
public string Error
{
get
{
return this.Validate("Name");
}
}
private string Validate(string properyName)
{
// Return error message if there is an error, else return empty or null string.
switch (properyName)
{
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;
if (application?.Settings != null)
{
int count = application.Settings.ConversionPresets.Count(match => match.name == this.Name);
if (count > 1)
{
return "The preset name is already used.";
}
}
}
break;
}
return string.Empty;
}
}
}
@@ -0,0 +1,511 @@
// <copyright file="ConversionPreset.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Xml.Serialization;
using FileConverter.Annotations;
using FileConverter.ValueConverters;
[XmlRoot]
[XmlType]
public class ConversionPreset : INotifyPropertyChanged, IDataErrorInfo, IXmlSerializable
{
private string name;
private OutputType outputType;
private List<string> inputTypes;
private InputPostConversionAction inputPostConversionAction;
private ConversionSettings settings = new ConversionSettings();
private string outputFileNameTemplate;
private FileNameConverter outputFileNameConverter = new FileNameConverter();
public ConversionPreset()
{
this.Name = "New Preset";
}
public ConversionPreset(string name, OutputType outputType, string[] inputTypes)
{
this.Name = name;
this.OutputType = outputType;
List<string> inputTypeList = new List<string>();
inputTypeList.AddRange(inputTypes);
this.InputTypes = inputTypeList;
this.outputFileNameTemplate = "(p)(f)";
}
public event PropertyChangedEventHandler PropertyChanged;
[XmlAttribute]
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
this.OnPropertyChanged();
}
}
[XmlAttribute]
public OutputType OutputType
{
get
{
return this.outputType;
}
set
{
this.outputType = value;
this.InitializeDefaultSettings(this.outputType);
this.OnPropertyChanged();
}
}
[XmlElement]
public List<string> InputTypes
{
get
{
return this.inputTypes;
}
set
{
this.inputTypes = value;
for (int index = 0; index < this.inputTypes.Count; index++)
{
this.inputTypes[index] = this.inputTypes[index].ToLowerInvariant();
}
this.OnPropertyChanged();
}
}
[XmlElement]
public InputPostConversionAction InputPostConversionAction
{
get
{
return this.inputPostConversionAction;
}
set
{
this.inputPostConversionAction = value;
this.OnPropertyChanged();
}
}
[XmlElement("Settings")]
public ConversionSetting[] XmlSerializableSettings
{
get
{
int index = 0;
ConversionSetting[] settings = new ConversionSetting[this.settings.Count];
foreach (KeyValuePair<string, string> keyValuePair in this.settings)
{
settings[index] = new ConversionSetting(keyValuePair);
index++;
}
return settings;
}
set
{
if (value != null)
{
for (int index = 0; index < value.Length; index++)
{
this.SetSettingsValue(value[index].Key, value[index].Value);
}
}
this.OnPropertyChanged("Settings");
}
}
[XmlElement]
public string OutputFileNameTemplate
{
get
{
return this.outputFileNameTemplate;
}
set
{
this.outputFileNameTemplate = value;
this.OnPropertyChanged();
}
}
[XmlIgnore]
public string ConversionArchiveFolderName
{
get
{
return "Conversion Archives";
}
}
[XmlIgnore]
public IConversionSettings Settings
{
get
{
return this.settings;
}
set
{
if (value == null)
{
return;
}
foreach (KeyValuePair<string, string> conversionSetting in value)
{
if (!this.settings.ContainsKey(conversionSetting.Key))
{
this.settings.Add(conversionSetting.Key, conversionSetting.Value);
}
else
{
this.settings[conversionSetting.Key] = conversionSetting.Value;
}
}
this.OnPropertyChanged();
}
}
public string Error
{
get
{
string errorString = this.Validate("Name");
if (!string.IsNullOrEmpty(errorString))
{
return errorString;
}
errorString = this.Validate("OutputFileNameTemplate");
if (!string.IsNullOrEmpty(errorString))
{
return errorString;
}
return string.Empty;
}
}
public string this[string columnName]
{
get
{
return this.Validate(columnName);
}
}
public void OnDeserializationComplete()
{
for (int index = 0; index < this.InputTypes.Count; index++)
{
this.InputTypes[index] = this.InputTypes[index].ToLowerInvariant();
}
}
public void AddInputType(string inputType)
{
if (this.inputTypes.Contains(inputType))
{
return;
}
this.inputTypes.Add(inputType);
this.OnPropertyChanged("InputTypes");
}
public void RemoveInputType(string inputType)
{
if (this.inputTypes.Remove(inputType))
{
this.OnPropertyChanged("InputTypes");
}
}
public string GenerateOutputFilePath(string inputFilePath)
{
return (string)this.outputFileNameConverter.Convert(new object[] { inputFilePath, this.OutputType, this.OutputFileNameTemplate }, typeof(string), null, null);
}
public void SetSettingsValue(string settingsKey, string value)
{
if (string.IsNullOrEmpty(settingsKey))
{
throw new ArgumentNullException("key");
}
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException("value");
}
if (!this.IsRelevantSetting(settingsKey))
{
return;
}
if (!this.settings.ContainsKey(settingsKey))
{
this.settings.Add(settingsKey, value);
}
this.settings[settingsKey] = value;
this.OnPropertyChanged("Settings");
}
public string GetSettingsValue(string settingsKey)
{
if (string.IsNullOrEmpty(settingsKey))
{
throw new ArgumentNullException("key");
}
if (this.settings.ContainsKey(settingsKey))
{
return this.settings[settingsKey];
}
return null;
}
public T GetSettingsValue<T>(string settingsKey)
{
string settingsValue = this.GetSettingsValue(settingsKey);
Type type = typeof(T);
if (type.IsEnum)
{
return (T)System.Enum.Parse(type, settingsValue);
}
return (T)System.Convert.ChangeType(settingsValue, type);
}
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private bool IsRelevantSetting(string settingsKey)
{
switch (this.OutputType)
{
case OutputType.Wav:
switch (settingsKey)
{
case "Encoding":
return true;
}
break;
case OutputType.Mp3:
switch (settingsKey)
{
case "Encoding":
case "Bitrate":
return true;
}
break;
case OutputType.Ogg:
switch (settingsKey)
{
case "Bitrate":
return true;
}
break;
}
return false;
}
private void InitializeDefaultSettings(OutputType outputType)
{
if (outputType == OutputType.Wav)
{
this.InitializeSettingsValue("Encoding", "Wav16");
}
if (outputType == OutputType.Mp3)
{
this.InitializeSettingsValue("Encoding", EncodingMode.Mp3VBR.ToString());
this.InitializeSettingsValue("Bitrate", "190");
}
if (outputType == OutputType.Ogg)
{
this.InitializeSettingsValue("Bitrate", "160");
}
this.OnPropertyChanged("Settings");
}
private void InitializeSettingsValue(string settingsKey, string value)
{
if (string.IsNullOrEmpty(settingsKey))
{
throw new ArgumentNullException("key");
}
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException("value");
}
if (!this.settings.ContainsKey(settingsKey))
{
this.settings.Add(settingsKey, value);
}
}
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);
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<string, string> keyValuePair)
{
this.Key = keyValuePair.Key;
this.Value = keyValuePair.Value;
}
[XmlAttribute]
public string Key
{
get;
set;
}
[XmlAttribute]
public string Value
{
get;
set;
}
}
}
}
@@ -0,0 +1,10 @@
// <copyright file="ConversionSettings.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter
{
using System.Collections.Generic;
public class ConversionSettings : Dictionary<string, string>, IConversionSettings
{
}
}
@@ -0,0 +1,84 @@
// <copyright file="ConversionSettingsOverride.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter
{
using System.Collections;
using System.Collections.Generic;
public struct ConversionSettingsOverride : IConversionSettings
{
private string key;
private string value;
public ConversionSettingsOverride(string key, string value)
{
this.key = key;
this.value = value;
}
public int Count
{
get
{
return 1;
}
}
public IEnumerable<string> Keys
{
get
{
yield return this.key;
}
}
public IEnumerable<string> Values
{
get
{
yield return this.value;
}
}
public string this[string key]
{
get
{
if (key == this.key)
{
return this.value;
}
throw new KeyNotFoundException();
}
}
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
{
yield return new KeyValuePair<string, string>(this.key, this.value);
}
public bool ContainsKey(string key)
{
return key == this.key;
}
public bool TryGetValue(string key, out string value)
{
value = null;
if (key == this.key)
{
value = this.value;
return true;
}
return false;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
}
@@ -0,0 +1,10 @@
// <copyright file="IConversionSettings.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter
{
using System.Collections.Generic;
public interface IConversionSettings : IReadOnlyDictionary<string, string>
{
}
}
+17
View File
@@ -0,0 +1,17 @@
// <copyright file="EncodingMode.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter
{
public enum EncodingMode
{
Wav8,
Wav16,
Wav24,
Wav32,
Mp3VBR,
Mp3CBR,
OggVBR,
}
}
+51 -8
View File
@@ -42,7 +42,7 @@
<OutputPath>bin\x64\Release\</OutputPath>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>Resources\ApplicationIcon-256x256.ico</ApplicationIcon>
<ApplicationIcon>Resources\ApplicationIcon.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<Reference Include="Accessibility" />
@@ -51,7 +51,9 @@
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Printing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Core" />
@@ -71,18 +73,53 @@
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</ApplicationDefinition>
<Compile Include="Controls\EncodingQualitySliderControl.xaml.cs">
<DependentUpon>EncodingQualitySliderControl.xaml</DependentUpon>
</Compile>
<Compile Include="ConversionJobs\ConversionJobFactory.cs" />
<Compile Include="ConversionJobs\ConversionJob_FFMPEG.cs" />
<Compile Include="ConversionPreset\ConversionSettingsOverride.cs" />
<Compile Include="ConversionPreset\ConversionSettings.cs" />
<Compile Include="EncodingMode.cs" />
<Compile Include="ConversionPreset\IConversionSettings.cs" />
<Compile Include="InputPostConversionAction.cs" />
<Compile Include="IXmlSerializable.cs" />
<Compile Include="PathHelpers.cs" />
<Compile Include="Properties\Resources.en.Designer.cs">
<DependentUpon>Resources.en.resx</DependentUpon>
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
</Compile>
<Compile Include="ValueConverters\ApplicationVersionToApplicationName.cs" />
<Compile Include="ConversionPreset.cs" />
<Compile Include="ConversionPreset\ConversionPreset.cs" />
<Compile Include="ValueConverters\BitrateToString.cs" />
<Compile Include="ValueConverters\FileNameConverter.cs" />
<Compile Include="ValueConverters\Generic\BoolToVisibility.cs" />
<Compile Include="ValueConverters\ConversionSettingsToString.cs" />
<Compile Include="ValueConverters\Generic\BoolInverterConverter.cs" />
<Compile Include="ValueConverters\Generic\EqualsConverter.cs" />
<Compile Include="ValueConverters\Generic\CollectionContainsElementToBool.cs" />
<Compile Include="ValueConverters\Generic\StringToValueType.cs" />
<Compile Include="ValueConverters\InputTypesToBool.cs" />
<Compile Include="Settings.cs" />
<Compile Include="ValueConverters\OutputTypeToVisibility.cs" />
<Compile Include="ValueConverters\Generic\StringToEnum.cs" />
<Compile Include="ValueConverters\Generic\ValueConverterGroup.cs" />
<Compile Include="Windows\DiagnosticsWindow.xaml.cs">
<DependentUpon>DiagnosticsWindow.xaml</DependentUpon>
</Compile>
<Compile Include="Windows\ConversionSettingsTemplateSelector.cs" />
<Compile Include="Windows\InputExtension.cs" />
<Compile Include="Windows\InputExtensionCategory.cs" />
<Compile Include="Windows\SettingsWindow.xaml.cs">
<DependentUpon>SettingsWindow.xaml</DependentUpon>
</Compile>
<Compile Include="Version.cs" />
<Compile Include="XmlHelpers.cs" />
<Page Include="Controls\EncodingQualitySliderControl.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Windows\DiagnosticsWindow.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
@@ -96,7 +133,7 @@
<SubType>Code</SubType>
</Compile>
<Compile Include="ValueConverters\ConversionStateToBrush.cs" />
<Compile Include="ConversionJob.cs" />
<Compile Include="ConversionJobs\ConversionJob.cs" />
<Compile Include="Diagnostics.cs" />
<Compile Include="Windows\MainWindow.xaml.cs">
<DependentUpon>MainWindow.xaml</DependentUpon>
@@ -109,9 +146,12 @@
</ItemGroup>
<ItemGroup>
<Compile Include="OutputType.cs" />
<Compile Include="Properties\Annotations.cs" />
<Compile Include="Properties\Annotations.cs">
<ExcludeFromStyleCop>true</ExcludeFromStyleCop>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs">
<SubType>Code</SubType>
<ExcludeFromStyleCop>true</ExcludeFromStyleCop>
</Compile>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
@@ -123,8 +163,12 @@
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<EmbeddedResource Include="Properties\Resources.en.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.en.Designer.cs</LastGenOutput>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<None Include="Properties\Settings.settings">
@@ -140,11 +184,10 @@
<Resource Include="Resources\ApplicationIcon.png" />
</ItemGroup>
<ItemGroup>
<Resource Include="Resources\ApplicationIcon-16x16.ico" />
<Resource Include="Resources\ApplicationIcon-256x256.ico" />
<Resource Include="Resources\ApplicationIcon.ico" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
@@ -4,12 +4,22 @@
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=StyleCop_002ESA1601/@EntryIndexedValue">DO_NOT_SHOW</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=StyleCop_002ESA1602/@EntryIndexedValue">DO_NOT_SHOW</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=SuggestUseVarKeywordEvident/@EntryIndexedValue">DO_NOT_SHOW</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=UnusedMember_002ELocal/@EntryIndexedValue">HINT</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/ValueAnalysisMode/@EntryValue">PESSIMISTIC</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/ThisQualifier/INSTANCE_MEMBERS_QUALIFY_MEMBERS/@EntryValue">Field, Property, Event, Method</s:String>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_ABSTRACT_ACCESSORHOLDER_ON_SINGLE_LINE/@EntryValue">False</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_SIMPLE_ACCESSOR_ATTRIBUTE_ON_SAME_LINE/@EntryValue">False</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_SIMPLE_ACCESSOR_ON_SINGLE_LINE/@EntryValue">False</s:Boolean>
<s:String x:Key="/Default/CodeStyle/CSharpVarKeywordUsage/ForBuiltInTypes/@EntryValue">UseExplicitType</s:String>
<s:String x:Key="/Default/CodeStyle/CSharpVarKeywordUsage/ForOtherTypes/@EntryValue">UseExplicitType</s:String>
<s:String x:Key="/Default/CodeStyle/CSharpVarKeywordUsage/ForSimpleTypes/@EntryValue">UseExplicitType</s:String>
<s:String x:Key="/Default/CodeStyle/FileHeader/FileHeaderText/@EntryValue">// &lt;copyright file="$FILENAME$" company="AAllard"&gt;License: http://www.gnu.org/licenses/gpl.html GPL version 3.&lt;/copyright&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=CBR/@EntryIndexedValue">CBR</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=OGGVBR/@EntryIndexedValue">OGGVBR</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=VBR/@EntryIndexedValue">VBR</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=MethodPropertyEvent/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb_AaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=PrivateInstanceFields/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=PrivateStaticFields/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /&gt;</s:String>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateBlankLinesAroundFieldToBlankLinesAroundProperty/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateThisQualifierSettings/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateThisQualifierSettings/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/UpdatesManger/IsDownloadUpdateDataAllowed/@EntryValue">False</s:Boolean></wpf:ResourceDictionary>
@@ -0,0 +1,9 @@
// <copyright file="IXmlSerializable.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter
{
public interface IXmlSerializable
{
void OnDeserializationComplete();
}
}
@@ -0,0 +1,11 @@
// <copyright file="InputPostConversionAction.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter
{
public enum InputPostConversionAction
{
None,
MoveInArchiveFolder,
Delete,
}
}
+84
View File
@@ -0,0 +1,84 @@
// <copyright file="PathHelpers.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter
{
using System.Collections.Generic;
using System.Text.RegularExpressions;
public static class PathHelpers
{
private static Regex driveLetterRegex = new Regex(@"[a-zA-Z]:\\");
private static Regex pathRegex = new Regex(@"^[a-zA-Z]:\\(?:[^\\/:*?""<>|\r\n]+\\)*[^\.\\/:*?""<>|\r\n][^\\/:*?""<>|\r\n]*$");
private static Regex filenameRegex = new Regex(@"[^\\]*", RegexOptions.RightToLeft);
private static Regex directoryRegex = new Regex(@"(?:([^\\]*)\\)*");
public static bool IsPathDriveLetterValid(string path)
{
return PathHelpers.driveLetterRegex.IsMatch(path);
}
public static bool IsPathValid(string path)
{
return PathHelpers.pathRegex.IsMatch(path);
}
public static string GetFileName(string path)
{
MatchCollection matchCollection = PathHelpers.filenameRegex.Matches(path);
Match filenameMatch = matchCollection.Count > 0 ? matchCollection[0] : null;
return filenameMatch?.Groups[0].Value;
}
public static IEnumerable<string> GetDirectories(string path)
{
MatchCollection matchCollection = PathHelpers.directoryRegex.Matches(path);
Match match = matchCollection.Count > 0 ? matchCollection[0] : null;
if (match == null || match.Groups.Count < 2)
{
yield break;
}
Group matchGroup = match.Groups[1];
for (int index = 0; index < matchGroup.Captures.Count; index++)
{
yield return matchGroup.Captures[index].Value;
}
}
public static string GenerateUniquePath(string path)
{
string baseExtension = System.IO.Path.GetExtension(path);
string basePath = path.Substring(0, path.Length - baseExtension.Length);
int index = 2;
while (System.IO.File.Exists(path))
{
path = string.Format("{0} ({1}){2}", basePath, index, baseExtension);
index++;
}
return path;
}
public static string GetExtensionCategory(string extension)
{
switch (extension)
{
case "aiff":
case "ape":
case "flac":
case "mp3":
case "m4a":
case "ogg":
case "wav":
case "wma":
return "Audio";
case "avi":
case "mp4":
return "Video";
}
return "Misc";
}
}
}
+43 -26
View File
@@ -1,17 +1,17 @@
//------------------------------------------------------------------------------
// <auto-generated>
// 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.
// </auto-generated>
//------------------------------------------------------------------------------
namespace FileConverter.Properties
{
namespace FileConverter.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
@@ -22,50 +22,67 @@ namespace FileConverter.Properties
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
public class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("FileConverter.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set
{
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to C:\Data\MyFolder\Default.wav.
/// </summary>
public static string OuputFileNameTemplateSample {
get {
return ResourceManager.GetString("OuputFileNameTemplateSample", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to (p): input file path
///(f): input filename
///(o): output extension type
///(i): input extension type
///(d0): input parent folder
///(d1): input sub parent folder
///...
///use maj for uppercase version.
/// </summary>
public static string OutputFilePathTemplateHelp {
get {
return ResourceManager.GetString("OutputFilePathTemplateHelp", resourceCulture);
}
}
}
}
Whitespace-only changes.
@@ -0,0 +1,133 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="OuputFileNameTemplateSample" xml:space="preserve">
<value>C:\Music\Artist\Album\Song.wav</value>
</data>
<data name="OutputFilePathTemplateHelp" xml:space="preserve">
<value>(p): input file path
(f): input filename
(o): output extension type
(i): input extension type
(d0): input parent folder
(d1): input sub parent folder
...
use maj for uppercase version</value>
</data>
</root>
@@ -46,7 +46,7 @@
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
@@ -60,6 +60,7 @@
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
@@ -68,9 +69,10 @@
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
@@ -85,9 +87,10 @@
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
@@ -109,9 +112,22 @@
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="OuputFileNameTemplateSample" xml:space="preserve">
<value>C:\Music\Artist\Album\Song.wav</value>
</data>
<data name="OutputFilePathTemplateHelp" xml:space="preserve">
<value>(p): input file path
(f): input filename
(o): output extension type
(i): input extension type
(d0): input parent folder
(d1): input sub parent folder
...
use maj for uppercase version</value>
</data>
</root>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 294 KiB

+72 -73
View File
@@ -5,18 +5,17 @@ namespace FileConverter
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Microsoft.Win32;
using FileConverter.Annotations;
using Microsoft.Win32;
public class Settings : INotifyPropertyChanged, IDataErrorInfo
{
@@ -26,6 +25,29 @@ namespace FileConverter
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<ConversionPreset> ConversionPresets
{
get { return this.conversionPresets; }
set { this.conversionPresets = value; }
}
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
@@ -34,16 +56,45 @@ namespace FileConverter
}
}
public ObservableCollection<ConversionPreset> ConversionPresets
public string this[string columnName]
{
get { return this.conversionPresets; }
set { this.conversionPresets = value; }
get
{
return this.Error;
}
}
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
public static void ApplyTemporarySettings()
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
// Load temporary settings.
string temporaryFilePath = Settings.GetUserSettingsTemporaryFilePath();
if (!File.Exists(temporaryFilePath))
{
return;
}
ICollection<ConversionPreset> conversionPresets = new ObservableCollection<ConversionPreset>();
XmlHelpers.LoadFromFile("Settings", temporaryFilePath, ref conversionPresets);
RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(@"Software\FileConverter");
if (registryKey == null)
{
MessageBox.Show("Can't apply settings in registry. (code 0x03)", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
// Compute the registry entries data from settings.
Dictionary<string, List<string>> registryEntries = ComputeRegistryEntriesFromConvertionPresets(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 ConversionPreset GetPresetFromName(string presetName)
@@ -118,51 +169,18 @@ namespace FileConverter
}
}
public static void ApplyTemporarySettings()
{
// Load temporary settings.
string temporaryFilePath = Settings.GetUserSettingsTemporaryFilePath();
if (!File.Exists(temporaryFilePath))
{
return;
}
ICollection<ConversionPreset> conversionPresets = new ObservableCollection<ConversionPreset>();
XmlHelpers.LoadFromFile("Settings", temporaryFilePath, ref conversionPresets);
RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(@"Software\FileConverter");
if (registryKey == null)
{
MessageBox.Show("Can't apply settings in registry.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
// Compute the registry entries data from settings.
Dictionary<string, List<string>> registryEntries = ComputeRegistryEntriesFromConvertionPresets(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);
}
}
private static bool ApplyRegistryModifications(Dictionary<string, List<string>> registryEntries)
{
if (!Settings.IsInAdmininstratorPrivileges)
{
MessageBox.Show("Can't apply settings in registry because the application is not in administrator privileges.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
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 = Registry.CurrentUser.OpenSubKey(@"Software\FileConverter", RegistryKeyPermissionCheck.ReadWriteSubTree);
if (registryKey == null)
{
MessageBox.Show("Can't apply settings in registry (ErrorCode=1).", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
MessageBox.Show("Can't apply settings in registry. (code 0x05)", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return false;
}
@@ -174,9 +192,9 @@ namespace FileConverter
{
registryKey.DeleteSubKey(subKeyNames[index]);
}
catch (Exception exception)
catch (Exception)
{
MessageBox.Show("Can't apply settings in registry (ErrorCode=2).", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
MessageBox.Show("Can't apply settings in registry. (code 0x06)", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return false;
}
}
@@ -207,7 +225,7 @@ namespace FileConverter
if (subKey == null)
{
MessageBox.Show("Can't apply settings in registry (ErrorCode=3).", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
MessageBox.Show("Can't apply settings in registry. (code 0x07)", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return false;
}
@@ -352,36 +370,17 @@ namespace FileConverter
process.Start();
process.WaitForExit();
}
catch (Exception exception)
catch (Exception)
{
MessageBox.Show("Can't apply settings in registry because the application has no administrator privileges.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
MessageBox.Show("Can't apply settings in registry because the application has no administrator privileges. (code 0x08)", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
}
public string this[string columnName]
[NotifyPropertyChangedInvocator]
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
get
{
return this.Error;
}
}
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;
}
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
+44 -17
View File
@@ -1,28 +1,55 @@
<?xml version="1.0" encoding="utf-8"?>
<Settings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ConversionPreset Name="To Ogg" OutputType="Ogg">
<InputTypes>Wav</InputTypes>
<InputTypes>Flac</InputTypes>
<InputTypes>Wma</InputTypes>
<InputTypes>Mp3</InputTypes>
<InputTypes>Ape</InputTypes>
<InputTypes>flac</InputTypes>
<InputTypes>ape</InputTypes>
<InputTypes>wav</InputTypes>
<InputTypes>wma</InputTypes>
<InputTypes>m4a</InputTypes>
<InputTypes>avi</InputTypes>
<InputTypes>mp4</InputTypes>
<InputTypes>mp3</InputTypes>
<InputTypes>aiff</InputTypes>
<InputPostConversionAction>None</InputPostConversionAction>
<Settings Key="Bitrate" Value="128" />
<OutputFileNameTemplate>(p)(f)</OutputFileNameTemplate>
</ConversionPreset>
<ConversionPreset Name="To Mp3" OutputType="Mp3">
<InputTypes>Flac</InputTypes>
<InputTypes>Ogg</InputTypes>
<InputTypes>Wav</InputTypes>
<InputTypes>Wma</InputTypes>
<InputTypes>Ape</InputTypes>
<InputTypes>ogg</InputTypes>
<InputTypes>flac</InputTypes>
<InputTypes>ape</InputTypes>
<InputTypes>wav</InputTypes>
<InputTypes>wma</InputTypes>
<InputTypes>m4a</InputTypes>
<InputTypes>mp4</InputTypes>
<InputTypes>avi</InputTypes>
<InputTypes>aiff</InputTypes>
<InputPostConversionAction>None</InputPostConversionAction>
<Settings Key="Encoding" Value="Mp3VBR" />
<Settings Key="Bitrate" Value="175" />
<OutputFileNameTemplate>(p)(f)</OutputFileNameTemplate>
</ConversionPreset>
<ConversionPreset Name="To Flac" OutputType="Flac">
<InputTypes>Wav</InputTypes>
<InputTypes>Ape</InputTypes>
<InputTypes>ape</InputTypes>
<InputTypes>wav</InputTypes>
<InputTypes>avi</InputTypes>
<InputTypes>mp4</InputTypes>
<InputTypes>aiff</InputTypes>
<InputPostConversionAction>None</InputPostConversionAction>
<OutputFileNameTemplate>(p)(f)</OutputFileNameTemplate>
</ConversionPreset>
<ConversionPreset Name="To Wav" OutputType="Wav">
<InputTypes>Flac</InputTypes>
<InputTypes>Mp3</InputTypes>
<InputTypes>Ogg</InputTypes>
<InputTypes>Wma</InputTypes>
<InputTypes>Ape</InputTypes>
<InputTypes>ape</InputTypes>
<InputTypes>flac</InputTypes>
<InputTypes>mp3</InputTypes>
<InputTypes>ogg</InputTypes>
<InputTypes>wma</InputTypes>
<InputTypes>avi</InputTypes>
<InputTypes>mp4</InputTypes>
<InputTypes>m4a</InputTypes>
<InputTypes>aiff</InputTypes>
<InputPostConversionAction>None</InputPostConversionAction>
<Settings Key="Encoding" Value="Wav16" />
<OutputFileNameTemplate>(p)(f)</OutputFileNameTemplate>
</ConversionPreset>
</Settings>
@@ -1,6 +1,6 @@
// <copyright file="ApplicationVersionToApplicationName.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter
namespace FileConverter.ValueConverters
{
using System;
using System.Globalization;
@@ -10,12 +10,12 @@ namespace FileConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is Version))
if (!(value is FileConverter.Version))
{
return "File Converter";
}
Version version = (Version)value;
FileConverter.Version version = (FileConverter.Version)value;
return string.Format("File Converter v{0}", version.ToString());
}
@@ -0,0 +1,28 @@
// <copyright file="BitrateToString.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter.ValueConverters
{
using System;
using System.Globalization;
using System.Windows.Data;
public class BitrateToString : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is double))
{
throw new ArgumentException("The value must be a double value.");
}
double bitrate = (double)value;
return string.Format("{0} kbit/s", bitrate.ToString("0"));
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
@@ -0,0 +1,76 @@
// <copyright file="ConversionSettingsToString.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter.ValueConverters
{
using System;
using System.Globalization;
using System.Windows.Data;
public class ConversionSettingsToString : 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 parameterString = parameter as string;
if (parameterString == null)
{
throw new ArgumentException("The parameter must be a string value.");
}
string[] parameters = parameterString.Split(',');
if (parameters.Length < 1 || parameters.Length > 2)
{
throw new ArgumentException("The parameter format must be 'SettingsKey[,DefaultValue]'.");
}
string key = parameters[0];
string setting;
if (settings.TryGetValue(key, out setting))
{
return setting;
}
if (parameters.Length >= 2)
{
return parameters[1];
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
{
return null;
}
if (!(value is string))
{
throw new ArgumentException("value");
}
string settingsValue = (string)value;
if (!(parameter is string))
{
throw new ArgumentException("parameter");
}
string settingsKey = (string)parameter;
return new ConversionSettingsOverride(settingsKey, settingsValue);
}
}
}
@@ -1,12 +1,14 @@
// <copyright file="ConversionStateToBrush.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter
namespace FileConverter.ValueConverters
{
using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;
using FileConverter.ConversionJobs;
public class ConversionStateToBrush : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
@@ -0,0 +1,81 @@
// <copyright file="FileNameConverter.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter.ValueConverters
{
using System;
using System.Globalization;
using System.Windows.Data;
public class FileNameConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values == null || values.Length != 3)
{
throw new ArgumentException("The values must contains the input file path, the output file extension and the ouput file template.");
}
if (!(values[1] is OutputType))
{
return "Invalid output file extension (argument 1).";
}
string inputFilePath = values[0] as string;
OutputType outputFileExtension = (OutputType)values[1];
string outputFileTemplate = values[2] as string;
if (inputFilePath == null)
{
return "Invalid input file path (argument 0).";
}
string inputExtension = System.IO.Path.GetExtension(inputFilePath).Substring(1);
string inputPathWithoutExtension = inputFilePath.Substring(0, inputFilePath.Length - inputExtension.Length - 1);
string outputExtension = outputFileExtension.ToString().ToLowerInvariant();
if (outputFileTemplate == null)
{
// Default output path.
return inputPathWithoutExtension + "." + outputExtension;
}
string fileName = System.IO.Path.GetFileName(inputPathWithoutExtension);
string parentDirectory = System.IO.Path.GetDirectoryName(inputPathWithoutExtension);
string[] directories = parentDirectory.Split(System.IO.Path.DirectorySeparatorChar);
parentDirectory += System.IO.Path.DirectorySeparatorChar;
// Generate output path from template.
string outputPath = outputFileTemplate;
outputPath = outputPath.Replace("(path)", parentDirectory);
outputPath = outputPath.Replace("(p)", parentDirectory);
outputPath = outputPath.Replace("(filename)", fileName);
outputPath = outputPath.Replace("(f)", fileName);
outputPath = outputPath.Replace("(F)", fileName.ToUpperInvariant());
outputPath = outputPath.Replace("(outputext)", outputExtension);
outputPath = outputPath.Replace("(o)", outputExtension);
outputPath = outputPath.Replace("(O)", outputExtension.ToUpperInvariant());
outputPath = outputPath.Replace("(inputext)", inputExtension);
outputPath = outputPath.Replace("(i)", inputExtension);
outputPath = outputPath.Replace("(I)", inputExtension.ToUpperInvariant());
for (int index = 0; index < directories.Length; index++)
{
outputPath = outputPath.Replace(string.Format("(d{0})", directories.Length - index - 1), directories[index]);
outputPath = outputPath.Replace(string.Format("(D{0})", directories.Length - index - 1), directories[index].ToUpperInvariant());
}
outputPath += "." + outputExtension;
return outputPath;
}
public object[] ConvertBack(object value, Type[] targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
@@ -0,0 +1,28 @@
// <copyright file="BoolInverterConverter.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter.ValueConverters.Generic
{
using System;
using System.Globalization;
using System.Windows.Data;
public class BoolInverterConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is bool))
{
throw new System.ArgumentException("The object must be a boolean value.");
}
bool boolValue = (bool)value;
return !boolValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
@@ -0,0 +1,28 @@
// <copyright file="BoolToVisibility.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter.ValueConverters.Generic
{
using System;
using System.Globalization;
using System.Windows.Data;
public class BoolToVisibility : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is bool))
{
throw new ArgumentException("The value must be a boolean.");
}
bool booleanValue = (bool)value;
return booleanValue ? "Visible" : "Hidden";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
@@ -0,0 +1,66 @@
// <copyright file="CollectionContainsElementToBool.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter.ValueConverters.Generic
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Data;
public class CollectionContainsElementToBool : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values == null || values.Length != 2)
{
throw new ArgumentException("The values must contains the collection of elements and the researched element.");
}
//// TODO: Make this converter generic.
if (!(values[0] is ICollection<string>))
{
return false;
}
bool? result = null;
if (values[1] is IEnumerable<string>)
{
ICollection<string> collection = values[0] as ICollection<string>;
IEnumerable<string> objectsToFind = values[1] as IEnumerable<string>;
bool all = true;
bool none = true;
foreach (string objectToFind in objectsToFind)
{
bool contains = collection.Contains(objectToFind);
all &= contains;
none &= !contains;
}
if (all)
{
result = true;
}
else if (none)
{
result = false;
}
}
else
{
ICollection<string> collection = values[0] as ICollection<string>;
string objectToFind = values[1] as string;
result = collection.Contains(objectToFind);
}
return result;
}
public object[] ConvertBack(object value, Type[] targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
@@ -0,0 +1,37 @@
// <copyright file="EqualsConverter.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter.ValueConverters.Generic
{
using System;
using System.Globalization;
using System.Windows.Data;
public class EqualsConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
{
return parameter == null;
}
return value.Equals(parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is bool))
{
throw new ArgumentException("value");
}
bool equals = (bool)value;
if (equals)
{
return parameter;
}
return null;
}
}
}
@@ -0,0 +1,40 @@
// <copyright file="StringToEnum.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter.ValueConverters.Generic
{
using System;
using System.Globalization;
using System.Windows.Data;
public class StringToEnum : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string stringValue = value as string;
if (value == null)
{
// TODO default value ?
return null;
}
string typeName = parameter as string;
if (typeName == null)
{
throw new ArgumentNullException("parameter", "The parameter must contains the enum type.");
}
Type enumType = Type.GetType(typeName);
if (enumType == null)
{
throw new Exception("Invalid enum type " + typeName + ".");
}
return Enum.Parse(enumType, stringValue);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
@@ -0,0 +1,43 @@
// <copyright file="StringToValueType.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter.ValueConverters.Generic
{
using System;
using System.Globalization;
using System.Windows.Data;
public class StringToValueType : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
{
return null;
}
string typeName = parameter as string;
if (typeName == null)
{
throw new ArgumentNullException("parameter", "The parameter must contains a convertible type.");
}
Type type = Type.GetType(typeName);
if (type == null)
{
throw new Exception("Invalid enum type " + typeName + ".");
}
return System.Convert.ChangeType(value, type);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
{
return null;
}
return value.ToString();
}
}
}
@@ -0,0 +1,68 @@
// <copyright file="ValueConverterGroup.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter.ValueConverters.Generic
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Data;
public class ValueConverterGroup : List<IValueConverter>, IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string[] parameters = null;
if (parameter == null)
{
parameters = new string[this.Count];
}
else
{
string parameterString = parameter as string;
if (parameterString == null)
{
throw new ArgumentException("The parameter must be a string value.");
}
parameters = parameterString.Split('|');
if (parameters.Length != this.Count)
{
throw new ArgumentException("The parameter format must be 'Converter1Parameters|Converter2Parameters|...'.");
}
}
object result = value;
for (int index = 0; index < this.Count; index++)
{
IValueConverter converter = this[index];
result = converter.Convert(result, targetType, parameters[index], culture);
}
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string parameterString = parameter as string;
if (parameterString == null)
{
throw new ArgumentException("The parameter must be a string value.");
}
string[] parameters = parameterString.Split('|');
if (parameters.Length != this.Count)
{
throw new ArgumentException("The parameter format must be 'Converter1Parameters|Converter2Parameters|...'.");
}
object result = value;
for (int index = this.Count - 1; index >= 0; index--)
{
IValueConverter converter = this[index];
result = converter.ConvertBack(result, targetType, parameters[index], culture);
}
return result;
}
}
}
@@ -1,6 +1,6 @@
// <copyright file="InputTypesToBool.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter
namespace FileConverter.ValueConverters
{
using System;
using System.Collections.Generic;
@@ -0,0 +1,40 @@
// <copyright file="OutputTypeToVisibility.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter.ValueConverters
{
using System;
using System.Globalization;
using System.Windows.Data;
public class OutputTypeToVisibility : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is OutputType))
{
throw new ArgumentException("The value must be an output type enum value.");
}
OutputType outputType = (OutputType)value;
string referenceTypeName = parameter as string;
if (string.IsNullOrEmpty(referenceTypeName))
{
return "Hidden";
}
OutputType referenceType;
if (!Enum.TryParse<OutputType>(referenceTypeName, out referenceType))
{
return "Hidden";
}
return outputType == referenceType ? "Visible" : "Hidden";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
+1 -5
View File
@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// <copyright file="Version.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter
{
@@ -0,0 +1,58 @@
// <copyright file="ConversionSettingsTemplateSelector.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter.Windows
{
using System.Windows;
using System.Windows.Controls;
public class ConversionSettingsTemplateSelector : DataTemplateSelector
{
public DataTemplate DefaultDataTemplate
{
get;
set;
}
public DataTemplate WavSettingsDataTemplate
{
get;
set;
}
public DataTemplate Mp3SettingsDataTemplate
{
get;
set;
}
public DataTemplate OggSettingsDataTemplate
{
get;
set;
}
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
if (item == null)
{
return this.DefaultDataTemplate;
}
OutputType outputType = (OutputType)item;
switch (outputType)
{
case OutputType.Wav:
return this.WavSettingsDataTemplate;
case OutputType.Mp3:
return this.Mp3SettingsDataTemplate;
case OutputType.Ogg:
return this.OggSettingsDataTemplate;
}
return this.DefaultDataTemplate;
}
}
}
@@ -6,7 +6,7 @@
xmlns:local="clr-namespace:FileConverter.Windows"
xmlns:fileConverter="clr-namespace:FileConverter"
mc:Ignorable="d"
Title="Diagnostics" Height="600" Width="800" Icon="/FileConverter;component/Resources/ApplicationIcon-16x16.ico">
Title="Diagnostics" Height="600" Width="800" Icon="/FileConverter;component/Resources/ApplicationIcon.ico">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30" />
@@ -1,27 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
// <copyright file="DiagnosticsWindow.xaml.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter.Windows
{
using System.Windows;
/// <summary>
/// Interaction logic for DiagnosticsWindow.xaml
/// Interaction logic for DiagnosticsWindow.
/// </summary>
public partial class DiagnosticsWindow : Window
{
public DiagnosticsWindow()
{
InitializeComponent();
this.InitializeComponent();
}
}
}
@@ -0,0 +1,41 @@
// <copyright file="InputExtension.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter
{
using System.ComponentModel;
using System.Runtime.CompilerServices;
using FileConverter.Annotations;
public class InputExtension : INotifyPropertyChanged
{
private string name;
public InputExtension(string name)
{
this.Name = name;
}
public event PropertyChangedEventHandler PropertyChanged;
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
this.OnPropertyChanged();
}
}
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
@@ -0,0 +1,74 @@
// <copyright file="InputExtensionCategory.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
namespace FileConverter
{
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using FileConverter.Annotations;
public class InputExtensionCategory : INotifyPropertyChanged
{
private string name;
private List<InputExtension> inputExtensions = new List<InputExtension>();
public InputExtensionCategory(string name)
{
this.Name = name;
}
public event PropertyChangedEventHandler PropertyChanged;
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
this.OnPropertyChanged();
}
}
public IEnumerable<InputExtension> InputExtensions
{
get
{
return this.inputExtensions;
}
}
public IEnumerable<string> 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);
this.OnPropertyChanged("InputExtensions");
this.OnPropertyChanged("InputExtensionNames");
}
}
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
@@ -1,13 +1,14 @@
<Window
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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="FileConverter.MainWindow"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:FileConverter"
x:Name="FileConverterMainWindow" Height="500" Width="950" MinHeight="250" MinWidth="450" WindowStartupLocation="CenterScreen" Icon="/FileConverter;component/Resources/ApplicationIcon-16x16.ico">
xmlns:valueConverters="clr-namespace:FileConverter.ValueConverters"
xmlns:conversionJobs="clr-namespace:FileConverter.ConversionJobs" mc:Ignorable="d" x:Class="FileConverter.MainWindow"
x:Name="FileConverterMainWindow" Height="500" Width="950" MinHeight="250" MinWidth="450" WindowStartupLocation="CenterScreen" Icon="/FileConverter;component/Resources/ApplicationIcon.ico">
<Window.Resources>
<local:ApplicationVersionToApplicationName x:Key="ApplicationVersionToApplicationName"/>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
<local:ConversionStateToBrush x:Key="ConversionStateToColor" />
<valueConverters:ApplicationVersionToApplicationName x:Key="ApplicationVersionToApplicationName"/>
<valueConverters:ConversionStateToBrush x:Key="ConversionStateToColor" />
</Window.Resources>
<Window.Title>
<Binding Converter="{StaticResource ApplicationVersionToApplicationName}" Mode="OneWay" Path="(local:Application.ApplicationVersion)"/>
@@ -26,19 +27,16 @@
<ColumnDefinition Width="100" />
</Grid.ColumnDefinitions>
<Label Name="Title" Grid.Column="0" Content="Files to convert" VerticalAlignment="Top" Height="30" FontSize="16" FontWeight="Bold"/>
<Button Name="DiagnosticsButton" Grid.Column="1" Content="Logs" Margin="3,3" Click="DiagnosticsButton_OnClick"/>
<Button Name="SettingsButton" Grid.Column="2" Content="Settings" Margin="3,3" Click="SettingsButton_OnClick"/>
<Label x:Name="Title" Grid.Column="0" Content="Files to convert" VerticalAlignment="Top" Height="30" FontSize="16" FontWeight="Bold"/>
<Button x:Name="DiagnosticsButton" Grid.Column="1" Content="Logs" Margin="3,3" Click="DiagnosticsButton_OnClick"/>
<Button x:Name="SettingsButton" Grid.Column="2" Content="Settings" Margin="3,3" Click="SettingsButton_OnClick"/>
</Grid>
<ScrollViewer x:Name="ScrollViewer" Grid.Row="1" VerticalScrollBarVisibility="Auto" CanContentScroll="True">
<ItemsControl Name="ConverterJobsList">
<ItemsControl.DataContext>
<local:ConversionJob/>
</ItemsControl.DataContext>
<ItemsControl x:Name="ConverterJobsList">
<ItemsControl.ItemTemplate>
<DataTemplate>
<DockPanel Background="{Binding State, Converter={StaticResource ConversionStateToColor}, ConverterParameter='Background'}" Margin="0,4">
<DockPanel Background="{Binding State, ConverterParameter=Background, Converter={StaticResource ConversionStateToColor}}" Margin="0,4">
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="20" />
@@ -56,16 +54,19 @@
<TextBlock Text="Converted from " FontSize="11" FontStyle="Italic" />
<TextBlock Text="{Binding InputFilePath}" FontSize="11" FontStyle="Italic" />
</WrapPanel>
<TextBlock Text="{Binding ExitingMessage}" Foreground="{Binding State, Converter={StaticResource ConversionStateToColor}, ConverterParameter='Foreground'}" />
<TextBlock Text="{Binding ErrorMessage}" Foreground="{Binding State, ConverterParameter=Foreground, Converter={StaticResource ConversionStateToColor}}" />
</StackPanel>
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding State}" FontWeight="Bold" Foreground="{Binding State, Converter={StaticResource ConversionStateToColor}, ConverterParameter='Foreground'}" />
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding State}" FontWeight="Bold" Foreground="{Binding State, ConverterParameter=Foreground, Converter={StaticResource ConversionStateToColor}}" />
<ProgressBar Grid.Row="1" Grid.Column="1" Height="18" Width="Auto" Minimum="0" Maximum="1" SmallChange="0.001" Value="{Binding Progress, Mode=OneWay}" Foreground="{Binding State, Converter={StaticResource ConversionStateToColor}, ConverterParameter='Foreground'}" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch" MinWidth="100" LargeChange="0.1" />
<ProgressBar Grid.Row="1" Grid.Column="1" Height="18" Width="Auto" Minimum="0" Maximum="1" SmallChange="0.001" Value="{Binding Progress, Mode=OneWay}" Foreground="{Binding State, ConverterParameter=Foreground, Converter={StaticResource ConversionStateToColor}}" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch" MinWidth="100" LargeChange="0.1" />
</Grid>
</DockPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.DataContext>
<conversionJobs:ConversionJob/>
</ItemsControl.DataContext>
</ItemsControl>
</ScrollViewer>
</Grid>
@@ -11,8 +11,6 @@ namespace FileConverter
public partial class MainWindow : Window, INotifyPropertyChanged
{
private bool verboseMode;
private DiagnosticsWindow diagnosticsWindow;
private SettingsWindow settingsWindow;
@@ -33,7 +31,7 @@ namespace FileConverter
this.Hide();
this.ShowSettingsWindow();
this.settingsWindow.Deactivated += this.SettingsWindow_Closed;
this.settingsWindow.OnSettingsWindowHide += this.SettingsWindow_Closed;
}
}
@@ -56,7 +54,7 @@ namespace FileConverter
private void SettingsWindow_Closed(object sender, System.EventArgs e)
{
settingsWindow.Deactivated -= this.SettingsWindow_Closed;
this.settingsWindow.OnSettingsWindowHide -= this.SettingsWindow_Closed;
this.Close();
}
@@ -1,11 +1,43 @@
<Window x:Name="window" x:Class="FileConverter.SettingsWindow"
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:FileConverter"
Height="370" Width="520" MinHeight="370" MinWidth="440"
WindowStartupLocation="CenterScreen" Icon="/FileConverter;component/Resources/ApplicationIcon-16x16.ico">
xmlns:controls="clr-namespace:FileConverter.Controls"
xmlns:valueConverters="clr-namespace:FileConverter.ValueConverters"
xmlns:generic="clr-namespace:FileConverter.ValueConverters.Generic"
xmlns:windows="clr-namespace:FileConverter.Windows"
xmlns:project="clr-namespace:FileConverter.Properties"
xmlns:System="clr-namespace:System;assembly=mscorlib" x:Name="window" x:Class="FileConverter.SettingsWindow"
Height="600" Width="800" MinHeight="480" MinWidth="640"
WindowStartupLocation="CenterScreen" Icon="/FileConverter;component/Resources/ApplicationIcon.ico"
Closing="SettingsWindow_OnClosing">
<Window.Resources>
<local:InputTypesToBool x:Key="InputTypesToBool"/>
<local:ApplicationVersionToApplicationName x:Key="ApplicationVersionToApplicationName"/>
<valueConverters:FileNameConverter x:Key="FileNameConverter"/>
<generic:BoolToVisibility x:Key="BoolToVisibility"/>
<valueConverters:InputTypesToBool x:Key="InputTypesToBool"/>
<valueConverters:OutputTypeToVisibility x:Key="OutputTypeToVisibility"/>
<valueConverters:ApplicationVersionToApplicationName x:Key="ApplicationVersionToApplicationName"/>
<generic:CollectionContainsElementToBool x:Key="CollectionContainsElementToBool"/>
<generic:ValueConverterGroup x:Key="ConversionSettingsToEnum">
<valueConverters:ConversionSettingsToString/>
<generic:StringToEnum/>
</generic:ValueConverterGroup>
<generic:ValueConverterGroup x:Key="ConversionSettingsEquals">
<valueConverters:ConversionSettingsToString/>
<generic:EqualsConverter/>
</generic:ValueConverterGroup>
<generic:ValueConverterGroup x:Key="ConversionSettingsToValueType">
<valueConverters:ConversionSettingsToString/>
<generic:StringToValueType/>
</generic:ValueConverterGroup>
<generic:ValueConverterGroup x:Key="ReferenceToVisibility">
<generic:EqualsConverter/>
<generic:BoolInverterConverter/>
<generic:BoolToVisibility/>
</generic:ValueConverterGroup>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Validation.ErrorTemplate">
@@ -13,10 +45,10 @@
<ControlTemplate>
<DockPanel LastChildFill="true">
<Border Background="#F44336" DockPanel.Dock="right" Margin="5,0,0,0" Width="20" Height="20" CornerRadius="10"
ToolTip="{Binding ElementName=customAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
ToolTip="{Binding AdornedElement.(Validation.Errors)[0].ErrorContent, ElementName=customAdorner}">
<TextBlock Text="!" VerticalAlignment="center" HorizontalAlignment="center" FontWeight="Bold" Foreground="white"/>
</Border>
<AdornedElementPlaceholder Name="customAdorner" VerticalAlignment="Center" >
<AdornedElementPlaceholder x:Name="customAdorner" VerticalAlignment="Center" >
<Border BorderBrush="#F44336" BorderThickness="1" />
</AdornedElementPlaceholder>
</DockPanel>
@@ -24,16 +56,64 @@
</Setter.Value>
</Setter>
</Style>
<DataTemplate x:Key="EmptyDataTemplate">
<StackPanel/>
</DataTemplate>
<DataTemplate x:Key="WavSettingsDataTemplate">
<StackPanel>
<DockPanel>
<Label Content="Encoding :" />
<RadioButton x:Name="WAV8radioButton" Content="8-bits" ToolTip="PCM signed 8-bit little-endian" Margin="5" IsChecked="{Binding SelectedPreset.Settings, ConverterParameter=Encoding|Wav8, Converter={StaticResource ConversionSettingsEquals}, ElementName=window, Mode=TwoWay}" />
<RadioButton x:Name="WAV16radioButton" Content="16-bits" ToolTip="PCM signed 16-bit little-endian" Margin="5" IsChecked="{Binding SelectedPreset.Settings, ConverterParameter=Encoding|Wav16, Converter={StaticResource ConversionSettingsEquals}, ElementName=window, Mode=TwoWay}"/>
<RadioButton x:Name="WAV24radioButton" Content="24-bits" ToolTip="PCM signed 24-bit little-endian" Margin="5" IsChecked="{Binding SelectedPreset.Settings, ConverterParameter=Encoding|Wav24, Converter={StaticResource ConversionSettingsEquals}, ElementName=window, Mode=TwoWay}"/>
<RadioButton x:Name="WAV32radioButton" Content="32-bits" ToolTip="PCM signed 32-bit little-endian" Margin="5" IsChecked="{Binding SelectedPreset.Settings, ConverterParameter=Encoding|Wav32, Converter={StaticResource ConversionSettingsEquals}, ElementName=window, Mode=TwoWay}"/>
</DockPanel>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="Mp3SettingsDataTemplate">
<StackPanel>
<DockPanel>
<Label Content="Encoding :" />
<RadioButton x:Name="VBRradioButton" Content="VBR" ToolTip="Variable bitrate encoding" Margin="5" IsChecked="{Binding SelectedPreset.Settings, ConverterParameter=Encoding|Mp3VBR, Converter={StaticResource ConversionSettingsEquals}, ElementName=window, Mode=TwoWay}" />
<RadioButton x:Name="CBRradioButton" Content="CBR" ToolTip="Constant bitrate encoding" Margin="5" IsChecked="{Binding SelectedPreset.Settings, ConverterParameter=Encoding|Mp3CBR, Converter={StaticResource ConversionSettingsEquals}, ElementName=window, Mode=TwoWay}"/>
</DockPanel>
<DockPanel>
<Label Content="Quality :" />
<controls:EncodingQualitySliderControl x:Name="EncodingQualitySlider"
EncodingMode="{Binding SelectedPreset.Settings, ConverterParameter=Encoding|FileConverter.EncodingMode, Converter={StaticResource ConversionSettingsToEnum}, ElementName=window, Mode=OneWay, TargetNullValue=VBR}"
Bitrate="{Binding SelectedPreset.Settings, ConverterParameter=Bitrate|System.Double, Converter={StaticResource ConversionSettingsToValueType}, ElementName=window, Mode=TwoWay, TargetNullValue=190}" />
</DockPanel>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="OggSettingsDataTemplate">
<StackPanel>
<DockPanel>
<Label Content="Quality :" />
<controls:EncodingQualitySliderControl x:Name="EncodingQualitySlider" EncodingMode="OggVBR"
Bitrate="{Binding SelectedPreset.Settings, ConverterParameter=Bitrate|System.Double, Converter={StaticResource ConversionSettingsToValueType}, ElementName=window, Mode=TwoWay, TargetNullValue=160}" />
</DockPanel>
</StackPanel>
</DataTemplate>
<windows:ConversionSettingsTemplateSelector x:Key="ConversionSettingsSelector"
DefaultDataTemplate="{StaticResource EmptyDataTemplate}"
WavSettingsDataTemplate="{StaticResource WavSettingsDataTemplate}"
Mp3SettingsDataTemplate="{StaticResource Mp3SettingsDataTemplate}"
OggSettingsDataTemplate="{StaticResource OggSettingsDataTemplate}" />
</Window.Resources>
<Window.Title>
<Binding Converter="{StaticResource ApplicationVersionToApplicationName}" Mode="OneWay" Path="(local:Application.ApplicationVersion)"/>
</Window.Title>
<Grid Margin="10">
<Grid.CommandBindings>
<Grid x:Name="grid" Margin="10">
<Grid.CommandBindings>
<CommandBinding Command="New" CanExecute="CanSaveSettings" />
</Grid.CommandBindings>
<Grid.RowDefinitions>
<RowDefinition Height="48"/>
<RowDefinition Height="*"/>
@@ -48,39 +128,54 @@
</Grid.ColumnDefinitions>
<Image HorizontalAlignment="Left" Height="48" Width="48" VerticalAlignment="Top" Source="..\Resources\ApplicationIcon.png" />
<Label Content="Settings" FontSize="20" Margin="4" Grid.Column="1" VerticalAlignment="Center" />
<Label HorizontalAlignment="Right" FontStyle="Italic" FontSize="14" Grid.Column="2" VerticalAlignment="Center">
<Label.Content>
<Binding Converter="{StaticResource ApplicationVersionToApplicationName}" Mode="OneWay" Path="(local:Application.ApplicationVersion)"/>
</Label.Content>
<Label Grid.Column="1" Content="Settings" FontSize="20" Margin="4" VerticalAlignment="Center" />
<Label Grid.Column="2" HorizontalAlignment="Right" FontStyle="Italic" FontSize="14" VerticalAlignment="Center">
<Label.Content>
<Binding Path="(local:Application.ApplicationVersion)" Converter="{StaticResource ApplicationVersionToApplicationName}" Mode="OneWay" />
</Label.Content>
</Label>
</Grid>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="122"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label Content="Presets" Margin="0,5,0,0" VerticalAlignment="Top" HorizontalContentAlignment="Center" HorizontalAlignment="Left" Width="100" Grid.ColumnSpan="2"/>
<ListBox Name="PresetList" HorizontalAlignment="Left" Margin="0,36,0,0" Width="100" Grid.ColumnSpan="2"
Grid.Column="0" IsSynchronizedWithCurrentItem="True" SelectedItem="{Binding SelectedPreset, ElementName=window}">
<ItemsControl.DataContext>
<local:ConversionPreset/>
</ItemsControl.DataContext>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Label Content="{Binding Name}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ListBox>
<Grid x:Name="PresetListGrid" Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="*"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<Label Content="Presets" Grid.Row="0" VerticalAlignment="Top" HorizontalContentAlignment="Center" HorizontalAlignment="Left" Width="{Binding ActualWidth, ElementName=PresetListGrid, Mode=OneWay}" />
<ListBox x:Name="PresetList" Grid.Row="1" HorizontalAlignment="Left" IsSynchronizedWithCurrentItem="True" SelectedItem="{Binding SelectedPreset, ElementName=window}" Width="{Binding ActualWidth, ElementName=PresetListGrid, Mode=OneWay}">
<ListBox.DataContext>
<local:ConversionPreset/>
</ListBox.DataContext>
<ListBox.ItemTemplate>
<DataTemplate>
<Label Content="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<DockPanel Grid.Row="2" Margin="0,5,0,0">
<Button x:Name="MoveUpPresetButton" Content="^" HorizontalAlignment="Left" Width="25" Margin="0,0,2,0" Click="MovePresetUpButton_Click"/>
<Button x:Name="AddPresetButton" Content="+" HorizontalAlignment="Left" Width="25" Margin="2,0" Click="AddPresetButton_Click"/>
<Button x:Name="RemovePresetButton" Content="-" HorizontalAlignment="Left" Width="25" Margin="2,0" Click="RemovePresetButton_Click"/>
<Button x:Name="MoveDownPresetButton" Content="v" HorizontalAlignment="Left" Width="25" Margin="2,0,0,0" Click="MovePresetDownButton_Click"/>
</DockPanel>
</Grid>
<!-- Preset settings -->
<GroupBox Header="Preset
" Margin="5,5,0,0" Grid.Column="1">
<GroupBox Header="Preset" Margin="5,5,0,0" Grid.Column="1" Visibility="{Binding SelectedPreset, Converter={StaticResource ReferenceToVisibility}, ElementName=window}">
<Grid Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*" MaxWidth="240"/>
<ColumnDefinition Width="2*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
@@ -88,32 +183,99 @@
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label Content="Preset name" Grid.Row="0" HorizontalContentAlignment="Right" Margin="0,0,5,0"/>
<TextBox Name="PresetNameTextBox" Grid.Row="0" Grid.Column="1" Margin="5,2,25,2" Text="{Binding SelectedPreset.Name, Mode=TwoWay, ElementName=window, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" TextWrapping="Wrap" Width="Auto" />
<TextBox x:Name="PresetNameTextBox" Grid.Row="0" Grid.Column="1" Margin="5,2,25,2" Text="{Binding SelectedPreset.Name, ElementName=window, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" TextWrapping="Wrap" Width="Auto" />
<GroupBox Grid.Row="1" Grid.Column="0" Header="Input formats" Margin="5">
<StackPanel>
<CheckBox Content="Ape" Height="20" VerticalAlignment="Top" Margin="2" Checked="ToggleButton_OnChecked" Unchecked="ToggleButton_OnUnchecked" IsChecked="{Binding SelectedPreset.InputTypes, Converter={StaticResource InputTypesToBool}, ConverterParameter='Ape', ElementName=window, Mode=OneWay}"/>
<CheckBox Content="Flac" Height="20" VerticalAlignment="Top" Margin="2" Checked="ToggleButton_OnChecked" Unchecked="ToggleButton_OnUnchecked" IsChecked="{Binding SelectedPreset.InputTypes, Converter={StaticResource InputTypesToBool}, ConverterParameter='Flac', ElementName=window, Mode=OneWay}"/>
<CheckBox Content="Mp3" Height="20" VerticalAlignment="Top" Margin="2" Checked="ToggleButton_OnChecked" Unchecked="ToggleButton_OnUnchecked" IsChecked="{Binding SelectedPreset.InputTypes, Converter={StaticResource InputTypesToBool}, ConverterParameter='Mp3', ElementName=window, Mode=OneWay}"/>
<CheckBox Content="Ogg" Height="20" VerticalAlignment="Top" Margin="2" Checked="ToggleButton_OnChecked" Unchecked="ToggleButton_OnUnchecked" IsChecked="{Binding SelectedPreset.InputTypes, Converter={StaticResource InputTypesToBool}, ConverterParameter='Ogg', ElementName=window, Mode=OneWay}"/>
<CheckBox Content="Wav" Height="20" VerticalAlignment="Top" Margin="2" Checked="ToggleButton_OnChecked" Unchecked="ToggleButton_OnUnchecked" IsChecked="{Binding SelectedPreset.InputTypes, Converter={StaticResource InputTypesToBool}, ConverterParameter='Wav', ElementName=window, Mode=OneWay}"/>
<CheckBox Content="Wma" Height="20" VerticalAlignment="Top" Margin="2" Checked="ToggleButton_OnChecked" Unchecked="ToggleButton_OnUnchecked" IsChecked="{Binding SelectedPreset.InputTypes, Converter={StaticResource InputTypesToBool}, ConverterParameter='Wma', ElementName=window, Mode=OneWay}"/>
</StackPanel>
<Grid Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="25"/>
<RowDefinition Height="25"/>
</Grid.RowDefinitions>
<TreeView x:Name="InputTypesTreeView" ItemsSource="{Binding InputCategories, ElementName=window}" >
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:InputExtensionCategory}" ItemsSource="{Binding InputExtensions}">
<CheckBox Content="{Binding Name}" Height="20" VerticalAlignment="Top" Margin="2" Checked="OnInputTypeCategoryChecked" Unchecked="OnInputTypeCategoryUnchecked" IsThreeState="True" >
<CheckBox.IsChecked>
<MultiBinding Converter="{StaticResource CollectionContainsElementToBool}" Mode="OneWay">
<Binding ElementName="window" Path="SelectedPreset.InputTypes" Mode="OneWay"/>
<Binding Path="InputExtensionNames" Mode="OneWay"/>
</MultiBinding>
</CheckBox.IsChecked>
</CheckBox>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type local:InputExtension}">
<CheckBox Content="{Binding Name}" Height="20" VerticalAlignment="Top" Margin="2" Checked="OnInputTypeChecked" Unchecked="OnInputTypeUnchecked">
<CheckBox.IsChecked>
<MultiBinding Converter="{StaticResource CollectionContainsElementToBool}" Mode="OneWay">
<Binding ElementName="window" Path="SelectedPreset.InputTypes" Mode="OneWay"/>
<Binding Path="Name" Mode="OneWay"/>
</MultiBinding>
</CheckBox.IsChecked>
</CheckBox>
</DataTemplate>
</TreeView.Resources>
<TreeView.ItemContainerStyle>
<Style TargetType="TreeViewItem">
<Setter Property="IsExpanded" Value="True" />
</Style>
</TreeView.ItemContainerStyle>
</TreeView>
<Label Grid.Row="1" Content="Action when conversion succeed"/>
<ComboBox Grid.Row="2" x:Name="PostConversionActionComboBox" SelectedItem="{Binding SelectedPreset.InputPostConversionAction, ElementName=window, Mode=TwoWay}" />
</Grid>
</GroupBox>
<GroupBox Header="Output format" Grid.Row="1" Grid.Column="1" Margin="5">
<ComboBox Name="OutputFormats" Grid.Row="1" Grid.Column="1" Margin="5" Height="25" VerticalAlignment="Top" SelectedItem="{Binding SelectedPreset.OutputType, ElementName=window, Mode=TwoWay}">
</ComboBox>
<StackPanel>
<ComboBox x:Name="OutputFormats" Margin="5" Height="25" VerticalAlignment="Top" SelectedItem="{Binding SelectedPreset.OutputType, ElementName=window, Mode=TwoWay}"/>
<ContentControl ContentTemplateSelector="{StaticResource ResourceKey=ConversionSettingsSelector}"
Content="{Binding SelectedPreset.OutputType, ElementName=window, UpdateSourceTrigger=PropertyChanged}" />
<Separator/>
<!-- Output file name template -->
<Grid Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="2*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="23"/>
<RowDefinition Height="23"/>
</Grid.RowDefinitions>
<Label Content="File name template" Grid.Row="0" HorizontalContentAlignment="Right" Margin="0,0,5,0"/>
<TextBox x:Name="FileNameTemplateTextBox" Grid.Row="0" Grid.Column="1" Margin="5,2,25,2" Text="{Binding SelectedPreset.OutputFileNameTemplate, ElementName=window, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" TextWrapping="Wrap" Width="Auto" ToolTip="{x:Static project:Resources.OutputFilePathTemplateHelp}" />
<Label Content="Input example" Grid.Row="1" Grid.Column="0" HorizontalContentAlignment="Right" Margin="0,0,5,0" Foreground="Gray" FontSize="10"/>
<TextBlock Text="{x:Static project:Resources.OuputFileNameTemplateSample}" Grid.Row="1" Grid.Column="1" Margin="5,0,5,0" Foreground="Gray" FontSize="10" VerticalAlignment="Center"/>
<Label Content="Output" Grid.Row="2" Grid.Column="0" HorizontalContentAlignment="Right" Margin="0,0,5,0" Foreground="Gray" FontSize="10"/>
<TextBlock Grid.Row="2" Grid.Column="1" Margin="5,0,5,0" Foreground="Gray" FontSize="10" VerticalAlignment="Center">
<TextBlock.Text>
<MultiBinding Converter="{StaticResource FileNameConverter}">
<Binding Source="{x:Static project:Resources.OuputFileNameTemplateSample}"/>
<Binding ElementName="window" Path="SelectedPreset.OutputType" Mode="OneWay"/>
<Binding ElementName="window" Path="SelectedPreset.OutputFileNameTemplate" Mode="OneWay"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Grid>
</StackPanel>
</GroupBox>
</Grid>
</GroupBox>
</Grid>
<Button Name="AddPresetButton" Grid.Row="2" Content="+" HorizontalAlignment="Left" Width="28" Margin="18,4,0,0" Click="AddPresetButton_Click"/>
<Button Name="RemovePresetButton" Grid.Row="2" Content="-" HorizontalAlignment="Left" Width="28" Margin="54,4,0,0" Click="RemovePresetButton_Click"/>
<Button Name="CloseButton" Grid.Row="2" Content="Close" HorizontalAlignment="Right" Width="100" Margin="0,4,105,0" Click="CloseButton_Click" />
<Button Name="SaveButton" Grid.Row="2" Content="Save" HorizontalAlignment="Right" Width="100" Margin="0,4,0,0" Click="SaveButton_Click" Command="New"/>
<Button x:Name="CloseButton" Grid.Row="2" Content="Close" HorizontalAlignment="Right" Width="100" Margin="0,4,105,0" Click="CloseButton_Click" />
<Button x:Name="SaveButton" Grid.Row="2" Content="Save" HorizontalAlignment="Right" Width="100" Margin="0,4,0,0" Click="SaveButton_Click" Command="New"/>
</Grid>
</Window>
@@ -2,16 +2,19 @@
namespace FileConverter
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.ComponentModel;
using System.Windows.Controls;
using System.Windows.Input;
using FileConverter.Annotations;
using Microsoft.Win32;
/// <summary>
/// Interaction logic for Settings.xaml
/// Interaction logic for Settings.
/// </summary>
public partial class SettingsWindow : Window, INotifyPropertyChanged
{
@@ -19,13 +22,15 @@ namespace FileConverter
private Settings settings;
private InputExtensionCategory[] inputCategories;
public SettingsWindow()
{
this.InitializeComponent();
Application application = Application.Current as Application;
settings = application.Settings;
this.PresetList.ItemsSource = settings.ConversionPresets;
this.settings = application.Settings;
this.PresetList.ItemsSource = this.settings.ConversionPresets;
OutputType[] outputTypes = new[]
{
@@ -36,10 +41,23 @@ namespace FileConverter
};
this.OutputFormats.ItemsSource = outputTypes;
InputPostConversionAction[] postConversionActions = new[]
{
InputPostConversionAction.None,
InputPostConversionAction.MoveInArchiveFolder,
InputPostConversionAction.Delete,
};
this.PostConversionActionComboBox.ItemsSource = postConversionActions;
this.InitializeCompatibleInputExtensions();
}
public event PropertyChangedEventHandler PropertyChanged;
public event System.EventHandler<System.EventArgs> OnSettingsWindowHide;
public ConversionPreset SelectedPreset
{
get
@@ -54,13 +72,27 @@ namespace FileConverter
}
}
public InputExtensionCategory[] InputCategories
{
get
{
return this.inputCategories;
}
set
{
this.inputCategories = value;
this.OnPropertyChanged();
}
}
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private void ToggleButton_OnChecked(object sender, RoutedEventArgs e)
private void OnInputTypeChecked(object sender, RoutedEventArgs e)
{
if (this.selectedPreset == null)
{
@@ -68,15 +100,46 @@ namespace FileConverter
}
CheckBox checkBox = sender as System.Windows.Controls.CheckBox;
string inputFormat = checkBox.Content as string;
string inputFormat = (checkBox.Content as string).ToLowerInvariant();
if (!this.selectedPreset.InputTypes.Contains(inputFormat))
this.selectedPreset.AddInputType(inputFormat);
}
private void OnInputTypeUnchecked(object sender, RoutedEventArgs e)
{
if (this.selectedPreset == null)
{
this.selectedPreset.InputTypes.Add(inputFormat);
return;
}
CheckBox checkBox = sender as System.Windows.Controls.CheckBox;
string inputFormat = (checkBox.Content as string).ToLowerInvariant();
this.selectedPreset.RemoveInputType(inputFormat);
}
private void OnInputTypeCategoryChecked(object sender, RoutedEventArgs e)
{
if (this.selectedPreset == null)
{
return;
}
CheckBox checkBox = sender as System.Windows.Controls.CheckBox;
string categoryName = checkBox.Content as string;
InputExtensionCategory category = System.Array.Find(this.inputCategories, match => match.Name == categoryName);
if (category == null)
{
return;
}
foreach (string inputExtension in category.InputExtensionNames)
{
this.selectedPreset.AddInputType(inputExtension);
}
}
private void ToggleButton_OnUnchecked(object sender, RoutedEventArgs e)
private void OnInputTypeCategoryUnchecked(object sender, RoutedEventArgs e)
{
if (this.selectedPreset == null)
{
@@ -84,18 +147,22 @@ namespace FileConverter
}
CheckBox checkBox = sender as System.Windows.Controls.CheckBox;
string inputFormat = checkBox.Content as string;
string categoryName = checkBox.Content as string;
InputExtensionCategory category = System.Array.Find(this.inputCategories, match => match.Name == categoryName);
if (category == null)
{
return;
}
this.selectedPreset.InputTypes.Remove(inputFormat);
foreach (string inputExtension in category.InputExtensionNames)
{
this.selectedPreset.RemoveInputType(inputExtension);
}
}
private void CloseButton_Click(object sender, RoutedEventArgs e)
{
// Load previous preset in order to cancel changes.
Application application = Application.Current as Application;
application.Settings.Load();
this.Hide();
this.HideSettingsWindow();
}
private void SaveButton_Click(object sender, RoutedEventArgs e)
@@ -105,6 +172,8 @@ namespace FileConverter
application.Settings.Save();
this.Hide();
this.OnSettingsWindowHide?.Invoke(this, new EventArgs());
}
private void AddPresetButton_Click(object sender, RoutedEventArgs e)
@@ -127,5 +196,87 @@ namespace FileConverter
{
e.CanExecute = this.settings != null && string.IsNullOrEmpty(this.settings.Error);
}
private void SettingsWindow_OnClosing(object sender, CancelEventArgs e)
{
e.Cancel = true;
this.HideSettingsWindow();
}
private void HideSettingsWindow()
{
// Load previous preset in order to cancel changes.
Application application = Application.Current as Application;
application.Settings.Load();
this.Hide();
this.OnSettingsWindowHide?.Invoke(this, new EventArgs());
}
private void MovePresetUpButton_Click(object sender, RoutedEventArgs e)
{
ConversionPreset presetToMove = this.SelectedPreset;
if (presetToMove == null)
{
return;
}
int indexOfSelectedPreset = this.settings.ConversionPresets.IndexOf(presetToMove);
int newIndexOfSelectedPreset = System.Math.Max(0, indexOfSelectedPreset - 1);
this.settings.ConversionPresets.Move(indexOfSelectedPreset, newIndexOfSelectedPreset);
}
private void MovePresetDownButton_Click(object sender, RoutedEventArgs e)
{
ConversionPreset presetToMove = this.SelectedPreset;
if (presetToMove == null)
{
return;
}
int indexOfSelectedPreset = this.settings.ConversionPresets.IndexOf(presetToMove);
int newIndexOfSelectedPreset = System.Math.Min(this.settings.ConversionPresets.Count - 1, indexOfSelectedPreset + 1);
this.settings.ConversionPresets.Move(indexOfSelectedPreset, newIndexOfSelectedPreset);
}
private void InitializeCompatibleInputExtensions()
{
RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(@"Software\FileConverter");
if (registryKey == null)
{
MessageBox.Show("Can't retrieve the list of compatible input extensions. (code 0x09)", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
string registryValue = registryKey.GetValue("CompatibleInputExtensions") as string;
if (registryValue == null)
{
MessageBox.Show("Can't retrieve the list of compatible input extensions. (code 0x0A)", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
string[] compatibleInputExtensions = registryValue.Split(';');
List<InputExtensionCategory> categories = new List<InputExtensionCategory>();
for (int index = 0; index < compatibleInputExtensions.Length; index++)
{
string compatibleInputExtension = compatibleInputExtensions[index];
string extensionCategory = PathHelpers.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();
}
}
}
+83 -61
View File
@@ -1,75 +1,97 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Documents;
using System.Xml;
using System.Xml.Serialization;
// <copyright file="XmlHelpers.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
using FileConverter;
public class XmlHelpers
namespace FileConverter
{
public static void LoadFromFile<T>(string root, string path, ref ICollection<T> collection)
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
public class XmlHelpers
{
if (string.IsNullOrEmpty(path))
public static void LoadFromFile<T>(string root, string path, ref ICollection<T> collection)
{
throw new ArgumentNullException("path");
}
XmlRootAttribute xmlRoot = new XmlRootAttribute
{
ElementName = root
};
XmlSerializer serializer = new XmlSerializer(typeof(List<T>), xmlRoot);
try
{
using (StreamReader reader = new StreamReader(path))
using (XmlReader xmlReader = XmlReader.Create(reader, new XmlReaderSettings { IgnoreWhitespace = true, IgnoreComments = true }))
if (string.IsNullOrEmpty(path))
{
List<T> elements = (List<T>)serializer.Deserialize(xmlReader);
foreach (T element in elements)
throw new ArgumentNullException("path");
}
XmlRootAttribute xmlRoot = new XmlRootAttribute
{
ElementName = root
};
XmlSerializer serializer = new XmlSerializer(typeof(List<T>), xmlRoot);
try
{
using (StreamReader reader = new StreamReader(path))
{
collection.Add(element);
XmlReaderSettings xmlReaderSettings = new XmlReaderSettings
{
IgnoreWhitespace = true, IgnoreComments = true
};
using (XmlReader xmlReader = XmlReader.Create(reader, xmlReaderSettings))
{
List<T> elements = (List<T>)serializer.Deserialize(xmlReader);
for (int index = 0; index < elements.Count; index++)
{
T item = elements[index];
if (item is IXmlSerializable)
{
(item as IXmlSerializable).OnDeserializationComplete();
}
collection.Add(item);
}
}
}
}
}
catch (System.Exception exception)
{
Diagnostics.Log("The database of type '" + typeof(T) + "' failed to load the asset. The following exception was raised:\n " + exception.Message);
}
}
public static void SaveToFile<T>(string root, string path, ICollection<T> objectsToSerialize)
{
if (string.IsNullOrEmpty(path))
{
return;
}
List<T> list = new List<T>();
list.AddRange(objectsToSerialize);
XmlRootAttribute xmlRoot = new XmlRootAttribute
{
ElementName = root
};
XmlSerializer serializer = new XmlSerializer(typeof(List<T>), xmlRoot);
try
{
using (StreamWriter writer = new StreamWriter(path))
using (XmlWriter xmlWriter = XmlWriter.Create(writer, new XmlWriterSettings { Indent = true, IndentChars = " " }))
catch (System.Exception exception)
{
serializer.Serialize(xmlWriter, list);
Diagnostics.Log("The database of type '" + typeof(T) + "' failed to load the asset. The following exception was raised:\n " + exception.Message);
}
}
catch (System.Exception exception)
public static void SaveToFile<T>(string root, string path, ICollection<T> objectsToSerialize)
{
Diagnostics.Log("The database of type '" + typeof(T) + "' failed to load the asset. The following exception was raised:\n " + exception.Message);
if (string.IsNullOrEmpty(path))
{
return;
}
List<T> list = new List<T>();
list.AddRange(objectsToSerialize);
XmlRootAttribute xmlRoot = new XmlRootAttribute
{
ElementName = root
};
XmlSerializer serializer = new XmlSerializer(typeof(List<T>), xmlRoot);
try
{
using (StreamWriter writer = new StreamWriter(path))
{
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings
{
Indent = true, IndentChars = " "
};
using (XmlWriter xmlWriter = XmlWriter.Create(writer, xmlWriterSettings))
{
serializer.Serialize(xmlWriter, list);
}
}
}
catch (System.Exception exception)
{
Diagnostics.Log("The database of type '" + typeof(T) + "' failed to load the asset. The following exception was raised:\n " + exception.Message);
}
}
}
}
}
@@ -16,6 +16,9 @@ namespace FileConverterExtension
using SharpShell.Attributes;
using SharpShell.SharpContextMenu;
/// <summary>
/// File converter context menu extension class.
/// </summary>
[ComVisible(true), Guid("AF9B72B5-F4E4-44B0-A3D9-B55B748EFE90")]
[COMServerAssociation(AssociationType.AllFiles)]
public class FileConverterExtension : SharpContextMenu
@@ -23,6 +26,7 @@ namespace FileConverterExtension
private string fileConverterPath;
private RegistryKey fileConverterRegistryKey;
private List<PresetDefinition> presetList = new List<PresetDefinition>();
private List<string> compatibleInputExtensions = new List<string>();
private RegistryKey FileConverterRegistryKey
{
@@ -54,6 +58,27 @@ namespace FileConverterExtension
}
}
private IEnumerable<string> CompatibleInputExtensions
{
get
{
if (this.compatibleInputExtensions != null && this.compatibleInputExtensions.Count > 0)
{
return this.compatibleInputExtensions;
}
this.compatibleInputExtensions.Clear();
string registryValue = this.FileConverterRegistryKey.GetValue("CompatibleInputExtensions") as string;
string[] extensions = registryValue.Split(';');
for (int index = 0; index < extensions.Length; index++)
{
this.compatibleInputExtensions.Add(extensions[index]);
}
return this.compatibleInputExtensions;
}
}
protected override bool CanShowMenu()
{
foreach (string filePath in this.SelectedItemPaths)
@@ -65,15 +90,9 @@ namespace FileConverterExtension
}
extension = extension.Substring(1).ToLowerInvariant();
switch (extension)
if (this.CompatibleInputExtensions.Contains(extension))
{
case "ape":
case "mp3":
case "wav":
case "ogg":
case "flac":
case "wma":
return true;
return true;
}
}
@@ -62,7 +62,9 @@
<ItemGroup>
<Compile Include="FileConverterExtension.cs" />
<Compile Include="PresetDefinition.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Properties\AssemblyInfo.cs">
<ExcludeFromStyleCop>true</ExcludeFromStyleCop>
</Compile>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
@@ -83,11 +85,11 @@
<None Include="Resources\ApplicationIcon-16x16.ico" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>
@@ -4,9 +4,6 @@ namespace FileConverterExtension
{
public class PresetDefinition
{
public bool Enabled;
public int ExtensionRefCount;
public PresetDefinition(string name)
{
this.Name = name;
@@ -17,5 +14,17 @@ namespace FileConverterExtension
get;
private set;
}
public bool Enabled
{
get;
set;
}
public int ExtensionRefCount
{
get;
set;
}
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

@@ -0,0 +1,24 @@
<StyleCopSettings Version="105">
<Analyzers>
<Analyzer AnalyzerId="StyleCop.CSharp.DocumentationRules">
<Rules>
<Rule Name="ElementsMustBeDocumented">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="EnumerationItemsMustBeDocumented">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="PartialElementsMustBeDocumented">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
</Rules>
<AnalyzerSettings />
</Analyzer>
</Analyzers>
</StyleCopSettings>
+21 -8
View File
@@ -11,7 +11,7 @@
<?endif ?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
<Product Id="*" Name="$(var.ProductName)" Language="1033" Version="0.2.0" Manufacturer="AAllard" UpgradeCode="e3ca717b-a897-418a-bbef-5c7e35c76e4b">
<Product Id="*" Name="$(var.ProductName)" Language="1033" Version="0.3.0" Manufacturer="AAllard" UpgradeCode="e3ca717b-a897-418a-bbef-5c7e35c76e4b">
<Package Id="*" InstallerVersion="200" Compressed="yes" InstallScope="perMachine" Platform="x64" />
<Icon Id="icon.ico" SourceFile="..\Resources\ApplicationIcon-256x256.ico"/>
@@ -69,26 +69,39 @@
<!-- Registry entries -->
<Component Id="RegistryEntries" Guid="{C3EF3D67-0206-4DBD-B2EA-78FF2E290093}">
<RegistryKey Root="HKCU" Key="Software\FileConverter" Action="createAndRemoveOnUninstall">
<RegistryKey Root="HKCU" Key="Software\FileConverter">
<RegistryValue Name="Path" Type="string" Value="[INSTALLFOLDER]FileConverter.exe"/>
<RegistryValue Name="CompatibleInputExtensions" Type="string" Value="aiff;ape;avi;flac;m4a;mp3;mp4;ogg;wav;wma"/>
</RegistryKey>
<RegistryKey Root="HKCU" Key="Software\FileConverter\ape" Action="createAndRemoveOnUninstall">
<RegistryKey Root="HKCU" Key="Software\FileConverter\aiff">
<RegistryValue Name="Presets" Type="string" Value="To Ogg;To Mp3;To Flac;To Wav"/>
</RegistryKey>
<RegistryKey Root="HKCU" Key="Software\FileConverter\flac" Action="createAndRemoveOnUninstall">
<RegistryKey Root="HKCU" Key="Software\FileConverter\ape">
<RegistryValue Name="Presets" Type="string" Value="To Ogg;To Mp3;To Flac;To Wav"/>
</RegistryKey>
<RegistryKey Root="HKCU" Key="Software\FileConverter\avi">
<RegistryValue Name="Presets" Type="string" Value="To Ogg;To Mp3;To Flac;To Wav"/>
</RegistryKey>
<RegistryKey Root="HKCU" Key="Software\FileConverter\flac">
<RegistryValue Name="Presets" Type="string" Value="To Ogg;To Mp3;To Wav"/>
</RegistryKey>
<RegistryKey Root="HKCU" Key="Software\FileConverter\mp3" Action="createAndRemoveOnUninstall">
<RegistryKey Root="HKCU" Key="Software\FileConverter\m4a">
<RegistryValue Name="Presets" Type="string" Value="To Ogg;To Mp3;To Wav"/>
</RegistryKey>
<RegistryKey Root="HKCU" Key="Software\FileConverter\mp3">
<RegistryValue Name="Presets" Type="string" Value="To Ogg;To Wav"/>
</RegistryKey>
<RegistryKey Root="HKCU" Key="Software\FileConverter\ogg" Action="createAndRemoveOnUninstall">
<RegistryKey Root="HKCU" Key="Software\FileConverter\mp4">
<RegistryValue Name="Presets" Type="string" Value="To Ogg;To Mp3;To Flac;To Wav"/>
</RegistryKey>
<RegistryKey Root="HKCU" Key="Software\FileConverter\ogg">
<RegistryValue Name="Presets" Type="string" Value="To Mp3;To Wav"/>
</RegistryKey>
<RegistryKey Root="HKCU" Key="Software\FileConverter\wav" Action="createAndRemoveOnUninstall">
<RegistryKey Root="HKCU" Key="Software\FileConverter\wav">
<RegistryValue Name="Presets" Type="string" Value="To Ogg;To Mp3;To Flac"/>
</RegistryKey>
<RegistryKey Root="HKCU" Key="Software\FileConverter\wma" Action="createAndRemoveOnUninstall">
<RegistryKey Root="HKCU" Key="Software\FileConverter\wma">
<RegistryValue Name="Presets" Type="string" Value="To Ogg;To Mp3;To Wav"/>
</RegistryKey>
</Component>
+70 -5
View File
@@ -1,16 +1,81 @@
# File Converter
## Description
File Converter is a very simple tool which allows you to convert one or several file(s) from one format to another using the context menu in windows explorer.
This program uses [ffmpeg](https://www.ffmpeg.org/) as file conversion tool.
**File Converter** is a very simple tool which allows you to convert one or several file(s) from one format to another using the context menu in windows explorer.
This program uses [ffmpeg](https://www.ffmpeg.org/) as file conversion software.
You can convert files from formats **Ape, Mp3, Ogg, Wav, Flac, Wma** to formats **Mp3, Ogg, Wav, Flac**
You can convert files from formats **Aiff, Ape, Avi, Flac, M4a, Mp3, Mp4, Ogg, Wav, Wma** to formats **Mp3, Ogg, Wav, Flac**.
**Remove any previous installation of the application before installing the newer version.**
*Note: If your source file is a video, the conversion to an audio format will extract the audio part of the video.*
***Remove any previous installation of the application before installing the newer version.***
This application is under GPL version 3 licence.
For more informations check the LICENSE file in your installation folder or the [gnu website](http://www.gnu.org/licenses/gpl.html).
## Input file post conversion actions
This actions allow you to chose what you want to do with your input files if the conversion succeed.
Action | Description
----------------------------|------------------------------------------------------------------------------------------------
**None** | Don't modify the input file. If the output file name conflict with the input, it will be renamed.
**Move in archive folder** | Move the input file in a folder named *Conversion Archives* if the conversion is a success.
**Delete** | Delete the input file if the conversion is a success (be careful no warning will be prompted).
## Output file path template
This template allow you to define how you want to generate the output file path (depending on the input file path).
You have access to the following informations:
Pattern | Description | Example (with input path: *C:\Music\Artist\Album\Song.wav*)
--------|-------------------------------|-----------------------------------------------------------------
(p) | Input file path | C:\Music\Artist\Album\
(f) | Input file name | Song
(o) | Output file format | mp3
(i) | Input file format | wav
(d0) | Input parent folder name | Album
(d1) | Input sub parent folder name | Artist
*Tips: You can use uppercase to retrieve caps lock informations. Example: (f) -> Default / (F) -> DEFAULT *
### Examples
Simple default template (just change the extension):
Input: C:\Music\Artist\Album\Song.wav
Template: (p)(f)
Generated output: C:\Music\Artist\Album\Song.mp3
File name customization:
Input: C:\Music\Artist\Album\Song.wav
Template: (p)(O)_(f) (from (i))
Generated output: C:\Music\Artist\Album\MP3_Song (from wav).mp3
File path customization:
Input: C:\Music\Artist\Album\Song.wav
Template: D:\(o)\(d1)\(f)
Generated output: D:\mp3\Artist\Song.mp3
## Change Log
v0.3
- New: Possibility to extract audio from videos.
- New: Support new input file formats: aiff, m4a, avi, mp4.
- New: Quality settings for Mp3 (Encoding mode vbr/cbr and bitrate).
- New: Quality settings for Ogg (Bitrate).
- New: Quality settings for Wav (bits per sample: 8, 16, 24 or 32).
- New: Add output file path template system.
- New: Add button to move up or down a preset.
- New: Add input files post conversion action (No action, move in archive folder or delete).
- New: Add categories on input file extensions.
- Fixed: Lose focus of main window don't terminate the application.
- Fixed: The application icon now have a correct resolution at any size.
- Tech: Add error codes on error messages.
v0.2
- New: Add decode support for file format Ape
- New: Support new input file format: ape.
- New: Add notion of conversion preset (in order to customize the conversion possibilities).
- New: Add settings window to edit conversion presets.
- New: Add application icon.
Binary file not shown.

After

Width:  |  Height:  |  Size: 294 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB