-
Notifications
You must be signed in to change notification settings - Fork 206
/
Copy pathvmenu.cpp
3539 lines (2968 loc) · 101 KB
/
vmenu.cpp
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
/*
vmenu.cpp
Обычное вертикальное меню
а так же:
* список в DI_COMBOBOX
* список в DI_LISTBOX
* ...
*/
/*
Copyright © 1996 Eugene Roshal
Copyright © 2000 Far Group
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// BUGBUG
#include "platform.headers.hpp"
// Self:
#include "vmenu.hpp"
// Internal:
#include "keyboard.hpp"
#include "keys.hpp"
#include "macroopcode.hpp"
#include "farcolor.hpp"
#include "dialog.hpp"
#include "savescr.hpp"
#include "clipboard.hpp"
#include "ctrlobj.hpp"
#include "manager.hpp"
#include "constitle.hpp"
#include "interf.hpp"
#include "colormix.hpp"
#include "config.hpp"
#include "processname.hpp"
#include "uuids.far.hpp"
#include "xlat.hpp"
#include "lang.hpp"
#include "vmenu2.hpp"
#include "strmix.hpp"
#include "string_sort.hpp"
#include "exception.hpp"
#include "global.hpp"
// Platform:
// Common:
#include "common.hpp"
#include "common/scope_exit.hpp"
#include "common/uuid.hpp"
#include "common/view/enumerate.hpp"
#include "common/view/zip.hpp"
// External:
//----------------------------------------------------------------------------
// Must be in the TU scope because it is befriended by VMenu
struct menu_layout
{
short BoxType{};
small_rectangle ClientRect{};
std::optional<short> LeftBox;
std::optional<short> CheckMark;
std::optional<short> LeftHScroll;
std::optional<std::pair<short, short>> TextArea; // Begin, Width
std::optional<short> RightHScroll;
std::optional<short> SubMenu;
std::optional<short> Scrollbar;
std::optional<short> RightBox;
explicit menu_layout(const VMenu& Menu)
: BoxType{ get_box_type(Menu) }
, ClientRect{ get_client_rect(Menu) }
{
auto Left{ Menu.m_Where.left };
if (need_box(BoxType)) LeftBox = Left++;
if (need_check_mark()) CheckMark = Left++;
if (need_left_hscroll()) LeftHScroll = Left++;
auto Right{ Menu.m_Where.right };
if (need_box(BoxType)) RightBox = Right;
if (need_scrollbar(Menu)) Scrollbar = Right;
if (RightBox || Scrollbar) Right--;
if (need_submenu(Menu)) SubMenu = Right--;
if (need_right_hscroll()) RightHScroll = Right--;
if (Left <= Right)
TextArea = { Left, Right + 1 - Left };
}
[[nodiscard]] static bool need_box(const VMenu& Menu) noexcept
{
return !(Menu.CheckFlags(VMENU_LISTBOX) && Menu.CheckFlags(VMENU_SHOWNOBOX));
}
[[nodiscard]] static short get_box_type(const VMenu& Menu) noexcept
{
if (Menu.CheckFlags(VMENU_LISTBOX))
{
if (Menu.CheckFlags(VMENU_LISTSINGLEBOX))
return SHORT_SINGLE_BOX;
else if (Menu.CheckFlags(VMENU_SHOWNOBOX))
return NO_BOX;
else if (Menu.CheckFlags(VMENU_LISTHASFOCUS))
return SHORT_DOUBLE_BOX;
else
return SHORT_SINGLE_BOX;
}
else if (Menu.CheckFlags(VMENU_COMBOBOX))
return SHORT_SINGLE_BOX;
else
return DOUBLE_BOX;
}
[[nodiscard]] static int get_service_area_size(const VMenu& Menu)
{
return get_service_area_size(Menu, need_box(Menu));
}
[[nodiscard]] static int get_service_area_size(const VMenu& Menu, const short BoxType)
{
return get_service_area_size(Menu, need_box(BoxType));
}
private:
[[nodiscard]] rectangle get_client_rect(const VMenu& Menu) const noexcept
{
if (!need_box(BoxType))
return Menu.m_Where;
return { Menu.m_Where.left + 1, Menu.m_Where.top + 1, Menu.m_Where.right - 1, Menu.m_Where.bottom - 1 };
}
[[nodiscard]] static int get_service_area_size(const VMenu& Menu, const bool NeedBox)
{
return NeedBox
+ need_check_mark()
+ need_left_hscroll()
+ need_right_hscroll()
+ need_submenu(Menu)
+ (NeedBox || need_scrollbar(Menu));
}
[[nodiscard]] static bool need_box(short BoxType) noexcept { return BoxType != NO_BOX; }
[[nodiscard]] static bool need_check_mark() noexcept { return true; }
[[nodiscard]] static bool need_left_hscroll() noexcept { return true; }
[[nodiscard]] static bool need_right_hscroll() noexcept { return true; }
[[nodiscard]] static bool need_submenu(const VMenu& Menu) noexcept { return Menu.ItemSubMenusCount > 0; }
[[nodiscard]] static bool need_scrollbar(const VMenu& Menu)
{
return (Menu.CheckFlags(VMENU_LISTBOX | VMENU_ALWAYSSCROLLBAR) || Global->Opt->ShowMenuScrollbar)
&& ScrollBarRequired(Menu.m_Where.height(), Menu.GetShowItemCount());
}
};
namespace
{
MenuItemEx far_list_to_menu_item(const FarListItem& FItem)
{
MenuItemEx Result;
Result.Flags = FItem.Flags;
Result.Name = NullToEmpty(FItem.Text);
Result.SimpleUserData = FItem.UserData;
return Result;
}
int find_nearest(std::ranges::contiguous_range auto const& Range, const int Pos, const auto Pred, const bool GoBackward, const bool DoWrap)
{
using namespace std::views;
assert(0 <= Pos && Pos < static_cast<int>(Range.size()));
const auto FindPos =
[&](const auto First, const auto Second)
{
const auto FindPosPart =
[&](const auto Part)
{
if (auto Filtered = Range | Part | filter(Pred))
return static_cast<int>(&Filtered.front() - Range.data());
return -1;
};
if (const auto Found{ FindPosPart(First) }; Found != -1) return Found;
if (const auto Found{ FindPosPart(Second) }; Found != -1) return Found;
return -1;
};
return GoBackward
? (DoWrap
? FindPos(take(Pos + 1) | reverse, drop(Pos + 1) | reverse)
: FindPos(take(Pos + 1) | reverse, drop(Pos + 1)))
: (DoWrap
? FindPos(drop(Pos), take(Pos))
: FindPos(drop(Pos), take(Pos) | reverse));
}
std::pair<int, int> intersect(std::pair<int, int> A, std::pair<int, int> B)
{
assert(A.first <= A.second);
assert(B.first <= B.second);
if (A.first == A.second || B.first == B.second)
return {};
if (B.first < A.first)
std::ranges::swap(A, B);
if (A.second <= B.first)
return {};
return { B.first, std::min(A.second, B.second) };
}
void markup_slice_boundaries(std::pair<int, int> Segment, std::ranges::input_range auto const& Slices, std::vector<int>& Markup)
{
assert(Segment.first <= Segment.second);
for (const auto& Slice : Slices)
{
if (Slice.first >= Slice.second)
continue;
const auto Intersection{ intersect(Segment, Slice) };
if (Intersection.first == Intersection.second)
continue;
Markup.emplace_back(Intersection.first);
Markup.emplace_back(Intersection.second);
Segment.first = Intersection.second;
if (Segment.first == Segment.second)
return;
}
Markup.emplace_back(Segment.second);
}
bool item_flags_allow_focus(unsigned long long const Flags)
{
return !(Flags & (LIF_DISABLE | LIF_HIDDEN | LIF_FILTERED | LIF_SEPARATOR));
}
bool item_can_have_focus(MenuItemEx const& Item)
{
return item_flags_allow_focus(Item.Flags);
}
bool item_can_be_entered(MenuItemEx const& Item)
{
return item_can_have_focus(Item) && !(Item.Flags & LIF_GRAYED);
}
bool item_is_visible(MenuItemEx const& Item)
{
return !(Item.Flags & (LIF_HIDDEN | LIF_FILTERED));
}
int get_item_visual_length(const bool ShowAmpersand, const string_view ItemName)
{
return static_cast<int>(ShowAmpersand ? visual_string_length(ItemName) : HiStrlen(ItemName));
}
enum class item_hscroll_policy
{
unbound, // The item can move freely beyond window edges.
cling_to_edge, // The item can move beyond window edges, but at least one character is always visible.
bound, // The item can move only within the window boundaries.
bound_stick_to_left // Like bound, but if the item shorter than TextAreaWidth, it is always attached to the left window edge.
};
std::pair<int, int> item_hpos_limits(const int ItemLength, const int TextAreaWidth, const item_hscroll_policy Policy) noexcept
{
using enum item_hscroll_policy;
assert(ItemLength > 0);
assert(TextAreaWidth > 0);
switch (Policy)
{
case unbound:
return{ std::numeric_limits<int>::min(), std::numeric_limits<int>::max()};
case cling_to_edge:
return{ 1 - ItemLength, TextAreaWidth - 1 };
case bound:
return{ std::min(0, TextAreaWidth - ItemLength), std::max(0, TextAreaWidth - ItemLength) };
case bound_stick_to_left:
return{ std::min(0, TextAreaWidth - ItemLength), 0 };
default:
std::unreachable();
}
}
int get_item_absolute_hpos(const int NewHPos, const int ItemLength, const int TextAreaWidth, const item_hscroll_policy Policy)
{
const auto [HPosMin, HPosMax]{ item_hpos_limits(ItemLength, TextAreaWidth, Policy) };
return std::clamp(NewHPos, HPosMin, HPosMax);
}
int get_item_smart_hpos(const int NewHPos, const int ItemLength, const int TextAreaWidth, const item_hscroll_policy Policy)
{
return get_item_absolute_hpos(NewHPos >= 0 ? NewHPos : TextAreaWidth - ItemLength + NewHPos + 1, ItemLength, TextAreaWidth, Policy);
}
int adjust_hpos_shift(const int Shift, const int Left, const int Right, const int TextAreaWidth)
{
assert(Left < Right);
if (Shift == 0) return 0;
// Shift left.
if (Shift > 0)
{
const auto ShiftLimit{ std::max(TextAreaWidth - Left - 1, 0) };
const auto GapLeftOfTextArea{ std::max(-Right, 0) };
return std::min(Shift + GapLeftOfTextArea, ShiftLimit);
}
// Shift right. It's just shift left seen from behind the screen.
return -adjust_hpos_shift(-Shift, TextAreaWidth - Right, TextAreaWidth - Left, TextAreaWidth);
}
// Indices in the color array
enum class color_indices
{
Body = 0, // background
Box = 1, // border
Title = 2, // title - top and bottom
Text = 3, // item text
Highlight = 4, // hot key
Separator = 5, // separator
Selected = 6, // selected
HSelect = 7, // selected - HotKey
ScrollBar = 8, // scrollBar
Disabled = 9, // disabled
Arrows =10, // '«' & '»' normal
ArrowsSelect =11, // '«' & '»' selected
ArrowsDisabled =12, // '«' & '»' disabled
Grayed =13, // grayed
SelGrayed =14, // selected grayed
COUNT // always the last - array dimension
};
static_assert(std::tuple_size_v<vmenu_colors_t> == std::to_underlying(color_indices::COUNT));
[[nodiscard]] const FarColor& get_color(const vmenu_colors_t& VMenuColors, color_indices ColorIndex) noexcept
{
return VMenuColors[std::to_underlying(ColorIndex)];
}
void set_color(const vmenu_colors_t& VMenuColors, color_indices ColorIndex)
{
SetColor(get_color(VMenuColors, ColorIndex));
}
struct item_color_indicies
{
color_indices Normal, Highlighted, HScroller;
item_color_indicies(const MenuItemEx& CurItem)
{
const auto Selected{ !!(CurItem.Flags & LIF_SELECTED) };
const auto Grayed{ !!(CurItem.Flags & LIF_GRAYED) };
const auto Disabled{ !!(CurItem.Flags & LIF_DISABLE) };
if (Disabled)
{
Normal = color_indices::Disabled;
Highlighted = color_indices::Disabled;
HScroller = color_indices::ArrowsDisabled;
return;
}
if (Selected)
{
Normal = Grayed ? color_indices::SelGrayed : color_indices::Selected;
Highlighted = Grayed ? color_indices::SelGrayed : color_indices::HSelect;
HScroller = color_indices::ArrowsSelect;
return;
}
Normal = Grayed ? color_indices::Grayed : color_indices::Text;
Highlighted = Grayed ? color_indices::Grayed : color_indices::Highlight;
HScroller = color_indices::Arrows;
}
};
std::tuple<color_indices, wchar_t> get_item_check_mark(const MenuItemEx& CurItem, item_color_indicies ColorIndices) noexcept
{
return
{
ColorIndices.Normal,
!(CurItem.Flags & LIF_CHECKED)
? L' '
: !(CurItem.Flags & 0x0000FFFF) ? L'√' : static_cast<wchar_t>(CurItem.Flags & 0x0000FFFF)
};
}
std::tuple<color_indices, wchar_t> get_item_submenu(const MenuItemEx& CurItem, item_color_indicies ColorIndices) noexcept
{
return
{
ColorIndices.Normal,
(CurItem.Flags & MIF_SUBMENU) ? L'►' : L' '
};
}
std::tuple<color_indices, wchar_t> get_item_left_hscroll(const bool NeedLeftHScroll, item_color_indicies ColorIndices) noexcept
{
return
{
NeedLeftHScroll ? ColorIndices.HScroller : ColorIndices.Normal,
NeedLeftHScroll ? L'«' : L' '
};
}
std::tuple<color_indices, wchar_t> get_item_right_hscroll(const bool NeedRightHScroll, item_color_indicies ColorIndices) noexcept
{
return
{
NeedRightHScroll ? ColorIndices.HScroller : ColorIndices.Normal,
NeedRightHScroll ? L'»' : L' '
};
}
}
VMenu::VMenu(private_tag, string Title, int MaxHeight, dialog_ptr ParentDialog):
strTitle(std::move(Title)),
MaxHeight(MaxHeight),
ParentDialog(ParentDialog),
MenuId(FarUuid)
{
}
vmenu_ptr VMenu::create(string Title, std::span<menu_item const> const Data, int MaxHeight, DWORD Flags, dialog_ptr ParentDialog)
{
auto VmenuPtr = std::make_shared<VMenu>(private_tag(), std::move(Title), MaxHeight, ParentDialog);
VmenuPtr->init(Data, Flags);
return VmenuPtr;
}
void VMenu::init(std::span<menu_item const> const Data, DWORD Flags)
{
SaveScr=nullptr;
SetMenuFlags(Flags | VMENU_MOUSEREACTION | VMENU_UPDATEREQUIRED);
ClearFlags(VMENU_MOUSEDOWN);
CurrentWindow = Global->WindowManager->GetCurrentWindow();
GetCursorType(PrevCursorVisible,PrevCursorSize);
bRightBtnPressed = false;
// инициализируем перед добавлением элемента
UpdateMaxLengthFromTitles();
for (const auto& i: Data)
{
MenuItemEx NewItem;
static_cast<menu_item&>(NewItem) = i;
AddItem(std::move(NewItem));
}
SetMaxHeight(MaxHeight);
SetColors(nullptr); //Установим цвет по умолчанию
}
VMenu::~VMenu()
{
VMenu::Hide();
clear();
if (Global->WindowManager->GetCurrentWindow() == CurrentWindow)
SetCursorType(PrevCursorVisible,PrevCursorSize);
}
void VMenu::ResetCursor()
{
GetCursorType(PrevCursorVisible,PrevCursorSize);
}
bool VMenu::UpdateRequired() const
{
return CheckFlags(VMENU_UPDATEREQUIRED)!=0;
}
void VMenu::UpdateItemFlags(int Pos, unsigned long long NewFlags)
{
if (Items[Pos].Flags & MIF_SUBMENU)
--ItemSubMenusCount;
if (!item_is_visible(Items[Pos]))
--ItemHiddenCount;
if (!item_flags_allow_focus(NewFlags))
NewFlags &= ~LIF_SELECTED;
//remove selection
if ((Items[Pos].Flags&LIF_SELECTED) && !(NewFlags&LIF_SELECTED))
{
SelectPos = -1;
}
//set new selection
else if (!(Items[Pos].Flags&LIF_SELECTED) && (NewFlags&LIF_SELECTED))
{
if (SelectPos>=0)
Items[SelectPos].Flags &= ~LIF_SELECTED;
SelectPos = Pos;
}
Items[Pos].Flags = NewFlags;
if (SelectPos < 0)
SetSelectPos(0,1);
if(const auto Value = extract_integer<WORD, 0>(Items[Pos].Flags))
{
Items[Pos].Flags|=LIF_CHECKED;
if (Value == 1)
{
Items[Pos].Flags&=0xFFFF0000;
}
}
if (NewFlags&MIF_SUBMENU)
ItemSubMenusCount++;
if (!item_is_visible(Items[Pos]))
ItemHiddenCount++;
}
// переместить курсор c учётом пунктов которые не могут получать фокус
int VMenu::SetSelectPos(int Pos, int Direct, bool stop_on_edge)
{
SelectPosResult=-1;
if (Items.empty())
return -1;
for (auto& i: Items)
{
i.Flags &= ~LIF_SELECTED;
}
const auto DoWrap{ CheckFlags(VMENU_WRAPMODE) && Direct != 0 && !stop_on_edge };
const auto GoBackward{ Direct < 0 };
const auto ItemsSize{ static_cast<int>(Items.size()) };
if (Pos < 0)
{
Pos = DoWrap ? ItemsSize - 1 : 0;
}
else if (Pos >= ItemsSize)
{
Pos = DoWrap ? 0 : ItemsSize - 1;
}
Pos = find_nearest(Items, Pos, item_can_have_focus, GoBackward, DoWrap);
if (Pos != SelectPos && CheckFlags(VMENU_COMBOBOX | VMENU_LISTBOX))
{
if (const auto Parent = GetDialog(); Parent && Parent->IsInited() && !Parent->SendMessage(DN_LISTCHANGE, DialogItemID, ToPtr(Pos)))
{
UpdateItemFlags(SelectPos, Items[SelectPos].Flags | LIF_SELECTED);
return -1;
}
}
if (Pos >= 0)
UpdateItemFlags(Pos, Items[Pos].Flags | LIF_SELECTED);
SetMenuFlags(VMENU_UPDATEREQUIRED);
SelectPosResult = Pos;
return Pos;
}
// установить курсор и верхний элемент
int VMenu::SetSelectPos(const FarListPos *ListPos, int Direct)
{
const auto pos = std::clamp(ListPos->SelectPos, intptr_t{}, static_cast<intptr_t>(Items.size() - 1));
const auto Ret = SetSelectPos(pos, Direct ? Direct : pos > SelectPos? 1 : -1);
if (Ret >= 0)
{
TopPos = ListPos->TopPos;
if (TopPos == -1)
{
if (GetShowItemCount() < MaxHeight)
{
TopPos = VisualPosToReal(0);
}
else
{
TopPos = GetVisualPos(TopPos);
TopPos = (GetVisualPos(SelectPos)-TopPos+1) > MaxHeight ? TopPos+1 : TopPos;
if (TopPos+MaxHeight > GetShowItemCount())
TopPos = GetShowItemCount()-MaxHeight;
TopPos = VisualPosToReal(TopPos);
}
}
if (TopPos < 0)
TopPos = 0;
}
return Ret;
}
//корректировка текущей позиции
void VMenu::UpdateSelectPos()
{
if (Items.empty())
return;
// если selection стоит в некорректном месте - сбросим его
if (SelectPos >= 0 && !item_can_have_focus(Items[SelectPos]))
SelectPos = -1;
for (const auto& [Item, Index]: enumerate(Items))
{
if (!item_can_have_focus(Item))
{
Item.SetSelect(false);
}
else
{
if (SelectPos == -1)
{
Item.SetSelect(true);
SelectPos = static_cast<int>(Index);
}
else if (SelectPos != static_cast<int>(Index))
{
Item.SetSelect(false);
}
else
{
Item.SetSelect(true);
}
}
}
}
int VMenu::GetItemPosition(int Position) const
{
int DataPos = (Position==-1) ? SelectPos : Position;
if (DataPos>=static_cast<int>(Items.size()))
DataPos = -1; //Items.size()-1;
return DataPos;
}
// получить позицию курсора и верхнюю позицию элемента
int VMenu::GetSelectPos(FarListPos *ListPos) const
{
ListPos->SelectPos=SelectPos;
ListPos->TopPos=TopPos;
return ListPos->SelectPos;
}
int VMenu::InsertItem(const FarListInsert *NewItem)
{
if (NewItem)
{
if (AddItem(far_list_to_menu_item(NewItem->Item), NewItem->Index) >= 0)
return static_cast<int>(Items.size());
}
return -1;
}
int VMenu::AddItem(const FarList* List)
{
if (List && List->Items)
{
for (const auto& Item: std::span(List->Items, List->ItemsNumber))
{
AddItem(far_list_to_menu_item(Item));
}
}
return static_cast<int>(Items.size());
}
int VMenu::AddItem(const wchar_t *NewStrItem)
{
FarListItem FarListItem0{};
if (!NewStrItem || NewStrItem[0] == 0x1)
{
FarListItem0.Flags=LIF_SEPARATOR;
if (NewStrItem)
FarListItem0.Text = NewStrItem + 1;
}
else
{
FarListItem0.Text=NewStrItem;
}
const FarList List{ sizeof(List), 1, &FarListItem0 };
return AddItem(&List) - 1; //-1 потому что AddItem(FarList) возвращает количество элементов
}
int VMenu::AddItem(MenuItemEx&& NewItem,int PosAdd)
{
PosAdd = std::clamp(PosAdd, 0, static_cast<int>(Items.size()));
Items.emplace(Items.begin() + PosAdd, std::move(NewItem));
auto& NewMenuItem = Items[PosAdd];
NewMenuItem.AutoHotkey = {};
NewMenuItem.AutoHotkeyPos = 0;
NewMenuItem.HorizontalPosition = 0;
if (PosAdd <= SelectPos)
SelectPos++;
const auto ItemLength{ get_item_visual_length(CheckFlags(VMENU_SHOWAMPERSAND), NewMenuItem.Name) };
UpdateMaxLength(ItemLength);
UpdateAllItemsBoundaries(NewMenuItem.HorizontalPosition, ItemLength);
const auto NewFlags = NewMenuItem.Flags;
NewMenuItem.Flags = 0;
UpdateItemFlags(PosAdd, NewFlags);
SetMenuFlags(VMENU_UPDATEREQUIRED | (bFilterEnabled ? VMENU_REFILTERREQUIRED : VMENU_NONE));
return static_cast<int>(Items.size()-1);
}
bool VMenu::UpdateItem(const FarListUpdate *NewItem)
{
if (!NewItem || static_cast<size_t>(NewItem->Index) >= Items.size())
return false;
auto& Item = Items[NewItem->Index];
// Освободим память... от ранее занятого ;-)
if (NewItem->Item.Flags&LIF_DELETEUSERDATA)
{
Item.ComplexUserData = {};
}
Item.Name = NullToEmpty(NewItem->Item.Text);
UpdateItemFlags(NewItem->Index, NewItem->Item.Flags);
Item.SimpleUserData = NewItem->Item.UserData;
const auto ItemLength{ get_item_visual_length(CheckFlags(VMENU_SHOWAMPERSAND), Item.Name) };
UpdateMaxLength(ItemLength);
UpdateAllItemsBoundaries(Item.HorizontalPosition, ItemLength);
SetMenuFlags(VMENU_UPDATEREQUIRED | (bFilterEnabled ? VMENU_REFILTERREQUIRED : VMENU_NONE));
return true;
}
//функция удаления N пунктов меню
int VMenu::DeleteItem(int ID, int Count)
{
if (ID < 0 || ID >= static_cast<int>(Items.size()) || Count <= 0)
return static_cast<int>(Items.size());
if (ID+Count > static_cast<int>(Items.size()))
Count=static_cast<int>(Items.size()-ID);
if (Count <= 0)
return static_cast<int>(Items.size());
if (!ID && Count == static_cast<int>(Items.size()))
{
clear();
return static_cast<int>(Items.size());
}
for (const auto I: std::views::iota(0, Count))
{
if (Items[ID+I].Flags & MIF_SUBMENU)
--ItemSubMenusCount;
if (!item_is_visible(Items[ID+I]))
--ItemHiddenCount;
}
// а вот теперь перемещения
const auto FirstIter = Items.begin() + ID, LastIter = FirstIter + Count;
if (Items.size() > 1)
Items.erase(FirstIter, LastIter);
// коррекция текущей позиции
if (SelectPos >= ID && SelectPos < ID+Count)
{
if(SelectPos==static_cast<int>(Items.size()))
{
ID--;
}
SelectPos = -1;
SetSelectPos(ID, 0, true);
}
else if (SelectPos >= ID+Count)
{
SelectPos -= Count;
if (TopPos >= ID+Count)
TopPos -= Count;
}
SetMenuFlags(VMENU_UPDATEREQUIRED);
return static_cast<int>(Items.size());
}
void VMenu::clear()
{
Items.clear();
ItemHiddenCount=0;
ItemSubMenusCount=0;
SelectPos=-1;
TopPos=0;
m_MaxItemLength = 0;
UpdateMaxLengthFromTitles();
ResetAllItemsBoundaries();
SetMenuFlags(VMENU_UPDATEREQUIRED);
}
int VMenu::GetCheck(int Position)
{
const auto ItemPos = GetItemPosition(Position);
if (ItemPos < 0)
return 0;
if (Items[ItemPos].Flags & LIF_SEPARATOR)
return 0;
if (!(Items[ItemPos].Flags & LIF_CHECKED))
return 0;
const auto Checked = Items[ItemPos].Flags & 0xFFFF;
return Checked ? Checked : 1;
}
void VMenu::SetCheck(int Position)
{
const auto ItemPos = GetItemPosition(Position);
if (ItemPos < 0)
return;
Items[ItemPos].SetCheck();
}
void VMenu::SetCustomCheck(wchar_t Char, int Position)
{
const auto ItemPos = GetItemPosition(Position);
if (ItemPos < 0)
return;
Items[ItemPos].SetCustomCheck(Char);
}
void VMenu::ClearCheck(int Position)
{
const auto ItemPos = GetItemPosition(Position);
if (ItemPos < 0)
return;
Items[ItemPos].ClearCheck();
}
void VMenu::RestoreFilteredItems()
{
for (auto& i: Items)
{
if (!(i.Flags & MIF_FILTERED))
continue;
i.Flags &= ~MIF_FILTERED;
if (item_is_visible(i))
--ItemHiddenCount;
}
FilterUpdateHeight();
// Подровнять, а то в нижней части списка может оставаться куча пустых строк
const FarListPos pos{ sizeof(pos), SelectPos < 0? 0 : SelectPos, -1 };
SetSelectPos(&pos);
}
void VMenu::FilterStringUpdated()
{
int PrevSeparator = -1, PrevGroup = -1;
int UpperVisible = -1, LowerVisible = -2;
bool bBottomMode = false;
if (SelectPos > 0)
{
// Определить, в верхней или нижней части расположен курсор
const auto TopVisible = GetVisualPos(TopPos);
const auto SelectedVisible = GetVisualPos(SelectPos);
const auto BottomVisible = (TopVisible+MaxHeight > GetShowItemCount()) ? (TopVisible+MaxHeight-1) : (GetShowItemCount()-1);
if (SelectedVisible >= ((TopVisible+BottomVisible)>>1))
bBottomMode = true;
}
ItemHiddenCount=0;
for (const auto& [CurItem, index]: enumerate(Items))
{
CurItem.Flags &= ~LIF_FILTERED;
if (!item_is_visible(CurItem))
{
++ItemHiddenCount;
continue;
}
if (CurItem.Flags & LIF_SEPARATOR)
{
// В предыдущей группе все элементы скрыты, разделитель перед группой - не нужен
if (PrevSeparator != -1)
{
Items[PrevSeparator].Flags |= LIF_FILTERED;
ItemHiddenCount++;
}
if (CurItem.Name.empty() && PrevGroup == -1)
{
CurItem.Flags |= LIF_FILTERED;
ItemHiddenCount++;
PrevSeparator = -1;
}
else
{
PrevSeparator = static_cast<int>(index);
}
}
else
{
if(!contains_icase(remove_highlight(trim(CurItem.Name)), strFilter))
{
CurItem.Flags |= LIF_FILTERED;
ItemHiddenCount++;
if (SelectPos == static_cast<int>(index))
{
CurItem.Flags &= ~LIF_SELECTED;
SelectPos = -1;
LowerVisible = -1;
}
}
else
{
PrevGroup = static_cast<int>(index);
if (LowerVisible == -2)
{
if (item_can_have_focus(CurItem))
UpperVisible = static_cast<int>(index);
}
else if (LowerVisible == -1)
{
if (item_can_have_focus(CurItem))
LowerVisible = static_cast<int>(index);
}