-
Notifications
You must be signed in to change notification settings - Fork 6
/
widgets.cpp
1465 lines (1340 loc) · 53.7 KB
/
widgets.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
#include "widgets.h"
#include "usvg/svgparser.h"
#include "usvg/svgpainter.h" // for elideText()
// Put these (and create*() fns) in a namespace? a class? as static or non-static members?
//static const char* widgetSVG = NULL;
//static const char* styleCSS = NULL;
static std::unique_ptr<SvgDocument> widgetDoc;
//static std::shared_ptr<SvgCssStylesheet> widgetStyle;
void setGuiResources(SvgDocument* svg) //, SvgCssStylesheet* css)
{
widgetDoc.reset(svg);
//widgetStyle.reset(css);
}
// assumes svg string contains a single top-level node
SvgNode* loadSVGFragment(const char* svg)
{
SvgDocument* svgDoc = SvgParser().parseFragment(svg);
SvgNode* node = NULL;
if(svgDoc && !svgDoc->children().empty()) {
ASSERT(svgDoc->children().size() == 1 && "Fragment contains multiple top-level nodes!");
node = svgDoc->children().front();
svgDoc->removeChild(node);
}
delete svgDoc;
return node;
}
// no caching for now; in the future, add an optional feature to SvgStructureNode to generate dict
// (unordered_multimap?) for quick node lookup by class and/or id
SvgNode* widgetNode(const char* sel)
{
// support selector or SVG fragment
if(StringRef(sel).trimmed().startsWith("<"))
return loadSVGFragment(sel);
SvgNode* proto = widgetDoc->selectFirst(sel);
ASSERT(proto && "Prototype not found for widget");
SvgNode* cloned = proto->clone();
cloned->setXmlId("");
return cloned;
}
static SvgG* createLayoutNode(const char* cls, const char* boxanchor,
const char* layout, const char* flexdir = "", const char* justify = "", const char* margin = "")
{
SvgG* row = new SvgG;
if(cls && cls[0]) row->addClass(cls);
if(boxanchor && boxanchor[0]) row->setAttribute("box-anchor", boxanchor);
if(layout && layout[0]) row->setAttribute("layout", layout);
if(flexdir && flexdir[0]) row->setAttribute("flex-direction", flexdir);
if(justify && justify[0]) row->setAttribute("justify-content", justify);
if(margin && margin[0]) row->setAttribute("margin", margin);
return row;
}
Widget* createRow(std::initializer_list<Widget*> contents, const char* margin, const char* justify, const char* boxanchor)
{
Widget* widget = new Widget(createLayoutNode("row-layout", boxanchor, "flex", "row", justify, margin));
for(Widget* w : contents) widget->addWidget(w);
return widget;
}
Widget* createColumn(std::initializer_list<Widget*> contents, const char* margin, const char* justify, const char* boxanchor)
{
Widget* widget = new Widget(createLayoutNode("col-layout", boxanchor, "flex", "column", justify, margin));
for(Widget* w : contents) widget->addWidget(w);
return widget;
}
Widget* createBoxLayout(std::initializer_list<Widget*> contents, const char* margin, const char* boxanchor)
{
Widget* widget = new Widget(createLayoutNode("box-layout", boxanchor, "box", "", "", margin));
for(Widget* w : contents) widget->addWidget(w);
return widget;
}
SvgText* createTextNode(const char* text)
{
SvgText* node = new SvgText();
if(text && text[0])
node->addText(text);
return node;
}
TextBox* createTextBox(const char* text)
{
return new TextBox(createTextNode(text));
}
// createTitledRow("Name", NULL, widget) to get gap between title and widget
Widget* createTitledRow(const char* title, Widget* control1, Widget* control2)
{
Widget* row = createRow({}, "5 0", "space-between");
if(title) {
SvgText* titlenode = createTextNode(title);
titlenode->setAttribute("margin", control1 ? "4 0" : "4 16 4 0");
titlenode->addClass("row-text");
row->containerNode()->addChild(titlenode);
}
if(control1) row->addWidget(control1);
if(control2) row->addWidget(control2);
return row;
}
Widget* createHRule(real height, const char* margin, const char* cls)
{
SvgRect* hrule = new SvgRect(Rect::wh(20, height));
hrule->setAttribute("box-anchor", "hfill");
hrule->addClass(cls);
if(margin && margin[0])
hrule->setAttribute("margin", margin);
return new Widget(hrule);
}
Widget* createFillRect(bool hasfill)
{
SvgRect* rect = new SvgRect(Rect::wh(20, 20));
rect->setAttribute("box-anchor", "fill");
if(!hasfill)
rect->setAttribute("fill", "none");
else
rect->addClass("background");
return new Widget(rect);
}
Widget* createStretch() { Widget* r = createFillRect(false); r->node->addClass("stretch"); return r; }
Toolbar::Toolbar(SvgNode* n) : Widget(n) {}
Widget* Toolbar::addSeparator()
{
const char* sepId = node->hasClass("vert-toolbar") ? "#vert-toolbar-separator" : "#toolbar-separator";
Widget* sep = new Widget(widgetNode(sepId));
addWidget(sep);
return sep;
}
Toolbar* createToolbar(std::initializer_list<Widget*> contents, const char* tbnode)
{
Toolbar* tb = new Toolbar(widgetNode(tbnode));
Widget* cc = tb->selectFirst(".child-container");
for(Widget* w : contents) cc->addWidget(w);
return tb;
}
Toolbar* createVertToolbar(std::initializer_list<Widget*> contents) { return createToolbar(contents, "#vert-toolbar"); }
void setupFocusable(Widget* widget)
{
widget->isFocusable = true;
widget->addHandler([widget](SvgGui* gui, SDL_Event* event){
if(event->type == SvgGui::FOCUS_GAINED)
widget->node->addClass("focused");
else if(event->type == SvgGui::FOCUS_LOST)
widget->node->removeClass("focused");
return false; // continue to next event handler
});
}
// Note: menubar now implemented as separate class which adds an additional handler to each button
// if we used a separate class=menuopen instead of class=pressed, we could confine menu stuff to onPressed()
Button::Button(SvgNode* n) : Widget(n), mMenu(NULL), m_checked(false)
{
addHandler([this](SvgGui* gui, SDL_Event* event){
if(event->type == SvgGui::ENTER)
node->addClass(gui->pressedWidget != NULL ? "pressed" : "hovered");
else if(event->type == SvgGui::LEAVE
|| event->type == SvgGui::OUTSIDE_PRESSED || event->type == SvgGui::DISABLED) {
// "hovered" and "pressed" should never be set simultaneously, so this should only restyle once
node->removeClass("hovered");
if(!mMenu || !mMenu->isVisible())
node->removeClass("pressed");
}
else if(event->type == SDL_FINGERDOWN && event->tfinger.fingerId == SDL_BUTTON_LMASK) {
if(mMenu && gui->lastClosedMenu != mMenu) {
gui->closeMenus(this); // close sibling menu if any
gui->showMenu(mMenu);
gui->setPressed(mMenu);
}
else {
gui->closeMenus(this);
gui->setPressed(this);
}
// do this after closeMenus, which might clear "pressed"
node->setXmlClass(addWord(removeWord(node->xmlClass(), "hovered"), "pressed").c_str());
if(onPressed)
onPressed();
}
else if(event->type == SDL_FINGERUP && event->tfinger.fingerId == SDL_BUTTON_LMASK) {
// don't need to check button since button up won't be sent unless button down is accepted
if(!mMenu || !mMenu->isVisible())
node->removeClass("pressed");
if(onClicked)
onClicked();
}
else if(event->type == SDL_KEYDOWN && event->key.keysym.sym == SDLK_RETURN) {
// we only receive key event if were are focusable and focused
if(onClicked)
onClicked();
}
else
return false;
return true;
});
}
void Button::setMenu(Menu* m)
{
// how could we associate menu with multiple buttons? <use>?
if(m) {
ASSERT(!mMenu && "Replacing menu not yet supported");
// menu can be positioned relative to a different control than this Button, in which case it should
// be added to that control's group before calling setMenu
//ASSERT(!m->parent() && "Currently, menu can only be associated with one button");
if(!m->parent())
addWidget(m);
}
mMenu = m;
}
void Button::setChecked(bool checked)
{
if(checked == m_checked)
return;
m_checked = checked;
if(m_checked)
node->addClass("checked");
else
node->removeClass("checked");
//redraw();
}
Button* createToolbutton(const SvgNode* icon, const char* title, bool showTitle)
{
Button* widget = new Button(widgetNode("#toolbutton"));
widget->setIcon(icon);
widget->setTitle(title);
widget->setShowTitle(showTitle);
return widget;
}
Button* createPushbutton(const char* title)
{
Button* widget = new Button(widgetNode("#pushbutton"));
widget->setTitle(title);
setupFocusable(widget); //widget->isFocusable = true; // pushbutton focusable but not toolbutton (?)
return widget;
}
//MenuItem::MenuItem(SvgNode* n) : Button(n)
void setupMenuItem(Button* btn)
{
// runs before handler for Button
btn->addHandler([btn](SvgGui* gui, SDL_Event* event){
// no need to handle button down event since it is always preceeded by ENTER event
if(event->type == SvgGui::ENTER) {
if(!btn->mMenu)
gui->closeMenus(btn); // close sibling menu if any
else if(!btn->mMenu->isVisible()) {
gui->closeMenus(btn); // close sibling menu if any
gui->showMenu(btn->mMenu);
btn->node->addClass("pressed");
}
}
else if(event->type == SDL_FINGERUP && !btn->mMenu)
gui->closeMenus(); // close all menus if item clicked
return false; // continue to Button handler
});
}
Button* createMenuItem(const char* title, const SvgNode* icon)
{
Button* cloned = new Button(widgetNode("#menuitem-standard"));
Widget* titleExt = cloned->selectFirst(".title");
titleExt->setText(title);
if(icon) {
Widget* iconExt = cloned->selectFirst(".icon");
iconExt->setVisible(true);
static_cast<SvgUse*>(iconExt->node)->setTarget(icon);
}
return cloned;
}
Button* createCheckBoxMenuItem(const char* title, const char* cbnode)
{
Button* item = new Button(widgetNode("#menuitem-standard"));
item->selectFirst(".title")->setText(title);
// insert the checkbox after the <use> node, which will remain invisible
item->selectFirst(".menu-icon-container")->addWidget(new Widget(widgetNode(cbnode)));
item->node->addClass("cbmenuitem");
return item;
}
Button* createMenuItem(Widget* contents)
{
Button* item = new Button(widgetNode("#menuitem-custom"));
item->selectFirst(".menuitem-container")->addWidget(contents);
return item;
}
Menu::Menu(SvgNode* n, int align) : AbsPosWidget(n)
{
setAlign(align);
// close all menus if button up or down outside menu (except for first click on opening button)
// - if our assumption of opening widget being (descendant of) parent fails, we could store opening
// widget in Menu (or just top level opening widget in SvgGui)
// - we could also use a flag to close on button up of 2nd click on opening button instead of button down
// - different GUIs handle details of menu opening/closing and menu bars differently - not a big deal
addHandler([this](SvgGui* gui, SDL_Event* event){
if(event->type == SDL_KEYDOWN && event->key.keysym.sym == SDLK_ESCAPE) {
gui->closeMenus();
return true;
}
if(event->type == SvgGui::OUTSIDE_PRESSED) {
// close unless button up over parent (assumed to include opening button)
Widget* target = static_cast<Widget*>(event->user.data2);
if(!target || !target->isDescendantOf(parent()))
gui->closeMenus(this->parent(), true); // close entire menu tree
else if(autoClose) {
gui->closeMenus(this->parent(), true);
parent()->sdlEvent(gui, static_cast<SDL_Event*>(event->user.data1));
}
return true;
}
if(event->type == SvgGui::OUTSIDE_MODAL)
gui->closeMenus(this->parent(), true); // close entire menu tree; note we don't swallow event
return false;
});
// modalWidget in SvgGui::sdlEvent needs to be menu (since outside modal handler is on menu), so if
// sdlEvent sets modalWidget to pressed group container for top-level menu, isPressedGroupContainer should
// be set for menu, not button
isPressedGroupContainer = true;
setVisible(false); // not visible initially
}
Point Menu::calcOffset(const Rect& pb) const
{
int align = mAlign;
if(!align) return AbsPosWidget::calcOffset(pb);
Point dr(0,0);
Rect b = node->bounds();
Rect winb = window()->gui()->getScreenRect();
if(!(align & (LEFT | RIGHT)))
align |= (pb.left < window()->winBounds().width() - pb.right) ? RIGHT : LEFT;
bool vert = align & VERT;
bool fitabove = (vert ? pb.top : pb.bottom) - b.height() > 0;
bool fitbelow = (vert ? pb.bottom : pb.top) + b.height() < winb.bottom;
if(!fitabove && !fitbelow) vert = false; // e.g. on mobile landscape orientation
bool fitleft = (vert ? pb.right : pb.left) - b.width() > 0;
bool fitright = (vert ? pb.left : pb.right) + b.width() < winb.right;
if((align & RIGHT) && (align & LEFT))
dr.x = pb.center().x - b.width()/2;
else if((align & RIGHT && fitright) || !fitleft)
dr.x = (vert ? pb.left : pb.right) - b.left;
else
dr.x = (vert ? pb.right : pb.left) - b.right;
if((align & ABOVE && fitabove) || !fitbelow)
dr.y = (vert ? pb.top : pb.bottom) - b.bottom;
else
dr.y = (vert ? pb.bottom : pb.top) - b.top;
return dr;
}
// (option for) menu alignment to be determined automatically based on orientation of parent container?
void Menu::setAlign(int align)
{
mAlign = align;
node->removeAttr("left");
node->removeAttr("right");
node->removeAttr("top");
node->removeAttr("bottom");
if(align & VERT && align & RIGHT)
node->setAttribute("left", "0"); //offsetLeft = SvgLength(0); ... would be overwritten by updateLayoutVars()
else if(align & VERT && align & LEFT)
node->setAttribute("right", "0"); //offsetRight = SvgLength(0);
else if(align & HORZ && align & RIGHT)
node->setAttribute("left", "100%"); //offsetLeft = SvgLength(100, SvgLength::PERCENT);
else if(align & HORZ && align & LEFT)
node->setAttribute("right", "100%"); //offsetRight = SvgLength(100, SvgLength::PERCENT);
if(align & VERT)
node->setAttribute(align & ABOVE ? "bottom" : "top", "100%"); //offsetTop = SvgLength(100, SvgLength::PERCENT);
else if(align & HORZ) // HORZ_*
node->setAttribute("top", "0"); //offsetTop = SvgLength(0);
}
Button* Menu::addSubmenu(const char* title, Menu* submenu)
{
//Button* item = createMenuItem(title);
Button* item = new Button(widgetNode("#menuitem-submenu"));
item->selectFirst(".title")->setText(title);
item->setMenu(submenu);
addItem(item);
return item;
}
void Menu::addSeparator()
{
addWidget(new Widget(widgetNode("#menu-separator")));
}
void Menu::addItem(Button* btn) { setupMenuItem(btn); addWidget(btn); }
// this breaks the idea of Menu class defining only behavior, but so does Menu::addAction and addSubmenu!
// - maybe change to standalone addMenuItem() (and addMenuAction()?)
// - or have addWidget() return its argument for chaining!
Button* Menu::addItem(const char* name, const SvgNode* icon, const std::function<void()>& callback)
{
Button* item = createMenuItem(name, icon);
item->onClicked = callback;
addItem(item);
return item;
}
Menu* createMenu(int align, bool showicons)
{
Menu* menu = new Menu(widgetNode("#menu"), align);
if(!showicons)
menu->node->addClass("no-icon-menu");
return menu;
}
// consider moving Action out of widgets.cpp and replace addAction with Action::addTo(Menu*),
// addTo(Toolbar*), ...
Action::Action(const char* _name, const char* _title, const SvgNode* _icon, const char* _shortcut)
: name(_name), title(_title), shortcut(_shortcut), m_icon(_icon) {}
void Action::setVisible(bool visible)
{
// some buttons may have been shown or hidden individually, so always forward to each button
//if(visible != m_visible) {
m_visible = visible;
for(Button* button : buttons)
button->setVisible(visible);
}
void Action::setEnabled(bool enabled)
{
//if(enabled != m_enabled) {
m_enabled = enabled;
for(Button* button : buttons)
button->setEnabled(enabled);
}
void Action::setChecked(bool checked)
{
if(checked != m_checked) {
m_checked = checked;
for(Button* button : buttons)
button->setChecked(checked);
}
}
void Action::addClass(const char* s) { for(Button* button : buttons) button->node->addClass(s); }
void Action::removeClass(const char* s) { for(Button* button : buttons) button->node->removeClass(s); }
void Action::setTitle(const char* s)
{
title = s;
for(Button* button : buttons)
button->setTitle(s);
}
void Action::setIcon(const SvgNode* icon)
{
m_icon = icon;
for(Button* button : buttons)
button->setIcon(icon);
}
// make this private and make just Toolbar and Menu friend?
void Action::addButton(Button* btn)
{
// menuActions is a list of actions from which to build a menu instead of storing already built menu (in
// which case the action can only be used once)
ASSERT(!menu || (buttons.empty() && menuActions.empty()));
if(!menuActions.empty()) {
Menu* m = createMenu(Menu::VERT);
btn->setMenu(m);
for(Action* a : menuActions)
m->addAction(a);
}
else
btn->setMenu(menu);
if(btn->mMenu && onTriggered)
btn->mMenu->autoClose = true; // btn->isPressedGroupContainer = true;
// set button id to action name for debugging - could use Action.buttons.size() to create unique id
btn->node->setXmlId(name.c_str());
if(priority != NormalPriority)
btn->node->setAttribute("ui-priority", fstring("%d", priority).c_str());
// can't do item->onClicked = action->onTriggered because onTriggered may change
// should we call an Action::triggered() member instead (which can in turn invoke onTriggered?)
btn->onClicked = [this](){ if(onTriggered) onTriggered(); };
btn->setChecked(m_checked);
btn->setEnabled(m_enabled);
buttons.push_back(btn);
//return button; // chaining?
}
Button* Menu::addAction(Action* action)
{
Button* item = (action->checkable && !action->icon()) ?
createCheckBoxMenuItem(action->title.c_str()) : createMenuItem(action->title.c_str(), action->icon());
action->addButton(item);
addItem(item);
if(!action->tooltip.empty())
setupTooltip(item, action->tooltip.c_str());
return item;
}
Button* Toolbar::addAction(Action* action)
{
Button* item = createToolbutton(action->icon(), action->title.c_str());
action->addButton(item);
addWidget(item);
setupTooltip(item, action->tooltip.empty() ? action->title.c_str() : action->tooltip.c_str());
return item;
}
Tooltips* Tooltips::inst = NULL;
void setupTooltip(Widget* target, const char* tiptext, int align)
{
if(Tooltips::inst)
Tooltips::inst->setup(target, tiptext, align);
}
void Tooltips::show(Widget* tooltip, Point p, int align)
{
Rect parentBounds = tooltip->node->parent()->bounds();
real dx = align & LEFT ? 0 : align & RIGHT ? parentBounds.width() : p.x - parentBounds.left;
real dy = align & TOP ? 0 : align & BOTTOM ? parentBounds.height() : p.y - parentBounds.top;
tooltip->node->setAttribute("left", fstring("%g", dx + offset.x).c_str());
tooltip->node->setAttribute(align & ABOVE ? "bottom" : "top", fstring("%g", dy + offset.y).c_str());
tooltip->setVisible(true);
}
void Tooltips::setup(Widget* target, const char* tiptext, int align)
{
Widget* tooltip = new AbsPosWidget(widgetNode("#tooltip"));
SvgNode* textNode = tiptext[0] == '<' ? loadSVGFragment(tiptext) : createTextNode(tiptext);
textNode->setAttribute("margin", "3");
tooltip->containerNode()->addChild(textNode);
tooltip->setVisible(false);
target->addWidget(tooltip);
// default alignment
bool isMenuItem = target->node->hasClass("menuitem");
if(align == -1)
align = isMenuItem ? (RIGHT | TOP) : (LEFT | BOTTOM);
target->addHandler([=](SvgGui* gui, SDL_Event* event) {
if(event->type == SvgGui::ENTER) {
if(gui->pressedWidget != NULL && !isMenuItem) // don't show tooltip if finger down, except menu items
return false;
if(event->user.timestamp < hideTime + nextMs) {
show(tooltip, gui->prevFingerPos, align);
}
else {
timer = gui->setTimer(delayMs, target, timer, [=]() {
show(tooltip, gui->prevFingerPos, align);
return 0; // single shot timer
});
}
}
else if(event->type == SvgGui::LEAVE || event->type == SDL_FINGERDOWN) {
if(tooltip->isVisible()) {
tooltip->setVisible(false);
hideTime = event->type == SDL_FINGERDOWN ? 0 : event->user.timestamp;
}
if(timer) {
gui->removeTimer(timer);
timer = NULL;
}
}
return false; // don't swallow event
});
}
CheckBox::CheckBox(SvgNode* n, bool _checked) : Button(n)
{
setChecked(_checked);
onClicked = [this](){
setChecked(!checked());
if(onToggled)
onToggled(checked());
};
}
CheckBox* createCheckBox(const char* title, bool checked)
{
SvgNode* cbnode = widgetNode("#checkbox");
if(title && title[0]) {
SvgG* row = createLayoutNode("checkbox", "", "flex", "row");
SvgText* titlenode = createTextNode(title);
titlenode->setAttribute("margin", "4 2");
row->addChild(cbnode);
row->addChild(titlenode);
cbnode->removeClass("checkbox");
cbnode = row;
}
CheckBox* widget = new CheckBox(cbnode, checked);
setupFocusable(widget); //widget->isFocusable = true;
return widget;
}
// TextBox allows ComboBox and SpinBox to support both editable and non-editable cases
TextBox::TextBox(SvgNode* n) : Widget(n), textNode(NULL)
{
if(n->type() == SvgNode::TEXT)
textNode = static_cast<SvgText*>(n);
else if(n->asContainerNode())
textNode = static_cast<SvgText*>(n->asContainerNode()->selectFirst("text"));
}
// Widget supporting text elision
TextLabel::TextLabel(SvgNode* n) : TextBox(n)
{
origText = TextBox::text();
onApplyLayout = [this](const Rect& src, const Rect& dest){
if(src.width() == dest.width() || (layBehave & LAY_HFILL) != LAY_HFILL)
return false;
Point dr(dest.left - src.left, dest.top - src.top);
if(std::abs(dr.x) < 1E-3 && std::abs(dr.y) < 1E-3 && src.width() < dest.width() && textNode->text() == origText)
return true;
textNode->setText(origText.c_str());
SvgPainter::elideText(textNode, dest.width());
m_layoutTransform.translate(dr);
node->invalidate(true);
return true;
};
}
void setMinWidth(Widget* widget, real w, const char* sel)
{
SvgNode* node = widget->containerNode()->selectFirst(sel);
if(node && node->type() == SvgNode::RECT) {
SvgRect* rectNode = static_cast<SvgRect*>(node);
rectNode->setRect(Rect::wh(w, rectNode->getRect().height()));
}
}
ComboBox::ComboBox(SvgNode* n, const std::vector<std::string>& _items) : Widget(n), currIndex(0)
{
comboMenu = new Menu(containerNode()->selectFirst(".combo_menu"), Menu::VERT_RIGHT);
//Menu* combomenu = new Menu(widgetNode("#combo_menu"), Menu::VERT_RIGHT);
//comboText = selectFirst(".combo_text");
SvgNode* textNode = containerNode()->selectFirst(".combo_text");
comboText = textNode->hasExt() ? static_cast<TextBox*>(textNode->ext()) : new TextBox(textNode);
addItems(_items);
if(!items.empty())
setText(items.front().c_str());
// combobox dropdown behaves the same as a menu
SvgNode* btn = containerNode()->selectFirst(comboText->isEditable() ? ".combo_open" : ".combo_content");
Button* comboopen = new Button(btn);
comboopen->setMenu(comboMenu);
// when combo menu opens, set min width to match the box
comboopen->onPressed = [this](){
SvgNode* minwidthnode = containerNode()->selectFirst(".combo-menu-min-width");
if(minwidthnode && minwidthnode->type() == SvgNode::RECT) {
SvgRect* rectNode = static_cast<SvgRect*>(minwidthnode);
real sx = node->bounds().width()/rectNode->bounds().width();
rectNode->setRect(Rect::wh(sx*rectNode->getRect().width(), rectNode->getRect().height()));
}
};
// allow stepping through items w/ up/down arrow
addHandler([this](SvgGui* gui, SDL_Event* event){
if(event->type == SDL_KEYDOWN && (event->key.keysym.sym == SDLK_UP || event->key.keysym.sym == SDLK_DOWN)) {
updateIndex(currIndex + (event->key.keysym.sym == SDLK_UP ? -1 : 1));
return true;
}
if(SvgGui::isFocusedWidgetEvent(event))
return comboText->sdlEvent(gui, event);
return false;
});
}
void ComboBox::addItems(const std::vector<std::string>& _items)
{
SvgNode* protonode = comboMenu->containerNode()->selectFirst(".combo_proto");
// populate combo dropdown by cloning prototype
for(const std::string& s : _items) {
int ii = items.size();
items.emplace_back(s);
Button* btn = new Button(protonode->clone());
btn->onClicked = [this, ii](){
window()->gui()->closeMenus(comboMenu->parent(), true);
updateIndex(ii);
};
btn->selectFirst("text")->setText(s.c_str());
//SvgText* textnode = (SvgText*)item->selectFirst("text"); textnode->clearText(); textnode->addText(s);
btn->setVisible(true); // prototypes have display="none"
comboMenu->addWidget(btn);
}
}
void ComboBox::updateIndex(int idx)
{
setIndex(idx);
if(onChanged)
onChanged(text());
}
void ComboBox::setIndex(int idx)
{
if(idx >= 0 && idx < int(items.size())) {
const char* s = items[idx].c_str();
setText(s);
currIndex = idx;
}
}
// called by TextEdit when text entered
void ComboBox::updateFromText(const char* s)
{
currText = s;
if(onChanged)
onChanged(s);
}
// vector of std::string is preferable to one of const char* since split strings are often std::strings
// and {"a", "b", ... } intializer lists work for std::string!
ComboBox* createComboBox(const std::vector<std::string>& items)
{
SvgNode* comboNode = widgetNode("#combobox");
comboNode->selectFirst(".combo_text")->asContainerNode()->addChild(widgetNode("#textbox"));
ComboBox* widget = new ComboBox(comboNode, items);
setupFocusable(widget); //widget->isFocusable = true;
return widget;
}
SpinBox::SpinBox(SvgNode* n, real val, real inc, real min, real max, const char* format)
: Widget(n), m_value(NAN), m_step(inc), m_min(min), m_max(max), m_format(format)
{
if(m_format.empty())
m_format = fstring("%%.%df", std::max(0, -int(floor(log10(inc)))));
// if text node already has an extension, assume it's a TextBox; otherwise create a TextBox
// ... I don't like this - feels hacky and unsafe - but let's see where it goes
//spinboxText = selectFirst(".spinbox_text");
SvgNode* textNode = containerNode()->selectFirst(".spinbox_text");
spinboxText = textNode->hasExt() ? static_cast<TextBox*>(textNode->ext()) : new TextBox(textNode);
// default onStep impl - can be override by user
onStep = [this](int nsteps){ return value() + nsteps*step(); };
incBtn = new Button(containerNode()->selectFirst(".spinbox_inc"));
incBtn->onClicked = [this](){ updateValue(onStep(1)); };
decBtn = new Button(containerNode()->selectFirst(".spinbox_dec"));
decBtn->onClicked = [this](){ updateValue(onStep(-1)); };
addHandler([this](SvgGui* gui, SDL_Event* event){
if(event->type == SDL_KEYDOWN && (event->key.keysym.sym == SDLK_UP || event->key.keysym.sym == SDLK_DOWN)) {
updateValue( onStep(event->key.keysym.sym == SDLK_UP ? 1 : -1) );
return true;
}
// make sure text matches value on focus lost
if(event->type == SvgGui::FOCUS_LOST) {
std::string s = fstring(m_format.c_str(), m_value);
if(s != spinboxText->text())
spinboxText->setText(s.c_str());
}
// don't forward focus event to textedit on mobile if buttons clicked so soft keyboard isn't shown
if(SvgGui::isFocusedWidgetEvent(event)
&& (!PLATFORM_MOBILE || (gui->pressedWidget != incBtn && gui->pressedWidget != decBtn)))
return spinboxText->sdlEvent(gui, event);
return false;
});
setValue(val);
}
void SpinBox::updateValue(real val)
{
real prev = m_value;
setValue(val);
if(onValueChanged && m_value != prev)
onValueChanged(m_value);
}
bool SpinBox::setValue(real val)
{
real v = std::min(std::max(val, m_min), m_max);
if(std::abs(v/m_step) < 1E-6)
v = 0.0; // floating point issues can cause tiny values when stepping
if(v == m_value)
return true;
decBtn->setEnabled(v > m_min);
incBtn->setEnabled(v < m_max);
m_value = v;
spinboxText->setText(fstring(m_format.c_str(), m_value).c_str());
return v == val;
}
bool SpinBox::updateValueFromText(const char* s)
{
char* next = NULL;
real v = strtof(s, &next);
if(!next || next == s || v < m_min || v > m_max)
return false;
if(v == m_value)
return true;
decBtn->setEnabled(v > m_min);
incBtn->setEnabled(v < m_max);
m_value = v;
if(onValueChanged)
onValueChanged(v);
//spinboxText->redraw();
return true;
}
SpinBox* createSpinBox(real val, real inc, real min, real max, const char* format, real minwidth)
{
SvgG* spinBoxNode = static_cast<SvgG*>(widgetNode("#spinbox"));
static_cast<SvgG*>(spinBoxNode->selectFirst(".spinbox_text"))->addChild(widgetNode("#textbox"));
SpinBox* widget = new SpinBox(spinBoxNode, val, inc, min, max, format);
setupFocusable(widget); //widget->isFocusable = true;
if(minwidth > 0)
setMinWidth(widget, minwidth);
return widget;
}
void Slider::setValue(real value)
{
value = std::min(std::max(value, 0.0), 1.0);
if(value == sliderPos)
return;
sliderPos = value;
// layout transform or SVG transform?
// sliderHandle->setTransform(Transform2D::translate(rect.width()*sliderPos, 0));
Rect rect = sliderBg->node->bounds();
//sliderHandle->node->appendStyleProperty(new SvgTransformStyle(Transform2D().translate(rect.width()*sliderPos, 0)));
sliderHandle->setLayoutTransform(Transform2D().translate(rect.width()*sliderPos, 0));
//redraw();
}
void Slider::updateValue(real value)
{
real oldval = sliderPos;
setValue(value);
if(onValueChanged && sliderPos != oldval)
onValueChanged(sliderPos);
}
Slider::Slider(SvgNode* n) : Widget(n), sliderPos(0)
{
sliderBg = new Widget(containerNode()->selectFirst(".slider-bg"));
sliderHandle = new Button(containerNode()->selectFirst(".slider-handle"));
// prevent global layout when moving slider handle - note that container bounds change when handle moves
Widget* handleContainer = selectFirst(".slider-handle-container");
if(handleContainer)
handleContainer->setLayoutIsolate(true);
sliderHandle->addHandler([this](SvgGui* gui, SDL_Event* event){
if(event->type == SDL_FINGERMOTION && gui->pressedWidget == sliderHandle) {
Rect rect = sliderBg->node->bounds();
updateValue((event->tfinger.x - rect.left)/rect.width()); //event->motion.x
return true;
}
return false;
});
// should this be on sliderbg instead?
addHandler([this](SvgGui* gui, SDL_Event* event){
if(event->type == SDL_FINGERDOWN && event->tfinger.fingerId == SDL_BUTTON_LMASK) {
// move slider handle to click position and make it the pressed node
Rect rect = sliderBg->node->bounds();
updateValue((event->tfinger.x - rect.left)/rect.width()); //event->button.x
sliderHandle->sdlEvent(gui, event);
gui->setPressed(sliderHandle);
return true;
}
// don't need to handle any other events because slider handle becomes the pressed node
return false;
});
sliderBg->onApplyLayout = [this](const Rect& src, const Rect& dest){
if(src.toSize() != dest.toSize()) {
//Rect rect = sliderBg->node->bounds();
sliderHandle->setLayoutTransform(Transform2D().translate(dest.width()*sliderPos, 0));
//sliderHandle->node->appendStyleProperty(new SvgTransformStyle(Transform2D().translate(rect.width()*sliderPos, 0)));
}
return false; // we do not replace the normal layout (although that should be a no-op)
};
}
Slider* createSlider()
{
Slider* slider = new Slider(widgetNode("#slider"));
setupFocusable(slider); //slider->isFocusable = true;
return slider;
}
Splitter::Splitter(SvgNode* n, SvgNode* sizer, SizerPosition pos, real minsize)
: Widget(n), sizerPos(pos), minSize(minsize)
{
ASSERT(sizer->type() == SvgNode::RECT);
sizingRectNode = static_cast<SvgRect*>(sizer);
addHandler([this](SvgGui* gui, SDL_Event* event){
if(event->type == SDL_FINGERDOWN && event->tfinger.fingerId == SDL_BUTTON_LMASK) {
initialSize = -1;
initialPos = Point(event->tfinger.x, event->tfinger.y);
gui->setPressed(this);
return true;
}
if(event->type == SDL_FINGERMOTION && gui->pressedWidget == this) {
if(gui->fingerClicks > 0) return true; // require minimum drag distance to activate
Point p = Point(event->tfinger.x, event->tfinger.y);
if(initialSize < 0) { // first drag point?
Point dr = p - initialPos;
bool horz = sizerPos == LEFT || sizerPos == RIGHT;
// require drag primarily along correct direction to activate
if((std::abs(dr.y) < std::abs(dr.x)) != horz) {
gui->pressedWidget = NULL;
return false;
}
Rect r = sizingRectNode->bounds();
initialSize = horz ? r.width() : r.height();
}
if(sizerPos == LEFT) setSplitSize(initialSize + (p.x - initialPos.x));
else if(sizerPos == TOP) setSplitSize(initialSize + (p.y - initialPos.y));
else if(sizerPos == RIGHT) setSplitSize(initialSize + (initialPos.x - p.x));
else if(sizerPos == BOTTOM) setSplitSize(initialSize + (initialPos.y - p.y));
return true;
}
return false;
});
}
void Splitter::setSplitSize(real size)
{
bool horz = sizerPos == LEFT || sizerPos == RIGHT;
currSize = std::max(minSize, size);
if(sizingRectNode->hasExt()) // may not have ext yet
static_cast<Widget*>(sizingRectNode->ext())->setLayoutTransform(Transform2D());
// hack to handle global scale != 1
Rect r0 = sizingRectNode->getRect();
Rect r1 = sizingRectNode->bounds();
//Rect handle = node->bounds();
// if you want to include handle size, must also include in initialSize
real w = horz ? currSize * r0.width()/r1.width() : r0.width(); // size - handle.width()/2
real h = horz ? r0.height() : currSize * r0.height()/r1.height(); // size - handle.height()/2
sizingRectNode->setRect(Rect::ltwh(r0.left, r0.top, w, h));
if(onSplitChanged)
onSplitChanged(currSize);
}
void Splitter::setDirection(SizerPosition pos)
{
bool horz = pos == LEFT || pos == RIGHT;
node->setAttribute("box-anchor", horz ? "vfill" : "hfill");
sizingRectNode->setAttribute("box-anchor", horz ? "vfill" : "hfill");
sizerPos = pos;
setLayoutTransform(Transform2D());
}
// ScrollWidget is built from an <svg> container holding a single <g>, the contents
// <svg> size set to fit to contents along non-scrolling direction on first layout:
// - vert scroll, fit to contents horz: <svg layout=scroll box-anchor=vfill width=100%> <g box-anchor=fill > (or hfill?)
// - horz scroll, fit to contents vert: <svg layout=scroll box-anchor=hfill height=100%> <g box-anchor=fill > (or vfill?)
// <svg> sized to fit parent (or has fixed width), contents width limited to svg width (deferred contents layout):
// - vert scroll: <svg layout=scroll box-anchor=vfill+hfill or width=W/height=H> <g box-anchor=hfill >
// - horz scroll: <svg layout=scroll box-anchor=vfill+hfill or width=W/height=H> <g box-anchor=vfill >
// <svg> fills parent (or has fixed w,h), scrolls contents horz and vert: vfill->set height
// - <svg layout=scroll box-anchor=vfill+hfill or width=W/height=H> <g box-anchor=none > - no root width or height
// Note <svg> is adjusted to fit contents only on first layout - subsequently, the relevant dimension is fixed
// - to force readjust, SvgDocument::setWidth/setHeight with widthPercent=true can be called
// - this involves a bit of an abuse of standard meaning of <svg> attributes; we could consider using a
// separate attribute, e.g. scroll=fit-contents, or overflow-x/-y
// Scrolling is accomplished by using layout transform to translate the contents <g>. Previously,
// viewBox on <svg> was used, but SvgDocument doesn't properly support viewBox yet (e.g., it is not included
// in transformedBounds() because it isn't applied in applyStyle). For layout, layout transforms on
// contents and container are cleared.
ScrollWidget::ScrollWidget(SvgDocument* doc, Widget* _contents) : Widget(doc), contents(_contents)
{
flingTimerMs = 16; // let's try 60 FPS
// TODO: if we follow the model of the other widget classes, this should use selectFirst() to find contents!
doc->addClass("scroll-widget");
addWidget(contents);
yHandle = new Widget(widgetNode("#scroll-handle"));
addWidget(yHandle);
yHandle->updateLayoutVars(); // this caching is stupid
yHandle->node->setAttr<float>("opacity", 0.0);