summaryrefslogtreecommitdiff
path: root/src/ui/widget.c
blob: 5c23860f8243c1c9738cb9cc2fa90a3d3b748047 (plain)
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
#include "widget.h"

#include "app.h"
#include "command.h"
#include "paint.h"
#include "util.h"
#include "window.h"

#include <the_Foundation/ptrset.h>
#include <SDL_mouse.h>
#include <stdarg.h>

iDeclareType(RootData)

struct Impl_RootData {
    iWidget *hover;
    iWidget *mouseGrab;
    iWidget *focus;
    iPtrSet *onTop;
    iPtrSet *pendingDestruction;
};

static iRootData rootData_;

iPtrSet *onTop_RootData_(void) {
    if (!rootData_.onTop) {
        rootData_.onTop = new_PtrSet();
    }
    return rootData_.onTop;
}

void destroyPending_Widget(void) {
    iForEach(PtrSet, i, rootData_.pendingDestruction) {
        iWidget *widget = *i.value;
        remove_PtrSet(onTop_RootData_(), widget);
        iRelease(removeChild_Widget(widget->parent, widget));
        remove_PtrSetIterator(&i);
    }
}

iDefineObjectConstruction(Widget)

void init_Widget(iWidget *d) {
    init_String(&d->id);
    d->flags          = 0;
    d->rect           = zero_Rect();
    d->bgColor        = none_ColorId;
    d->children       = NULL;
    d->parent         = NULL;
    d->commandHandler = NULL;
}

void deinit_Widget(iWidget *d) {
    iReleasePtr(&d->children);
    deinit_String(&d->id);
}

static void aboutToBeDestroyed_Widget_(iWidget *d) {
    if (isFocused_Widget(d)) {
        setFocus_Widget(NULL);
        return;
    }
    if (isHover_Widget(d)) {
        rootData_.hover = NULL;
    }
    iForEach(ObjectList, i, d->children) {
        aboutToBeDestroyed_Widget_(as_Widget(i.object));
    }
}

void destroy_Widget(iWidget *d) {
    aboutToBeDestroyed_Widget_(d);
    if (!rootData_.pendingDestruction) {
        rootData_.pendingDestruction = new_PtrSet();
    }
    insert_PtrSet(rootData_.pendingDestruction, d);
}

void setId_Widget(iWidget *d, const char *id) {
    setCStr_String(&d->id, id);
}

const iString *id_Widget(const iWidget *d) {
    return &d->id;
}

int flags_Widget(const iWidget *d) {
    return d->flags;
}

void setFlags_Widget(iWidget *d, int flags, iBool set) {
    iChangeFlags(d->flags, flags, set);
    if (flags & keepOnTop_WidgetFlag) {
        if (set) {
            insert_PtrSet(onTop_RootData_(), d);
        }
        else {
            remove_PtrSet(onTop_RootData_(), d);
        }
    }
}

void setPos_Widget(iWidget *d, iInt2 pos) {
    d->rect.pos = pos;
}

void setSize_Widget(iWidget *d, iInt2 size) {    
    d->rect.size = size;
    setFlags_Widget(d, fixedSize_WidgetFlag, iTrue);
}

void setBackgroundColor_Widget(iWidget *d, int bgColor) {
    d->bgColor = bgColor;
}

void setCommandHandler_Widget(iWidget *d, iBool (*handler)(iWidget *, const char *)) {
    d->commandHandler = handler;
}

static int numExpandingChildren_Widget_(const iWidget *d) {
    int count = 0;
    iConstForEach(ObjectList, i, d->children) {
        const iWidget *child = constAs_Widget(i.object);
        if (flags_Widget(child) & expand_WidgetFlag) {
            count++;
        }
    }
    return count;
}

static int widestChild_Widget_(const iWidget *d) {
    int width = 0;
    iConstForEach(ObjectList, i, d->children) {
        const iWidget *child = constAs_Widget(i.object);
        width = iMax(width, child->rect.size.x);
    }
    return width;
}

static void setWidth_Widget_(iWidget *d, int width) {
    if (~d->flags & fixedWidth_WidgetFlag) {
        d->rect.size.x = width;
    }
}

static void setHeight_Widget_(iWidget *d, int height) {
    if (~d->flags & fixedHeight_WidgetFlag) {
        d->rect.size.y = height;
    }
}

void arrange_Widget(iWidget *d) {
    if (d->flags & moveToParentRightEdge_WidgetFlag) {
        d->rect.pos.x = width_Rect(d->parent->rect) - width_Rect(d->rect);
    }
    if (d->flags & resizeToParentWidth_WidgetFlag) {
        setWidth_Widget_(d, d->parent->rect.size.x);
    }
    if (d->flags & resizeToParentHeight_WidgetFlag) {
        setHeight_Widget_(d, d->parent->rect.size.y);
    }
    /* The rest of the arrangement depends on child widgets. */
    if (!d->children) {
        return;
    }
    /* Resize children to fill the parent widget. */
    const size_t childCount = size_ObjectList(d->children);
    if (d->flags & resizeChildren_WidgetFlag) {
        const int expCount = numExpandingChildren_Widget_(d);
        /* Only resize the expanding children, not touching the others. */
        if (expCount > 0) {
            iInt2 avail = d->rect.size;
            iConstForEach(ObjectList, i, d->children) {
                const iWidget *child = constAs_Widget(i.object);
                if (~child->flags & expand_WidgetFlag) {
                    subv_I2(&avail, child->rect.size);
                }
            }
            avail = divi_I2(avail, expCount);
            iForEach(ObjectList, j, d->children) {
                iWidget *child = as_Widget(j.object);
                if (child->flags & expand_WidgetFlag) {
                    if (d->flags & arrangeHorizontal_WidgetFlag) {
                        setWidth_Widget_(child, avail.x);
                        setHeight_Widget_(child, d->rect.size.y);
                    }
                    else if (d->flags & arrangeVertical_WidgetFlag) {
                        setWidth_Widget_(child, d->rect.size.x);
                        setHeight_Widget_(child, avail.y);
                    }
                }
                else {
                    /* Fill the off axis, though. */
                    if (d->flags & arrangeHorizontal_WidgetFlag) {
                        setHeight_Widget_(child, d->rect.size.y);
                    }
                    else if (d->flags & arrangeVertical_WidgetFlag) {
                        setWidth_Widget_(child, d->rect.size.x);
                    }
                }
            }
        }
        else {
            /* Evenly size all children. */
            iInt2 childSize = d->rect.size;
            if (d->flags & arrangeHorizontal_WidgetFlag) {
                childSize.x /= childCount;
            }
            else if (d->flags & arrangeVertical_WidgetFlag) {
                childSize.y /= childCount;
            }
            iForEach(ObjectList, i, d->children) {
                iWidget *child = as_Widget(i.object);
                setWidth_Widget_(child, childSize.x);
                setHeight_Widget_(child, childSize.y);
            }
        }
    }
    if (d->flags & resizeChildrenToWidestChild_WidgetFlag) {
        const int widest = widestChild_Widget_(d);
        iForEach(ObjectList, i, d->children) {
            setWidth_Widget_(as_Widget(i.object), widest);
        }
    }
    iInt2 pos = zero_I2();
    iForEach(ObjectList, i, d->children) {
        iWidget *child = as_Widget(i.object);
        arrange_Widget(child);
        if (d->flags & (arrangeHorizontal_WidgetFlag | arrangeVertical_WidgetFlag)) {
            child->rect.pos = pos;
            if (d->flags & arrangeHorizontal_WidgetFlag) {
                pos.x += child->rect.size.x;
            }
            else {
                pos.y += child->rect.size.y;
            }
        }
    }
    /* Update the size of the widget according to the arrangement. */
    if (d->flags & arrangeSize_WidgetFlag) {
        iRect bounds = zero_Rect();
        iConstForEach(ObjectList, i, d->children) {
            const iWidget *child = constAs_Widget(i.object);
            if (isEmpty_Rect(bounds)) {
                bounds = child->rect;
            }
            else {
                bounds = union_Rect(bounds, child->rect);
            }
        }
        if (d->flags & arrangeWidth_WidgetFlag) {
            setWidth_Widget_(d, bounds.size.x);
            /* Parent size changed, must update the children.*/
            iForEach(ObjectList, j, d->children) {
                iWidget *child = as_Widget(j.object);
                if (child->flags &
                    (resizeToParentWidth_WidgetFlag | moveToParentRightEdge_WidgetFlag)) {
                    arrange_Widget(child);
                }
            }
        }
        if (d->flags & arrangeHeight_WidgetFlag) {
            setHeight_Widget_(d, bounds.size.y);
            /* Parent size changed, must update the children.*/
            iForEach(ObjectList, j, d->children) {
                iWidget *child = as_Widget(j.object);
                if (child->flags & resizeToParentHeight_WidgetFlag) {
                    arrange_Widget(child);
                }
            }
        }
    }
}

iRect bounds_Widget(const iWidget *d) {
    iRect bounds = d->rect;
    for (const iWidget *w = d->parent; w; w = w->parent) {
        addv_I2(&bounds.pos, w->rect.pos);
    }
    return bounds;
}

iInt2 localCoord_Widget(const iWidget *d, iInt2 coord) {
    for (const iWidget *w = d; w; w = w->parent) {
        subv_I2(&coord, w->rect.pos);
    }
    return coord;
}

iBool contains_Widget(const iWidget *d, iInt2 coord) {
    const iRect bounds = { zero_I2(), d->rect.size };
    return contains_Rect(bounds, localCoord_Widget(d, coord));
}

iLocalDef iBool isKeyboardEvent_(const SDL_Event *ev) {
    return (ev->type == SDL_KEYUP || ev->type == SDL_KEYDOWN || ev->type == SDL_TEXTINPUT);
}

iLocalDef iBool isMouseEvent_(const SDL_Event *ev) {
    return (ev->type == SDL_MOUSEWHEEL || ev->type == SDL_MOUSEMOTION ||
            ev->type == SDL_MOUSEBUTTONUP || ev->type == SDL_MOUSEBUTTONDOWN);
}

static iBool filterEvent_Widget_(const iWidget *d, const SDL_Event *ev) {
    const iBool isKey   = isKeyboardEvent_(ev);
    const iBool isMouse = isMouseEvent_(ev);
    if (d->flags & disabled_WidgetFlag) {
        if (isKey || isMouse) return iFalse;
    }
    if (d->flags & hidden_WidgetFlag) {
        if (isMouse) return iFalse;
    }
    return iTrue;
}

void unhover_Widget(void) {
    rootData_.hover = NULL;
}

iBool dispatchEvent_Widget(iWidget *d, const SDL_Event *ev) {
    if (!d->parent) {
        if (ev->type == SDL_MOUSEMOTION) {
            /* Hover widget may change. */
            rootData_.hover = NULL;
        }
        if (rootData_.focus && isKeyboardEvent_(ev)) {
            /* Root dispatches keyboard events directly to the focused widget. */
            if (dispatchEvent_Widget(rootData_.focus, ev)) {
                return iTrue;
            }
        }
        /* Root offers events first to widgets on top. */
        iForEach(PtrSet, i, rootData_.onTop) {
            iWidget *widget = *i.value;
            if (isVisible_Widget(widget) && dispatchEvent_Widget(widget, ev)) {
                return iTrue;
            }
        }
    }
    else if (ev->type == SDL_MOUSEMOTION && !rootData_.hover &&
             flags_Widget(d) & hover_WidgetFlag && ~flags_Widget(d) & hidden_WidgetFlag &&
             ~flags_Widget(d) & disabled_WidgetFlag) {
        if (contains_Widget(d, init_I2(ev->motion.x, ev->motion.y))) {
            rootData_.hover = d;
        }
    }
    if (filterEvent_Widget_(d, ev)) {
        /* Children may handle it first. Done in reverse so children drawn on top get to
           handle the events first. */
        iReverseForEach(ObjectList, i, d->children) {
            iWidget *child = as_Widget(i.object);
            if (child == rootData_.focus && isKeyboardEvent_(ev)) {
                continue; /* Already dispatched. */
            }
            if (isVisible_Widget(child) && child->flags & keepOnTop_WidgetFlag) {
                /* Already dispatched. */
                continue;
            }
            if (dispatchEvent_Widget(child, ev)) {
                return iTrue;
            }
        }
        if (class_Widget(d)->processEvent(d, ev)) {
            return iTrue;
        }
    }
    return iFalse;
}

iBool processEvent_Widget(iWidget *d, const SDL_Event *ev) {
    if (ev->type == SDL_KEYDOWN) {
        if (ev->key.keysym.sym == SDLK_TAB) {
            setFocus_Widget(findFocusable_Widget(focus_Widget(),
                                                 ev->key.keysym.mod & KMOD_SHIFT
                                                     ? backward_WidgetFocusDir
                                                     : forward_WidgetFocusDir));
            return iTrue;
        }
    }
    switch (ev->type) {
        case SDL_USEREVENT: {
            if (ev->user.code == command_UserEventCode && d->commandHandler &&
                d->commandHandler(d, ev->user.data1)) {
                return iTrue;
            }
            break;
        }
    }
    return iFalse;
}

void draw_Widget(const iWidget *d) {
    if (d->flags & hidden_WidgetFlag) return;
    if (d->bgColor >= 0) {
        iPaint p;
        init_Paint(&p);
        fillRect_Paint(&p, bounds_Widget(d), d->bgColor);
    }
    iConstForEach(ObjectList, i, d->children) {
        const iWidget *child = constAs_Widget(i.object);
        if (~child->flags & keepOnTop_WidgetFlag && ~child->flags & hidden_WidgetFlag) {
            class_Widget(child)->draw(child);
        }
    }
    /* Root draws the on-top widgets on top of everything else. */
    if (!d->parent) {
        iConstForEach(PtrSet, i, onTop_RootData_()) {
            draw_Widget(*i.value);
        }
    }
}

iAny *addChild_Widget(iWidget *d, iAnyObject *child) {
    return addChildPos_Widget(d, child, back_WidgetAddPos);
}

iAny *addChildPos_Widget(iWidget *d, iAnyObject *child, enum iWidgetAddPos addPos) {
    iAssert(child);
    iAssert(d != child);
    iWidget *widget = as_Widget(child);
    iAssert(!widget->parent);
    if (!d->children) {
        d->children = new_ObjectList();
    }
    if (addPos == back_WidgetAddPos) {
        pushBack_ObjectList(d->children, widget); /* ref */
    }
    else {
        pushFront_ObjectList(d->children, widget); /* ref */
    }
    widget->parent = d;
    return child;
}

iAny *addChildFlags_Widget(iWidget *d, iAnyObject *child, int childFlags) {
    setFlags_Widget(child, childFlags, iTrue);
    return addChild_Widget(d, child);
}

iAny *removeChild_Widget(iWidget *d, iAnyObject *child) {
    ref_Object(child);
    iBool found = iFalse;
    iForEach(ObjectList, i, d->children) {
        if (i.object == child) {
            remove_ObjectListIterator(&i);
            found = iTrue;
            break;
        }
    }
    iAssert(found);
    ((iWidget *) child)->parent = NULL;
    return child;
}

iAny *child_Widget(iWidget *d, size_t index) {
    iForEach(ObjectList, i, d->children) {
        if (index-- == 0) {
            return i.object;
        }
    }
    return NULL;
}

iAny *findChild_Widget(const iWidget *d, const char *id) {
    if (cmp_String(id_Widget(d), id) == 0) {
        return iConstCast(iAny *, d);
    }
    iConstForEach(ObjectList, i, d->children) {
        iAny *found = findChild_Widget(constAs_Widget(i.object), id);
        if (found) return found;
    }
    return NULL;
}

size_t childCount_Widget(const iWidget *d) {
    if (!d->children) return 0;
    return size_ObjectList(d->children);
}

iBool isVisible_Widget(const iWidget *d) {
    for (const iWidget *w = d; w; w = w->parent) {
        if (w->flags & hidden_WidgetFlag) {
            return iFalse;
        }
    }
    return iTrue;
}

iBool isDisabled_Widget(const iWidget *d) {
    for (const iWidget *w = d; w; w = w->parent) {
        if (w->flags & disabled_WidgetFlag) {
            return iTrue;
        }
    }
    return iFalse;
}

iBool isFocused_Widget(const iWidget *d) {
    return rootData_.focus == d;
}

iBool isHover_Widget(const iWidget *d) {
    return rootData_.hover == d;
}

iBool isSelected_Widget(const iWidget *d) {
    return (d->flags & selected_WidgetFlag) != 0;
}

iBool isCommand_Widget(const iWidget *d, const SDL_Event *ev, const char *cmd) {
    if (isCommand_UserEvent(ev, cmd)) {
        const iWidget *src = pointer_Command(command_UserEvent(ev));
        iAssert(!src || strstr(ev->user.data1, " ptr:"));
        return src == d || hasParent_Widget(src, d);
    }
    return iFalse;
}

iBool hasParent_Widget(const iWidget *d, const iWidget *someParent) {
    if (d) {
        for (const iWidget *w = d->parent; w; w = w->parent) {
            if (w == someParent) return iTrue;
        }
    }
    return iFalse;
}

void setFocus_Widget(iWidget *d) {
    if (rootData_.focus != d) {
        if (rootData_.focus) {
            iAssert(!contains_PtrSet(rootData_.pendingDestruction, rootData_.focus));
            postCommand_Widget(rootData_.focus, "focus.lost");
        }
        rootData_.focus = d;
        if (d) {
            iAssert(flags_Widget(d) & focusable_WidgetFlag);
            postCommand_Widget(d, "focus.gained");
        }
    }
}

iWidget *focus_Widget(void) {
    return rootData_.focus;
}

iWidget *hover_Widget(void) {
    return rootData_.hover;
}

static const iWidget *findFocusable_Widget_(const iWidget *d, const iWidget *startFrom,
                                            iBool *getNext, enum iWidgetFocusDir focusDir) {
    if (startFrom == d) {
        *getNext = iTrue;
        return NULL;
    }
    if ((d->flags & focusable_WidgetFlag) && isVisible_Widget(d) && !isDisabled_Widget(d) &&
        *getNext) {
        return d;
    }
    if (focusDir == forward_WidgetFocusDir) {
        iConstForEach(ObjectList, i, d->children) {
            const iWidget *found =
                findFocusable_Widget_(constAs_Widget(i.object), startFrom, getNext, focusDir);
            if (found) return found;
        }
    }
    else {
        iReverseConstForEach(ObjectList, i, d->children) {
            const iWidget *found =
                findFocusable_Widget_(constAs_Widget(i.object), startFrom, getNext, focusDir);
            if (found) return found;
        }
    }
    return NULL;
}

iAny *findFocusable_Widget(const iWidget *startFrom, enum iWidgetFocusDir focusDir) {
    iWidget *root = get_Window()->root;
    iBool getNext = (startFrom ? iFalse : iTrue);
    const iWidget *found = findFocusable_Widget_(root, startFrom, &getNext, focusDir);
    if (!found && startFrom) {
        getNext = iTrue;
        found = findFocusable_Widget_(root, NULL, &getNext, focusDir);
    }
    return iConstCast(iWidget *, found);
}

void setMouseGrab_Widget(iWidget *d) {
    if (rootData_.mouseGrab != d) {
        rootData_.mouseGrab = d;
        SDL_CaptureMouse(d != NULL);
    }
}

iWidget *mouseGrab_Widget(void) {
    return rootData_.mouseGrab;
}

void postCommand_Widget(const iWidget *d, const char *cmd, ...) {
    iString str;
    init_String(&str); {
        va_list args;
        va_start(args, cmd);
        vprintf_Block(&str.chars, cmd, args);
        va_end(args);
    }
    iBool isGlobal = iFalse;
    if (*cstr_String(&str) == '!')  {
        isGlobal = iTrue;
        remove_Block(&str.chars, 0, 1);
    }
    if (!isGlobal) {
        appendFormat_String(&str, " ptr:%p", d);
    }
    postCommandString_App(&str);
    deinit_String(&str);
}

iBeginDefineClass(Widget)
    .processEvent = processEvent_Widget,
    .draw         = draw_Widget,
iEndDefineClass(Widget)