forked from Flow-Launcher/Flow.Launcher
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainViewModel.cs
More file actions
1980 lines (1706 loc) · 73.3 KB
/
MainViewModel.cs
File metadata and controls
1980 lines (1706 loc) · 73.3 KB
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.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using CommunityToolkit.Mvvm.DependencyInjection;
using CommunityToolkit.Mvvm.Input;
using Flow.Launcher.Core.Plugin;
using Flow.Launcher.Infrastructure;
using Flow.Launcher.Infrastructure.Hotkey;
using Flow.Launcher.Infrastructure.Storage;
using Flow.Launcher.Infrastructure.UserSettings;
using Flow.Launcher.Plugin;
using Flow.Launcher.Plugin.SharedCommands;
using Flow.Launcher.Storage;
using Microsoft.VisualStudio.Threading;
namespace Flow.Launcher.ViewModel
{
public partial class MainViewModel : BaseModel, ISavable, IDisposable
{
#region Private Fields
private static readonly string ClassName = nameof(MainViewModel);
private bool _isQueryRunning;
private Query _lastQuery;
private bool _previousIsHomeQuery;
private string _queryTextBeforeLeaveResults;
private string _ignoredQueryText; // Used to ignore query text change when switching between context menu and query results
private readonly FlowLauncherJsonStorage<History> _historyItemsStorage;
private readonly FlowLauncherJsonStorage<UserSelectedRecord> _userSelectedRecordStorage;
private readonly FlowLauncherJsonStorageTopMostRecord _topMostRecord;
private readonly History _history;
private int lastHistoryIndex = 1;
private readonly UserSelectedRecord _userSelectedRecord;
private CancellationTokenSource _updateSource; // Used to cancel old query flows
private CancellationToken _updateToken; // Used to avoid ObjectDisposedException of _updateSource.Token
private ChannelWriter<ResultsForUpdate> _resultsUpdateChannelWriter;
private Task _resultsViewUpdateTask;
private readonly IReadOnlyList<Result> _emptyResult = new List<Result>();
private readonly PluginMetadata _historyMetadata = new()
{
ID = "298303A65D128A845D28A7B83B3968C2", // ID is for identifying the update plugin in UpdateActionAsync
Priority = 0 // Priority is for calculating scores in UpdateResultView
};
#endregion
#region Constructor
public MainViewModel()
{
_queryTextBeforeLeaveResults = "";
_queryText = "";
_lastQuery = new Query();
_ignoredQueryText = null; // null as invalid value
Settings = Ioc.Default.GetRequiredService<Settings>();
Settings.PropertyChanged += (_, args) =>
{
switch (args.PropertyName)
{
case nameof(Settings.WindowSize):
OnPropertyChanged(nameof(MainWindowWidth));
break;
case nameof(Settings.WindowHeightSize):
OnPropertyChanged(nameof(MainWindowHeight));
break;
case nameof(Settings.QueryBoxFontSize):
OnPropertyChanged(nameof(QueryBoxFontSize));
break;
case nameof(Settings.ItemHeightSize):
OnPropertyChanged(nameof(ItemHeightSize));
break;
case nameof(Settings.ResultItemFontSize):
OnPropertyChanged(nameof(ResultItemFontSize));
break;
case nameof(Settings.ResultSubItemFontSize):
OnPropertyChanged(nameof(ResultSubItemFontSize));
break;
case nameof(Settings.AlwaysStartEn):
OnPropertyChanged(nameof(StartWithEnglishMode));
break;
case nameof(Settings.OpenResultModifiers):
OnPropertyChanged(nameof(OpenResultCommandModifiers));
break;
case nameof(Settings.PreviewHotkey):
OnPropertyChanged(nameof(PreviewHotkey));
break;
case nameof(Settings.AutoCompleteHotkey):
OnPropertyChanged(nameof(AutoCompleteHotkey));
break;
case nameof(Settings.CycleHistoryUpHotkey):
OnPropertyChanged(nameof(CycleHistoryUpHotkey));
break;
case nameof(Settings.CycleHistoryDownHotkey):
OnPropertyChanged(nameof(CycleHistoryDownHotkey));
break;
case nameof(Settings.AutoCompleteHotkey2):
OnPropertyChanged(nameof(AutoCompleteHotkey2));
break;
case nameof(Settings.SelectNextItemHotkey):
OnPropertyChanged(nameof(SelectNextItemHotkey));
break;
case nameof(Settings.SelectNextItemHotkey2):
OnPropertyChanged(nameof(SelectNextItemHotkey2));
break;
case nameof(Settings.SelectPrevItemHotkey):
OnPropertyChanged(nameof(SelectPrevItemHotkey));
break;
case nameof(Settings.SelectPrevItemHotkey2):
OnPropertyChanged(nameof(SelectPrevItemHotkey2));
break;
case nameof(Settings.SelectNextPageHotkey):
OnPropertyChanged(nameof(SelectNextPageHotkey));
break;
case nameof(Settings.SelectPrevPageHotkey):
OnPropertyChanged(nameof(SelectPrevPageHotkey));
break;
case nameof(Settings.OpenContextMenuHotkey):
OnPropertyChanged(nameof(OpenContextMenuHotkey));
break;
case nameof(Settings.SettingWindowHotkey):
OnPropertyChanged(nameof(SettingWindowHotkey));
break;
case nameof(Settings.OpenHistoryHotkey):
OnPropertyChanged(nameof(OpenHistoryHotkey));
break;
}
};
_historyItemsStorage = new FlowLauncherJsonStorage<History>();
_userSelectedRecordStorage = new FlowLauncherJsonStorage<UserSelectedRecord>();
_topMostRecord = new FlowLauncherJsonStorageTopMostRecord();
_history = _historyItemsStorage.Load();
_userSelectedRecord = _userSelectedRecordStorage.Load();
ContextMenu = new ResultsViewModel(Settings, this)
{
LeftClickResultCommand = OpenResultCommand,
RightClickResultCommand = LoadContextMenuCommand,
IsPreviewOn = Settings.AlwaysPreview
};
Results = new ResultsViewModel(Settings, this)
{
LeftClickResultCommand = OpenResultCommand,
RightClickResultCommand = LoadContextMenuCommand,
IsPreviewOn = Settings.AlwaysPreview
};
History = new ResultsViewModel(Settings, this)
{
LeftClickResultCommand = OpenResultCommand,
RightClickResultCommand = LoadContextMenuCommand,
IsPreviewOn = Settings.AlwaysPreview
};
_selectedResults = Results;
Results.PropertyChanged += (o, args) =>
{
switch (args.PropertyName)
{
case nameof(Results.SelectedItem):
_selectedItemFromQueryResults = true;
PreviewSelectedItem = Results.SelectedItem;
_ = UpdatePreviewAsync();
break;
}
};
History.PropertyChanged += (o, args) =>
{
switch (args.PropertyName)
{
case nameof(History.SelectedItem):
_selectedItemFromQueryResults = false;
PreviewSelectedItem = History.SelectedItem;
_ = UpdatePreviewAsync();
break;
}
};
RegisterViewUpdate();
_ = RegisterClockAndDateUpdateAsync();
}
private void RegisterViewUpdate()
{
var resultUpdateChannel = Channel.CreateUnbounded<ResultsForUpdate>();
_resultsUpdateChannelWriter = resultUpdateChannel.Writer;
_resultsViewUpdateTask =
Task.Run(UpdateActionAsync).ContinueWith(continueAction, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default);
async Task UpdateActionAsync()
{
var queue = new Dictionary<string, ResultsForUpdate>();
var channelReader = resultUpdateChannel.Reader;
// it is not supposed to be false because it won't be complete
while (await channelReader.WaitToReadAsync())
{
await Task.Delay(20);
while (channelReader.TryRead(out var item))
{
if (!item.Token.IsCancellationRequested)
queue[item.ID] = item;
}
UpdateResultView(queue.Values);
queue.Clear();
}
if (!_disposed)
App.API.LogError(ClassName, "Unexpected ResultViewUpdate ends");
}
void continueAction(Task t)
{
#if DEBUG
throw t.Exception;
#else
App.API.LogError(ClassName, $"Error happen in task dealing with viewupdate for results. {t.Exception}");
_resultsViewUpdateTask =
Task.Run(UpdateActionAsync).ContinueWith(continueAction, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default);
#endif
}
}
public void RegisterResultsUpdatedEvent()
{
foreach (var pair in PluginManager.GetPluginsForInterface<IResultUpdated>())
{
var plugin = (IResultUpdated)pair.Plugin;
plugin.ResultsUpdated += (s, e) =>
{
if (e.Query.RawQuery != QueryText || e.Token.IsCancellationRequested)
{
return;
}
var token = e.Token == default ? _updateToken : e.Token;
// make a clone to avoid possible issue that plugin will also change the list and items when updating view model
var resultsCopy = DeepCloneResults(e.Results, token);
foreach (var result in resultsCopy)
{
if (string.IsNullOrEmpty(result.BadgeIcoPath))
{
result.BadgeIcoPath = pair.Metadata.IcoPath;
}
}
PluginManager.UpdatePluginMetadata(resultsCopy, pair.Metadata, e.Query);
if (token.IsCancellationRequested) return;
if (!_resultsUpdateChannelWriter.TryWrite(new ResultsForUpdate(resultsCopy, pair.Metadata, e.Query,
token)))
{
App.API.LogError(ClassName, "Unable to add item to Result Update Queue");
}
};
}
}
private async Task RegisterClockAndDateUpdateAsync()
{
var timer = new PeriodicTimer(TimeSpan.FromSeconds(1));
// ReSharper disable once MethodSupportsCancellation
while (await timer.WaitForNextTickAsync().ConfigureAwait(false))
{
if (Settings.UseClock)
ClockText = DateTime.Now.ToString(Settings.TimeFormat, CultureInfo.CurrentCulture);
if (Settings.UseDate)
DateText = DateTime.Now.ToString(Settings.DateFormat, CultureInfo.CurrentCulture);
}
}
[RelayCommand]
private async Task ReloadPluginDataAsync()
{
Hide();
await PluginManager.ReloadDataAsync().ConfigureAwait(false);
App.API.ShowMsg(App.API.GetTranslation("success"),
App.API.GetTranslation("completedSuccessfully"));
}
[RelayCommand]
private void LoadHistory()
{
if (QueryResultsSelected())
{
SelectedResults = History;
History.SelectedIndex = _history.Items.Count - 1;
}
else
{
SelectedResults = Results;
}
}
[RelayCommand]
public void ReQuery()
{
if (QueryResultsSelected())
{
// When we are re-querying, we should not delay the query
_ = QueryResultsAsync(false, isReQuery: true);
}
}
public void ReQuery(bool reselect)
{
BackToQueryResults();
// When we are re-querying, we should not delay the query
_ = QueryResultsAsync(false, isReQuery: true, reSelect: reselect);
}
[RelayCommand]
public void ReverseHistory()
{
if (_history.Items.Count > 0)
{
ChangeQueryText(_history.Items[^lastHistoryIndex].Query);
if (lastHistoryIndex < _history.Items.Count)
{
lastHistoryIndex++;
}
}
}
[RelayCommand]
public void ForwardHistory()
{
if (_history.Items.Count > 0)
{
ChangeQueryText(_history.Items[^lastHistoryIndex].Query);
if (lastHistoryIndex > 1)
{
lastHistoryIndex--;
}
}
}
[RelayCommand]
private void LoadContextMenu()
{
if (QueryResultsSelected())
{
// When switch to ContextMenu from QueryResults, but no item being chosen, should do nothing
// i.e. Shift+Enter/Ctrl+O right after Alt + Space should do nothing
if (SelectedResults.SelectedItem != null)
SelectedResults = ContextMenu;
}
else
{
SelectedResults = Results;
}
}
[RelayCommand]
private void Backspace(object index)
{
var query = QueryBuilder.Build(QueryText.Trim(), PluginManager.NonGlobalPlugins);
// GetPreviousExistingDirectory does not require trailing '\', otherwise will return empty string
var path = FilesFolders.GetPreviousExistingDirectory((_) => true, query.Search.TrimEnd('\\'));
var actionKeyword = string.IsNullOrEmpty(query.ActionKeyword) ? string.Empty : $"{query.ActionKeyword} ";
ChangeQueryText($"{actionKeyword}{path}");
}
[RelayCommand]
private void AutocompleteQuery()
{
var result = SelectedResults.SelectedItem?.Result;
if (result != null && QueryResultsSelected()) // SelectedItem returns null if selection is empty.
{
var autoCompleteText = result.Title;
if (!string.IsNullOrEmpty(result.AutoCompleteText))
{
autoCompleteText = result.AutoCompleteText;
}
else if (!string.IsNullOrEmpty(SelectedResults.SelectedItem?.QuerySuggestionText))
{
//var defaultSuggestion = SelectedResults.SelectedItem.QuerySuggestionText;
//// check if result.actionkeywordassigned is empty
//if (!string.IsNullOrEmpty(result.ActionKeywordAssigned))
//{
// autoCompleteText = $"{result.ActionKeywordAssigned} {defaultSuggestion}";
//}
autoCompleteText = SelectedResults.SelectedItem.QuerySuggestionText;
}
var specialKeyState = GlobalHotkey.CheckModifiers();
if (specialKeyState.ShiftPressed)
{
autoCompleteText = result.SubTitle;
}
ChangeQueryText(autoCompleteText);
}
}
[RelayCommand]
private async Task OpenResultAsync(string index)
{
var results = SelectedResults;
if (index is not null)
{
results.SelectedIndex = int.Parse(index);
}
var result = results.SelectedItem?.Result;
if (result == null)
{
return;
}
var hideWindow = await result.ExecuteAsync(new ActionContext
{
// not null means pressing modifier key + number, should ignore the modifier key
SpecialKeyState = index is not null ? SpecialKeyState.Default : GlobalHotkey.CheckModifiers()
})
.ConfigureAwait(false);
if (QueryResultsSelected())
{
_userSelectedRecord.Add(result);
_history.Add(result.OriginQuery.RawQuery);
lastHistoryIndex = 1;
}
if (hideWindow)
{
Hide();
}
}
private static IReadOnlyList<Result> DeepCloneResults(IReadOnlyList<Result> results, CancellationToken token = default)
{
var resultsCopy = new List<Result>();
foreach (var result in results.ToList())
{
if (token.IsCancellationRequested)
{
break;
}
var resultCopy = result.Clone();
resultsCopy.Add(resultCopy);
}
return resultsCopy;
}
#endregion
#region BasicCommands
[RelayCommand]
private void OpenSetting()
{
App.API.OpenSettingDialog();
}
[RelayCommand]
private void SelectHelp()
{
App.API.OpenUrl("https://www.flowlauncher.com/docs/#/usage-tips");
}
[RelayCommand]
private void SelectFirstResult()
{
SelectedResults.SelectFirstResult();
}
[RelayCommand]
private void SelectLastResult()
{
SelectedResults.SelectLastResult();
}
[RelayCommand]
private void SelectPrevPage()
{
SelectedResults.SelectPrevPage();
}
[RelayCommand]
private void SelectNextPage()
{
SelectedResults.SelectNextPage();
}
[RelayCommand]
private void SelectPrevItem()
{
if (QueryResultsSelected() // Results selected
&& string.IsNullOrEmpty(QueryText) // No input
&& Results.Visibility != Visibility.Visible // No items in result list, e.g. when home page is off and no query text is entered, therefore the view is collapsed.
&& _history.Items.Count > 0) // Have history items
{
lastHistoryIndex = 1;
ReverseHistory();
}
else
{
SelectedResults.SelectPrevResult();
}
}
[RelayCommand]
private void SelectNextItem()
{
SelectedResults.SelectNextResult();
}
[RelayCommand]
private void Esc()
{
if (!QueryResultsSelected())
{
SelectedResults = Results;
}
else
{
Hide();
}
}
public void BackToQueryResults()
{
if (!QueryResultsSelected())
{
SelectedResults = Results;
}
}
[RelayCommand]
public void ToggleGameMode()
{
GameModeStatus = !GameModeStatus;
}
[RelayCommand]
public void CopyAlternative()
{
var result = Results.SelectedItem?.Result?.CopyText;
if (result != null)
{
App.API.CopyToClipboard(result, directCopy: false);
}
}
#endregion
#region ViewModel Properties
public Settings Settings { get; }
public string ClockText { get; private set; }
public string DateText { get; private set; }
public ResultsViewModel Results { get; private set; }
public ResultsViewModel ContextMenu { get; private set; }
public ResultsViewModel History { get; private set; }
public bool GameModeStatus { get; set; } = false;
private string _queryText;
public string QueryText
{
get => _queryText;
set
{
_queryText = value;
OnPropertyChanged();
}
}
[RelayCommand]
private void IncreaseWidth()
{
MainWindowWidth += 100;
Settings.WindowLeft -= 50;
OnPropertyChanged(nameof(MainWindowWidth));
}
[RelayCommand]
private void DecreaseWidth()
{
if (MainWindowWidth - 100 < 400 || MainWindowWidth == 400)
{
MainWindowWidth = 400;
}
else
{
MainWindowWidth -= 100;
Settings.WindowLeft += 50;
}
OnPropertyChanged(nameof(MainWindowWidth));
}
[RelayCommand]
private void IncreaseMaxResult()
{
if (Settings.MaxResultsToShow == 17)
return;
Settings.MaxResultsToShow += 1;
}
[RelayCommand]
private void DecreaseMaxResult()
{
if (Settings.MaxResultsToShow == 2)
return;
Settings.MaxResultsToShow -= 1;
}
/// <summary>
/// we need move cursor to end when we manually changed query
/// but we don't want to move cursor to end when query is updated from TextBox
/// </summary>
/// <param name="queryText"></param>
/// <param name="isReQuery">Force query even when Query Text doesn't change</param>
public void ChangeQueryText(string queryText, bool isReQuery = false)
{
// Must check access so that we will not block the UI thread which causes window visibility issue
if (!Application.Current.Dispatcher.CheckAccess())
{
Application.Current.Dispatcher.Invoke(() => ChangeQueryText(queryText, isReQuery));
return;
}
if (QueryText != queryText)
{
// Change query text first
QueryText = queryText;
// When we are changing query from codes, we should not delay the query
Query(false, isReQuery: false);
// set to false so the subsequent set true triggers
// PropertyChanged and MoveQueryTextToEnd is called
QueryTextCursorMovedToEnd = false;
}
else if (isReQuery)
{
// When we are re-querying, we should not delay the query
Query(false, isReQuery: true);
}
QueryTextCursorMovedToEnd = true;
}
/// <summary>
/// Async version of <see cref="ChangeQueryText"/>
/// </summary>
private async Task ChangeQueryTextAsync(string queryText, bool isReQuery = false)
{
// Must check access so that we will not block the UI thread which causes window visibility issue
if (!Application.Current.Dispatcher.CheckAccess())
{
await Application.Current.Dispatcher.InvokeAsync(() => ChangeQueryTextAsync(queryText, isReQuery));
return;
}
if (QueryText != queryText)
{
// Change query text first
QueryText = queryText;
// When we are changing query from codes, we should not delay the query
await QueryAsync(false, isReQuery: false);
// set to false so the subsequent set true triggers
// PropertyChanged and MoveQueryTextToEnd is called
QueryTextCursorMovedToEnd = false;
}
else if (isReQuery)
{
// When we are re-querying, we should not delay the query
await QueryAsync(false, isReQuery: true);
}
QueryTextCursorMovedToEnd = true;
}
public bool LastQuerySelected { get; set; }
// This is not a reliable indicator of the cursor's position, it is manually set for a specific purpose.
public bool QueryTextCursorMovedToEnd { get; set; }
private ResultsViewModel _selectedResults;
private ResultsViewModel SelectedResults
{
get => _selectedResults;
set
{
var isReturningFromQueryResults = QueryResultsSelected();
var isReturningFromContextMenu = ContextMenuSelected();
var isReturningFromHistory = HistorySelected();
_selectedResults = value;
if (QueryResultsSelected())
{
Results.Visibility = Visibility.Visible;
ContextMenu.Visibility = Visibility.Collapsed;
History.Visibility = Visibility.Collapsed;
// QueryText setter (used in ChangeQueryText) runs the query again, resetting the selected
// result from the one that was selected before going into the context menu to the first result.
// The code below correctly restores QueryText and puts the text caret at the end without
// running the query again when returning from the context menu.
if (isReturningFromContextMenu)
{
_queryText = _queryTextBeforeLeaveResults;
// When executing OnPropertyChanged, QueryTextBox_TextChanged1 and Query will be called
// So we need to ignore it so that we will not call Query again
_ignoredQueryText = _queryText;
OnPropertyChanged(nameof(QueryText));
QueryTextCursorMovedToEnd = true;
}
else
{
ChangeQueryText(_queryTextBeforeLeaveResults);
}
// If we are returning from history and we have not set select item yet,
// we need to clear the preview selected item
if (isReturningFromHistory && _selectedItemFromQueryResults.HasValue && (!_selectedItemFromQueryResults.Value))
{
PreviewSelectedItem = null;
}
}
else
{
Results.Visibility = Visibility.Collapsed;
if (HistorySelected())
{
ContextMenu.Visibility = Visibility.Collapsed;
History.Visibility = Visibility.Visible;
}
else
{
ContextMenu.Visibility = Visibility.Visible;
History.Visibility = Visibility.Collapsed;
}
_queryTextBeforeLeaveResults = QueryText;
// Because of Fody's optimization
// setter won't be called when property value is not changed.
// so we need manually call Query()
// http://stackoverflow.com/posts/25895769/revisions
QueryText = string.Empty;
// When we are changing query because selected results are changed to history or context menu,
// we should not delay the query
Query(false);
if (HistorySelected())
{
// If we are returning from query results and we have not set select item yet,
// we need to clear the preview selected item
if (isReturningFromQueryResults && _selectedItemFromQueryResults.HasValue && _selectedItemFromQueryResults.Value)
{
PreviewSelectedItem = null;
}
}
}
}
}
public Visibility ProgressBarVisibility { get; set; }
public Visibility MainWindowVisibility { get; set; }
// This is to be used for determining the visibility status of the main window instead of MainWindowVisibility
// because it is more accurate and reliable representation than using Visibility as a condition check
public bool MainWindowVisibilityStatus { get; set; } = true;
public event VisibilityChangedEventHandler VisibilityChanged;
public Visibility ClockPanelVisibility { get; set; }
public Visibility SearchIconVisibility { get; set; }
public double ClockPanelOpacity { get; set; } = 1;
public double SearchIconOpacity { get; set; } = 1;
private string _placeholderText;
public string PlaceholderText
{
get => string.IsNullOrEmpty(_placeholderText) ? App.API.GetTranslation("queryTextBoxPlaceholder") : _placeholderText;
set
{
_placeholderText = value;
OnPropertyChanged();
}
}
public double MainWindowWidth
{
get => Settings.WindowSize;
set
{
if (!MainWindowVisibilityStatus) return;
Settings.WindowSize = value;
}
}
public double MainWindowHeight
{
get => Settings.WindowHeightSize;
set => Settings.WindowHeightSize = value;
}
public double QueryBoxFontSize
{
get => Settings.QueryBoxFontSize;
set => Settings.QueryBoxFontSize = value;
}
public double ItemHeightSize
{
get => Settings.ItemHeightSize;
set => Settings.ItemHeightSize = value;
}
public double ResultItemFontSize
{
get => Settings.ResultItemFontSize;
set => Settings.ResultItemFontSize = value;
}
public double ResultSubItemFontSize
{
get => Settings.ResultSubItemFontSize;
set => Settings.ResultSubItemFontSize = value;
}
public ImageSource PluginIconSource { get; private set; } = null;
public string PluginIconPath { get; set; } = null;
public string OpenResultCommandModifiers => Settings.OpenResultModifiers;
private static string VerifyOrSetDefaultHotkey(string hotkey, string defaultHotkey)
{
try
{
var converter = new KeyGestureConverter();
var key = (KeyGesture)converter.ConvertFromString(hotkey);
}
catch (Exception e) when (e is NotSupportedException || e is InvalidEnumArgumentException)
{
return defaultHotkey;
}
return hotkey;
}
public string PreviewHotkey => VerifyOrSetDefaultHotkey(Settings.PreviewHotkey, "F1");
public string AutoCompleteHotkey => VerifyOrSetDefaultHotkey(Settings.AutoCompleteHotkey, "Ctrl+Tab");
public string AutoCompleteHotkey2 => VerifyOrSetDefaultHotkey(Settings.AutoCompleteHotkey2, "");
public string SelectNextItemHotkey => VerifyOrSetDefaultHotkey(Settings.SelectNextItemHotkey, "Tab");
public string SelectNextItemHotkey2 => VerifyOrSetDefaultHotkey(Settings.SelectNextItemHotkey2, "");
public string SelectPrevItemHotkey => VerifyOrSetDefaultHotkey(Settings.SelectPrevItemHotkey, "Shift+Tab");
public string SelectPrevItemHotkey2 => VerifyOrSetDefaultHotkey(Settings.SelectPrevItemHotkey2, "");
public string SelectNextPageHotkey => VerifyOrSetDefaultHotkey(Settings.SelectNextPageHotkey, "");
public string SelectPrevPageHotkey => VerifyOrSetDefaultHotkey(Settings.SelectPrevPageHotkey, "");
public string OpenContextMenuHotkey => VerifyOrSetDefaultHotkey(Settings.OpenContextMenuHotkey, "Ctrl+O");
public string SettingWindowHotkey => VerifyOrSetDefaultHotkey(Settings.SettingWindowHotkey, "Ctrl+I");
public string OpenHistoryHotkey => VerifyOrSetDefaultHotkey(Settings.OpenHistoryHotkey, "Ctrl+H");
public string CycleHistoryUpHotkey => VerifyOrSetDefaultHotkey(Settings.CycleHistoryUpHotkey, "Alt+Up");
public string CycleHistoryDownHotkey => VerifyOrSetDefaultHotkey(Settings.CycleHistoryDownHotkey, "Alt+Down");
public bool StartWithEnglishMode => Settings.AlwaysStartEn;
#endregion
#region Preview
private static readonly int ResultAreaColumnPreviewShown = 1;
private static readonly int ResultAreaColumnPreviewHidden = 3;
private bool? _selectedItemFromQueryResults;
private ResultViewModel _previewSelectedItem;
public ResultViewModel PreviewSelectedItem
{
get => _previewSelectedItem;
set
{
_previewSelectedItem = value;
OnPropertyChanged();
}
}
public bool InternalPreviewVisible
{
get
{
if (ResultAreaColumn == ResultAreaColumnPreviewShown)
return true;
if (ResultAreaColumn == ResultAreaColumnPreviewHidden)
return false;
#if DEBUG
throw new NotImplementedException("ResultAreaColumn should match ResultAreaColumnPreviewShown/ResultAreaColumnPreviewHidden value");
#else
App.API.LogError(ClassName, "ResultAreaColumnPreviewHidden/ResultAreaColumnPreviewShown int value not implemented", "InternalPreviewVisible");
return false;
#endif
}
}
public int ResultAreaColumn { get; set; } = ResultAreaColumnPreviewShown;
// This is not a reliable indicator of whether external preview is visible due to the
// ability of manually closing/exiting the external preview program which, does not inform flow that
// preview is no longer available.
public bool ExternalPreviewVisible { get; private set; }
private async Task ShowPreviewAsync()
{
var useExternalPreview = PluginManager.UseExternalPreview();
switch (useExternalPreview)
{
case true
when CanExternalPreviewSelectedResult(out var path):
// Internal preview may still be on when user switches to external
if (InternalPreviewVisible)
HideInternalPreview();
_ = OpenExternalPreviewAsync(path);
break;
case true
when !CanExternalPreviewSelectedResult(out var _):
if (ExternalPreviewVisible)
await CloseExternalPreviewAsync();
ShowInternalPreview();
break;
case false:
ShowInternalPreview();
break;
}
}
private void HidePreview()
{
if (PluginManager.UseExternalPreview())
_ = CloseExternalPreviewAsync();
if (InternalPreviewVisible)
HideInternalPreview();
}
[RelayCommand]
private void TogglePreview()
{
if (InternalPreviewVisible || ExternalPreviewVisible)
{
HidePreview();
}
else
{
_ = ShowPreviewAsync();
}
}
private async Task OpenExternalPreviewAsync(string path, bool sendFailToast = true)
{
await PluginManager.OpenExternalPreviewAsync(path, sendFailToast).ConfigureAwait(false);
ExternalPreviewVisible = true;
}
private async Task CloseExternalPreviewAsync()