forked from swiftlang/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIOHandlerCursesGUI.cpp
4365 lines (3867 loc) · 138 KB
/
IOHandlerCursesGUI.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
//===-- IOHandlerCursesGUI.cpp --------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "lldb/Core/IOHandlerCursesGUI.h"
#include "lldb/Host/Config.h"
#if LLDB_ENABLE_CURSES
#if CURSES_HAVE_NCURSES_CURSES_H
#include <ncurses/curses.h>
#include <ncurses/panel.h>
#else
#include <curses.h>
#include <panel.h>
#endif
#endif
#if defined(__APPLE__)
#include <deque>
#endif
#include <string>
#include "lldb/Core/Debugger.h"
#include "lldb/Core/StreamFile.h"
#include "lldb/Host/File.h"
#include "lldb/Utility/Predicate.h"
#include "lldb/Utility/Status.h"
#include "lldb/Utility/StreamString.h"
#include "lldb/Utility/StringList.h"
#include "lldb/lldb-forward.h"
#include "lldb/Interpreter/CommandCompletions.h"
#include "lldb/Interpreter/CommandInterpreter.h"
#if LLDB_ENABLE_CURSES
#include "lldb/Breakpoint/BreakpointLocation.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/ValueObject.h"
#include "lldb/Core/ValueObjectRegister.h"
#include "lldb/Symbol/Block.h"
#include "lldb/Symbol/Function.h"
#include "lldb/Symbol/Symbol.h"
#include "lldb/Symbol/VariableList.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/RegisterContext.h"
#include "lldb/Target/StackFrame.h"
#include "lldb/Target/StopInfo.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include "lldb/Utility/State.h"
#endif
#include "llvm/ADT/StringRef.h"
#ifdef _WIN32
#include "lldb/Host/windows/windows.h"
#endif
#include <memory>
#include <mutex>
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <locale.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <type_traits>
using namespace lldb;
using namespace lldb_private;
using llvm::None;
using llvm::Optional;
using llvm::StringRef;
// we may want curses to be disabled for some builds for instance, windows
#if LLDB_ENABLE_CURSES
#define KEY_RETURN 10
#define KEY_ESCAPE 27
namespace curses {
class Menu;
class MenuDelegate;
class Window;
class WindowDelegate;
typedef std::shared_ptr<Menu> MenuSP;
typedef std::shared_ptr<MenuDelegate> MenuDelegateSP;
typedef std::shared_ptr<Window> WindowSP;
typedef std::shared_ptr<WindowDelegate> WindowDelegateSP;
typedef std::vector<MenuSP> Menus;
typedef std::vector<WindowSP> Windows;
typedef std::vector<WindowDelegateSP> WindowDelegates;
#if 0
type summary add -s "x=${var.x}, y=${var.y}" curses::Point
type summary add -s "w=${var.width}, h=${var.height}" curses::Size
type summary add -s "${var.origin%S} ${var.size%S}" curses::Rect
#endif
struct Point {
int x;
int y;
Point(int _x = 0, int _y = 0) : x(_x), y(_y) {}
void Clear() {
x = 0;
y = 0;
}
Point &operator+=(const Point &rhs) {
x += rhs.x;
y += rhs.y;
return *this;
}
void Dump() { printf("(x=%i, y=%i)\n", x, y); }
};
bool operator==(const Point &lhs, const Point &rhs) {
return lhs.x == rhs.x && lhs.y == rhs.y;
}
bool operator!=(const Point &lhs, const Point &rhs) {
return lhs.x != rhs.x || lhs.y != rhs.y;
}
struct Size {
int width;
int height;
Size(int w = 0, int h = 0) : width(w), height(h) {}
void Clear() {
width = 0;
height = 0;
}
void Dump() { printf("(w=%i, h=%i)\n", width, height); }
};
bool operator==(const Size &lhs, const Size &rhs) {
return lhs.width == rhs.width && lhs.height == rhs.height;
}
bool operator!=(const Size &lhs, const Size &rhs) {
return lhs.width != rhs.width || lhs.height != rhs.height;
}
struct Rect {
Point origin;
Size size;
Rect() : origin(), size() {}
Rect(const Point &p, const Size &s) : origin(p), size(s) {}
void Clear() {
origin.Clear();
size.Clear();
}
void Dump() {
printf("(x=%i, y=%i), w=%i, h=%i)\n", origin.x, origin.y, size.width,
size.height);
}
void Inset(int w, int h) {
if (size.width > w * 2)
size.width -= w * 2;
origin.x += w;
if (size.height > h * 2)
size.height -= h * 2;
origin.y += h;
}
// Return a status bar rectangle which is the last line of this rectangle.
// This rectangle will be modified to not include the status bar area.
Rect MakeStatusBar() {
Rect status_bar;
if (size.height > 1) {
status_bar.origin.x = origin.x;
status_bar.origin.y = size.height;
status_bar.size.width = size.width;
status_bar.size.height = 1;
--size.height;
}
return status_bar;
}
// Return a menubar rectangle which is the first line of this rectangle. This
// rectangle will be modified to not include the menubar area.
Rect MakeMenuBar() {
Rect menubar;
if (size.height > 1) {
menubar.origin.x = origin.x;
menubar.origin.y = origin.y;
menubar.size.width = size.width;
menubar.size.height = 1;
++origin.y;
--size.height;
}
return menubar;
}
void HorizontalSplitPercentage(float top_percentage, Rect &top,
Rect &bottom) const {
float top_height = top_percentage * size.height;
HorizontalSplit(top_height, top, bottom);
}
void HorizontalSplit(int top_height, Rect &top, Rect &bottom) const {
top = *this;
if (top_height < size.height) {
top.size.height = top_height;
bottom.origin.x = origin.x;
bottom.origin.y = origin.y + top.size.height;
bottom.size.width = size.width;
bottom.size.height = size.height - top.size.height;
} else {
bottom.Clear();
}
}
void VerticalSplitPercentage(float left_percentage, Rect &left,
Rect &right) const {
float left_width = left_percentage * size.width;
VerticalSplit(left_width, left, right);
}
void VerticalSplit(int left_width, Rect &left, Rect &right) const {
left = *this;
if (left_width < size.width) {
left.size.width = left_width;
right.origin.x = origin.x + left.size.width;
right.origin.y = origin.y;
right.size.width = size.width - left.size.width;
right.size.height = size.height;
} else {
right.Clear();
}
}
};
bool operator==(const Rect &lhs, const Rect &rhs) {
return lhs.origin == rhs.origin && lhs.size == rhs.size;
}
bool operator!=(const Rect &lhs, const Rect &rhs) {
return lhs.origin != rhs.origin || lhs.size != rhs.size;
}
enum HandleCharResult {
eKeyNotHandled = 0,
eKeyHandled = 1,
eQuitApplication = 2
};
enum class MenuActionResult {
Handled,
NotHandled,
Quit // Exit all menus and quit
};
struct KeyHelp {
int ch;
const char *description;
};
// COLOR_PAIR index names
enum {
// First 16 colors are 8 black background and 8 blue background colors,
// needed by OutputColoredStringTruncated().
BlackOnBlack = 1,
RedOnBlack,
GreenOnBlack,
YellowOnBlack,
BlueOnBlack,
MagentaOnBlack,
CyanOnBlack,
WhiteOnBlack,
BlackOnBlue,
RedOnBlue,
GreenOnBlue,
YellowOnBlue,
BlueOnBlue,
MagentaOnBlue,
CyanOnBlue,
WhiteOnBlue,
// Other colors, as needed.
BlackOnWhite,
MagentaOnWhite,
LastColorPairIndex = MagentaOnWhite
};
class WindowDelegate {
public:
virtual ~WindowDelegate() = default;
virtual bool WindowDelegateDraw(Window &window, bool force) {
return false; // Drawing not handled
}
virtual HandleCharResult WindowDelegateHandleChar(Window &window, int key) {
return eKeyNotHandled;
}
virtual const char *WindowDelegateGetHelpText() { return nullptr; }
virtual KeyHelp *WindowDelegateGetKeyHelp() { return nullptr; }
};
class HelpDialogDelegate : public WindowDelegate {
public:
HelpDialogDelegate(const char *text, KeyHelp *key_help_array);
~HelpDialogDelegate() override;
bool WindowDelegateDraw(Window &window, bool force) override;
HandleCharResult WindowDelegateHandleChar(Window &window, int key) override;
size_t GetNumLines() const { return m_text.GetSize(); }
size_t GetMaxLineLength() const { return m_text.GetMaxStringLength(); }
protected:
StringList m_text;
int m_first_visible_line;
};
class Window {
public:
Window(const char *name)
: m_name(name), m_window(nullptr), m_panel(nullptr), m_parent(nullptr),
m_subwindows(), m_delegate_sp(), m_curr_active_window_idx(UINT32_MAX),
m_prev_active_window_idx(UINT32_MAX), m_delete(false),
m_needs_update(true), m_can_activate(true), m_is_subwin(false) {}
Window(const char *name, WINDOW *w, bool del = true)
: m_name(name), m_window(nullptr), m_panel(nullptr), m_parent(nullptr),
m_subwindows(), m_delegate_sp(), m_curr_active_window_idx(UINT32_MAX),
m_prev_active_window_idx(UINT32_MAX), m_delete(del),
m_needs_update(true), m_can_activate(true), m_is_subwin(false) {
if (w)
Reset(w);
}
Window(const char *name, const Rect &bounds)
: m_name(name), m_window(nullptr), m_parent(nullptr), m_subwindows(),
m_delegate_sp(), m_curr_active_window_idx(UINT32_MAX),
m_prev_active_window_idx(UINT32_MAX), m_delete(true),
m_needs_update(true), m_can_activate(true), m_is_subwin(false) {
Reset(::newwin(bounds.size.height, bounds.size.width, bounds.origin.y,
bounds.origin.y));
}
virtual ~Window() {
RemoveSubWindows();
Reset();
}
void Reset(WINDOW *w = nullptr, bool del = true) {
if (m_window == w)
return;
if (m_panel) {
::del_panel(m_panel);
m_panel = nullptr;
}
if (m_window && m_delete) {
::delwin(m_window);
m_window = nullptr;
m_delete = false;
}
if (w) {
m_window = w;
m_panel = ::new_panel(m_window);
m_delete = del;
}
}
void AttributeOn(attr_t attr) { ::wattron(m_window, attr); }
void AttributeOff(attr_t attr) { ::wattroff(m_window, attr); }
void Box(chtype v_char = ACS_VLINE, chtype h_char = ACS_HLINE) {
::box(m_window, v_char, h_char);
}
void Clear() { ::wclear(m_window); }
void Erase() { ::werase(m_window); }
Rect GetBounds() const {
return Rect(GetParentOrigin(), GetSize());
} // Get the rectangle in our parent window
int GetChar() { return ::wgetch(m_window); }
int GetCursorX() const { return getcurx(m_window); }
int GetCursorY() const { return getcury(m_window); }
Rect GetFrame() const {
return Rect(Point(), GetSize());
} // Get our rectangle in our own coordinate system
Point GetParentOrigin() const { return Point(GetParentX(), GetParentY()); }
Size GetSize() const { return Size(GetWidth(), GetHeight()); }
int GetParentX() const { return getparx(m_window); }
int GetParentY() const { return getpary(m_window); }
int GetMaxX() const { return getmaxx(m_window); }
int GetMaxY() const { return getmaxy(m_window); }
int GetWidth() const { return GetMaxX(); }
int GetHeight() const { return GetMaxY(); }
void MoveCursor(int x, int y) { ::wmove(m_window, y, x); }
void MoveWindow(int x, int y) { MoveWindow(Point(x, y)); }
void Resize(int w, int h) { ::wresize(m_window, h, w); }
void Resize(const Size &size) {
::wresize(m_window, size.height, size.width);
}
void PutChar(int ch) { ::waddch(m_window, ch); }
void PutCString(const char *s, int len = -1) { ::waddnstr(m_window, s, len); }
void SetBackground(int color_pair_idx) {
::wbkgd(m_window, COLOR_PAIR(color_pair_idx));
}
void PutCStringTruncated(int right_pad, const char *s, int len = -1) {
int bytes_left = GetWidth() - GetCursorX();
if (bytes_left > right_pad) {
bytes_left -= right_pad;
::waddnstr(m_window, s, len < 0 ? bytes_left : std::min(bytes_left, len));
}
}
void MoveWindow(const Point &origin) {
const bool moving_window = origin != GetParentOrigin();
if (m_is_subwin && moving_window) {
// Can't move subwindows, must delete and re-create
Size size = GetSize();
Reset(::subwin(m_parent->m_window, size.height, size.width, origin.y,
origin.x),
true);
} else {
::mvwin(m_window, origin.y, origin.x);
}
}
void SetBounds(const Rect &bounds) {
const bool moving_window = bounds.origin != GetParentOrigin();
if (m_is_subwin && moving_window) {
// Can't move subwindows, must delete and re-create
Reset(::subwin(m_parent->m_window, bounds.size.height, bounds.size.width,
bounds.origin.y, bounds.origin.x),
true);
} else {
if (moving_window)
MoveWindow(bounds.origin);
Resize(bounds.size);
}
}
void Printf(const char *format, ...) __attribute__((format(printf, 2, 3))) {
va_list args;
va_start(args, format);
vwprintw(m_window, format, args);
va_end(args);
}
void PrintfTruncated(int right_pad, const char *format, ...)
__attribute__((format(printf, 3, 4))) {
va_list args;
va_start(args, format);
StreamString strm;
strm.PrintfVarArg(format, args);
va_end(args);
PutCStringTruncated(right_pad, strm.GetData());
}
size_t LimitLengthToRestOfLine(size_t length) const {
return std::min<size_t>(length, std::max(0, GetWidth() - GetCursorX() - 1));
}
// Curses doesn't allow direct output of color escape sequences, but that's
// how we get source lines from the Highligher class. Read the line and
// convert color escape sequences to curses color attributes. Use
// first_skip_count to skip leading visible characters. Returns false if all
// visible characters were skipped due to first_skip_count.
bool OutputColoredStringTruncated(int right_pad, StringRef string,
size_t skip_first_count,
bool use_blue_background) {
attr_t saved_attr;
short saved_pair;
bool result = false;
wattr_get(m_window, &saved_attr, &saved_pair, nullptr);
if (use_blue_background)
::wattron(m_window, COLOR_PAIR(WhiteOnBlue));
while (!string.empty()) {
size_t esc_pos = string.find('\x1b');
if (esc_pos == StringRef::npos) {
string = string.substr(skip_first_count);
if (!string.empty()) {
PutCStringTruncated(right_pad, string.data(), string.size());
result = true;
}
break;
}
if (esc_pos > 0) {
if (skip_first_count > 0) {
int skip = std::min(esc_pos, skip_first_count);
string = string.substr(skip);
skip_first_count -= skip;
esc_pos -= skip;
}
if (esc_pos > 0) {
PutCStringTruncated(right_pad, string.data(), esc_pos);
result = true;
string = string.drop_front(esc_pos);
}
}
bool consumed = string.consume_front("\x1b");
assert(consumed);
UNUSED_IF_ASSERT_DISABLED(consumed);
// This is written to match our Highlighter classes, which seem to
// generate only foreground color escape sequences. If necessary, this
// will need to be extended.
if (!string.consume_front("[")) {
llvm::errs() << "Missing '[' in color escape sequence.\n";
continue;
}
// Only 8 basic foreground colors and reset, our Highlighter doesn't use
// anything else.
int value;
if (!!string.consumeInteger(10, value) || // Returns false on success.
!(value == 0 || (value >= 30 && value <= 37))) {
llvm::errs() << "No valid color code in color escape sequence.\n";
continue;
}
if (!string.consume_front("m")) {
llvm::errs() << "Missing 'm' in color escape sequence.\n";
continue;
}
if (value == 0) { // Reset.
wattr_set(m_window, saved_attr, saved_pair, nullptr);
if (use_blue_background)
::wattron(m_window, COLOR_PAIR(WhiteOnBlue));
} else {
// Mapped directly to first 16 color pairs (black/blue background).
::wattron(m_window,
COLOR_PAIR(value - 30 + 1 + (use_blue_background ? 8 : 0)));
}
}
wattr_set(m_window, saved_attr, saved_pair, nullptr);
return result;
}
void Touch() {
::touchwin(m_window);
if (m_parent)
m_parent->Touch();
}
WindowSP CreateSubWindow(const char *name, const Rect &bounds,
bool make_active) {
auto get_window = [this, &bounds]() {
return m_window
? ::subwin(m_window, bounds.size.height, bounds.size.width,
bounds.origin.y, bounds.origin.x)
: ::newwin(bounds.size.height, bounds.size.width,
bounds.origin.y, bounds.origin.x);
};
WindowSP subwindow_sp = std::make_shared<Window>(name, get_window(), true);
subwindow_sp->m_is_subwin = subwindow_sp.operator bool();
subwindow_sp->m_parent = this;
if (make_active) {
m_prev_active_window_idx = m_curr_active_window_idx;
m_curr_active_window_idx = m_subwindows.size();
}
m_subwindows.push_back(subwindow_sp);
::top_panel(subwindow_sp->m_panel);
m_needs_update = true;
return subwindow_sp;
}
bool RemoveSubWindow(Window *window) {
Windows::iterator pos, end = m_subwindows.end();
size_t i = 0;
for (pos = m_subwindows.begin(); pos != end; ++pos, ++i) {
if ((*pos).get() == window) {
if (m_prev_active_window_idx == i)
m_prev_active_window_idx = UINT32_MAX;
else if (m_prev_active_window_idx != UINT32_MAX &&
m_prev_active_window_idx > i)
--m_prev_active_window_idx;
if (m_curr_active_window_idx == i)
m_curr_active_window_idx = UINT32_MAX;
else if (m_curr_active_window_idx != UINT32_MAX &&
m_curr_active_window_idx > i)
--m_curr_active_window_idx;
window->Erase();
m_subwindows.erase(pos);
m_needs_update = true;
if (m_parent)
m_parent->Touch();
else
::touchwin(stdscr);
return true;
}
}
return false;
}
WindowSP FindSubWindow(const char *name) {
Windows::iterator pos, end = m_subwindows.end();
size_t i = 0;
for (pos = m_subwindows.begin(); pos != end; ++pos, ++i) {
if ((*pos)->m_name == name)
return *pos;
}
return WindowSP();
}
void RemoveSubWindows() {
m_curr_active_window_idx = UINT32_MAX;
m_prev_active_window_idx = UINT32_MAX;
for (Windows::iterator pos = m_subwindows.begin();
pos != m_subwindows.end(); pos = m_subwindows.erase(pos)) {
(*pos)->Erase();
}
if (m_parent)
m_parent->Touch();
else
::touchwin(stdscr);
}
WINDOW *get() { return m_window; }
operator WINDOW *() { return m_window; }
// Window drawing utilities
void DrawTitleBox(const char *title, const char *bottom_message = nullptr) {
attr_t attr = 0;
if (IsActive())
attr = A_BOLD | COLOR_PAIR(BlackOnWhite);
else
attr = 0;
if (attr)
AttributeOn(attr);
Box();
MoveCursor(3, 0);
if (title && title[0]) {
PutChar('<');
PutCString(title);
PutChar('>');
}
if (bottom_message && bottom_message[0]) {
int bottom_message_length = strlen(bottom_message);
int x = GetWidth() - 3 - (bottom_message_length + 2);
if (x > 0) {
MoveCursor(x, GetHeight() - 1);
PutChar('[');
PutCString(bottom_message);
PutChar(']');
} else {
MoveCursor(1, GetHeight() - 1);
PutChar('[');
PutCStringTruncated(1, bottom_message);
}
}
if (attr)
AttributeOff(attr);
}
virtual void Draw(bool force) {
if (m_delegate_sp && m_delegate_sp->WindowDelegateDraw(*this, force))
return;
for (auto &subwindow_sp : m_subwindows)
subwindow_sp->Draw(force);
}
bool CreateHelpSubwindow() {
if (m_delegate_sp) {
const char *text = m_delegate_sp->WindowDelegateGetHelpText();
KeyHelp *key_help = m_delegate_sp->WindowDelegateGetKeyHelp();
if ((text && text[0]) || key_help) {
std::unique_ptr<HelpDialogDelegate> help_delegate_up(
new HelpDialogDelegate(text, key_help));
const size_t num_lines = help_delegate_up->GetNumLines();
const size_t max_length = help_delegate_up->GetMaxLineLength();
Rect bounds = GetBounds();
bounds.Inset(1, 1);
if (max_length + 4 < static_cast<size_t>(bounds.size.width)) {
bounds.origin.x += (bounds.size.width - max_length + 4) / 2;
bounds.size.width = max_length + 4;
} else {
if (bounds.size.width > 100) {
const int inset_w = bounds.size.width / 4;
bounds.origin.x += inset_w;
bounds.size.width -= 2 * inset_w;
}
}
if (num_lines + 2 < static_cast<size_t>(bounds.size.height)) {
bounds.origin.y += (bounds.size.height - num_lines + 2) / 2;
bounds.size.height = num_lines + 2;
} else {
if (bounds.size.height > 100) {
const int inset_h = bounds.size.height / 4;
bounds.origin.y += inset_h;
bounds.size.height -= 2 * inset_h;
}
}
WindowSP help_window_sp;
Window *parent_window = GetParent();
if (parent_window)
help_window_sp = parent_window->CreateSubWindow("Help", bounds, true);
else
help_window_sp = CreateSubWindow("Help", bounds, true);
help_window_sp->SetDelegate(
WindowDelegateSP(help_delegate_up.release()));
return true;
}
}
return false;
}
virtual HandleCharResult HandleChar(int key) {
// Always check the active window first
HandleCharResult result = eKeyNotHandled;
WindowSP active_window_sp = GetActiveWindow();
if (active_window_sp) {
result = active_window_sp->HandleChar(key);
if (result != eKeyNotHandled)
return result;
}
if (m_delegate_sp) {
result = m_delegate_sp->WindowDelegateHandleChar(*this, key);
if (result != eKeyNotHandled)
return result;
}
// Then check for any windows that want any keys that weren't handled. This
// is typically only for a menubar. Make a copy of the subwindows in case
// any HandleChar() functions muck with the subwindows. If we don't do
// this, we can crash when iterating over the subwindows.
Windows subwindows(m_subwindows);
for (auto subwindow_sp : subwindows) {
if (!subwindow_sp->m_can_activate) {
HandleCharResult result = subwindow_sp->HandleChar(key);
if (result != eKeyNotHandled)
return result;
}
}
return eKeyNotHandled;
}
WindowSP GetActiveWindow() {
if (!m_subwindows.empty()) {
if (m_curr_active_window_idx >= m_subwindows.size()) {
if (m_prev_active_window_idx < m_subwindows.size()) {
m_curr_active_window_idx = m_prev_active_window_idx;
m_prev_active_window_idx = UINT32_MAX;
} else if (IsActive()) {
m_prev_active_window_idx = UINT32_MAX;
m_curr_active_window_idx = UINT32_MAX;
// Find first window that wants to be active if this window is active
const size_t num_subwindows = m_subwindows.size();
for (size_t i = 0; i < num_subwindows; ++i) {
if (m_subwindows[i]->GetCanBeActive()) {
m_curr_active_window_idx = i;
break;
}
}
}
}
if (m_curr_active_window_idx < m_subwindows.size())
return m_subwindows[m_curr_active_window_idx];
}
return WindowSP();
}
bool GetCanBeActive() const { return m_can_activate; }
void SetCanBeActive(bool b) { m_can_activate = b; }
void SetDelegate(const WindowDelegateSP &delegate_sp) {
m_delegate_sp = delegate_sp;
}
Window *GetParent() const { return m_parent; }
bool IsActive() const {
if (m_parent)
return m_parent->GetActiveWindow().get() == this;
else
return true; // Top level window is always active
}
void SelectNextWindowAsActive() {
// Move active focus to next window
const int num_subwindows = m_subwindows.size();
int start_idx = 0;
if (m_curr_active_window_idx != UINT32_MAX) {
m_prev_active_window_idx = m_curr_active_window_idx;
start_idx = m_curr_active_window_idx + 1;
}
for (int idx = start_idx; idx < num_subwindows; ++idx) {
if (m_subwindows[idx]->GetCanBeActive()) {
m_curr_active_window_idx = idx;
return;
}
}
for (int idx = 0; idx < start_idx; ++idx) {
if (m_subwindows[idx]->GetCanBeActive()) {
m_curr_active_window_idx = idx;
break;
}
}
}
void SelectPreviousWindowAsActive() {
// Move active focus to previous window
const int num_subwindows = m_subwindows.size();
int start_idx = num_subwindows - 1;
if (m_curr_active_window_idx != UINT32_MAX) {
m_prev_active_window_idx = m_curr_active_window_idx;
start_idx = m_curr_active_window_idx - 1;
}
for (int idx = start_idx; idx >= 0; --idx) {
if (m_subwindows[idx]->GetCanBeActive()) {
m_curr_active_window_idx = idx;
return;
}
}
for (int idx = num_subwindows - 1; idx > start_idx; --idx) {
if (m_subwindows[idx]->GetCanBeActive()) {
m_curr_active_window_idx = idx;
break;
}
}
}
const char *GetName() const { return m_name.c_str(); }
protected:
std::string m_name;
WINDOW *m_window;
PANEL *m_panel;
Window *m_parent;
Windows m_subwindows;
WindowDelegateSP m_delegate_sp;
uint32_t m_curr_active_window_idx;
uint32_t m_prev_active_window_idx;
bool m_delete;
bool m_needs_update;
bool m_can_activate;
bool m_is_subwin;
private:
Window(const Window &) = delete;
const Window &operator=(const Window &) = delete;
};
class MenuDelegate {
public:
virtual ~MenuDelegate() = default;
virtual MenuActionResult MenuDelegateAction(Menu &menu) = 0;
};
class Menu : public WindowDelegate {
public:
enum class Type { Invalid, Bar, Item, Separator };
// Menubar or separator constructor
Menu(Type type);
// Menuitem constructor
Menu(const char *name, const char *key_name, int key_value,
uint64_t identifier);
~Menu() override = default;
const MenuDelegateSP &GetDelegate() const { return m_delegate_sp; }
void SetDelegate(const MenuDelegateSP &delegate_sp) {
m_delegate_sp = delegate_sp;
}
void RecalculateNameLengths();
void AddSubmenu(const MenuSP &menu_sp);
int DrawAndRunMenu(Window &window);
void DrawMenuTitle(Window &window, bool highlight);
bool WindowDelegateDraw(Window &window, bool force) override;
HandleCharResult WindowDelegateHandleChar(Window &window, int key) override;
MenuActionResult ActionPrivate(Menu &menu) {
MenuActionResult result = MenuActionResult::NotHandled;
if (m_delegate_sp) {
result = m_delegate_sp->MenuDelegateAction(menu);
if (result != MenuActionResult::NotHandled)
return result;
} else if (m_parent) {
result = m_parent->ActionPrivate(menu);
if (result != MenuActionResult::NotHandled)
return result;
}
return m_canned_result;
}
MenuActionResult Action() {
// Call the recursive action so it can try to handle it with the menu
// delegate, and if not, try our parent menu
return ActionPrivate(*this);
}
void SetCannedResult(MenuActionResult result) { m_canned_result = result; }
Menus &GetSubmenus() { return m_submenus; }
const Menus &GetSubmenus() const { return m_submenus; }
int GetSelectedSubmenuIndex() const { return m_selected; }
void SetSelectedSubmenuIndex(int idx) { m_selected = idx; }
Type GetType() const { return m_type; }
int GetStartingColumn() const { return m_start_col; }
void SetStartingColumn(int col) { m_start_col = col; }
int GetKeyValue() const { return m_key_value; }
std::string &GetName() { return m_name; }
int GetDrawWidth() const {
return m_max_submenu_name_length + m_max_submenu_key_name_length + 8;
}
uint64_t GetIdentifier() const { return m_identifier; }
void SetIdentifier(uint64_t identifier) { m_identifier = identifier; }
protected:
std::string m_name;
std::string m_key_name;
uint64_t m_identifier;
Type m_type;
int m_key_value;
int m_start_col;
int m_max_submenu_name_length;
int m_max_submenu_key_name_length;
int m_selected;
Menu *m_parent;
Menus m_submenus;
WindowSP m_menu_window_sp;
MenuActionResult m_canned_result;
MenuDelegateSP m_delegate_sp;
};
// Menubar or separator constructor
Menu::Menu(Type type)
: m_name(), m_key_name(), m_identifier(0), m_type(type), m_key_value(0),
m_start_col(0), m_max_submenu_name_length(0),
m_max_submenu_key_name_length(0), m_selected(0), m_parent(nullptr),
m_submenus(), m_canned_result(MenuActionResult::NotHandled),
m_delegate_sp() {}
// Menuitem constructor
Menu::Menu(const char *name, const char *key_name, int key_value,
uint64_t identifier)
: m_name(), m_key_name(), m_identifier(identifier), m_type(Type::Invalid),
m_key_value(key_value), m_start_col(0), m_max_submenu_name_length(0),
m_max_submenu_key_name_length(0), m_selected(0), m_parent(nullptr),
m_submenus(), m_canned_result(MenuActionResult::NotHandled),
m_delegate_sp() {
if (name && name[0]) {
m_name = name;
m_type = Type::Item;
if (key_name && key_name[0])
m_key_name = key_name;
} else {
m_type = Type::Separator;
}
}
void Menu::RecalculateNameLengths() {