~aleteoryx/muditaos

muditaos/module-gui/gui/widgets/BoxLayout.cpp -rw-r--r-- 20.5 KiB
a405cad6Aleteoryx trim readme 6 days ago
                                                                                
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
// Copyright (c) 2017-2024, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/blob/master/LICENSE.md

#include "BoxLayout.hpp"
#include "BoxLayoutSizeStore.hpp"
#include <InputEvent.hpp>
#include <Label.hpp>
#include "assert.h"

namespace gui
{
    BoxLayout::BoxLayout(Item *parent, const uint32_t &x, const uint32_t &y, const uint32_t &w, const uint32_t &h)
        : Rect(parent, x, y, w, h)
    {
        alignment = gui::Alignment(Alignment::Horizontal::None, Alignment::Vertical::None);
        sizeStore = std::make_unique<BoxLayoutSizeStore>();
    }

    BoxLayout::BoxLayout() : BoxLayout(nullptr, 0, 0, 0, 0)
    {}

    bool BoxLayout::onInput(const InputEvent &inputEvent)
    {
        if (inputCallback && inputCallback(*this, inputEvent)) {
            return true;
        }
        if (focusItem && focusItem->onInput(inputEvent)) {
            return true;
        }
        if (handleNavigation(inputEvent)) {
            return true;
        }
        if (borderCallback && isInputNavigation(inputEvent) && borderCallback(inputEvent)) {
            outOfDrawAreaItems.clear();
            return true;
        }
        // let item logic rule it
        return false;
    }

    bool BoxLayout::onFocus(bool state)
    {
        if (state) {
            this->setVisible(state);
        }
        else {
            this->setFocusItem(nullptr);
        }

        this->setNavigation();
        if (this->focusChangedCallback && state != focus) {
            this->focusChangedCallback(*this);
        }
        return true;
    }

    void BoxLayout::resizeItems()
    {}

    void BoxLayout::setAlignment(const Alignment &value)
    {
        if (alignment != value) {
            alignment = value;
            resizeItems();
        }
    }

    void BoxLayout::addWidget(Item *item)
    {
        Rect::addWidget(item);
        resizeItems();
    }

    template <Axis axis>
    void BoxLayout::addWidget(Item *item)
    {
        Rect::addWidget(item);
        resizeItems<axis>();
    }

    bool BoxLayout::removeWidget(Item *item)
    {
        const auto ret = Rect::removeWidget(item);

        outOfDrawAreaItems.remove(item);
        resizeItems();

        return ret;
    }

    bool BoxLayout::erase(Item *item)
    {
        auto ret = Item::erase(item);

        outOfDrawAreaItems.remove(item);
        resizeItems();

        return ret;
    }

    void BoxLayout::erase()
    {
        Item::erase();
    }

    bool BoxLayout::empty() const noexcept
    {
        return children.empty();
    }

    void BoxLayout::setVisible(bool value, bool previous)
    {
        visible = value; // maybe use parent setVisible(...)? would be better but which one?
        if (value) {
            resizeItems();         // move items in box in proper places
            setNavigation();       // set navigation through kids -> TODO handle out of last/first to parent
            if (children.size()) { // set first visible kid as focused item - TODO should check for actionItems too...
                /// this if back / front is crappy :|
                if (previous) {
                    for (auto el = children.rbegin(); el != children.rend(); ++el) {
                        if ((*el)->isActive()) {
                            setFocusItem(*el);
                            break;
                        }
                    }
                }
                else {
                    for (auto &el : children) {
                        if (el->isActive()) {
                            setFocusItem(el);
                            break;
                        }
                    }
                }
            }
        }
    }

    void BoxLayout::setVisible(bool value)
    {
        setVisible(value, false);
    }

    unsigned int BoxLayout::getVisibleChildrenCount()
    {
        assert(children.size() >= outOfDrawAreaItems.size());
        return children.size() - outOfDrawAreaItems.size();
    }

    void BoxLayout::setReverseOrder(bool value)
    {
        reverseOrder = value;
    }

    bool BoxLayout::getReverseOrder()
    {
        return reverseOrder;
    }

    Length BoxLayout::getPrimarySize()
    {
        if (type == ItemType::HBOX) {
            return getSize(Axis::X);
        }
        else if (type == ItemType::VBOX) {
            return getSize(Axis::Y);
        }

        return 0;
    }

    Length BoxLayout::getPrimarySizeLeft()
    {
        if (type == ItemType::HBOX) {
            return sizeLeft<Axis::X>(this, Area::Normal);
        }
        else if (type == ItemType::VBOX) {
            return sizeLeft<Axis::Y>(this, Area::Normal);
        }

        return 0;
    }

    void BoxLayout::addToOutOfDrawAreaList(Item *it)
    {
        if (it->visible) {
            outOfDrawAreaItems.push_back(it);
            it->visible = false;
        }
    }

    void BoxLayout::addFromOutOfDrawAreaList()
    {
        if (!children.empty()) {
            for (auto it : outOfDrawAreaItems) {
                it->setVisible(true);
                it->setFocusItem(nullptr);
            }
        }

        outOfDrawAreaItems.clear();
        resizeItems();
    }

    // space left disposition `first is better` tactics
    // there could be other i.e. socialism: each element take in equal part up to it's max size
    // not needed now == not implemented
    template <Axis axis>
    void BoxLayout::resizeItems()
    {
        Position startingPosition = reverseOrder ? this->area().size(axis) : 0;
        Position leftPosition     = this->getSize(axis);
        Length toSplit            = sizeLeft<axis>(this);

        for (auto &el : children) {

            if (!el->visible) {
                continue;
            }

            auto axisItemPosition       = 0;
            auto orthogonalItemPosition = 0;
            auto axisItemSize           = 0;
            auto calculatedResize       = 0;
            auto orthogonalItemSize     = 0;

            // 1. Calculate element axis resize.
            calculatedResize = calculateElemResize<axis>(el, toSplit);

            // 2. Check if new size in axis can be applied and set it or use element minimal size in axis.
            axisItemSize = calculateElemAxisSize<axis>(el, calculatedResize, toSplit);

            // 3. Calculate orthogonal axis size.
            orthogonalItemSize = calculateElemOrtAxisSize<axis>(el);

            // 4. Calculate element position in axis and apply in axis alignment.
            axisItemPosition = calculateElemAxisPosition<axis>(el, axisItemSize, startingPosition, leftPosition);

            // 5. Calculate element orthogonal axis position based on Layout alignment or on element alignment.
            orthogonalItemPosition = calculateElemOrtAxisPosition<axis>(el, orthogonalItemSize);

            // 6. If element still visible (not added to outOfDrawAreaList) set it Area with calculated values.
            if (el->visible) {
                el->setAreaInAxis(axis, axisItemPosition, orthogonalItemPosition, axisItemSize, orthogonalItemSize);
            }
        }

        Rect::updateDrawArea();
    }

    template <Axis axis>
    Length BoxLayout::calculateElemResize(Item *el, Length &toSplit)
    {
        auto grantedSize        = sizeStore->get(el);
        Length calculatedResize = 0;

        // Check if element has stored requested size in axis.
        if (!grantedSize.isZero()) {
            calculatedResize = grantedSize.get(axis) < el->area(Area::Min).size(axis)
                                   ? 0
                                   : grantedSize.get(axis) - el->area(Area::Min).size(axis);

            // If requested size bigger than left size in layout push out last visible element in layout into
            // outOfDrawAreaList.
            if (sizeLeft<axis>(this) < calculatedResize) {
                addToOutOfDrawAreaList(getLastVisibleElement());
                toSplit = sizeLeft<axis>(this);
            }
        }
        else {
            // If not calculate possible size in axis from min-max difference.
            calculatedResize = el->area(Area::Max).size(axis) < el->area(Area::Min).size(axis)
                                   ? 0
                                   : el->area(Area::Max).size(axis) - el->area(Area::Min).size(axis);
        }

        return calculatedResize;
    }

    template <Axis axis>
    Length BoxLayout::calculateElemAxisSize(Item *el, Length calculatedResize, Length &toSplit)
    {
        Length axisItemSize = 0;

        if (toSplit > 0 && calculatedResize > 0) {
            axisItemSize = el->area(Area::Min).size(axis) + std::min(calculatedResize, toSplit);
            toSplit -= std::min(calculatedResize, toSplit);
        }
        else {
            axisItemSize = el->area(Area::Min).size(axis);
        }

        return axisItemSize;
    }

    template <Axis axis>
    Length BoxLayout::calculateElemOrtAxisSize(Item *el)
    {
        // Get maximum size that element in orthogonal axis can occupy in current layout size.
        const Length maxOrthogonalItemInParentSize =
            static_cast<Position>(this->area(Area::Normal).size(orthogonal(axis))) <=
                    el->getMargins().getSumInAxis(orthogonal(axis))
                ? 0
                : this->area(Area::Normal).size(orthogonal(axis)) - el->getMargins().getSumInAxis(orthogonal(axis));

        // Get maximum size of element in orthogonal axis based on its min-max.
        const Length maxOrthogonalItemSize =
            el->area(Area::Max).size(orthogonal(axis)) > el->area(Area::Min).size(orthogonal(axis))
                ? el->area(Area::Max).size(orthogonal(axis))
                : el->area(Area::Min).size(orthogonal(axis));

        // Return minimal from both max sizes.
        return std::min(maxOrthogonalItemInParentSize, maxOrthogonalItemSize);
    }

    template <Axis axis>
    Position BoxLayout::calculateElemAxisPosition(Item *el,
                                                  Length axisItemSize,
                                                  Position &startingPosition,
                                                  Position &leftPosition)
    {
        auto axisItemPosition = 0;

        // Check if elements in axis can fit with margins in layout free space.
        if (static_cast<Position>(axisItemSize + el->getMargins().getSumInAxis(axis)) <= leftPosition) {

            if (reverseOrder) {
                startingPosition -= el->getMargins().getMarginInAxis(axis, MarginInAxis::Second);
                startingPosition -= axisItemSize;
                axisItemPosition = startingPosition;
                startingPosition -= el->getMargins().getMarginInAxis(axis, MarginInAxis::First);
            }

            if (!reverseOrder) {
                startingPosition += el->getMargins().getMarginInAxis(axis, MarginInAxis::First);
                axisItemPosition = startingPosition;
                startingPosition += axisItemSize;
                startingPosition += el->getMargins().getMarginInAxis(axis, MarginInAxis::Second);
            }

            leftPosition -= axisItemSize + el->getMargins().getSumInAxis(axis);

            // Recalculate element axis position if axis alignment provided.
            axisItemPosition = getAxisAlignmentValue<axis>(axisItemPosition, axisItemSize, el);
        }
        else {
            // If not add it to outOfDrawAreaList.
            addToOutOfDrawAreaList(el);
        }

        return axisItemPosition;
    }

    template <Axis axis>
    Position BoxLayout::calculateElemOrtAxisPosition(Item *el, Length orthogonalItemSize)
    {
        return el->getAxisAlignmentValue(orthogonal(axis), orthogonalItemSize);
    }

    template <Axis axis>
    Position BoxLayout::getAxisAlignmentValue(Position calcPos, Length calcSize, Item *el)
    {
        auto offset = sizeLeftWithoutElem<axis>(this, el, Area::Normal) <= calcSize
                          ? 0
                          : sizeLeftWithoutElem<axis>(this, el, Area::Normal) - calcSize;

        switch (getAlignment(axis).vertical) {
        case gui::Alignment::Vertical::Top:
            if (reverseOrder) {
                return calcPos + el->getMargins().getSumInAxis(axis) - offset;
            }
            break;
        case gui::Alignment::Vertical::Center:
            if (reverseOrder) {
                return calcPos - ((offset - el->getMargins().getSumInAxis(axis)) / 2);
            }
            else {
                return calcPos + ((offset - el->getMargins().getSumInAxis(axis)) / 2);
            }
            break;
        case gui::Alignment::Vertical::Bottom:
            if (!reverseOrder) {
                return calcPos - el->getMargins().getSumInAxis(axis) + offset;
            }
            break;
        default:
            break;
        }

        switch (getAlignment(axis).horizontal) {
        case gui::Alignment::Horizontal::Left:
            if (reverseOrder) {
                return calcPos + el->getMargins().getSumInAxis(axis) - offset;
            }
            break;
        case gui::Alignment::Horizontal::Center:
            if (reverseOrder) {
                return calcPos - ((offset - el->getMargins().getSumInAxis(axis)) / 2);
            }
            else {
                return calcPos + ((offset - el->getMargins().getSumInAxis(axis)) / 2);
            }
            break;
        case gui::Alignment::Horizontal::Right:
            if (!reverseOrder) {
                return calcPos - el->getMargins().getSumInAxis(axis) + offset;
            }
            break;
        default:
            break;
        }

        return calcPos;
    }

    std::list<Item *>::iterator BoxLayout::nextNavigationItem(std::list<Item *>::iterator from)
    {
        return std::find_if(from, this->children.end(), [](const auto &el) { return el->isActive(); });
    }

    std::list<Item *>::iterator BoxLayout::getNavigationFocusedItem()
    {
        return std::find(this->children.begin(), this->children.end(), this->getFocusItem());
    }

    void BoxLayout::setNavigation()
    {
        auto previous = nextNavigationItem(children.begin()), next = children.end();
        if (type == ItemType::VBOX) {
            while ((previous != children.end()) &&
                   ((next = nextNavigationItem(std::next(previous))) != std::end(children))) {
                (*previous)->setNavigationItem(reverseOrder ? NavigationDirection::UP : NavigationDirection::DOWN,
                                               *next);
                (*next)->setNavigationItem(reverseOrder ? NavigationDirection::DOWN : NavigationDirection::UP,
                                           *previous);
                previous = next;
            }

            if (previous != children.end()) {
                if ((*previous) != nullptr) {
                    (*previous)->setNavigationItem(reverseOrder ? NavigationDirection::UP : NavigationDirection::DOWN,
                                                   nullptr);
                }
            }
        }

        if (type == ItemType::HBOX) {
            while ((previous != children.end()) &&
                   ((next = nextNavigationItem(std::next(previous))) != std::end(children))) {
                (*previous)->setNavigationItem(reverseOrder ? NavigationDirection::LEFT : NavigationDirection::RIGHT,
                                               *next);
                (*next)->setNavigationItem(reverseOrder ? NavigationDirection::RIGHT : NavigationDirection::LEFT,
                                           *previous);
                previous = next;
            }

            if (previous != children.end()) {
                if ((*previous) != nullptr) {
                    (*previous)->setNavigationItem(
                        reverseOrder ? NavigationDirection::LEFT : NavigationDirection::RIGHT, nullptr);
                }
            }
        }
    }

    template <Axis axis>
    Size BoxLayout::handleRequestResize(const Item *child, Length request_w, Length request_h)
    {
        if (parent != nullptr) {
            auto [w, h] = requestSize(request_w, request_h);
            request_w   = std::min(w, static_cast<Length>(request_w));
            request_h   = std::min(h, static_cast<Length>(request_h));
        }

        auto el = std::find(children.begin(), children.end(), child);
        if (el == std::end(children)) {
            return {0, 0};
        }

        Size granted = {std::min((*el)->area(Area::Max).w, request_w), std::min((*el)->area(Area::Max).h, request_h)};

        // Currently not used option for Layouts that don't push out objects.
        if (!sizeStore->getReleaseSpaceFlag()) {
            if ((granted.get(axis) + (*el)->getMargins().getSumInAxis(axis)) >=
                sizeLeftWithoutElem<axis>(this, *el, Area::Min)) {

                granted = Size((*el)->area(Area::Normal).w, (*el)->area(Area::Normal).h);
            }
        }

        // If granted size decreased check if pushed out elements can fit
        if (sizeStore->isSizeSmaller(*el, granted, axis)) {
            addFromOutOfDrawAreaList();
        }

        sizeStore->store(*el, granted);
        resizeItems(); // vs mark dirty
        setNavigation();

        if (parentOnRequestedResizeCallback != nullptr) {
            parentOnRequestedResizeCallback();
        }

        return granted;
    }

    bool BoxLayout::setFocusOnElement(unsigned int elementNumber)
    {
        unsigned int i = 0;
        bool success   = false;

        for (auto child : children) {
            if (child->isActive()) {

                if (elementNumber == i) {
                    child->setFocus(true);
                    focusItem = child;
                    success   = true;
                }
                else {
                    child->setFocus(false);
                }
                ++i;
            }
        }

        return success;
    }

    void BoxLayout::setFocusOnLastElement()
    {
        auto last = true;
        for (auto child = children.rbegin(); child != children.rend(); child++) {

            if ((*child)->isActive() && last) {
                (*child)->setFocus(true);
                focusItem = (*child);
                last      = false;
            }
            else {
                (*child)->setFocus(false);
            }
        }
    }

    unsigned int BoxLayout::getFocusItemIndex() const
    {
        auto index     = 0;
        auto focusItem = getFocusItem();

        for (auto child : children) {
            if (child == focusItem) {
                break;
            }
            if (child->isActive()) {
                index++;
            }
        }
        return index;
    }

    Item *BoxLayout::getLastVisibleElement()
    {
        for (auto child = children.rbegin(); child != children.rend(); child++) {
            if ((*child)->visible) {
                return (*child);
            }
        }
        return nullptr;
    }

    bool BoxLayout::onDimensionChanged(const BoundingBox &oldDim, const BoundingBox &newDim)
    {
        addFromOutOfDrawAreaList();
        resizeItems();
        setNavigation();

        return Item::onDimensionChanged(oldDim, newDim);
    }

    void BoxLayout::handleContentChanged()
    {
        // Check if there is parent and it is Layout
        if (parent != nullptr && (dynamic_cast<gui::BoxLayout *>(parent) != nullptr)) {
            // If so invalidate content and request Content change to parent
            contentChanged = true;
            Item::informContentChanged();
        }
        else {
            resizeItems();
        }
    }

    HBox::HBox() : BoxLayout()
    {
        type = ItemType::HBOX;
    }

    HBox::HBox(Item *parent, const uint32_t &x, const uint32_t &y, const uint32_t &w, const uint32_t &h)
        : BoxLayout(parent, x, y, w, h)
    {
        type = ItemType::HBOX;
    }

    void HBox::resizeItems()
    {
        BoxLayout::resizeItems<Axis::X>();
    }

    void HBox::addWidget(Item *item)
    {
        BoxLayout::addWidget<Axis::X>(item);
    }

    Size HBox::handleRequestResize(const Item *child, Length request_w, Length request_h)
    {
        return BoxLayout::handleRequestResize<Axis::X>(child, request_w, request_h);
    }

    VBox::VBox() : BoxLayout()
    {
        type = ItemType::VBOX;
    }

    VBox::VBox(Item *parent, const uint32_t &x, const uint32_t &y, const uint32_t &w, const uint32_t &h)
        : BoxLayout(parent, x, y, w, h)
    {
        type = ItemType::VBOX;
    }

    void VBox::resizeItems()
    {
        BoxLayout::resizeItems<Axis::Y>();
    }

    void VBox::addWidget(Item *item)
    {
        BoxLayout::addWidget<Axis::Y>(item);
    }

    Size VBox::handleRequestResize(const Item *child, Length request_w, Length request_h)
    {
        return BoxLayout::handleRequestResize<Axis::Y>(child, request_w, request_h);
    }

} /* namespace gui */