// --------------------------------------------------------------------------------------------------------------------
//
// This file is part of the HandBrake source code - It may be used under the terms of the GNU General Public License.
//
//
// HandBrakes Main Window
//
// --------------------------------------------------------------------------------------------------------------------
namespace HandBrakeWPF.ViewModels
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows;
using Caliburn.Micro;
using HandBrake.ApplicationServices;
using HandBrake.ApplicationServices.Model;
using HandBrake.ApplicationServices.Model.Encoding;
using HandBrake.ApplicationServices.Parsing;
using HandBrake.ApplicationServices.Services.Interfaces;
using HandBrake.ApplicationServices.Utilities;
using HandBrakeWPF.ViewModels.Interfaces;
using Ookii.Dialogs.Wpf;
using HandBrakeWPF.Services.Interfaces;
///
/// HandBrakes Main Window
///
[Export(typeof(IMainViewModel))]
public class MainViewModel : ViewModelBase, IMainViewModel
{
#region Private Variables and Services
///
/// The Source Scan Service.
///
private readonly IScan scanService;
///
/// The Encode Service
///
private readonly IEncode encodeService;
///
/// The Encode Service
///
private readonly IQueueProcessor queueProcessor;
///
/// The preset service
///
private readonly IPresetService presetService;
///
/// The Error Service Backing field.
///
private readonly IErrorService errorService;
///
/// HandBrakes Main Window Title
///
private string windowName;
///
/// The Source Label
///
private string sourceLabel;
///
/// The Selected Output Format Backing Field
///
private OutputFormat selectedOutputFormat;
///
/// Is a MKV file backing field
///
private bool isMkv;
public string sourcePath;
private string dvdDrivePath;
private string dvdDriveLabel;
private List drives;
///
/// The Toolbar Status Label
///
private string programStatusLabel;
///
/// Backing field for the scanned source.
///
private Source scannedSource;
///
/// Backing field for the selected title.
///
private Title selectedTitle;
///
/// Backing field for duration
///
private string duration;
///
/// Is Encoding Backing Field
///
private bool isEncoding;
///
/// Backing field for the selected preset.
///
private Preset selectedPreset;
#endregion
///
/// Initializes a new instance of the class.
/// The viewmodel for HandBrakes main window.
///
///
/// The window manager.
///
///
/// The User Setting Service
///
///
/// The scan Service.
///
///
/// The encode Service.
///
///
/// The preset Service.
///
///
/// The Error Service
///
[ImportingConstructor]
public MainViewModel(IWindowManager windowManager, IUserSettingService userSettingService, IScan scanService, IEncode encodeService, IPresetService presetService,
IErrorService errorService)
{
this.scanService = scanService;
this.encodeService = encodeService;
this.presetService = presetService;
this.errorService = errorService;
this.queueProcessor = IoC.Get(); // TODO Instance ID!
// Setup Properties
this.WindowTitle = "HandBrake WPF Test Application";
this.CurrentTask = new EncodeTask();
this.ScannedSource = new Source();
// Setup Events
this.scanService.ScanStared += this.ScanStared;
this.scanService.ScanCompleted += this.ScanCompleted;
this.scanService.ScanStatusChanged += this.ScanStatusChanged;
this.queueProcessor.QueueCompleted += this.QueueCompleted;
this.queueProcessor.QueuePaused += this.QueuePaused;
this.queueProcessor.EncodeService.EncodeStarted += this.EncodeStarted;
this.queueProcessor.EncodeService.EncodeStatusChanged += this.EncodeStatusChanged;
}
#region View Model Properties
///
/// Gets or sets PictureSettingsViewModel.
///
public IPictureSettingsViewModel PictureSettingsViewModel { get; set; }
///
/// Gets or sets AudioViewModel.
///
public IAudioViewModel AudioViewModel { get; set; }
///
/// Gets or sets SubtitleViewModel.
///
public ISubtitlesViewModel SubtitleViewModel { get; set; }
///
/// Gets or sets ChaptersViewModel.
///
public IChaptersViewModel ChaptersViewModel { get; set; }
///
/// Gets or sets AdvancedViewModel.
///
public IAdvancedViewModel AdvancedViewModel { get; set; }
///
/// Gets or sets VideoViewModel.
///
public IVideoViewModel VideoViewModel { get; set; }
///
/// Gets or sets FiltersViewModel.
///
public IFiltersViewModel FiltersViewModel { get; set; }
#endregion
#region Properties
///
/// Gets or sets TestProperty.
///
public string WindowTitle
{
get
{
return this.windowName;
}
set
{
if (!object.Equals(this.windowName, value))
{
this.windowName = value;
}
}
}
///
/// Gets or sets the Program Status Toolbar Label
/// This indicates the status of HandBrake
///
public string ProgramStatusLabel
{
get
{
return string.IsNullOrEmpty(this.programStatusLabel) ? "Ready" : this.sourceLabel;
}
set
{
if (!object.Equals(this.programStatusLabel, value))
{
this.programStatusLabel = value;
this.NotifyOfPropertyChange("ProgramStatusLabel");
}
}
}
///
/// Gets a list of presets
///
public ObservableCollection Presets
{
get
{
return this.presetService.Presets;
}
}
///
/// Gets or sets SelectedPreset.
///
public Preset SelectedPreset
{
get
{
return this.selectedPreset;
}
set
{
this.selectedPreset = value;
this.NotifyOfPropertyChange("SelectedPreset");
}
}
///
/// Gets or sets The Current Encode Task that the user is building
///
public EncodeTask CurrentTask { get; set; }
///
/// Gets or sets the Last Scanned Source
/// This object contains information about the scanned source.
///
public Source ScannedSource
{
get
{
return this.scannedSource;
}
set
{
this.scannedSource = value;
this.NotifyOfPropertyChange("ScannedSource");
}
}
///
/// Gets or sets the Source Label
/// This indicates the status of scans.
///
public string SourceLabel
{
get
{
return string.IsNullOrEmpty(this.sourceLabel) ? "Select 'Source' to continue" : this.sourceLabel;
}
set
{
if (!object.Equals(this.sourceLabel, value))
{
this.sourceLabel = value;
this.NotifyOfPropertyChange("SourceLabel");
}
}
}
///
/// Gets SourceName.
///
public string SourceName
{
get
{
// TODO
//if (this.selectedSourceType == SourceType.DvdDrive)
//{
// return this.dvdDriveLabel;
//}
if (selectedTitle != null && !string.IsNullOrEmpty(selectedTitle.SourceName))
{
return Path.GetFileName(selectedTitle.SourceName);
}
// We have a drive, selected as a folder.
if (this.sourcePath.EndsWith("\\"))
{
drives = GeneralUtilities.GetDrives();
foreach (DriveInformation item in drives)
{
if (item.RootDirectory.Contains(this.sourcePath))
{
return item.VolumeLabel;
}
}
}
if (Path.GetFileNameWithoutExtension(this.sourcePath) != "VIDEO_TS")
return Path.GetFileNameWithoutExtension(this.sourcePath);
return Path.GetFileNameWithoutExtension(Path.GetDirectoryName(this.sourcePath));
}
}
///
/// Gets RangeMode.
///
public IEnumerable RangeMode
{
get
{
return new List
{
PointToPointMode.Chapters, PointToPointMode.Seconds, PointToPointMode.Frames
};
}
}
///
/// Gets StartEndRangeItems.
///
public IEnumerable StartEndRangeItems
{
get
{
if (this.SelectedTitle == null)
{
return null;
}
return this.SelectedTitle.Chapters.Select(item => item.ChapterNumber).Select(dummy => (int)dummy).ToList();
}
}
///
/// Gets Angles.
///
public IEnumerable Angles
{
get
{
if (this.SelectedTitle == null)
{
return null;
}
List items = new List();
for (int i = 1; i <= this.selectedTitle.AngleCount + 1; i++)
{
items.Add(i);
}
return items;
}
}
///
/// Gets or sets Duration.
///
public string Duration
{
get
{
return string.IsNullOrEmpty(duration) ? "--:--:--" : duration;
}
set
{
duration = value;
this.NotifyOfPropertyChange("Duration");
}
}
///
/// Gets or sets a value indicating whether IsEncoding.
///
public bool IsEncoding
{
get
{
return this.isEncoding;
}
set
{
this.isEncoding = value;
this.NotifyOfPropertyChange("IsEncoding");
}
}
///
/// Gets or sets a value indicating whether IsMkv.
///
public bool IsMkv
{
get
{
return this.isMkv;
}
set
{
this.isMkv = value;
this.NotifyOfPropertyChange("IsMkv");
}
}
///
/// Gets RangeMode.
///
public IEnumerable OutputFormats
{
get
{
return new List
{
OutputFormat.Mp4, OutputFormat.Mkv
};
}
}
#endregion
#region Properties for Settings
///
/// Gets or sets SelectedTitle.
///
public Title SelectedTitle
{
get
{
return this.selectedTitle;
}
set
{
if (!object.Equals(this.selectedTitle, value))
{
this.selectedTitle = value;
if (selectedTitle == null)
{
return;
}
// Use the Path on the Title, or the Source Scan path if one doesn't exist.
this.CurrentTask.Source = !string.IsNullOrEmpty(this.selectedTitle.SourceName) ? this.selectedTitle.SourceName : this.ScannedSource.ScanPath;
this.CurrentTask.Title = value.TitleNumber;
this.NotifyOfPropertyChange("StartEndRangeItems");
this.NotifyOfPropertyChange("SelectedTitle");
this.NotifyOfPropertyChange("Angles");
// Default the Start and End Point dropdowns
this.SelectedStartPoint = 1;
this.SelectedEndPoint = selectedTitle.Chapters.Last().ChapterNumber;
this.SelectedPointToPoint = PointToPointMode.Chapters;
this.SelectedAngle = 1;
}
}
}
///
/// Gets or sets SelectedAngle.
///
public int SelectedAngle
{
get
{
return this.CurrentTask.StartPoint;
}
set
{
this.CurrentTask.EndPoint = value;
this.NotifyOfPropertyChange("SelectedAngle");
}
}
///
/// Gets or sets SelectedStartPoint.
///
public int SelectedStartPoint
{
get
{
return this.CurrentTask.StartPoint;
}
set
{
this.CurrentTask.StartPoint = value;
this.NotifyOfPropertyChange("SelectedStartPoint");
}
}
///
/// Gets or sets SelectedEndPoint.
///
public int SelectedEndPoint
{
get
{
return this.CurrentTask.EndPoint;
}
set
{
this.CurrentTask.EndPoint = value;
this.NotifyOfPropertyChange("SelectedEndPoint");
}
}
///
/// Gets or sets SelectedPointToPoint.
///
public PointToPointMode SelectedPointToPoint
{
get
{
return this.CurrentTask.PointToPointMode;
}
set
{
this.CurrentTask.PointToPointMode = value;
this.NotifyOfPropertyChange("SelectedPointToPoint");
}
}
///
/// Gets or sets SelectedOutputFormat.
///
public OutputFormat SelectedOutputFormat
{
get
{
return this.selectedOutputFormat;
}
set
{
this.selectedOutputFormat = value;
this.NotifyOfPropertyChange("SelectedOutputFormat");
this.NotifyOfPropertyChange("IsMkv");
this.SetExtension(string.Format(".{0}", this.selectedOutputFormat.ToString().ToLower())); // TODO, tidy up
}
}
#endregion
#region Load and Shutdown Handling
///
/// Initialise this view model.
///
public override void OnLoad()
{
// TODO
}
///
/// Shutdown this View
///
public void Shutdown()
{
// Unsubscribe from Events.
this.scanService.ScanStared -= this.ScanStared;
this.scanService.ScanCompleted -= this.ScanCompleted;
this.scanService.ScanStatusChanged -= this.ScanStatusChanged;
this.queueProcessor.QueueCompleted -= this.QueueCompleted;
this.queueProcessor.QueuePaused -= this.QueuePaused;
this.queueProcessor.EncodeService.EncodeStarted -= this.EncodeStarted;
this.queueProcessor.EncodeService.EncodeStatusChanged -= this.EncodeStatusChanged;
}
#endregion
#region Menu and Taskbar
///
/// Open the About Window
///
public void OpenAboutApplication()
{
this.WindowManager.ShowWindow(IoC.Get());
}
///
/// Open the Options Window
///
public void OpenOptionsWindow()
{
this.WindowManager.ShowWindow(IoC.Get());
}
///
/// Open the Log Window
///
public void OpenLogWindow()
{
this.WindowManager.ShowWindow(IoC.Get());
}
///
/// Open the Queue Window.
///
public void OpenQueueWindow()
{
this.WindowManager.ShowWindow(IoC.Get());
}
///
/// Open the Queue Window.
///
public void OpenPreviewWindow()
{
this.WindowManager.ShowWindow(IoC.Get());
}
///
/// Launch the Help pages.
///
public void LaunchHelp()
{
Process.Start("https://trac.handbrake.fr/wiki/HandBrakeGuide");
}
///
/// Check for Updates.
///
public void CheckForUpdates()
{
throw new NotImplementedException("Not Yet Implemented");
}
///
/// Add the current task to the queue.
///
public void AddToQueue()
{
if (this.ScannedSource == null || string.IsNullOrEmpty(this.ScannedSource.ScanPath) || this.ScannedSource.Titles.Count == 0)
{
this.errorService.ShowMessageBox("You must first scan a source and setup your job before adding to the queue.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
QueueTask task = new QueueTask
{
Task = this.CurrentTask,
Query = QueryGeneratorUtility.GenerateQuery(this.CurrentTask)
};
this.queueProcessor.QueueManager.Add(task);
if (!this.IsEncoding)
{
this.ProgramStatusLabel = string.Format("{0} Encodes Pending", this.queueProcessor.QueueManager.Count);
}
}
///
/// Folder Scan
///
public void FolderScan()
{
VistaFolderBrowserDialog dialog = new VistaFolderBrowserDialog { Description = "Please select a folder.", UseDescriptionForTitle = true };
dialog.ShowDialog();
this.StartScan(dialog.SelectedPath, 0);
}
///
/// File Scan
///
public void FileScan()
{
VistaOpenFileDialog dialog = new VistaOpenFileDialog { Filter = "All files (*.*)|*.*" };
dialog.ShowDialog();
this.StartScan(dialog.FileName, 0);
}
///
/// Cancel a Scan
///
public void CancelScan()
{
this.scanService.Stop();
}
///
/// Start an Encode
///
public void StartEncode()
{
// Santiy Checking.
if (this.ScannedSource == null || this.CurrentTask == null)
{
this.errorService.ShowMessageBox("You must first scan a source.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
if (string.IsNullOrEmpty(this.CurrentTask.Destination))
{
this.errorService.ShowMessageBox("The Destination field was empty.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
if (this.queueProcessor.IsProcessing)
{
this.errorService.ShowMessageBox("HandBrake is already encoding.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
if (File.Exists(this.CurrentTask.Destination))
{
MessageBoxResult result = this.errorService.ShowMessageBox("The current file already exists, do you wish to overwrite it?", "Question", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result == MessageBoxResult.No)
{
return;
}
}
// Create the Queue Task and Start Processing
QueueTask task = new QueueTask(null)
{
Destination = this.CurrentTask.Destination,
Task = this.CurrentTask,
Query = QueryGeneratorUtility.GenerateQuery(this.CurrentTask),
CustomQuery = false
};
this.queueProcessor.QueueManager.Add(task);
this.queueProcessor.Start();
this.IsEncoding = true;
}
///
/// Pause an Encode
///
public void PauseEncode()
{
this.queueProcessor.Pause();
}
///
/// Stop an Encode.
///
public void StopEncode()
{
this.encodeService.Stop();
}
///
/// Shutdown the Application
///
public void ExitApplication()
{
Application.Current.Shutdown();
}
#endregion
#region Main Window Public Methods
///
/// The Destination Path
///
public void BrowseDestination()
{
VistaSaveFileDialog dialog = new VistaSaveFileDialog
{
Filter = "mp4|*.mp4;*.m4v|mkv|*.mkv",
AddExtension = true,
OverwritePrompt = true,
DefaultExt = ".mp4"
};
dialog.ShowDialog();
this.CurrentTask.Destination = dialog.FileName;
this.NotifyOfPropertyChange("CurrentTask");
this.SetExtension(Path.GetExtension(dialog.FileName));
}
///
/// Add a Preset
///
public void PresetAdd()
{
IAddPresetViewModel presetViewModel = IoC.Get();
presetViewModel.Setup(this.CurrentTask);
this.WindowManager.ShowWindow(presetViewModel);
}
///
/// Remove a Preset
///
public void PresetRemove()
{
if (this.selectedPreset != null)
{
this.presetService.Remove(this.selectedPreset);
}
else
{
MessageBox.Show("Please select a preset.", "Presets", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
///
/// Set a default preset
///
public void PresetSetDefault()
{
if (this.selectedPreset != null)
{
this.presetService.SetDefault(this.selectedPreset);
MessageBox.Show(string.Format("New Default Preset Set: {0}", this.selectedPreset.Name), "Presets", MessageBoxButton.OK, MessageBoxImage.Warning);
}
else
{
MessageBox.Show("Please select a preset.", "Presets", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
///
/// Import a Preset
///
public void PresetImport()
{
VistaOpenFileDialog dialog = new VistaOpenFileDialog { Filter = "Plist (*.plist)|*.plist", CheckFileExists = true };
dialog.ShowDialog();
string filename = dialog.FileName;
if (!string.IsNullOrEmpty(filename))
{
EncodeTask parsed = PlistPresetHandler.Import(filename);
if (this.presetService.CheckIfPresetExists(parsed.PresetName))
{
if (!presetService.CanUpdatePreset(parsed.PresetName))
{
MessageBox.Show(
"You can not import a preset with the same name as a built-in preset.",
"Error",
MessageBoxButton.OK,
MessageBoxImage.Error);
return;
}
MessageBoxResult result =
MessageBox.Show(
"This preset appears to already exist. Would you like to overwrite it?",
"Overwrite preset?",
MessageBoxButton.YesNo,
MessageBoxImage.Warning);
if (result == MessageBoxResult.Yes)
{
Preset preset = new Preset { Name = parsed.PresetName, CropSettings = parsed.UsesPictureSettings, Task = parsed };
presetService.Update(preset);
}
}
else
{
Preset preset = new Preset { Name = parsed.PresetName, Task = parsed, CropSettings = parsed.UsesPictureSettings, };
presetService.Add(preset);
}
this.NotifyOfPropertyChange("Presets");
}
}
///
/// Export a Preset
///
public void PresetExport()
{
VistaSaveFileDialog savefiledialog = new VistaSaveFileDialog { Filter = "plist|*.plist", CheckPathExists = true };
if (this.selectedPreset != null)
{
savefiledialog.ShowDialog();
string filename = savefiledialog.FileName;
if (filename != null)
{
PlistPresetHandler.Export(savefiledialog.FileName, this.selectedPreset);
}
}
else
{
MessageBox.Show("Please select a preset.", "Presets", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
///
/// Reset built-in presets
///
public void PresetReset()
{
this.presetService.UpdateBuiltInPresets();
this.NotifyOfPropertyChange("Presets");
this.SelectedPreset = this.presetService.DefaultPreset;
}
#endregion
#region Private Methods
///
/// Start a Scan
///
///
/// The filename.
///
///
/// The title.
///
private void StartScan(string filename, int title)
{
// TODO
// 1. Disable GUI.
this.sourcePath = filename;
this.scanService.Scan(filename, title, this.UserSettingService.GetUserSetting(ASUserSettingConstants.PreviewScanCount));
}
///
/// Make sure the correct file extension is set based on user preferences and setup the GUI for the file container selected.
///
///
/// The new extension.
///
private void SetExtension(string newExtension)
{
// Make sure the output extension is set correctly based on the users preferences and selection.
if (newExtension == ".mp4" || newExtension == ".m4v")
{
switch (this.UserSettingService.GetUserSetting(UserSettingConstants.UseM4v))
{
case 0: // Auto
newExtension = this.CurrentTask.RequiresM4v ? ".m4v" : ".mp4";
break;
case 1: // MP4
newExtension = ".mp4";
break;
case 2: // M4v
newExtension = ".m4v";
break;
}
this.selectedOutputFormat = OutputFormat.Mp4;
this.IsMkv = false;
}
// Now disable controls that are not required. The Following are for MP4 only!
if (newExtension == ".mkv")
{
this.IsMkv = true;
this.CurrentTask.LargeFile = false;
this.CurrentTask.OptimizeMP4 = false;
this.CurrentTask.IPod5GSupport = false;
this.selectedOutputFormat = OutputFormat.Mkv;
}
// Update The browse file extension display
if (Path.HasExtension(newExtension))
{
this.CurrentTask.Destination = Path.ChangeExtension(this.CurrentTask.Destination, newExtension);
}
// Update the UI Display
this.NotifyOfPropertyChange("CurrentTask");
}
#endregion
#region Event Handlers
///
/// Handle the Scan Status Changed Event.
///
///
/// The Sender
///
///
/// The EventArgs
///
private void ScanStatusChanged(object sender, HandBrake.ApplicationServices.EventArgs.ScanProgressEventArgs e)
{
this.SourceLabel = "Scanning Title " + e.CurrentTitle + " of " + e.Titles;
}
///
/// Handle the Scan Completed Event
///
///
/// The Sender
///
///
/// The EventArgs
///
private void ScanCompleted(object sender, HandBrake.ApplicationServices.EventArgs.ScanCompletedEventArgs e)
{
if (e.Successful)
{
this.scanService.SouceData.CopyTo(this.ScannedSource);
this.NotifyOfPropertyChange("ScannedSource");
this.NotifyOfPropertyChange("ScannedSource.Titles");
this.SelectedTitle = this.ScannedSource.Titles.Where(t => t.MainTitle).FirstOrDefault();
this.JobContextService.CurrentSource = this.ScannedSource;
this.JobContextService.CurrentTask = this.CurrentTask;
}
this.SourceLabel = "Scan Completed";
// TODO Re-enable GUI.
}
///
/// Handle the Scan Started Event
///
///
/// The Sender
///
///
/// The EventArgs
///
private void ScanStared(object sender, EventArgs e)
{
// TODO - Disable relevant parts of the UI.
}
///
/// The Encode Status has changed Handler
///
///
/// The Sender
///
///
/// The Encode Progress Event Args
///
private void EncodeStatusChanged(object sender, HandBrake.ApplicationServices.EventArgs.EncodeProgressEventArgs e)
{
ProgramStatusLabel =
string.Format(
"{0:00.00}%, FPS: {1:000.0}, Avg FPS: {2:000.0}, Time Remaining: {3}, Elapsed: {4:hh\\:mm\\:ss}, Pending Jobs {5}",
e.PercentComplete,
e.CurrentFrameRate,
e.AverageFrameRate,
e.EstimatedTimeLeft,
e.ElapsedTime,
this.queueProcessor.QueueManager.Count);
}
///
/// Encode Started Handler
///
///
/// The Sender
///
///
/// The EventArgs
///
private void EncodeStarted(object sender, EventArgs e)
{
// TODO Handle Updating the UI
}
///
/// The Queue has been paused handler
///
///
/// The Sender
///
///
/// The EventArgs
///
private void QueuePaused(object sender, EventArgs e)
{
// TODO Handle Updating the UI
}
///
/// The Queue has completed handler
///
///
/// The Sender
///
///
/// The EventArgs
///
private void QueueCompleted(object sender, EventArgs e)
{
this.IsEncoding = false;
// TODO Handle Updating the UI
}
#endregion
}
}