forked from sumatrapdfreader/sumatrapdf
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommandPalette.cpp
More file actions
1354 lines (1218 loc) · 41.5 KB
/
Copy pathCommandPalette.cpp
File metadata and controls
1354 lines (1218 loc) · 41.5 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
/* Copyright 2022 the SumatraPDF project authors (see AUTHORS file).
License: Simplified BSD (see COPYING.BSD) */
#include "utils/BaseUtil.h"
#include "utils/WinUtil.h"
#include "utils/Dpi.h"
#include "utils/UITask.h"
#include "utils/FileUtil.h"
#include "wingui/UIModels.h"
#include "wingui/Layout.h"
#include "wingui/WinGui.h"
#include "Settings.h"
#include "AppSettings.h"
#include "DocController.h"
#include "EngineBase.h"
#include "EngineAll.h"
#include "GlobalPrefs.h"
#include "DisplayMode.h"
#include "DisplayModel.h"
#include "MainWindow.h"
#include "Theme.h"
#include "WindowTab.h"
#include "SumatraConfig.h"
#include "Commands.h"
#include "CommandPalette.h"
#include "Accelerators.h"
#include "SumatraPDF.h"
#include "Tabs.h"
#include "ExternalViewers.h"
#include "Annotation.h"
#include "FileHistory.h"
#include "DarkModeSubclass.h"
#include "Notifications.h"
#include "Translations.h"
#include "utils/Log.h"
constexpr const char* kInfoRegular = "↑ ↓ to navigate Enter to select Esc to close";
constexpr const char* kInfoSmartTab = "Ctrl+Tab to navigate Release Ctrl to select Space for sticky mode";
// clang-format off
// those commands never show up in command palette
static i32 gBlacklistCommandsFromPalette[] = {
CmdNone,
CmdOpenWithKnownExternalViewerFirst,
CmdOpenWithKnownExternalViewerLast,
CmdCommandPalette,
CmdNextTabSmart,
CmdPrevTabSmart,
CmdSetTheme,
// managing frequently list in home tab
CmdOpenSelectedDocument,
CmdPinSelectedDocument,
CmdForgetSelectedDocument,
CmdExpandAll, // TODO: figure proper context for it
CmdCollapseAll, // TODO: figure proper context for it
CmdMoveFrameFocus,
//CmdFavoriteAdd,
CmdFavoriteDel,
CmdPresentationWhiteBackground,
CmdPresentationBlackBackground,
CmdSaveEmbeddedFile, // TODO: figure proper context for it
CmdOpenEmbeddedPDF,
CmdSaveAttachment,
CmdOpenAttachment,
CmdCreateShortcutToFile, // not sure I want this at all
0,
};
// most commands are not valid when document is not opened
// it's shorter to list the remaining commands
static i32 gDocumentNotOpenWhitelist[] = {
CmdOpenFile,
CmdExit,
CmdNewWindow,
CmdContributeTranslation,
CmdOptions,
CmdAdvancedOptions,
CmdAdvancedSettings,
CmdChangeLanguage,
CmdCheckUpdate,
CmdHelpOpenManual,
CmdHelpOpenManualOnWebsite,
CmdHelpOpenKeyboardShortcuts,
CmdHelpVisitWebsite,
CmdHelpAbout,
CmdDebugDownloadSymbols,
CmdDebugShowNotif,
CmdDebugStartStressTest,
CmdDebugTestApp,
CmdDebugTogglePredictiveRender,
CmdDebugToggleRtl,
CmdFavoriteToggle,
CmdToggleFullscreen,
CmdToggleMenuBar,
CmdToggleToolbar,
CmdShowLog,
CmdClearHistory,
CmdReopenLastClosedFile,
CmdSelectNextTheme,
CmdToggleFrequentlyRead,
CmdDebugCrashMe,
CmdDebugCorruptMemory,
0,
};
// for those commands do not activate main window
// for example those that show dialogs (because the main window takes
// focus away from them)
static i32 gCommandsNoActivate[] = {
CmdOptions,
CmdChangeLanguage,
CmdHelpAbout,
CmdHelpOpenManual,
CmdHelpOpenManualOnWebsite,
CmdHelpOpenKeyboardShortcuts,
CmdHelpVisitWebsite,
CmdOpenFile,
CmdProperties,
CmdNewWindow,
CmdDuplicateInNewWindow,
// TOOD: probably more
0,
};
static i32 gCommandsDebugOnly[] = {
CmdDebugCorruptMemory,
CmdDebugCrashMe,
CmdDebugDownloadSymbols,
CmdDebugTestApp,
CmdDebugShowNotif,
CmdDebugStartStressTest,
0,
};
// clang-format on
// those are shared with Menu.cpp
extern UINT_PTR removeIfAnnotsNotSupported[];
extern UINT_PTR disableIfNoSelection[];
extern UINT_PTR removeIfNoInternetPerms[];
extern UINT_PTR removeIfNoFullscreenPerms[];
extern UINT_PTR removeIfNoPrefsPerms[];
extern UINT_PTR removeIfNoDiskAccessPerm[];
extern UINT_PTR removeIfNoCopyPerms[];
extern UINT_PTR removeIfChm[];
static bool IsCmdInList(i32 cmdId, i32* ids) {
while (*ids) {
if (cmdId == *ids) {
return true;
}
ids++;
}
return false;
}
// a must end with sentinel value of 0
static bool IsCmdInMenuList(i32 cmdId, UINT_PTR* a) {
UINT_PTR id = (UINT_PTR)cmdId;
for (int i = 0; a[i]; i++) {
if (a[i] == id) {
return true;
}
}
return false;
}
struct ItemDataCP {
i32 cmdId = 0;
WindowTab* tab = nullptr;
const char* filePath = nullptr;
};
using StrVecCP = StrVecWithData<ItemDataCP>;
struct ListBoxModelCP : ListBoxModel {
StrVecCP strings;
ListBoxModelCP() = default;
~ListBoxModelCP() override = default;
int ItemsCount() override { return strings.Size(); }
const char* Item(int i) override { return strings.At(i); }
ItemDataCP* Data(int i) { return strings.AtData(i); }
};
struct CommandPaletteWnd : Wnd {
~CommandPaletteWnd() override = default;
HFONT font = nullptr;
MainWindow* win = nullptr;
Edit* editQuery = nullptr;
StrVecCP tabs;
StrVecCP fileHistory;
StrVecCP commands;
ListBox* listBox = nullptr;
Static* staticInfo = nullptr;
StrVec filterWords;
int currTabIdx = 0;
bool smartTabMode = false;
bool stickyMode = false;
bool PreTranslateMessage(MSG&) override;
LRESULT WndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) override;
void CollectStrings(MainWindow*);
void FilterStringsForQuery(const char*, StrVecCP&);
bool Create(MainWindow* win, const char* prefix, int smartTabAdvance);
void QueryChanged();
void ExecuteCurrentSelection();
bool AdvanceSelection(int dir);
void SwitchToCommands();
void SwitchToTabs();
void SwitchToFileHistory();
void OnSelectionChange();
void OnListDoubleClick();
void DrawListBoxItem(ListBox::DrawItemEvent* ev);
};
struct CommandPaletteBuildCtx {
const char* filePath = nullptr;
bool isDocLoaded = false;
bool supportsAnnots = false;
bool hasSelection = false;
bool isChm = false;
bool canSendEmail = false;
Annotation* annotationUnderCursor = nullptr;
bool hasUnsavedAnnotations = false;
bool isCursorOnPage = false;
bool cursorOnLinkTarget = false;
bool cursorOnComment = false;
bool cursorOnImage = false;
bool hasToc = false;
bool allowToggleMenuBar = false;
bool canCloseOtherTabs = false;
bool canCloseTabsToRight = false;
bool canCloseTabsToLeft = false;
~CommandPaletteBuildCtx() = default;
};
static const char* SkipWS(const char* s) {
while (str::IsWs(*s)) {
s++;
}
return s;
}
static bool AllowCommand(const CommandPaletteBuildCtx& ctx, i32 cmdId) {
if (cmdId <= CmdFirst) {
return false;
}
CustomCommand* cmd = FindCustomCommand(cmdId);
int origCmdId = cmd ? cmd->origId : 0;
if (origCmdId == CmdSetTheme) {
return true;
}
if (IsCmdInList(cmdId, gCommandsDebugOnly)) {
return gIsDebugBuild;
}
if (IsCmdInList(cmdId, gBlacklistCommandsFromPalette)) {
return false;
}
if (CmdCloseOtherTabs == cmdId) {
return ctx.canCloseOtherTabs;
}
if (CmdCloseTabsToTheRight == cmdId) {
return ctx.canCloseTabsToRight;
}
if (CmdCloseTabsToTheLeft == cmdId) {
return ctx.canCloseTabsToLeft;
}
if (CmdReopenLastClosedFile == cmdId) {
return RecentlyCloseDocumentsCount() > 0;
}
// when document is not loaded, most commands are not available
// except those white-listed
if (IsCmdInList(cmdId, gDocumentNotOpenWhitelist)) {
return true;
}
if (!ctx.isDocLoaded) {
return false;
}
bool isKnownEV = (cmdId >= CmdOpenWithKnownExternalViewerFirst) && (cmdId <= CmdOpenWithKnownExternalViewerLast);
if (origCmdId == CmdViewWithExternalViewer || isKnownEV) {
if (!ctx.isDocLoaded) {
return false;
}
if (isKnownEV) {
// TODO: match file name
return HasKnownExternalViewerForCmd(cmdId);
}
const char* filter = GetCommandStringArg(cmd, kCmdArgFilter, nullptr);
return PathMatchFilter(ctx.filePath, filter);
}
if ((origCmdId == CmdSelectionHandler) || IsCmdInMenuList(cmdId, disableIfNoSelection)) {
return ctx.hasSelection;
}
// we only want to show this in home page
if (cmdId == CmdToggleFrequentlyRead) {
return !ctx.isDocLoaded;
}
if (cmdId == CmdToggleMenuBar) {
return ctx.allowToggleMenuBar;
}
if (!ctx.supportsAnnots) {
if ((cmdId >= (i32)CmdCreateAnnotFirst) && (cmdId <= (i32)CmdCreateAnnotLast)) {
return false;
}
if (IsCmdInMenuList(cmdId, removeIfAnnotsNotSupported)) {
return false;
}
}
if (ctx.isChm && IsCmdInMenuList(cmdId, removeIfChm)) {
return false;
}
if (!ctx.canSendEmail && (cmdId == CmdSendByEmail)) {
return false;
}
if (!ctx.annotationUnderCursor) {
if (cmdId == CmdDeleteAnnotation) {
return false;
}
}
if ((cmdId == CmdSaveAnnotations) || (cmdId == CmdSaveAnnotationsNewFile)) {
return ctx.hasUnsavedAnnotations;
}
if ((cmdId == CmdCheckUpdate) && gIsStoreBuild) {
return false;
}
bool remove = false;
if (!HasPermission(Perm::InternetAccess)) {
remove |= IsCmdInMenuList(cmdId, removeIfNoInternetPerms);
}
if (!HasPermission(Perm::FullscreenAccess)) {
remove |= IsCmdInMenuList(cmdId, removeIfNoFullscreenPerms);
}
if (!HasPermission(Perm::SavePreferences)) {
remove |= IsCmdInMenuList(cmdId, removeIfNoPrefsPerms);
}
if (!HasPermission(Perm::PrinterAccess)) {
remove |= (cmdId == CmdPrint);
}
if (!CanAccessDisk()) {
remove |= IsCmdInMenuList(cmdId, removeIfNoDiskAccessPerm);
}
if (!HasPermission(Perm::CopySelection)) {
remove |= IsCmdInMenuList(cmdId, removeIfNoCopyPerms);
}
if (remove) {
return false;
}
if (!ctx.cursorOnLinkTarget && (cmdId == CmdCopyLinkTarget)) {
return false;
}
if (!ctx.cursorOnComment && (cmdId == CmdCopyComment)) {
return false;
}
if (!ctx.cursorOnImage && (cmdId == CmdCopyImage)) {
return false;
}
if ((cmdId == CmdToggleBookmarks) || (cmdId == CmdToggleTableOfContents)) {
return ctx.hasToc;
}
if ((cmdId == CmdToggleScrollbars) && !gGlobalPrefs->fixedPageUI.hideScrollbars) {
return false;
}
return true;
}
static TempStr ConvertPathForDisplayTemp(const char* s) {
TempStr name = path::GetBaseNameTemp(s);
TempStr dir = path::GetDirTemp(s);
TempStr res = str::JoinTemp(name, " (", dir);
res = str::JoinTemp(res, ")");
return res;
}
static TempStr RemovePrefixFromString(const char* s) {
return str::ReplaceTemp(s, "&", "");
}
static const char* UpdateCommandNameTemp(MainWindow* win, int cmdId, const char* s) {
bool isToggle = false;
bool newIsOn = false;
switch (cmdId) {
case CmdToggleInverseSearch: {
extern bool gDisableInteractiveInverseSearch;
isToggle = true;
newIsOn = !gDisableInteractiveInverseSearch;
} break;
case CmdToggleFrequentlyRead: {
isToggle = true;
newIsOn = !gGlobalPrefs->showStartPage;
} break;
case CmdToggleFullscreen: {
isToggle = true;
newIsOn = !(win->isFullScreen || win->presentation);
} break;
case CmdToggleToolbar: {
isToggle = true;
newIsOn = !gGlobalPrefs->showToolbar;
} break;
case CmdToggleScrollbars: {
isToggle = true;
// hideScrollbars is inverted: true means hidden, toggling will show them
newIsOn = gGlobalPrefs->fixedPageUI.hideScrollbars;
} break;
case CmdToggleMenuBar: {
isToggle = true;
// isMenuHidden: true means hidden, toggling will show it
newIsOn = win->isMenuHidden;
} break;
case CmdToggleBookmarks:
case CmdToggleTableOfContents: {
isToggle = true;
newIsOn = !win->tocVisible;
} break;
case CmdTogglePresentationMode: {
isToggle = true;
newIsOn = !win->presentation;
} break;
case CmdToggleLinks: {
isToggle = true;
newIsOn = !gGlobalPrefs->showLinks;
} break;
case CmdToggleShowAnnotations: {
WindowTab* tab = win->CurrentTab();
if (tab) {
isToggle = true;
newIsOn = tab->hideAnnotations;
}
} break;
case CmdToggleContinuousView: {
if (win->ctrl) {
isToggle = true;
newIsOn = !IsContinuous(win->ctrl->GetDisplayMode());
}
} break;
case CmdToggleMangaMode: {
DisplayModel* dm = win->AsFixed();
if (dm) {
isToggle = true;
newIsOn = !dm->GetDisplayR2L();
}
} break;
case CmdFindToggleMatchCase: {
isToggle = true;
newIsOn = !win->findMatchCase;
} break;
case CmdFavoriteToggle: {
isToggle = true;
newIsOn = !gGlobalPrefs->showFavorites;
} break;
case CmdToggleAntiAlias: {
isToggle = true;
newIsOn = gGlobalPrefs->disableAntiAlias;
} break;
case CmdToggleZoom: {
// TODO: this toggles via different values
} break;
case CmdToggleCursorPosition: {
// TODO: this toggles 3 states
// isToggle = true;
// auto notif = GetNotificationForGroup(win->hwndCanvas, kNotifCursorPos);
// newIsOn = !notif;
} break;
case CmdTogglePageInfo: {
auto wnd = GetNotificationForGroup(win->hwndCanvas, kNotifPageInfo);
isToggle = true;
newIsOn = !wnd;
} break;
}
if (isToggle) {
s = (const char*)str::JoinTemp(s, newIsOn ? ": on" : ": off");
}
return s;
}
void CommandPaletteWnd::CollectStrings(MainWindow* mainWin) {
CommandPaletteBuildCtx ctx;
ctx.isDocLoaded = mainWin->IsDocLoaded();
WindowTab* currTab = mainWin->CurrentTab();
ctx.filePath = currTab ? currTab->filePath : nullptr;
ctx.hasSelection = ctx.isDocLoaded && currTab && mainWin->showSelection && currTab->selectionOnPage;
ctx.canSendEmail = CanSendAsEmailAttachment(currTab);
ctx.allowToggleMenuBar = !mainWin->tabsInTitlebar;
int nTabs = mainWin->TabCount();
int tabIdx = mainWin->GetTabIdx(currTab);
ctx.canCloseTabsToRight = tabIdx < (nTabs - 1);
ctx.canCloseTabsToLeft = false;
int nFirstDocTab = 0;
for (int i = 0; i < nTabs; i++) {
WindowTab* t = mainWin->GetTab(i);
if (t->IsAboutTab()) {
if (i > 0) {
logf("CommandPaletteWnd::CollectStrings: unexpected about tab at idx: %d out of %d\n", i, nTabs);
for (int j = 0; j < nTabs; j++) {
if (!t->IsAboutTab()) {
logf("i: %d path: %s\n", j, t->filePath ? t->filePath : "");
}
}
ReportIf(i > 0);
}
nFirstDocTab = 1;
continue;
}
if (t == currTab) {
if (i > nFirstDocTab) {
ctx.canCloseTabsToLeft = true;
}
continue;
}
ctx.canCloseOtherTabs = true;
}
Point cursorPos = HwndGetCursorPos(mainWin->hwndCanvas);
DisplayModel* dm = mainWin->AsFixed();
if (dm) {
auto engine = dm->GetEngine();
ctx.supportsAnnots = EngineSupportsAnnotations(engine);
ctx.hasUnsavedAnnotations = EngineHasUnsavedAnnotations(engine);
int pageNoUnderCursor = dm->GetPageNoByPoint(cursorPos);
if (pageNoUnderCursor > 0) {
ctx.isCursorOnPage = true;
}
ctx.annotationUnderCursor = dm->GetAnnotationAtPos(cursorPos, nullptr);
// PointF ptOnPage = dm->CvtFromScreen(cursorPos, pageNoUnderCursor);
// TODO: should this be point on page?
IPageElement* pageEl = dm->GetElementAtPos(cursorPos, nullptr);
if (pageEl) {
char* value = pageEl->GetValue();
ctx.cursorOnLinkTarget = value && pageEl->Is(kindPageElementDest);
ctx.cursorOnComment = value && pageEl->Is(kindPageElementComment);
ctx.cursorOnImage = pageEl->Is(kindPageElementImage);
}
}
if (!CanAccessDisk()) {
ctx.supportsAnnots = false;
ctx.hasUnsavedAnnotations = false;
}
ctx.hasToc = mainWin->ctrl && mainWin->ctrl->HasToc();
// append paths of opened files
currTabIdx = 0;
tabs.Reset();
for (MainWindow* w : gWindows) {
for (WindowTab* tab : w->Tabs()) {
ItemDataCP data;
data.tab = tab;
if (tab->IsAboutTab()) {
tabs.Append(_TRA("Home"), data);
continue;
}
auto name = path::GetBaseNameTemp(tab->filePath);
tabs.Append(name, data);
if (tab == currTab) {
currTabIdx = tabs.Size() - 1;
logf("currTabIdx: %d\n", currTabIdx);
}
}
}
// append paths of files from history, excluding
// already appended (from opened files)
fileHistory.Reset();
for (FileState* fs : *gGlobalPrefs->fileStates) {
char* s = fs->filePath;
s = ConvertPathForDisplayTemp(s);
ItemDataCP data;
data.filePath = fs->filePath;
fileHistory.Append(s, data);
}
StrVecCP tempCommands;
int cmdId = (int)CmdFirst + 1;
for (SeqStrings name = gCommandDescriptions; name; seqstrings::Next(name, &cmdId)) {
if (AllowCommand(ctx, (i32)cmdId)) {
ReportIf(str::Leni(name) == 0);
ItemDataCP data;
data.cmdId = (i32)cmdId;
auto nameTranslated = trans::GetTranslation(name);
auto nameUpdated = UpdateCommandNameTemp(mainWin, cmdId, (TempStr)nameTranslated);
tempCommands.Append(nameUpdated, data);
}
}
// includes externalViewers, selectionHandlers and keyboardShortcuts
auto curr = gFirstCustomCommand;
while (curr) {
TempStr name = (TempStr)curr->name;
cmdId = curr->id;
if (cmdId > 0 && !str::IsEmptyOrWhiteSpace(name)) {
if (AllowCommand(ctx, cmdId)) {
ItemDataCP data;
data.cmdId = cmdId;
name = RemovePrefixFromString(name);
tempCommands.Append(name, data);
}
}
curr = curr->next;
}
// we want the commands sorted
SortNoCase(&tempCommands);
int n = tempCommands.Size();
commands.Reset();
for (int i = 0; i < n; i++) {
commands.AppendFrom(&tempCommands, i);
}
}
static void EditSetTextAndFocus(Edit* e, const char* s) {
e->SetText(s);
e->SetCursorPositionAtEnd();
HwndSetFocus(e->hwnd);
}
void CommandPaletteWnd::SwitchToCommands() {
EditSetTextAndFocus(editQuery, kPalettePrefixCommands);
}
void CommandPaletteWnd::SwitchToTabs() {
EditSetTextAndFocus(editQuery, kPalettePrefixTabs);
}
void CommandPaletteWnd::SwitchToFileHistory() {
EditSetTextAndFocus(editQuery, kPalettePrefixFileHistory);
}
CommandPaletteWnd* gCommandPaletteWnd = nullptr;
HWND gCommandPaletteHwnd = nullptr;
static HWND gHwndToActivateOnClose = nullptr;
void SafeDeleteCommandPaletteWnd() {
if (!gCommandPaletteWnd) {
return;
}
auto tmp = gCommandPaletteWnd;
gCommandPaletteWnd = nullptr;
gCommandPaletteHwnd = nullptr;
delete tmp;
if (gHwndToActivateOnClose) {
SetActiveWindow(gHwndToActivateOnClose);
gHwndToActivateOnClose = nullptr;
}
}
static void ScheduleDelete() {
if (!gCommandPaletteWnd) {
return;
}
if (IsMainWindowValid(gCommandPaletteWnd->win)) {
HighlightTab(gCommandPaletteWnd->win, nullptr);
}
auto fn = MkFunc0Void(SafeDeleteCommandPaletteWnd);
uitask::Post(fn, "SafeDeleteCommandPaletteWnd");
}
LRESULT CommandPaletteWnd::WndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
switch (msg) {
case WM_ACTIVATE:
if (wp == WA_INACTIVE) {
ScheduleDelete();
return 0;
}
break;
case WM_COMMAND: {
int cmdId = LOWORD(wp);
CustomCommand* cmd = FindCustomCommand(cmdId);
if (cmd != nullptr) {
cmdId = cmd->origId;
}
switch (cmdId) {
case CmdNextTabSmart:
case CmdPrevTabSmart: {
int dir = cmdId == CmdNextTabSmart ? 1 : -1;
return AdvanceSelection(dir);
}
}
}
}
return WndProcDefault(hwnd, msg, wp, lp);
}
void CommandPaletteWnd::OnSelectionChange() {
int idx = listBox->GetCurrentSelection();
// logf("Selection changed: %d\n", idx);
if (!smartTabMode) {
return;
}
auto m = (ListBoxModelCP*)listBox->model;
ItemDataCP* data = m->strings.AtData(idx);
HighlightTab(win, data->tab);
}
static void SetCurrentSelection(CommandPaletteWnd* wnd, int idx) {
wnd->listBox->SetCurrentSelection(idx);
wnd->OnSelectionChange();
}
bool CommandPaletteWnd::AdvanceSelection(int dir) {
if (dir == 0) {
return false;
}
int n = listBox->GetCount();
if (n == 0) {
return false;
}
int currSel = listBox->GetCurrentSelection();
int sel = currSel + dir;
if (sel < 0) {
sel = n - 1;
}
if (sel >= n) {
sel = 0;
}
SetCurrentSelection(this, sel);
return true;
}
bool CommandPaletteWnd::PreTranslateMessage(MSG& msg) {
if (msg.message == WM_KEYDOWN) {
int dir = 0;
if (msg.wParam == VK_ESCAPE) {
ScheduleDelete();
return true;
}
if (msg.wParam == VK_RETURN) {
ExecuteCurrentSelection();
return true;
}
if (msg.wParam == VK_DELETE) {
const char* filter = editQuery->GetTextTemp();
filter = SkipWS(filter);
if (str::StartsWith(filter, kPalettePrefixFileHistory)) {
int n = listBox->GetCount();
if (n == 0) {
return false;
}
int currSel = listBox->GetCurrentSelection();
auto m = (ListBoxModelCP*)listBox->model;
auto d = m->Data(currSel);
FileState* fs = gFileHistory.FindByPath(d->filePath);
if (!fs) {
return true;
}
gFileHistory.Remove(fs);
CollectStrings(this->win);
this->QueryChanged();
// restore selection for fluid use
n = listBox->GetCount();
if (n == 0) {
return true;
}
int lastIdx = n - 1;
if (currSel > lastIdx) {
currSel = lastIdx;
}
listBox->SetCurrentSelection(currSel);
return true;
}
return true;
}
if (msg.wParam == VK_UP) {
dir = -1;
} else if (msg.wParam == VK_DOWN) {
dir = 1;
}
// ctrl+tab, ctrl+shift+tab is like up / down
if (msg.wParam == VK_TAB) {
if (IsCtrlPressed()) {
dir = IsShiftPressed() ? -1 : 1;
}
}
return AdvanceSelection(dir);
}
if (smartTabMode) {
// in smart tab mode releasing ctrl + tab selects a tab
if (msg.message == WM_KEYUP) {
if (msg.wParam == VK_CONTROL) {
if (!stickyMode) {
ExecuteCurrentSelection();
}
return true;
}
}
}
return false;
}
// all words must be present in str, ignoring the case
static bool FilterMatches(const char* str, const StrVec& words) {
int nWords = words.Size();
for (int i = 0; i < nWords; i++) {
auto word = words.At(i);
if (!str::ContainsI(str, word)) {
return false;
}
}
return true;
}
static void SplitFilterToWords(const char* filter, StrVec& words) {
char* s = str::DupTemp(filter);
char* wordStart = s;
bool wasWs = false;
while (*s) {
if (str::IsWs(*s)) {
*s = 0;
if (!wasWs) {
AppendIfNotExists(&words, wordStart);
wasWs = true;
}
wordStart = s + 1;
}
s++;
}
if (str::Leni(wordStart) > 0) {
AppendIfNotExists(&words, wordStart);
}
}
static void FilterStrings(StrVecCP& strs, const StrVec& words, StrVecCP& matchedOut) {
int n = strs.Size();
for (int i = 0; i < n; i++) {
const char* s = strs.At(i);
if (!FilterMatches(s, words)) {
continue;
}
matchedOut.AppendFrom(&strs, i);
}
}
void CommandPaletteWnd::FilterStringsForQuery(const char* filter, StrVecCP& strings) {
// for efficiency, reusing existing model
strings.Reset();
if (!filter) {
filter = "";
}
// strip prefix and remember which lists to search
bool searchTabs = false, searchHistory = false, searchCommands = false;
if (str::StartsWith(filter, kPalettePrefixAll)) {
filter++;
searchTabs = searchHistory = searchCommands = true;
} else if (str::StartsWith(filter, kPalettePrefixTabs)) {
filter++;
searchTabs = true;
} else if (str::StartsWith(filter, kPalettePrefixFileHistory)) {
filter++;
searchHistory = true;
} else {
if (str::StartsWith(filter, kPalettePrefixCommands)) {
filter++;
}
searchCommands = true;
}
// split filter into words once
filterWords.Reset();
SplitFilterToWords(filter, filterWords);
if (searchTabs) {
FilterStrings(tabs, filterWords, strings);
}
if (searchHistory) {
FilterStrings(fileHistory, filterWords, strings);
}
if (searchCommands) {
FilterStrings(commands, filterWords, strings);
}
}
void CommandPaletteWnd::QueryChanged() {
const char* filter = editQuery->GetTextTemp();
filter = SkipWS(filter);
int currSelIdx = 0;
auto m = (ListBoxModelCP*)listBox->model;
int nItemsPrev = m->ItemsCount();
if (smartTabMode) {
if (!stickyMode) {
if (str::Len(filter) > 1) {
// we only advertise this for 'space' but any change to query
// enables sticky mode (i.e. no auto-selection
stickyMode = true;
currSelIdx = listBox->GetCurrentSelection();
}
}
}
FilterStringsForQuery(filter, m->strings);
listBox->SetModel(m);
int nItems = m->ItemsCount();
if (nItems == 0) {
return;
}
if (stickyMode && nItemsPrev == nItems) {
SetCurrentSelection(this, currSelIdx);
return;
}
SetCurrentSelection(this, 0);
}
void CommandPaletteWnd::ExecuteCurrentSelection() {
int idx = listBox->GetCurrentSelection();
if (idx < 0) {
return;
}
auto m = (ListBoxModelCP*)listBox->model;
ItemDataCP* data = m->strings.AtData(idx);
i32 cmdId = data->cmdId;
if (cmdId != 0) {
bool noActivate = IsCmdInList(cmdId, gCommandsNoActivate);
if (noActivate) {
gHwndToActivateOnClose = nullptr;
}
HwndSendCommand(win->hwndFrame, cmdId);
ScheduleDelete();
return;
}
WindowTab* tab = data->tab;
if (tab != nullptr) {
MainWindow* mainWin = tab->win;
if (mainWin->CurrentTab() != tab) {
SelectTabInWindow(tab);
}
gHwndToActivateOnClose = mainWin->hwndFrame;
ScheduleDelete();
return;
}
auto filePath = data->filePath;
if (filePath) {
LoadArgs args(filePath, win);
args.forceReuse = false; // open in a new tab
StartLoadDocument(&args);
ScheduleDelete();
return;
}
logf("CommandPaletteWnd::ExecuteCurrentSelection: no match for selection '%s'\n", m->strings.At(idx));
ReportIf(true);
ScheduleDelete();
}
void CommandPaletteWnd::OnListDoubleClick() {
ExecuteCurrentSelection();
}
void OnDestroy(Wnd::DestroyEvent*) {
ScheduleDelete();
}
// almost like HwndPositionInCenterOf but y is near top of hwndRelative
static void PositionCommandPalette(HWND hwnd, HWND hwndRelative) {
Rect rRelative = WindowRect(hwndRelative);
Rect r = WindowRect(hwnd);
int x = rRelative.x + (rRelative.dx / 2) - (r.dx / 2);