-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTimelineTab.cs
551 lines (462 loc) · 17.7 KB
/
TimelineTab.cs
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using TimelineCreator.Controls;
using JsonSchema = NJsonSchema.JsonSchema;
namespace TimelineCreator
{
/// <summary>
/// Represents a timeline document in the form of a <see cref="TabControl"/> tab.
/// </summary>
public class TimelineTab : TabItem, IDisposable
{
/// <summary>
/// Window that owns the tab. Used to associate opened dialogs with the window.
/// </summary>
private readonly Window owner;
/// <summary>
/// Gets the tab's header text.
/// </summary>
public new string Header => ((TextBlock)base.Header).Text;
private bool hasUnsavedChanges = false;
/// <summary>
/// Gets whether any changes have been made to the document since it was created or last saved.
/// </summary>
public bool HasUnsavedChanges
{
get => hasUnsavedChanges;
private set
{
hasUnsavedChanges = value;
UpdateTabHeader();
}
}
/// <summary>
/// Path to the file that is being used to store the document on disk. This can only be changed using
/// <see cref="SaveDocumentAs(string)"/>.
/// </summary>
public string FilePath { get; private set; } = string.Empty;
private FileStream? fileStream = null;
private string description = string.Empty;
/// <summary>
/// Description section of the document.
/// </summary>
public string Description
{
get => description;
set
{
description = value;
HasUnsavedChanges = true;
}
}
private TimeZoneInfo timeZone = TimeZoneInfo.Local;
/// <summary>
/// Time zone that all times in the document are stored in.
/// </summary>
public TimeZoneInfo TimeZone
{
get => timeZone;
set
{
timeZone = value;
HasUnsavedChanges = true;
}
}
/// <summary>
/// The <see cref="TimelineCreator.Timeline"/> control that the tab is using to render the document's timeline.
/// </summary>
public readonly Timeline Timeline;
/// <summary>
/// Gets or sets the maximum width of the timeline itself within the tab.
/// </summary>
public int TimelineWidth
{
get => Timeline.MaxTimelineWidth;
set => Timeline.MaxTimelineWidth = value;
}
private bool isTZeroModeEnabled = false;
/// <summary>
/// Gets or sets whether the timeline should show times relative to <see cref="TZeroTime"/> if it it set.
/// </summary>
public bool IsTZeroModeEnabled
{
get => isTZeroModeEnabled;
set
{
isTZeroModeEnabled = value;
Timeline.TZeroTime = isTZeroModeEnabled ? TZeroTime : null;
}
}
private DateTime? tZeroTime = null;
/// <summary>
/// Gets or sets the T-0 time to use when <see cref="IsTZeroModeEnabled"/> is set to <see cref="true"/>.
/// </summary>
public DateTime? TZeroTime
{
get => tZeroTime;
set
{
tZeroTime = value;
Timeline.TZeroTime = IsTZeroModeEnabled ? tZeroTime : null;
}
}
private string searchPhrase = string.Empty;
/// <summary>
/// Gets or sets the phrase that is being searched for in the timeline. When set, a search is performed.
/// </summary>
public string SearchPhrase
{
get => searchPhrase;
set
{
searchPhrase = value;
SearchTimeline(searchPhrase);
}
}
/// <summary>
/// Gets the number of search results for the set search phrase.
/// </summary>
public int SearchResultCount { get; private set; } = 0;
/// <summary>
/// Invoked when the tab's header text changes.
/// </summary>
public event EventHandler<HeaderChangedEventArgs>? HeaderChanged;
private TimelineTab(bool isFromFile, Window owner)
{
this.owner = owner;
Timeline = new Timeline()
{
Margin = new Thickness(10),
FontSize = 14,
MaxTimelineWidth = 800
};
Timeline.PreviewMouseDoubleClick += Timeline_PreviewMouseDoubleClick;
Timeline.SelectionChanged += Timeline_SelectionChanged;
if (!isFromFile)
{
Timeline.Items.CollectionChanged += Items_CollectionChanged;
}
Content = Timeline;
UpdateTabHeader();
}
/// <summary>
/// Creates a tab containing a new, empty document.
/// </summary>
public static TimelineTab NewDocument(Window owner)
{
return new TimelineTab(false, owner);
}
/// <summary>
/// Creates a tab containing the contents of an existing timeline document.
/// </summary>
public async static Task<TimelineTab> OpenDocument(string filePath, Window owner)
{
// Locks the file until the tab is disposed
FileStream stream = new(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
using StreamReader reader = new(stream, leaveOpen: true);
string json = reader.ReadToEnd();
if (await ValidateJson(json))
{
dynamic documentJson = JsonConvert.DeserializeObject<JObject>(json,
new JsonSerializerSettings() { DateParseHandling = DateParseHandling.None })!;
if (documentJson.version != 1)
throw new InvalidFileException();
TimeZoneInfo? timeZone = TimeZoneInfo.GetSystemTimeZones()
.FirstOrDefault(tzi => tzi.Id == (string)documentJson.timeZone);
if (timeZone == null)
throw new InvalidFileException();
TimelineTab tab = new(true, owner)
{
FilePath = filePath,
fileStream = stream,
Description = documentJson["description"],
TimeZone = timeZone
};
tab.HasUnsavedChanges = false; // Also sets the tab header
foreach (dynamic itemJson in documentJson.items)
{
try
{
TimelineItem item = new()
{
DateTime = DateTime.ParseExact((string)itemJson.time, "yyyy-MM-dd'T'HH:mm:ss", null),
Text = itemJson.text
};
if (itemJson.ContainsKey("isImportant"))
{
item.IsImportant = itemJson["isImportant"];
}
tab.AddPropertyChangedHandler(item);
tab.Timeline.Items.Add(item);
}
catch (FormatException)
{
throw new InvalidFileException();
}
}
tab.AddCollectionChangedHandler();
tab.Timeline.ResetZoom();
return tab;
}
else
{
throw new InvalidFileException();
}
}
/// <summary>
/// Determines whether the JSON contents of a timeline file are valid.
/// </summary>
private static async Task<bool> ValidateJson(string json)
{
try
{
string schemaJson;
using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(
"TimelineCreator.FileSchema.json")!)
{
using StreamReader reader = new(stream);
schemaJson = reader.ReadToEnd();
}
JsonSchema schema = await JsonSchema.FromJsonAsync(schemaJson);
ICollection<NJsonSchema.Validation.ValidationError> jsonErrors = schema.Validate(json);
return jsonErrors.Count == 0;
}
catch (JsonReaderException)
{
return false;
}
}
/// <summary>
/// Saves the timeline document to a specific/new location. Must be called on a new document before
/// <see cref="SaveDocument()"/>.
/// </summary>
public void SaveDocumentAs(string filePath)
{
fileStream?.Dispose();
fileStream = null;
FilePath = filePath;
UpdateTabHeader();
SaveDocument();
}
/// <summary>
/// Saves the timeline document to its currently set file path.
/// </summary>
public void SaveDocument()
{
if (FilePath == string.Empty)
throw new InvalidOperationException("Document has never been saved.");
dynamic documentJson = new JObject();
documentJson.version = 1;
documentJson.description = Description;
documentJson.timeZone = TimeZone.Id;
documentJson.items = new JArray();
// TODO: Items should be written to file in ascending time order
foreach (TimelineItem item in Timeline.Items)
{
dynamic itemJson = new JObject();
itemJson.time = item.DateTime;
itemJson.text = item.Text;
if (item.IsImportant)
{
itemJson.isImportant = true;
}
documentJson.items.Add(itemJson);
}
JsonSerializerSettings settings = new()
{
Formatting = Formatting.Indented,
DateFormatString = "yyyy-MM-dd'T'HH:mm:ss"
};
bool fileCreated = false;
if (fileStream == null)
{
// Locks the file until the tab is disposed
fileStream = new(FilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
fileCreated = true;
}
try
{
using StreamWriter writer = new(fileStream, leaveOpen: true);
fileStream.SetLength(0); // We're going to rewrite the whole file, so empty it
writer.Write(JsonConvert.SerializeObject(documentJson, settings));
}
catch
{
// Delete the empty file if it's just been created but failed to be written to
if (fileCreated)
{
File.Delete(FilePath);
fileStream.Dispose();
fileStream = null;
}
throw;
}
HasUnsavedChanges = false;
}
/// <summary>
/// Adds the handler to the CollectionChanged event of the tab's timeline items list. Necessary as part of the
/// static <see cref="OpenDocument(string)"/> method.
/// </summary>
private void AddCollectionChangedHandler()
{
Timeline.Items.CollectionChanged += Items_CollectionChanged;
}
/// <summary>
/// Invoked whenever the tab's timeline item list changes.
/// </summary>
private void Items_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (TimelineItem item in e.NewItems!)
{
item.PropertyChanged += Item_PropertyChanged;
}
TimelineItem newItem = (TimelineItem)e.NewItems[0]!;
// Centre view range on the new item if it's outside the current view
if (newItem.DateTime < Timeline.GetViewRange().Item1 ||
newItem.DateTime > Timeline.GetViewRange().Item2)
{
TimeSpan halfViewRange = (Timeline.GetViewRange().Item2 - Timeline.GetViewRange().Item1) / 2;
Timeline.GoToViewRange(newItem.DateTime - halfViewRange, newItem.DateTime + halfViewRange);
}
Timeline.SelectedItem = newItem;
// Refresh search to take account of new items
SearchTimeline(SearchPhrase);
}
else if (e.Action == NotifyCollectionChangedAction.Remove)
{
foreach (TimelineItem item in e.OldItems!)
{
item.PropertyChanged -= Item_PropertyChanged;
}
}
HasUnsavedChanges = true;
}
/// <summary>
/// Adds the the handler to the PropertyChanged event of a timeline item. Necessary as part of the static
/// <see cref="OpenDocument(string)"/> method.
/// </summary>
private void AddPropertyChangedHandler(TimelineItem item)
{
item.PropertyChanged += Item_PropertyChanged;
}
/// <summary>
/// Invoked whenever the DateTime or Text properties of a timeline item change.
/// </summary>
private void Item_PropertyChanged(object? sender, PropertyChangedEventArgs e)
{
HasUnsavedChanges = true;
// Refresh search to take account of possibly changed item text
SearchTimeline(SearchPhrase);
}
private void Timeline_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (((Timeline)sender).SelectedItem != null)
{
ItemDialog dialog = new(TimeZone, ((Timeline)sender).SelectedItem!)
{
TZeroTime = TZeroTime,
IsTZeroMode = IsTZeroModeEnabled,
Owner = owner
};
if (dialog.ShowDialog() == true)
{
if (dialog.WasDeleted)
{
Timeline.Items.Remove(dialog.Item);
}
}
}
else
{
ItemDialog dialog = new(TimeZone)
{
TZeroTime = TZeroTime,
IsTZeroMode = IsTZeroModeEnabled,
Owner = owner
};
if (dialog.ShowDialog() == true)
{
Timeline.Items.Add(dialog.Item);
}
}
}
private void Timeline_SelectionChanged(object? sender, SelectionChangedEventArgs e)
{
// Calculate time difference if control-clicking on two items
if (e.AddedItems.Count == 1 && e.RemovedItems.Count == 1 && Keyboard.Modifiers == ModifierKeys.Control)
{
// If we don't do this, a stack overflow will happen because the line after this
// will invoke SelectionChanged again, and the condition above will match again, which
// will invoke it again, and so on.
((Timeline)sender!).SelectedItem = null;
((Timeline)sender!).SelectedItem = (TimelineItem)e.RemovedItems[0]!;
TimeSpan diff = ((TimelineItem)e.AddedItems[0]!).DateTime - ((TimelineItem)e.RemovedItems[0]!).DateTime;
MessageBox.Show($"Difference is {diff.Duration().ToString("h'h 'm'm 's's'")}");
}
}
/// <summary>
/// Highlights all occurrences of a search phrase within the timeline. <see cref="string.Empty"/> to clear
/// search.
/// </summary>
private void SearchTimeline(string phrase)
{
int resultCount = 0;
foreach (TimelineItem item in Timeline.Items)
{
resultCount += item.SearchText(phrase);
}
SearchResultCount = resultCount;
}
/// <summary>
/// Sets the tab's header text based on the file path and whether there are any unsaved changes.
/// </summary>
private void UpdateTabHeader()
{
string header = hasUnsavedChanges ? "* " : "";
if (FilePath != string.Empty)
{
string fileName = Path.GetFileNameWithoutExtension(FilePath);
header += fileName != string.Empty ? fileName : "Untitled Timeline";
}
else
{
header += "Untitled Timeline";
}
TextBlock headerTextBlock = new() { Text = header };
if (FilePath != string.Empty)
{
headerTextBlock.ToolTip = FilePath;
}
base.Header = headerTextBlock;
HeaderChanged?.Invoke(this, new HeaderChangedEventArgs(header));
}
public void Dispose()
{
fileStream?.Dispose();
fileStream = null;
GC.SuppressFinalize(this);
}
}
public class HeaderChangedEventArgs : Exception
{
public string Header { get; private set; }
public HeaderChangedEventArgs(string header)
{
Header = header;
}
}
public class InvalidFileException : Exception { }
}