-
Notifications
You must be signed in to change notification settings - Fork 123
/
Copy pathMainWindowViewModel.cs
2004 lines (1693 loc) · 70.3 KB
/
MainWindowViewModel.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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Data;
using ToDoLib;
using System.Windows;
using System.Windows.Input;
using System.IO;
using ColorFont;
using CommonExtensions;
using System.Reflection;
using System.Diagnostics;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Globalization;
using Microsoft.Win32;
using System.Windows.Threading;
namespace Client
{
// INotifyPropertyChanged interface implemented to notify UI for status bar changes.
public class MainWindowViewModel : INotifyPropertyChanged
{
private CollectionView _myView;
private FileChangeObserver _changefile;
private SortType _sortType;
private MainWindow _window;
private Task _updating;
private int _numberOfItemsInCurrentGroup;
private List<CollectionViewGroup> _viewGroups;
private int _nextGroupAtTaskNumber;
private List<Task> _selectedTasks;
public TaskList TaskList { get; set; }
public Help HelpPage { get; private set; }
public SortType SortType
{
get { return _sortType; }
set
{
bool raiseEvent = false;
if (_sortType != value)
{
User.Default.CurrentSort = (int)value;
User.Default.Save();
raiseEvent = true;
}
_sortType = value;
if(raiseEvent)
{
RaiseProperyChanged(nameof(SortType));
}
}
}
private int _activeFilterNumber = -1;
public int ActiveFilterNumber
{
get
{
return _activeFilterNumber;
}
private set
{
if (_activeFilterNumber != value)
{
_activeFilterNumber = value;
RaiseProperyChanged(nameof(ActiveFilterNumber));
}
}
}
private int totalTasks = 0;
public int TotalTasks
{
get
{
return totalTasks;
}
set
{
if (totalTasks != value)
{
totalTasks = value;
RaiseProperyChanged(nameof(TotalTasks));
}
}
}
private int filteredTasks = 0;
public int FilteredTasks
{
get
{
return filteredTasks;
}
set
{
if (filteredTasks != value)
{
filteredTasks = value;
RaiseProperyChanged(nameof(FilteredTasks));
}
}
}
private int incompleteTasks = 0;
public int IncompleteTasks
{
get
{
return incompleteTasks;
}
set
{
if (incompleteTasks != value)
{
incompleteTasks = value;
RaiseProperyChanged(nameof(IncompleteTasks));
}
}
}
private int tasksDueToday = 0;
public int TasksDueToday
{
get
{
return tasksDueToday;
}
set
{
if (tasksDueToday != value)
{
tasksDueToday = value;
RaiseProperyChanged(nameof(TasksDueToday));
}
}
}
public int TasksOverdue
{
get
{
return tasksOverdue;
}
set
{
if (tasksOverdue != value)
{
tasksOverdue = value;
RaiseProperyChanged(nameof(TasksOverdue));
}
}
}
private int tasksOverdue = 0;
public event PropertyChangedEventHandler PropertyChanged;
public MainWindowViewModel(MainWindow window)
{
_window = window;
_selectedTasks = new List<Task>();
Log.LogLevel = User.Default.DebugLoggingOn ? LogLevel.Debug : LogLevel.Error;
Log.Debug("Initializing Todotxt.net");
SortType = (SortType)User.Default.CurrentSort;
ActiveFilterNumber=0;
if (!string.IsNullOrEmpty(User.Default.FilePath))
{
LoadTasks(User.Default.FilePath);
}
window.sbTaskSummary.Visibility = User.Default.DisplayStatusBar ? Visibility.Visible : Visibility.Collapsed;
}
#region File Change Observer
private void EnableFileChangeObserver()
{
if (!User.Default.AutoRefresh)
{
return;
}
Log.Debug("Enabling file change observer for '{0}'", User.Default.FilePath);
_changefile = new FileChangeObserver();
_changefile.OnFileChanged += () => _window.Dispatcher.BeginInvoke(new Action(ReloadFile));
_changefile.ObserveFile(User.Default.FilePath);
Log.Debug("File change observer enabled");
}
private void DisableFileChangeObserver()
{
if (_changefile == null)
{
return;
}
Log.Debug("Disabling file change observer for '{0}'", User.Default.FilePath);
_changefile.Dispose();
_changefile = null;
Log.Debug("File change observer disabled");
}
#endregion
#region Task List ListBox Management Methods
/// <summary>
/// Captures the list box's selection on the task list. To be used prior to modifying or sorting and reloading the task list.
/// The SetSelectedTasks() method reapplies the selections captured in this method.
/// </summary>
private void GetSelectedTasks()
{
_selectedTasks.Clear();
foreach (var task in _window.lbTasks.SelectedItems)
{
_selectedTasks.Add((Task)task);
}
}
/// <summary>
/// Restores the task list box's selection that was captured by the GetSelectedTasks() method.
/// To be used after reloading the task list after a modification or sort.
/// </summary>
private void SetSelectedTasks()
{
if (_selectedTasks == null || _selectedTasks.Count == 0)
{
_window.lbTasks.SelectedIndex = 0;
return;
}
_window.lbTasks.SelectedItems.Clear();
int selectedItemCount = 0;
// Loop through the listbox tasks, then loop through the items that should be selected. If the items match, select them in the list box.
for (int i = 0; i < _window.lbTasks.Items.Count; i++)
{
Task listBoxItemTask = _window.lbTasks.Items[i] as Task;
int j = 0;
while (j < _selectedTasks.Count)
{
Task task = _selectedTasks[j];
if (listBoxItemTask.Raw.Equals(task.Raw))
{
_window.lbTasks.SelectedItems.Add(_window.lbTasks.Items[i]);
// Make sure the keyboard focus is on the uppermost or only task that is to be selected in the task list.
selectedItemCount++;
if (selectedItemCount == 1)
{
SelectTaskByIndex(i);
}
_selectedTasks.RemoveAt(j);
break;
}
else
{
j++;
}
}
}
if (selectedItemCount == 0)
{
_window.lbTasks.SelectedIndex = 0;
SelectTaskByIndex(0);
}
}
/// <summary>
/// Selects a task in the listbox based on its index in _window.lbtasks.Items
/// </summary>
/// <param name="index">Index of the task to select</param>
private void SelectTaskByIndex(int index)
{
try
{
var listBoxItem = (ListBoxItem)_window.lbTasks.ItemContainerGenerator.ContainerFromItem(_window.lbTasks.Items[index]);
listBoxItem.Focus();
}
catch
{
_window.lbTasks.Focus();
}
}
public void LoadTasks(string filePath)
{
Log.Debug("Loading tasks");
try
{
TaskList = new TaskList(filePath, User.Default.PreserveWhiteSpace);
if (TaskList != null)
{
// The first time the task list has been modified before we got a chance to hook to the modified event
// so call the method and then hook to the Modified event
TaskList.Modified += TaskList_Modified;
TaskList_Modified(TaskList, EventArgs.Empty);
}
User.Default.FilePath = filePath;
User.Default.Save();
EnableFileChangeObserver();
UpdateDisplayedTasks();
_window.SetSelectionOfMenuItem("FutureTasks", User.Default.FilterFutureTasks);
_window.SetSelectionOfMenuItem("HiddenTasks", User.Default.ShowHidenTasks);
}
catch (Exception ex)
{
ex.Handle("An error occurred while opening " + filePath);
}
}
private void TaskList_Modified(object sender, EventArgs e)
{
this.TotalTasks = TaskList.Tasks.Count;
}
public void ReloadFile()
{
Log.Debug("Reloading file");
try
{
TaskList.ReloadTasks();
}
catch (Exception ex)
{
ex.Handle("Error loading tasks");
}
GetSelectedTasks();
UpdateDisplayedTasks();
SetSelectedTasks();
}
public void UpdateDisplayedTasks()
{
if (TaskList == null)
{
return;
}
string sortProperty = "";
try
{
var sortedTaskList = FilterList(TaskList.Tasks);
sortedTaskList = SortList(sortedTaskList);
switch (SortType)
{
case SortType.Project:
sortProperty = "Projects";
break;
case SortType.Context:
sortProperty = "Contexts";
break;
case SortType.DueDate:
sortProperty = "DueDate";
break;
case SortType.Completed:
sortProperty = "CompletedDate";
break;
case SortType.Priority:
sortProperty = "Priority";
break;
case SortType.Created:
sortProperty = "CreationDate";
break;
}
_myView = (CollectionView)CollectionViewSource.GetDefaultView(sortedTaskList);
if (User.Default.AllowGrouping && SortType != SortType.Alphabetical && SortType != SortType.None)
{
if (_myView.CanGroup)
{
var groupDescription = new PropertyGroupDescription(sortProperty);
groupDescription.Converter = new GroupConverter();
_myView.GroupDescriptions.Add(groupDescription);
}
}
else
{
_myView.GroupDescriptions.Clear();
}
var selectedTasksList = sortedTaskList.ToList();
_window.lbTasks.ItemsSource = sortedTaskList;
_window.lbTasks.UpdateLayout();
//sortedTaskList.
UpdateSummary(selectedTasksList);
}
catch (Exception ex)
{
ex.Handle("Error while sorting tasks");
}
// Set the menu item to Bold to easily identify if there is a filter in force
_window.filterMenu.FontWeight = User.Default.FilterText.Length == 0 ? FontWeights.Normal : FontWeights.Bold;
}
protected void UpdateSummary(List<Task> selectedTasksList)
{
FilteredTasks = selectedTasksList.Count;
int fTask = 0, incompTask = 0, dueTodayTask = 0, overdueTask = 0;
foreach (Task t in selectedTasksList)
{
if (!t.Completed)
{
incompTask++;
if (!String.IsNullOrEmpty(t.DueDate))
{
DateTime dueDt;
if (DateTime.TryParseExact(t.DueDate, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dueDt))
{
if (dueDt.Date == DateTime.Today.Date)
{
dueTodayTask++;
}
else if (dueDt.Date < DateTime.Today)
{
overdueTask++;
}
}
}
}
}
IncompleteTasks = incompTask;
TasksOverdue = overdueTask;
TasksDueToday = dueTodayTask;
}
/// <summary>
/// Returns true if a single task is selected in the task list.
/// </summary>
/// <returns>True if a single task is selected in the task list. False if zero or more than one tasks are selected in the task list.</returns>
private bool IsTaskSelected()
{
return (_window.lbTasks.SelectedItems.Count == 1);
}
/// <summary>
/// Returns true if a one or more task is selected in the task list.
/// </summary>
/// <returns>True if one or more tasks are selected in the task list. False if zero or one task is selected.</returns>
private bool AreTasksSelected()
{
return (_window.lbTasks.SelectedItems.Count > 0);
}
/// <summary>
/// Helper function to determine if the correct keysequence has been entered to create a task.
/// Added to enable the check for Ctrl-Enter if set in options.
/// </summary>
/// <param name="e">The stroked key and any modifiers.</param>
/// <returns>true if the task should be added to the list, false otherwise.</returns>
private bool ShouldAddTask(KeyEventArgs e)
{
const Key NewTaskKey = Key.Enter;
if (e.Key == NewTaskKey)
{
if (User.Default.RequireCtrlEnter)
{
if (e.KeyboardDevice.Modifiers == ModifierKeys.Control)
return true;
}
else
{
return true;
}
}
return false;
}
#endregion
#region Task List ListBox Event Handling Methods
/// <summary>
/// Emulates a keydown event, as if "key" were pressed when the "target" control has focus.
/// </summary>
/// <param name="target">Control to send keyDown event to.</param>
/// <param name="key">Key press to emulate in KeyDown event.</param>
private void SendKeyDownEvent(Control target, Key key)
{
var routedEvent = Keyboard.KeyDownEvent; // Event to send
target.RaiseEvent(
new KeyEventArgs(
Keyboard.PrimaryDevice,
PresentationSource.FromVisual(target),
0,
key) { RoutedEvent = routedEvent }
);
}
public void EmulateDownArrow()
{
SendKeyDownEvent(_window.lbTasks, Key.Down);
}
public void EmulateUpArrow()
{
SendKeyDownEvent(_window.lbTasks, Key.Up);
}
#endregion
#region Filter Methods
public void ShowFilterDialog()
{
var f = new FilterDialog(this);
f.Owner = _window;
f.FilterText = User.Default.FilterText;
f.FilterTextPreset1 = User.Default.FilterTextPreset1;
f.FilterTextPreset2 = User.Default.FilterTextPreset2;
f.FilterTextPreset3 = User.Default.FilterTextPreset3;
f.FilterTextPreset4 = User.Default.FilterTextPreset4;
f.FilterTextPreset5 = User.Default.FilterTextPreset5;
f.FilterTextPreset6 = User.Default.FilterTextPreset6;
f.FilterTextPreset7 = User.Default.FilterTextPreset7;
f.FilterTextPreset8 = User.Default.FilterTextPreset8;
f.FilterTextPreset9 = User.Default.FilterTextPreset9;
if (f.ShowDialog().Value)
{
User.Default.FilterText = f.FilterText.Trim();
User.Default.FilterTextPreset1 = f.FilterTextPreset1.Trim();
User.Default.FilterTextPreset2 = f.FilterTextPreset2.Trim();
User.Default.FilterTextPreset3 = f.FilterTextPreset3.Trim();
User.Default.FilterTextPreset4 = f.FilterTextPreset4.Trim();
User.Default.FilterTextPreset5 = f.FilterTextPreset5.Trim();
User.Default.FilterTextPreset6 = f.FilterTextPreset6.Trim();
User.Default.FilterTextPreset7 = f.FilterTextPreset7.Trim();
User.Default.FilterTextPreset8 = f.FilterTextPreset8.Trim();
User.Default.FilterTextPreset9 = f.FilterTextPreset9.Trim();
User.Default.Save();
GetSelectedTasks();
UpdateDisplayedTasks();
SetSelectedTasks();
}
}
public static IEnumerable<Task> FilterList(IEnumerable<Task> tasks)
{
var filters = User.Default.FilterText;
var comparer = User.Default.FilterCaseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase;
var filteredTasks = new List<Task>();
foreach (var task in tasks)
{
bool include = true;
if (!User.Default.ShowHidenTasks)
include = !task.Raw.Contains("h:1");
if (include)
if (User.Default.FilterFutureTasks)
include = String.IsNullOrEmpty(task.ThresholdDate) || task.ThresholdDate.IsDateLessThan(DateTime.Now.AddDays(1));
if (include)
{
foreach (
var filter in
filters.Split(new string[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries))
{
if (filter.Equals("due:today", StringComparison.OrdinalIgnoreCase)
&& task.DueDate == DateTime.Now.ToString("yyyy-MM-dd"))
continue;
if (filter.Equals("due:future", StringComparison.OrdinalIgnoreCase)
&& task.DueDate.IsDateGreaterThan(DateTime.Now))
continue;
if (filter.Equals("due:past", StringComparison.OrdinalIgnoreCase)
&& task.DueDate.IsDateLessThan(DateTime.Now))
continue;
if (filter.Equals("due:active", StringComparison.OrdinalIgnoreCase)
&& !task.DueDate.IsNullOrEmpty()
&& !task.DueDate.IsDateGreaterThan(DateTime.Now))
continue;
if (filter.Equals("-due:today", StringComparison.OrdinalIgnoreCase)
&& task.DueDate == DateTime.Now.ToString("yyyy-MM-dd"))
{
include = false;
continue;
}
if (filter.Equals("-due:future", StringComparison.OrdinalIgnoreCase)
&& task.DueDate.IsDateGreaterThan(DateTime.Now))
{
include = false;
continue;
}
if (filter.Equals("-due:past", StringComparison.OrdinalIgnoreCase)
&& task.DueDate.IsDateLessThan(DateTime.Now))
{
include = false;
continue;
}
if (filter.Equals("-due:active", StringComparison.OrdinalIgnoreCase)
&& !task.DueDate.IsNullOrEmpty()
&& !task.DueDate.IsDateGreaterThan(DateTime.Now))
{
include = false;
continue;
}
// "DONE" filter is different from "due" filter in that
// "due" is part of todotxt syntax and would very unlikely occur in task text
// while the word "done" can occur in the text
if (filter.Equals("-DONE", StringComparison.Ordinal))
{
if (task.Completed) include = false;
}
else if (filter.Equals("DONE", StringComparison.Ordinal))
{
if (!task.Completed) include = false;
}
// so if the filter is "DONE" or "-DONE", pass the substring test
else
{
if (filter.Substring(0, 1) == "-")
{
if (task.Raw.Contains(filter.Substring(1), comparer))
include = false;
}
else if (!task.Raw.Contains(filter, comparer))
{
include = false;
}
}
}
}
if (include)
filteredTasks.Add(task);
}
return filteredTasks;
}
public void ApplyFilterPreset0()
{
ApplyFilterPreset(0);
}
public void ApplyFilterPreset1()
{
ApplyFilterPreset(1);
}
public void ApplyFilterPreset2()
{
ApplyFilterPreset(2);
}
public void ApplyFilterPreset3()
{
ApplyFilterPreset(3);
}
public void ApplyFilterPreset4()
{
ApplyFilterPreset(4);
}
public void ApplyFilterPreset5()
{
ApplyFilterPreset(5);
}
public void ApplyFilterPreset6()
{
ApplyFilterPreset(6);
}
public void ApplyFilterPreset7()
{
ApplyFilterPreset(7);
}
public void ApplyFilterPreset8()
{
ApplyFilterPreset(8);
}
public void ApplyFilterPreset9()
{
ApplyFilterPreset(9);
}
public void ApplyHideFutureTasks()
{
User.Default.FilterFutureTasks = !User.Default.FilterFutureTasks;
UpdateDisplayedTasks();
SetSelectedTasks();
User.Default.Save();
}
public void ApplyShowHiddenTasks()
{
User.Default.ShowHidenTasks = !User.Default.ShowHidenTasks;
GetSelectedTasks();
UpdateDisplayedTasks();
SetSelectedTasks();
User.Default.Save();
}
private void ApplyFilterPreset(int filterPresetNumber)
{
switch (filterPresetNumber)
{
case 0:
User.Default.FilterText = "";
break;
case 1:
User.Default.FilterText = User.Default.FilterTextPreset1;
break;
case 2:
User.Default.FilterText = User.Default.FilterTextPreset2;
break;
case 3:
User.Default.FilterText = User.Default.FilterTextPreset3;
break;
case 4:
User.Default.FilterText = User.Default.FilterTextPreset4;
break;
case 5:
User.Default.FilterText = User.Default.FilterTextPreset5;
break;
case 6:
User.Default.FilterText = User.Default.FilterTextPreset6;
break;
case 7:
User.Default.FilterText = User.Default.FilterTextPreset7;
break;
case 8:
User.Default.FilterText = User.Default.FilterTextPreset8;
break;
case 9:
User.Default.FilterText = User.Default.FilterTextPreset9;
break;
default:
return;
}
GetSelectedTasks();
UpdateDisplayedTasks();
SetSelectedTasks();
User.Default.Save();
ActiveFilterNumber = filterPresetNumber;
}
#endregion
#region Sort Methods
public void SortList(SortType sortType)
{
GetSelectedTasks();
this.SortType = sortType;
UpdateDisplayedTasks();
SetSelectedTasks();
}
public IEnumerable<Task> SortList(IEnumerable<Task> tasks)
{
Log.Debug("Sorting {0} tasks by {1}.", tasks.Count().ToString(), SortType.ToString());
switch (SortType)
{
case SortType.Completed:
_window.SetSelectedMenuItem(_window.sortMenu, "Completed");
return tasks.OrderBy(t => t.Completed)
.ThenBy(t => (string.IsNullOrEmpty(t.Priority) ? "(zzz)" : t.Priority))
.ThenBy(t => (string.IsNullOrEmpty(t.DueDate) ? "9999-99-99" : t.DueDate))
.ThenBy(t => (string.IsNullOrEmpty(t.CreationDate) ? "0000-00-00" : t.CreationDate));
case SortType.Context:
_window.SetSelectedMenuItem(_window.sortMenu, "Context");
return tasks.OrderBy(t =>
{
var s = "";
if (t.Contexts != null && t.Contexts.Count > 0)
s += t.PrimaryContext;
else
s += "zzz";
return s;
})
.ThenBy(t => t.Completed)
.ThenBy(t => (string.IsNullOrEmpty(t.Priority) ? "(zzz)" : t.Priority))
.ThenBy(t => (string.IsNullOrEmpty(t.DueDate) ? "9999-99-99" : t.DueDate))
.ThenBy(t => (string.IsNullOrEmpty(t.CreationDate) ? "0000-00-00" : t.CreationDate));
case SortType.Alphabetical:
_window.SetSelectedMenuItem(_window.sortMenu, "Alphabetical");
return tasks.OrderBy(t => t.Raw);
case SortType.DueDate:
_window.SetSelectedMenuItem(_window.sortMenu, "DueDate");
return tasks.OrderBy(t => (string.IsNullOrEmpty(t.DueDate) ? "9999-99-99" : t.DueDate))
.ThenBy(t => t.Completed)
.ThenBy(t => (string.IsNullOrEmpty(t.Priority) ? "(zzz)" : t.Priority))
.ThenBy(t => (string.IsNullOrEmpty(t.CreationDate) ? "0000-00-00" : t.CreationDate));
case SortType.Priority:
_window.SetSelectedMenuItem(_window.sortMenu, "Priority");
return tasks.OrderBy(t => (string.IsNullOrEmpty(t.Priority) ? "(zzz)" : t.Priority))
.ThenBy(t => t.Completed)
.ThenBy(t => (string.IsNullOrEmpty(t.DueDate) ? "9999-99-99" : t.DueDate))
.ThenBy(t => (string.IsNullOrEmpty(t.CreationDate) ? "0000-00-00" : t.CreationDate));
case SortType.Project:
_window.SetSelectedMenuItem(_window.sortMenu, "Project");
return tasks
.OrderBy(t =>
{
var s = "";
if (t.Projects != null && t.Projects.Count > 0)
s += t.PrimaryProject;
else
s += "zzz";
return s;
})
.ThenBy(t => t.Completed)
.ThenBy(t => (string.IsNullOrEmpty(t.Priority) ? "(zzz)" : t.Priority))
.ThenBy(t => (string.IsNullOrEmpty(t.DueDate) ? "9999-99-99" : t.DueDate))
.ThenBy(t => (string.IsNullOrEmpty(t.CreationDate) ? "0000-00-00" : t.CreationDate));
case SortType.Created:
_window.SetSelectedMenuItem(_window.sortMenu, "CreatedDate");
return tasks.OrderBy(t => (string.IsNullOrEmpty(t.CreationDate) ? "0000-00-00" : t.CreationDate))
.ThenBy(t => t.Completed)
.ThenBy(t => (string.IsNullOrEmpty(t.Priority) ? "(zzz)" : t.Priority))
.ThenBy(t => (string.IsNullOrEmpty(t.DueDate) ? "9999-99-99" : t.DueDate));
default:
_window.SetSelectedMenuItem(_window.sortMenu, "File");
return tasks;
}
}
#endregion
#region Edit Methods
public void CopySelectedTaskToTextBox()
{
if (!IsTaskSelected())
{
return;
}
var currentTask = _window.lbTasks.SelectedItem as Task;
if (currentTask != null)
{
_window.taskText.Text = currentTask.Raw;
_window.taskText.Select(_window.taskText.Text.Length, 0); // puts cursor at the end
_window.taskText.Focus();
}
}
public void PasteTasksIntoTaskList()
{
// Abort if clipboard does not contain text.
if (!Clipboard.ContainsText())
{
return;
}
// Split clipboard text into lines.
string clipboardText = Clipboard.GetText();
string[] clipboardLines = clipboardText.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
DisableFileChangeObserver();
// Add each line from the clipboard to the task list.
foreach (string clipboardLine in clipboardLines)
{
TaskList.Add(new Task(clipboardLine));
}
UpdateDisplayedTasks();
EnableFileChangeObserver();
}
#endregion
#region Task Methods
/// <summary>
/// This is a generic method used to update one or more selected tasks in the task list.
/// It is called by all the methods that update one or more tasks in the task list.
/// It is not called by the task update method or the task deletion method.
/// </summary>
/// <param name="modificationFunction">A function that returns a Task object and takes as parameters a Task object and a dynamic variable.</param>
/// <param name="parameter">The parameter (or null) to pass to modificationFunction.</param>
public void ModifySelectedTasks(Func<Task, dynamic, Task> modificationFunction, dynamic parameter = null)
{
// Abort if no tasks are selected.
if (!AreTasksSelected()) {
return;
}
DisableFileChangeObserver();
// Save which tasks were selected, because the selection will be lost later when UpdateDisplayedTasks() is called.
GetSelectedTasks();
// Make sure we are working with the latest version of the file.
TaskList.ReloadTasks();
// For each selected task, perform the modification, update the task list, and update the copy of the task in _selectedTasks.
foreach (var task in _selectedTasks)
{
Task newTask = modificationFunction(task, parameter);
TaskList.Update(task, newTask);
task.Raw = newTask.Raw;
}
// Reload the task list and re-sort it.
UpdateDisplayedTasks();
// Re-apply the selections captured above in the GetSelectedTasks() method call.
SetSelectedTasks();
EnableFileChangeObserver();
}
public void AddNewTask()
{
// create one-line string of all filter but not ones beginning with a minus, and use as the starting text for a new task
string filters = "";
foreach (var filter in User.Default.FilterText.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
{
if (filter.Substring(0, 1) != "-")
{
if (filter.Contains("due:active"))
filters = filters + " " + "due:today"; // If the current filter is "active", replace it here with "today"
else if (filter.Equals("DONE", StringComparison.Ordinal)
|| filter.Equals("-DONE", StringComparison.Ordinal))
continue;
else
filters = filters + " " + filter;
}
}
_window.taskText.Text = filters;
_window.taskText.Focus();
}
public void AddNewTaskWithPriority()
{
AddNewTask();
_window.taskText.Text = _window.taskText.Text.Length > 0 ? $"( {_window.taskText.Text}" : "(";
_window.taskText.CaretIndex = 1;
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>_window.taskText.CheckKeyAndShowPopup()));
}
public void UpdateTask()
{
// Abort if no task, or more than one task, is selected.
if (!IsTaskSelected())
{