-
Notifications
You must be signed in to change notification settings - Fork 6
/
GUI.cpp
executable file
·2684 lines (2332 loc) · 78.3 KB
/
GUI.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
//
// GUI.cpp - widget library
//
// Copyright (c) 2013-2016 Arthur Danskin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "StdAfx.h"
#include "ZipFile.h"
#define DEF_COLOR(X, Y) DEFINE_CVAR(uint, X, Y)
#include "GUI.h"
#undef DEF_COLOR
#include "Shaders.h"
#if HAS_SOUND
#include "Sound.h"
#define PLAY_BUTTON_HOVER() globals.sound->OnButtonHover()
#define PLAY_BUTTON_PRESS() globals.sound->OnButtonPress()
#else
#define PLAY_BUTTON_HOVER()
#define PLAY_BUTTON_PRESS()
#endif
#define HAS_KEYS 1
#if HAS_KEYS
#include "Keys.h"
#define GET_MENU_TRANSLATION(E) KeyBindings::instance().getMenuTranslation(E)
#else
struct KeyBinding;
#define GET_MENU_TRANSLATION(E) int2()
#endif
static DEFINE_CVAR(float, kScrollbarWidth, 25.f);
DEFINE_CVAR(float2, kButtonPad, float2(4.f));
bool ButtonBase::HandleEvent(const Event* event, bool* isActivate, bool* isPress)
{
const float2 sz = 0.5f*size;
bool handled = false;
if (event->type == Event::KEY_DOWN || event->type == Event::KEY_UP)
{
if (active && event->key && (event->key == keys[0] ||
event->key == keys[1] ||
event->key == keys[2] ||
event->key == keys[3]))
{
bool activate = !pressed && (event->type == Event::KEY_DOWN);
handled = true;
pressed = activate;
if (isActivate)
*isActivate = activate;
}
}
else
{
if (event->isMouse())
hovered = intersectPointRectangle(event->pos, position, sz);
handled = visible && hovered && ((event->type == Event::MOUSE_DOWN) ||
(event->type == Event::MOUSE_UP));
// && (event->key == 0);
const bool wasPressed = pressed;
if (active && handled)
{
if (wasPressed && (event->type == Event::MOUSE_UP)) {
if (isActivate)
*isActivate = true;
pressed = false;
} else if (!wasPressed && event->type == Event::MOUSE_DOWN) {
if (isPress)
*isPress = true;
pressed = true;
}
}
else if (event->type == Event::MOUSE_MOVED || event->type == Event::LOST_FOCUS)
{
pressed = false;
}
}
return handled;
}
bool ButtonBase::renderTooltip(const ShaderState &ss, const View& view, uint color, bool force) const
{
if (tooltip.empty() || !visible || (!force && !hovered) || alpha < epsilon)
return false;
TextBox dat;
dat.tSize = 11.f;
dat.alpha = alpha;
dat.fgColor = color;
dat.bgColor = kGUIToolBg;
dat.font = kMonoFont;
dat.view = &view;
dat.rad = size / 2.f;
dat.Draw(ss, position, tooltip);
return true;
}
void ButtonBase::renderSelected(const ShaderState &ss, uint bgcolor, uint linecolor, float alpha) const
{
ShaderState s = ss;
const float2 sz = 0.5f * size;
const float2 p = position + float2(-sz.x - sz.y, 0);
s.color32(bgcolor, alpha);
ShaderUColor::instance().DrawTri(s, p + float2(0, sz.y), p + float2(sz.y / 2, 0), p + float2(0, -sz.y));
s.translateZ(0.1f);
s.color32(linecolor, alpha);
ShaderUColor::instance().DrawLineTri(s, p + float2(0, sz.y), p + float2(sz.y / 2, 0), p + float2(0, -sz.y));
}
void ButtonBase::render(const ShaderState &ss, bool selected)
{
if (!visible)
return;
{
DMesh::Handle h(theDMesh());
renderButton(h.mp, selected);
h.Draw(ss);
}
renderContents(ss);
}
float2 Button::getTextSize() const
{
const GLText* tx = GLText::get(textFont, textSize, text);
float2 sz = tx->getSize();
if (subtext.size())
{
const GLText* stx = GLText::get(textFont, subtextSize, text);
sz.x = max(sz.x, stx->getSize().x);
sz.y += stx->getSize().y;
}
return sz + padding;
}
void Button::renderButton(DMesh& mesh, bool selected)
{
if (!visible)
return;
if (text.size() && !(style&S_FIXED))
{
const float2 sz = getTextSize();
size.y = sz.y;
size.x = max(max(size.x, sz.x), size.y * (float)kGoldenRatio);
}
mesh.translateZ(0.1f);
position = floor(position) + f2(0.5f);
size = 2.f * round(size * 0.5f);
const uint bg = getBGColor();
const uint fg = getFGColor(selected);
if (style&S_BOX) {
PushRect(&mesh.tri, &mesh.line, position, 0.5f * size, bg, fg, alpha);
} else if (style&S_HEX) {
PushHex(&mesh.tri, &mesh.line, position, 0.5f * size, bg, fg, alpha);
} else if (style&S_CORNERS) {
PushButton(&mesh.tri, &mesh.line, position, 0.5f * size, bg, fg, alpha);
}
mesh.translateZ(-0.1f);
}
void Button::renderContents(const ShaderState &ss)
{
if (!visible)
return;
const uint tcolor = MultAlphaAXXX((!active) ? inactiveTextColor : textColor, alpha);
const uint stc = MultAlphaAXXX(subtextColor, alpha);
const float2 pos = position + justY(subtext.size() ? size.y * (0.5f - (textSize / (subtextSize + textSize))) : 0.f);
const GLText::Align align = subtext.size() ? GLText::CENTERED : GLText::MID_CENTERED;
if (style&S_FIXED)
{
const float w = size.x - 2.f * padding.x;
renderButtonText(ss, pos, w, align, textFont, tcolor, &dynamicTextSize, 6.f, textSize, text);
renderButtonText(ss, pos, w, GLText::DOWN_CENTERED, textFont, stc, &dynamicSubtextSize, 6.f, subtextSize, subtext);
}
else
{
GLText::Put(ss, pos, align, textFont, tcolor, textSize, text);
if (subtext.size())
GLText::Put(ss, pos, GLText::DOWN_CENTERED, textFont, stc, subtextSize, subtext);
}
}
bool URLButton::HandleEvent(const Event* event, bool *isActivate, bool *isPress)
{
bool activate = false;
if (!Button::HandleEvent(event, &activate))
return false;
if (activate) {
if (str_startswith(url, "http"))
OL_OpenWebBrowser(url.c_str());
else
OL_OpenFolder(url.c_str());
if (isActivate)
*isActivate = activate;
}
return true;
}
void TextInputBase::setText(const char* text)
{
std::lock_guard<std::recursive_mutex> l(mutex);
lines.clear();
if (text)
pushText(text);
if (lines.empty())
lines.push_back(string());
cursor = int2(lines.back().size(), lines.size()-1);
}
void TextInputBase::setLines(const vector<string> &lns)
{
std::lock_guard<std::recursive_mutex> l(mutex);
lines.clear();
vec_extend(lines, lns);
cursor = int2(lines[lines.size()-1].size(), lines.size()-1);
}
static void cursor_move_utf8(const string& line, int2& cursor, int adjust)
{
cursor.x += adjust;
while (0 <= cursor.x && cursor.x < line.size() && utf8_iscont(line[cursor.x]))
cursor.x += adjust;
}
static bool forward_char(int2& cursor, deque<string> &lines, int offset)
{
if (offset == -1)
{
if (cursor.x == 0) {
if (cursor.y <= 0)
return false;
cursor.y--;
cursor.x = (int)lines[cursor.y].size();
} else {
cursor_move_utf8(lines[cursor.y], cursor, -1);
}
}
else if (offset == 1)
{
if (cursor.x == lines[cursor.y].size()) {
if (cursor.y >= lines.size()-1)
return false;
cursor.y++;
cursor.x = 0;
} else
cursor_move_utf8(lines[cursor.y], cursor, +1);
}
return true;
}
static void forward_when(int2& cursor, deque<string> &lines, int offset, int (*pred)(int))
{
forward_char(cursor, lines, offset);
while (cursor.y < lines.size() &&
(cursor.x >= lines[cursor.y].size() ||
pred(lines[cursor.y][cursor.x])) &&
forward_char(cursor, lines, offset));
}
static bool delete_char(int2& cursor, deque<string> &lines)
{
if (0 > cursor.y || cursor.y >= lines.size()) {
return '\0';
} else if (cursor.x > 0) {
string &line = lines[cursor.y];
cursor_move_utf8(line, cursor, -1);
line = utf8_erase(line, cursor.x, 1);
return true;
} else if (cursor.y > 0) {
int nx = lines[cursor.y-1].size();
lines[cursor.y - 1].append(lines[cursor.y]);
lines.erase(lines.begin() + cursor.y);
cursor.y--;
cursor.x = nx;
return true;
} else {
return false;
}
}
static void delete_region(int2& cursor, deque<string> &lines, int2 mark)
{
if (mark.y < cursor.y || (mark.y == cursor.y && mark.x < cursor.x))
swap(cursor, mark);
while (mark != cursor && delete_char(mark, lines));
}
bool TextInputBase::HandleEvent(const Event* event, bool *textChanged)
{
hovered = intersectPointRectangle(KeyState::instance().cursorPosScreen, position, 0.5f * size);
active = forceActive || hovered;
if (active && event->type == Event::SCROLL_WHEEL)
{
startChars.y += ceil_int(-event->vel.y);
startChars.y = clamp(startChars.y, 0, max(0, (int)lines.size() - sizeChars.y));
return true;
}
else if (active && event->type == Event::KEY_DOWN)
{
if (event->key == NSPageUpFunctionKey)
{
startChars.y -= sizeChars.y;
startChars.y = clamp(startChars.y, 0, max(0, (int)lines.size() - sizeChars.y));
return true;
}
else if (event->key == NSPageDownFunctionKey)
{
startChars.y += sizeChars.y;
startChars.y = clamp(startChars.y, 0, max(0, (int)lines.size() - sizeChars.y));
return true;
}
}
if (locked)
return false;
if (textChanged)
*textChanged = false;
if (active && event->type == Event::KEY_DOWN)
{
std::lock_guard<std::recursive_mutex> l(mutex);
cursor.y = clamp(cursor.y, 0, lines.size()-1);
cursor.x = clamp(cursor.x, 0, lines[cursor.y].size());
switch (KeyState::instance().keyMods() | event->key)
{
case MOD_CTRL|'b': forward_char(cursor, lines, -1); break;
case MOD_CTRL|'f': forward_char(cursor, lines, +1); break;
case MOD_CTRL|'p': cursor.y--; break;
case MOD_CTRL|'n': cursor.y++; break;
case MOD_CTRL|'a': cursor.x = 0; break;
case MOD_CTRL|'e': cursor.x = lines[cursor.y].size(); break;
case MOD_CTRL|'k': {
string &line = lines[cursor.y];
OL_WriteClipboard(line.substr(cursor.x).c_str());
if (cursor.x == line.size() && cursor.y+1 < lines.size()) {
line.append(lines[cursor.y+1]);
lines.erase(lines.begin() + cursor.y + 1);
} else
line.erase(cursor.x);
break;
}
case MOD_CTRL|'v':
case MOD_CTRL|'y':
insertText(OL_ReadClipboard());
if (textChanged)
*textChanged = true;
break;
case MOD_ALT|NSRightArrowFunctionKey:
case MOD_ALT|'f': forward_when(cursor, lines, +1, isalnum); break;
case MOD_ALT|NSLeftArrowFunctionKey:
case MOD_ALT|'b': forward_when(cursor, lines, -1, isalnum); break;
case MOD_ALT|NSBackspaceCharacter: {
const int2 scursor = cursor;
forward_when(cursor, lines, -1, isalnum);
delete_region(cursor, lines, scursor);
if (textChanged)
*textChanged = true;
break;
}
case MOD_ALT|'d': {
const int2 scursor = cursor;
forward_when(cursor, lines, 1, isalnum);
delete_region(cursor, lines, scursor);
if (textChanged)
*textChanged = true;
break;
}
case MOD_ALT|'m':
cursor.x = 0;
forward_when(cursor, lines, +1, isspace);
break;
case NSLeftArrowFunctionKey: forward_char(cursor, lines, -1); break;
case NSRightArrowFunctionKey: forward_char(cursor, lines, +1); break;
case NSUpArrowFunctionKey: cursor.y = max(0, cursor.y-1); break;
case NSDownArrowFunctionKey: cursor.y = min((int)lines.size()-1, cursor.y+1); break;
case NSHomeFunctionKey: cursor.x = 0; break;
case NSEndFunctionKey: cursor.x = lines[cursor.y].size(); break;
case MOD_CTRL|'d':
case NSDeleteFunctionKey:
if (!forward_char(cursor, lines, +1))
break;
// fallthrough!
case NSBackspaceCharacter:
delete_char(cursor, lines);
if (textChanged)
*textChanged = true;
break;
case '\r':
{
if (fixedHeight && lines.size() >= sizeChars.y)
return false;
string s = utf8_substr(lines[cursor.y], cursor.x);
lines[cursor.y] = utf8_erase(lines[cursor.y], cursor.x);
lines.insert(lines.begin() + cursor.y + 1, s);
if (textChanged)
*textChanged = true;
cursor.y++;
cursor.x = 0;
break;
}
default:
{
string str = event->toUTF8();
if (str.empty())
return false;
ASSERT(cursor.x == utf8_advance(lines[cursor.y], cursor.x));
lines[cursor.y].insert(cursor.x, str);
cursor.x += str.size();
if (textChanged)
*textChanged = true;
break;
}
}
if (lines.size() == 0)
lines.push_back("");
if (cursor.y >= lines.size()) {
cursor.x = lines.back().size();
cursor.y = lines.size()-1;
}
cursor.y = clamp(cursor.y, 0, (int)lines.size()-1);
cursor.x = clamp(cursor.x, 0, lines[cursor.y].size());
scrollForInput();
return true;
}
return false;
}
void TextInputBase::popText(int chars)
{
std::lock_guard<std::recursive_mutex> l(mutex);
while (chars && lines.size())
{
string &str = lines.back();
int remove = min(chars, (int) str.size());
str.resize(str.size() - remove);
chars -= remove;
if (str.size() == 0)
lines.pop_back();
}
}
void TextInputBase::pushText(string txt, int linesback)
{
if (wrapText)
txt = str_word_wrap(txt, sizeChars.x);
vector<string> nlines = str_split('\n', txt);
std::lock_guard<std::recursive_mutex> l(mutex);
const int pt = lines.size() - linesback;
lines.insert(lines.end() - min(linesback, (int)lines.size()), nlines.begin(), nlines.end());
if (cursor.y >= pt)
cursor.y += nlines.size();
// cursor.x = lines[cursor.y].size();
scrollForInput();
}
void TextInputBase::insertText(const char *txt)
{
if (!txt)
return;
vector<string> nlines = str_split('\n', txt);
if (nlines.size() == 0)
return;
std::lock_guard<std::recursive_mutex> l(mutex);
lines[cursor.y].insert(cursor.x, nlines[0]);
cursor.x += nlines[0].size();
lines.insert(lines.begin() + cursor.y + 1, nlines.begin() + 1, nlines.end());
cursor.y += nlines.size()-1;
scrollForInput();
}
float2 TextInputBase::getCharSize() const
{
float2 size = FontStats::get(kMonoFont, textSize).charMaxSize;
return size;
}
void TextInputBase::render(const ShaderState &s_)
{
std::lock_guard<std::recursive_mutex> l(mutex);
ShaderState s = s_;
startChars.x = 0;
const int2 start = startChars;
const int drawLines = min((int)lines.size() - start.y, sizeChars.y);
if (!fixedWidth)
{
float longestPointWidth = 0.f;
int longestChars = 0;
for (int i=start.y; i<(start.y + drawLines); i++)
{
const GLText* tx = GLText::get(kMonoFont, textSize, lines[i]);
if (tx->getSize().x > longestPointWidth) {
longestPointWidth = tx->getSize().x;
longestChars = lines[i].size();
}
}
sizeChars.x = max(sizeChars.x, (int)longestChars + 1);
if (longestChars) {
const float mwidth = max(longestPointWidth, sizeChars.x * (longestPointWidth / longestChars));
size.x = max(size.x, kButtonPad.x + mwidth);
}
}
const float charHeight = getCharSize().y;
size.y = charHeight * sizeChars.y + kPadDist;
const float2 sz = 0.5f * size;
{
DMesh::Handle h(theDMesh());
h.mp.tri.color32(active ? activeBGColor : defaultBGColor, alpha);
if (h.mp.tri.cur().color&ALPHA_OPAQUE)
h.mp.tri.PushRect(position, sz);
h.mp.line.color32(active ? activeLineColor : defaultLineColor, alpha);
if (h.mp.line.cur().color&ALPHA_OPAQUE)
h.mp.line.PushRect(position, sz);
if (lines.size() > sizeChars.y && defaultLineColor)
{
scrollbar.size = float2(kScrollbarWidth, size.y - kButtonPad.y);
scrollbar.position = position + justX(size/2.f) - justX(scrollbar.size.x/2.f + kButtonPad.x);
scrollbar.alpha = alpha;
scrollbar.first = startChars.y;
scrollbar.sfirst = scrollbar.first;
scrollbar.visible = sizeChars.y;
scrollbar.total = lines.size();
scrollbar.defaultBGColor = defaultBGColor;
scrollbar.hoveredFGColor = activeLineColor;
scrollbar.defaultFGColor = defaultLineColor;
scrollbar.render(h.mp);
}
h.Draw(s);
}
s.translate(position);
s.translate(float2(-sz.x + kPadDist, sz.y - charHeight - kPadDist));
s.color32(textColor, alpha);
const int2 curs = cursor;
for (int i=start.y; i<(start.y + drawLines); i++)
{
// const string txt = lines[i].substr(start,
// min(lines[i].size(), start.x + sizeChars.x));
const GLText* tx = GLText::get(kMonoFont, textSize, lines[i]);
if (lines[i].size())
{
tx->render(&s);
}
// draw cursor
if (active && !locked && curs.y == i) {
ShaderState s1 = s;
const float spos = tx->getCharStart(curs.x);
const float2 size = tx->getCharSize(curs.x);
s1.translate(float2(spos, 0));
s1.color(textColor, alpha);
s1.translateZ(1.f);
ShaderUColor::instance().DrawRectCorners(s1, float2(0), float2(size.x, charHeight));
if (curs.x < lines[i].size()) {
GLText::Put(s1, float2(0.f), GLText::LEFT, kMonoFont,
ALPHA_OPAQUE|GetContrastWhiteBlack(textColor),
textSize, utf8_substr(lines[i], curs.x, 1));
}
}
s.translate(float2(0.f, -charHeight));
}
}
TextInputCommandLine::TextInputCommandLine()
{
// 120 on mac, 100 on windows??
sizeChars = int2(100, 10);
fixedHeight = false;
fixedWidth = true;
wrapText = true;
registerCommand(cmd_help, comp_help, this, "help", "[command]: list help for specified command, or all commands if unspecified");
registerCommand(cmd_find, comp_help, this, "find", "[string]: list commands matching search");
setLineText("");
}
void TextInputCommandLine::saveHistory(const char *fname)
{
string str = str_join("\n", commandHistory);
int status = ZF_SaveFile(fname, str.c_str(), str.size());
Reportf("Wrote %d lines of console history to '%s': %s",
(int) commandHistory.size(), fname, status ? "OK" : "FAILED");
}
void TextInputCommandLine::loadHistory(const char *fname)
{
string data = ZF_LoadFile(fname);
if (data.size()) {
#if WIN32
data = str_replace(data, "\r", "");
#endif
data = str_chomp(data);
commandHistory = str_split('\n', data);
}
historyIndex = commandHistory.size();
}
vector<string> TextInputCommandLine::comp_help(void* data, const char* name, const char* args)
{
vector<string> options;
TextInputCommandLine *self = (TextInputCommandLine*) data;
for (std::map<string, Command>::iterator it=self->commands.begin(), end=self->commands.end(); it != end; ++it)
{
options.push_back(it->first);
}
return options;
}
string TextInputCommandLine::cmd_help(void* data, const char* name, const char* args)
{
TextInputCommandLine* self = (TextInputCommandLine*) data;
const string arg = str_strip(args);
vector<string> helps = self->completeCommand(arg);
if (helps.size() == 0)
{
for (std::map<string, Command>::iterator it=self->commands.begin(), end=self->commands.end(); it != end; ++it)
helps.push_back(it->first);
}
string ss;
foreach (const string &cmd, helps)
ss += "^2" + cmd + "^7 " + self->commands[cmd].description + "\n";
ss.pop_back();
return ss;
}
string TextInputCommandLine::cmd_find(void* data, const char* name, const char* args)
{
TextInputCommandLine* self = (TextInputCommandLine*) data;
const string arg = str_strip(args);
string ss;
int count = 0;
foreach (const auto& x, self->commands) {
if (str_contains(x.first, arg) || str_contains(x.second.description, arg))
{
ss += "^2" + x.first + "^7 " + x.second.description + "\n";
count++;
}
}
if (count) {
ss.pop_back();
} else {
ss = str_format("No commands matching '%s'", arg.c_str());
}
return ss;
}
void TextInputCommandLine::pushPrompt()
{
std::lock_guard<std::recursive_mutex> l(mutex);
lines.push_back(prompt);
cursor.y = (int)lines.size() - 1;
cursor.x = lines[cursor.y].size();
scrollForInput();
}
vector<string> TextInputCommandLine::completeCommand(string cmd) const
{
vector<string> possible;
foreach (const auto& x, commands) {
if (x.first.size() >= cmd.size() && x.first.substr(0, cmd.size()) == cmd)
possible.push_back(x.first);
}
return possible;
}
bool TextInputCommandLine::doCommand(const string& line)
{
pushHistory(line);
const vector<string> expressions = str_split_quoted(';', line);
foreach (const string &expr, expressions)
{
vector<string> args = str_split_quoted(' ', str_strip(expr));
if (!args.size())
return false;
string cmd = str_tolower(args[0]);
Command *c = NULL;
if (map_contains(commands, cmd)) {
c = &commands[cmd];
} else {
const vector<string> possible = completeCommand(cmd);
if (possible.size() == 1) {
c = &commands[possible[0]];
} else {
pushText(str_format("No such command '%s'%s", cmd.c_str(),
possible.size() ? str_format(", did you mean %s?",
str_join(", ", possible).c_str()).c_str() : ""), 0);
pushPrompt();
return false;
}
}
DPRINT(CONSOLE, ("'%s'", expr.c_str()));
const string argstr = str_join(" ", args.begin() + 1, args.end());
const string ot = c->func(c->data, cmd.c_str(), argstr.c_str());
DPRINT(CONSOLE, ("-> '%s'", ot.c_str()));
const vector<string> nlines = str_split('\n', str_word_wrap(ot, sizeChars.x));
std::lock_guard<std::recursive_mutex> l(mutex);
lines.insert(lines.end(), nlines.begin(), nlines.end());
}
pushPrompt();
return true;
}
bool TextInputCommandLine::pushCommand(const string& line)
{
setLineText(line);
return doCommand(line);
}
const TextInputCommandLine::Command *TextInputCommandLine::getCommand(const string &abbrev) const
{
const string cmd = str_tolower(abbrev);
if (map_contains(commands, cmd)) {
return map_addr(commands, cmd);
} else {
vector<string> possible;
foreach (const auto& x, commands) {
if (x.first.size() > cmd.size() && x.first.substr(0, cmd.size()) == cmd)
possible.push_back(x.first);
}
if (possible.size() == 1) {
return map_addr(commands, possible[0]);
}
return NULL;
}
}
bool TextInputCommandLine::HandleEvent(const Event* event, bool *textChanged)
{
if (textChanged)
*textChanged = false;
if (active && event->type == Event::KEY_DOWN)
{
std::unique_lock<std::recursive_mutex> l(mutex);
switch (KeyState::instance().keyMods() | event->key)
{
case MOD_CTRL|'l': {
lines.erase(lines.begin(), lines.end()-1);
scrollForInput();
break;
}
case NSUpArrowFunctionKey:
case NSDownArrowFunctionKey:
case MOD_CTRL|'p':
case MOD_CTRL|'n':
if (commandHistory.size())
{
lastSearch = "";
const int delta = (event->key == NSUpArrowFunctionKey || event->key == 'p') ? -1 : 1;
historyIndex = modulo((historyIndex + delta), (commandHistory.size() + 1));
setLineText(historyIndex >= commandHistory.size() ? currentCommand : commandHistory[historyIndex]);
}
return true;
case '\r':
{
lastSearch = "";
string cmd = getLineText();
l.unlock();
doCommand(cmd);
return true;
}
case MOD_CTRL|'r':
case MOD_CTRL|'s':
case MOD_ALT|'p':
case MOD_ALT|'n':
{
int end = 0;
int delta = 0;
if (event->key == 'p' || event->key == 'r') {
end = 0;
delta = -1;
} else if (event->key == 'n' ||event->key == 's') {
end = commandHistory.size();
delta = 1;
}
if (lastSearch.empty())
lastSearch = getLineText();
if (lastSearch.empty())
return true;
for (int i=historyIndex; i != end; i += delta)
{
if (i != historyIndex &&
commandHistory[i].size() >= lastSearch.size() &&
commandHistory[i].substr(0, lastSearch.size()) == lastSearch)
{
historyIndex = i;
setLineText(commandHistory[i]);
break;
}
}
return true;
}
case '\t':
{
lastSearch = "";
string line = getLineText();
string suffix;
const int curs = cursor.x - prompt.size();
if (curs < line.size()) {
suffix = line.substr(curs);
line = line.substr(0, curs);
}
string prefix;
int cmdStart = line.rfind(';');
if (cmdStart > 0) {
while (cmdStart < line.size() && str_contains(" ;", line[cmdStart]))
cmdStart++;
prefix = line.substr(0, cmdStart);
line = line.substr(cmdStart);
}
int start = line.rfind(' ');
vector<string> options;
if (start > 0)
{
// complete arguments
vector<string> args = str_split(' ', str_strip(line));
if (args.size() >= 1)
{
const Command *cmd = getCommand(args[0]);
if (cmd && cmd->comp)
{
const string argstr = str_join(" ", args.begin() + 1, args.end());
const string largs = str_tolower(argstr);
options = cmd->comp(cmd->data, cmd->name.c_str(), argstr.c_str());
for (int i=0; i<options.size(); ) {
vec_pop_increment(
options, i, str_tolower(options[i].substr(0, largs.size())) != largs);
}
for_ (op, options) {
if (op.find(' ') != string::npos)
op = '"' + op + '"';
}
line = cmd->name + " " + argstr;
start = argstr.size();
}
}
}
else
{
// complete commands
const string lline = str_tolower(line);
for (std::map<string, Command>::iterator it=commands.begin(), end=commands.end(); it != end; ++it)
{
if (str_tolower(it->first.substr(0, lline.size())) == lline)
options.push_back(it->second.name);
}
start = line.size();
}
if (options.empty()) {
pushText("No completions");
return true;
}
bool done = false;
const string oline = line;
line.resize(line.size() - start); // update case
line += options[0].substr(0, start);
for (int i=start; ; i++) {
const char c = options[0][i];
for (uint j=0; j<options.size(); j++) {
if (i == options[j].size() || options[j][i] != c) {
done = true;
break;
}
}
if (done)
break;
else
line += c;
}
if (options.size() > 1 && oline.size() == line.size())
{
pushText(prompt + oline);
pushText(str_join(" ", options));
}
setLineText(prefix + line + suffix, prefix.size() + line.size());
if (textChanged)
*textChanged = true;
return true;
}
default:
break;
}
}
bool changed = false;
if (!TextInputBase::HandleEvent(event, &changed))
return false;
std::lock_guard<std::recursive_mutex> l(mutex);
if (changed)
{
currentCommand = getLineText();
historyIndex = commandHistory.size();
if (textChanged)
*textChanged = true;
}
if (cursor.y >= lines.size()) {
cursor.x = lines.back().size();
} else {
cursor.x = clamp(cursor.x, prompt.size(), lines.back().size());
}
cursor.y = (int)lines.size()-1;
string& line = lines[cursor.y];
if (line.size() < prompt.size()) {
setLineText("");
} else if (!str_startswith(line, prompt)) {
for (int i=0; i<prompt.size(); i++) {
if (line[i] != prompt[i])
line.insert(i, 1, prompt[i]);
}
}
lastSearch = "";
return true;
}
void ContextMenu::setLine(int line, const string &txt)
{
if (line >= lines.size()) {