1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ChaptersViewModel.cs" company="HandBrake Project (http://handbrake.fr)">
// This file is part of the HandBrake source code - It may be used under the terms of the GNU General Public License.
// </copyright>
// <summary>
// The Chapters View Model
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace HandBrakeWPF.ViewModels
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using Caliburn.Micro;
using HandBrakeWPF.Properties;
using HandBrakeWPF.Services.Interfaces;
using HandBrakeWPF.Services.Presets.Model;
using HandBrakeWPF.Services.Scan.Model;
using HandBrakeWPF.Utilities.Input;
using HandBrakeWPF.Utilities.Output;
using HandBrakeWPF.ViewModels.Interfaces;
using Microsoft.VisualBasic.FileIO;
using ChapterMarker = HandBrakeWPF.Services.Encode.Model.Models.ChapterMarker;
using EncodeTask = HandBrakeWPF.Services.Encode.Model.EncodeTask;
using GeneralApplicationException = HandBrakeWPF.Exceptions.GeneralApplicationException;
/// <summary>
/// The Chapters View Model
/// </summary>
public class ChaptersViewModel : ViewModelBase, IChaptersViewModel
{
/// <summary>
/// The source chapters backing field
/// </summary>
private List<Chapter> sourceChaptersList;
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="ChaptersViewModel"/> class.
/// </summary>
/// <param name="windowManager">
/// The window manager.
/// </param>
/// <param name="userSettingService">
/// The user Setting Service.
/// </param>
public ChaptersViewModel(IWindowManager windowManager, IUserSettingService userSettingService)
{
this.Task = new EncodeTask();
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets Task.
/// </summary>
public EncodeTask Task { get; set; }
/// <summary>
/// Gets or sets a value indicating whether chapter markers are enabled.
/// </summary>
public bool IncludeChapterMarkers
{
get
{
return this.Task.IncludeChapterMarkers;
}
set
{
this.Task.IncludeChapterMarkers = value;
this.NotifyOfPropertyChange(() => this.IncludeChapterMarkers);
}
}
#endregion
#region Properties
/// <summary>
/// Gets or sets SourceChapterList.
/// </summary>
private ObservableCollection<Chapter> SourceChapterList { get; set; }
#endregion
#region Public Methods
/// <summary>
/// Export the Chapter Markers to a CSV file
/// </summary>
/// <exception cref="GeneralApplicationException">
/// Thrown if exporting fails.
/// </exception>
public void Export()
{
string fileName = null;
using (var saveFileDialog = new SaveFileDialog()
{
Filter = "Csv File|*.csv",
DefaultExt = "csv",
CheckPathExists = true,
OverwritePrompt = true
})
{
var dialogResult = saveFileDialog.ShowDialog();
fileName = saveFileDialog.FileName;
// Exit early if the user cancelled or the filename is invalid
if (dialogResult != DialogResult.OK || string.IsNullOrWhiteSpace(fileName))
return;
}
try
{
using (var csv = new StreamWriter(fileName))
{
foreach (ChapterMarker row in this.Task.ChapterNames)
{
csv.Write("{0},{1}{2}", row.ChapterNumber, CsvHelper.Escape(row.ChapterName), Environment.NewLine);
}
}
}
catch (Exception exc)
{
throw new GeneralApplicationException(
Resources.ChaptersViewModel_UnableToExportChaptersWarning,
Resources.ChaptersViewModel_UnableToExportChaptersMsg,
exc);
}
}
/// <summary>
/// Imports a Chapter marker file
/// </summary>
/// <exception cref="GeneralApplicationException">
/// Thrown if importing fails.
/// </exception>
public void Import()
{
string filename = null;
string fileExtension = null;
using (var dialog = new OpenFileDialog()
{
Filter = string.Join("|", ChapterImporterCsv.FileFilter, ChapterImporterXml.FileFilter, ChapterImporterTxt.FileFilter),
FilterIndex = 1, // 1 based, the index value of the first filter entry is 1
CheckFileExists = true
})
{
var dialogResult = dialog.ShowDialog();
filename = dialog.FileName;
// Exit if the user didn't press the OK button or the file name is invalid
if (dialogResult != DialogResult.OK || string.IsNullOrWhiteSpace(filename))
return;
// Retrieve the file extension after we've confirmed that the user selected something to open
fileExtension = Path.GetExtension(filename)?.ToLowerInvariant();
}
var importedChapters = new Dictionary<int, Tuple<string, TimeSpan>>();
// Execute the importer based on the file extension
switch (fileExtension)
{
case ".csv":
ChapterImporterCsv.Import(filename, ref importedChapters);
break;
case ".xml":
ChapterImporterXml.Import(filename, ref importedChapters);
break;
case ".txt":
ChapterImporterTxt.Import(filename, ref importedChapters);
break;
default:
throw new GeneralApplicationException(
Resources.ChaptersViewModel_UnsupportedFileFormatWarning,
string.Format(Resources.ChaptersViewModel_UnsupportedFileFormatMsg, fileExtension));
}
// Exit early if no chapter information was extracted
if (importedChapters == null || importedChapters.Count <= 0)
return;
// Validate the chaptermap against the current chapter list extracted from the source
string validationErrorMessage;
if (!this.ValidateImportedChapters(importedChapters, out validationErrorMessage))
{
if( !string.IsNullOrEmpty(validationErrorMessage))
throw new GeneralApplicationException(Resources.ChaptersViewModel_ValidationFailedWarning, validationErrorMessage);
}
// Now iterate over each chatper we have, and set it's name
foreach (ChapterMarker item in this.Task.ChapterNames)
{
// If we don't have a chapter name for this chapter then
// fallback to the value that is already set for the chapter
string chapterName = item.ChapterName;
// Attempt to retrieve the imported chapter name
Tuple<string, TimeSpan> chapterInfo;
if (importedChapters.TryGetValue(item.ChapterNumber, out chapterInfo))
chapterName = chapterInfo.Item1;
// Assign the chapter name unless the name is not set or only whitespace charaters
item.ChapterName = !string.IsNullOrWhiteSpace(chapterName) ? chapterName : string.Empty;
}
}
/// <summary>
/// Validates any imported chapter information against the currently detected chapter information in the
/// source media. If validation fails then an error message is returned via the out parameter <see cref="validationErrorMessage"/>
/// </summary>
/// <param name="importedChapters">The list of imported chapter information</param>
/// <param name="validationErrorMessage">In case of a validation error this variable will hold
/// a detailed message that can be presented to the user</param>
/// <returns>True if there are no errors with imported chapters, false otherwise</returns>
private bool ValidateImportedChapters(Dictionary<int, Tuple<string, TimeSpan>> importedChapters, out string validationErrorMessage)
{
validationErrorMessage = null;
// If the number of chapters don't match, prompt for confirmation
if (importedChapters.Count != this.Task.ChapterNames.Count)
{
if (DialogResult.Yes !=
MessageBox.Show(
string.Format(Resources.ChaptersViewModel_ValidateImportedChapters_ChapterCountMismatchMsg, this.Task.ChapterNames.Count, importedChapters.Count),
Resources.ChaptersViewModel_ValidateImportedChapters_ChapterCountMismatchWarning,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2))
{
return false;
}
}
// If the average discrepancy in timings between chapters is either:
// a) more than 15 sec for more than 2 chapters
// (I chose 15sec based on empirical evidence from testing a few DVDs and comparing to chapter-marker files I downloaded)
// => This check will not be performed for the first and last chapter as they're very likely to differ significantly due to language and region
// differences (e.g. longer title sequences and different distributor credits)
var diffs = importedChapters.Zip(this.Task.ChapterNames, (import, source) => source.Duration - import.Value.Item2);
if (diffs.Count(diff => Math.Abs(diff.TotalSeconds) > 15) > 2)
{
if (DialogResult.Yes !=
MessageBox.Show(
Resources.ChaptersViewModel_ValidateImportedChapters_ChapterDurationMismatchMsg,
Resources.ChaptersViewModel_ValidateImportedChapters_ChapterDurationMismatchWarning,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2))
{
return false;
}
}
// All is well, we should import chapters
return true;
}
/// <summary>
/// Setup this window for a new source
/// </summary>
/// <param name="source">
/// The source.
/// </param>
/// <param name="title">
/// The title.
/// </param>
/// <param name="preset">
/// The preset.
/// </param>
/// <param name="task">
/// The task.
/// </param>
public void SetSource(Source source, Title title, Preset preset, EncodeTask task)
{
this.Task = task;
this.NotifyOfPropertyChange(() => this.Task);
if (preset != null)
{
this.IncludeChapterMarkers = preset.Task.IncludeChapterMarkers;
}
this.sourceChaptersList = title.Chapters;
this.SetSourceChapters(title.Chapters);
}
/// <summary>
/// Setup this tab for the specified preset.
/// </summary>
/// <param name="preset">
/// The preset.
/// </param>
/// <param name="task">
/// The task.
/// </param>
public void SetPreset(Preset preset, EncodeTask task)
{
this.Task = task;
this.Task.IncludeChapterMarkers = preset.Task.IncludeChapterMarkers;
this.NotifyOfPropertyChange(() => this.Task);
}
/// <summary>
/// Update all the UI controls based on the encode task passed in.
/// </summary>
/// <param name="task">
/// The task.
/// </param>
public void UpdateTask(EncodeTask task)
{
this.Task = task;
this.NotifyOfPropertyChange(() => this.Task.IncludeChapterMarkers);
this.NotifyOfPropertyChange(() => this.Task.ChapterNames);
}
/// <summary>
/// Reset Chapter Names
/// </summary>
public void Reset()
{
if (this.sourceChaptersList != null)
{
this.SetSourceChapters(this.sourceChaptersList);
}
}
/// <summary>
/// Set the Source Chapters List
/// </summary>
/// <param name="sourceChapters">
/// The source chapters.
/// </param>
public void SetSourceChapters(IEnumerable<Chapter> sourceChapters)
{
// Cache the chapters in this screen
this.SourceChapterList = new ObservableCollection<Chapter>(sourceChapters);
this.Task.ChapterNames.Clear();
// Then Add new Chapter Markers.
int counter = 1;
foreach (Chapter chapter in this.SourceChapterList)
{
string chapterName = string.IsNullOrEmpty(chapter.ChapterName) ? string.Format("Chapter {0}", counter) : chapter.ChapterName;
var marker = new ChapterMarker(chapter.ChapterNumber, chapterName, chapter.Duration);
this.Task.ChapterNames.Add(marker);
counter += 1;
}
}
#endregion
}
}
|