ZenitUI
Retained-mode C++20 UI framework
Loading...
Searching...
No Matches
Layout.hpp
Go to the documentation of this file.
1#pragma once
2
36
37#include "Common.hpp"
38
39#include "Style.hpp"
40#include "Theme.hpp"
41#include "UIContext.hpp"
42#include "AnimPrimitives.hpp"
43#include "Logger.hpp"
44#include "ScrollState.hpp"
45#include "StyleResolver.hpp"
46#include "AnimationPlayer.hpp"
47#include "InputController.hpp"
48#include "ScrollController.hpp"
49#include "UIEnums.hpp"
50#include "Media.hpp"
51#include "SmallVector.hpp"
52
53namespace ZenitUI
54{
58
67 struct NodeState
68 {
69 uint32_t hovered : 1;
70 uint32_t pressed : 1;
71 uint32_t focused : 1;
72 uint32_t checked : 1;
73 };
74
86 {
87 uint32_t interactive : 1;
88 uint32_t blocksRaycast : 1;
89 uint32_t enabled : 1;
90 uint32_t visible : 1;
91 uint32_t focusable : 1;
92 uint32_t focusScope : 1;
93 uint32_t keyboardActivates : 1;
94 uint32_t updateWhenDisabled : 1;
95 uint32_t portal : 1;
96 uint32_t passThrough : 1;
97 uint32_t draggable : 1;
98 uint32_t droppable : 1;
99 };
100
109 {
110 uint32_t subtreeDirty : 1;
111 uint32_t styleInitialized : 1;
112 uint32_t pendingTransition : 1;
114 uint32_t wantsRemoval : 1;
115 uint32_t pressedInChain : 1;
116 uint32_t hadRemovedChildren : 1;
117 uint32_t layoutDirty : 1;
118 };
119
128 {
129 std::function<void(DragPayload &)> onDragStart;
130 std::function<void()> onDragEnd;
131 std::function<void()> onDragCancel;
132
133 std::function<bool(const DragPayload &)> canAcceptDrop;
134 std::function<void(const DragPayload &)> onDrop;
135 std::function<void()> onDragEnter;
136 std::function<void()> onDragLeave;
137
138 std::function<std::shared_ptr<Layout>(const DragPayload &)> onGhostFactory;
139 };
140
153 class Layout : public std::enable_shared_from_this<Layout>
154 {
155 public:
164 {
165 config.interactive = 1;
166 config.enabled = 1;
167 config.visible = 1;
168 internal_.subtreeDirty = 1;
169 internal_.pendingTransition = 1;
170 }
171
183 virtual ~Layout()
184 {
185 if (ctx_)
187 }
188
195 template <typename T = Layout>
196 std::shared_ptr<T> as()
197 {
198 return std::static_pointer_cast<T>(shared_from_this());
199 }
200
201 // Subsystems need write access to private members for performance.
202 friend struct StyleResolver;
203 friend struct AnimationPlayer;
204 friend struct InputController;
205 friend struct ScrollController;
206
207 // ---- Class / id / tag management ----
208
217 void addClass(const std::string &className);
218
225 void removeClass(const std::string &className);
226
229
237 void setStyleTag(const std::string &t);
238
240 bool hasClass(const std::string &className) const;
241
243 bool hasId(const std::string &targetId) const
244 {
245 return !targetId.empty() && nodeId == targetId;
246 }
247
249 void setId(const std::string &node_id);
251 void setRef(const std::string &r)
252 {
253 ref = r;
254 }
255
256 const std::string &getStyleTag() const { return styleTag; }
257 const std::vector<std::string> &getStyleClasses() const { return styleClasses; }
258
260 void setSize(Value w, Value h)
261 {
262 auto &ib = style_.ensureInlineBase();
263 ib.width = w;
264 ib.height = h;
265 internal_.pendingTransition = 1;
266 }
267
268 // ---- Fluent builder shortcuts ----
269
271 std::shared_ptr<Layout> cls(const std::string &className)
272 {
273 addClass(className);
274 return shared_from_this();
275 }
276
277 std::shared_ptr<Layout> id(const std::string &node_id)
278 {
279 setId(node_id);
280 return shared_from_this();
281 }
282
283 std::shared_ptr<Layout> size(Value w, Value h)
284 {
285 setSize(w, h);
286 return shared_from_this();
287 }
288
289 std::shared_ptr<Layout> with(std::shared_ptr<Layout> child)
290 {
291 addChild(std::move(child));
292 return shared_from_this();
293 }
294
302 void addChild(std::shared_ptr<Layout> child)
303 {
304 if (!child)
305 return;
306
307 if (weak_from_this().expired())
308 {
309 logWarn("Layout", "", 0, 0,
310 "addChild called on a node not handled with shared_ptr."
311 "Use X::create() and put this logic in onBuild().");
312 return;
313 }
314
315 if (child->ctx_)
316 {
317 if (child->ctx_ == ctx_)
318 ctx_->unregisterRoot(child.get());
319 else
320 child->detachContext();
321 }
322 child->parent = weak_from_this();
323 if (ctx_ && child->ctx_ != ctx_)
324 child->attachContext(ctx_);
325 children.push_back(std::move(child));
326 internal_.pendingTransition = 1;
327 if (theme().hasSiblingCombinators)
328 invalidateChildrenForSiblingRules();
329 }
330
334 void insertChildBefore(const Layout *anchor, std::shared_ptr<Layout> child);
335
341 bool moveChildBefore(const Layout *anchor, const Layout *child);
342
347 bool removeChild(const Layout *child);
348
356 virtual Layout *contentTarget() { return this; }
357
365 void removeFromParent() { internal_.wantsRemoval = 1; }
366
374 virtual void removeAllChildren();
375
383 void retainObject(std::shared_ptr<void> obj)
384 {
385 if (!obj)
386 return;
387 if (!retainedObjects_)
388 retainedObjects_ = std::make_unique<std::vector<std::shared_ptr<void>>>();
389 retainedObjects_->push_back(std::move(obj));
390 }
391
392 std::shared_ptr<Layout> getParent() const { return parent.lock(); }
393 bool hasParent() const { return !parent.expired(); }
394
401 bool isAncestorOf(const Layout *other) const
402 {
403 if (!other)
404 return false;
405 auto p = other->getParent();
406 while (p)
407 {
408 if (p.get() == this)
409 return true;
410 p = p->getParent();
411 }
412 return false;
413 }
414
415 // ---- Configuration setters ----
416
417 void setInteractive(bool interactive) { config.interactive = interactive ? 1 : 0; }
418 void setBlocksRaycast(bool blocks) { config.blocksRaycast = blocks ? 1 : 0; }
419
428 void setEnabled(bool e);
429 bool getEnabled() const { return config.enabled != 0; }
430
438 void setVisible(bool v);
439 bool isVisible() const { return config.visible != 0; }
440
447 void setChecked(bool c)
448 {
449 if ((state.checked != 0) == c)
450 return;
451 state.checked = c ? 1 : 0;
452 internal_.pendingTransition = 1;
454 if (theme().hasSiblingCombinators)
455 invalidateFollowingSiblingsCache();
457 }
458 bool getChecked() const { return state.checked != 0; }
459
460 bool isHoveredState() const { return state.hovered != 0; }
461 bool isPressedState() const { return state.pressed != 0; }
462 bool isFocusedState() const { return state.focused != 0; }
463 bool isDisabledState() const { return config.enabled == 0; }
464 bool isCheckedState() const { return state.checked != 0; }
465
466 void setUpdateWhenDisabled(bool v) { config.updateWhenDisabled = v ? 1 : 0; }
467 bool getUpdateWhenDisabled() const { return config.updateWhenDisabled != 0; }
468
477 {
478 internal_.pendingTransition = 1;
479 style_.restartTransition();
480 }
481
482 void setFocusable(bool f) { config.focusable = f ? 1 : 0; }
483 bool isFocusable() const
484 {
485 return config.focusable != 0 && config.enabled != 0 && config.visible != 0;
486 }
487 bool getFocused() const { return state.focused != 0; }
488
489 void setFocusScope(bool s) { config.focusScope = s ? 1 : 0; }
490 bool isFocusScope() const { return config.focusScope != 0; }
491
493 void notifyDescendantFocused(Layout *descendant) { onDescendantFocused(descendant); }
494
496 bool isStackingContext() const
497 {
498 return style_.currentStyle.position != Position::Static && !style_.currentStyle.zIndex.isAuto;
499 }
500
501 int getZIndex() const
502 {
503 return style_.currentStyle.zIndex.isAuto ? 0 : style_.currentStyle.zIndex.value;
504 }
505
507 bool isScrollContainer() const
508 {
509 return style_.currentStyle.overflowX != Overflow::Visible || style_.currentStyle.overflowY != Overflow::Visible;
510 }
511
512 // ---- Scroll API ----
513
521 void scrollTo(float x, float y)
522 {
523 if (!isScrollContainer())
524 return;
525 scroll_.state.offset.x = std::max(0.0f, x);
526 scroll_.state.offset.y = std::max(0.0f, y);
527 scroll_.state.clamp();
528 }
529 void scrollToX(float x) { scrollTo(x, scroll_.state.offset.y); }
530 void scrollToY(float y) { scrollTo(scroll_.state.offset.x, y); }
531 void scrollToTop()
532 {
533 if (isScrollContainer())
534 scrollToY(0.0f);
535 }
536 void scrollToBottom()
537 {
538 if (isScrollContainer())
539 scrollToY(scroll_.state.maxScroll.y);
540 }
541 void scrollToLeft()
542 {
543 if (isScrollContainer())
544 scrollToX(0.0f);
545 }
546 void scrollToRight()
547 {
548 if (isScrollContainer())
549 scrollToX(scroll_.state.maxScroll.x);
550 }
551
558 bool scrollIntoView(float margin = 0.0f);
559
570 bool scrollIntoView(const Rect &subRect, float margin = 0.0f);
571
572 float getScrollX() const { return scroll_.state.offset.x; }
573 float getScrollY() const { return scroll_.state.offset.y; }
574 float getMaxScrollX() const { return scroll_.state.maxScroll.x; }
575 float getMaxScrollY() const { return scroll_.state.maxScroll.y; }
576
577 // ---- Portal / capture / keyboard ----
578
586 void setPortal(bool p)
587 {
588 config.portal = p ? 1 : 0;
589 internal_.pendingTransition = 1;
590 }
591 bool isPortal() const { return config.portal != 0; }
592
593 void setPassThrough(bool p) { config.passThrough = p ? 1 : 0; }
594 bool getPassThrough() const { return config.passThrough != 0; }
595
596 void setDraggable(bool d) { config.draggable = d ? 1 : 0; }
597 bool isDraggable() const { return config.draggable != 0; }
598
599 void setDroppable(bool d) { config.droppable = d ? 1 : 0; }
600 bool isDroppable() const { return config.droppable != 0; }
601
604 {
605 if (!dragHandlers_)
606 dragHandlers_ = std::make_unique<DragHandlers>();
607 return *dragHandlers_;
608 }
609
611 const DragHandlers *dragHandlers() const noexcept { return dragHandlers_.get(); }
612
621 {
622 if (auto *ctx = context())
623 ctx->pointerCapture = shared_from_this();
624 }
625
627 {
628 if (auto *ctx = context())
629 {
630 auto sp = ctx->pointerCapture.lock();
631 if (sp.get() == this)
632 ctx->pointerCapture.reset();
633 }
634 }
635
636 bool hasPointerCapture() const
637 {
638 auto *ctx = context();
639 return ctx && ctx->pointerCapture.lock().get() == this;
640 }
641
642 void setKeyboardActivates(bool v) { config.keyboardActivates = v ? 1 : 0; }
643 bool getKeyboardActivates() const { return config.keyboardActivates != 0; }
644
645 LayoutType getLayoutType() const { return type; }
646
647 LayoutType getEffectiveLayoutType() const
648 {
649 if (type == LayoutType::Grid ||
650 !style_.currentStyle.gridTemplateColumns.empty() ||
651 !style_.currentStyle.gridTemplateRows.empty())
652 return LayoutType::Grid;
653 if (style_.currentStyle.direction == Direction::Row)
655 if (style_.currentStyle.direction == Direction::Column)
657 return type;
658 }
659
660 // ---- Asset convenience helpers ----
661
667 inline FontHandle resolveFont(const ComputedStyle &style, FontHandle fallback = {}) const
668 {
669 auto *ctx = context();
670 if (!ctx)
671 return fallback;
672 return ctx->textEngine.resolveFont(style.font, fallback);
673 }
674
678 {
679 TextureHandle tex;
680 NineSlice slice;
681 bool valid() const { return tex.valid(); }
682 };
683
689 const ComputedStyle &style,
690 TextureHandle fallbackTex = {},
691 NineSlice fallbackSlice = {0, 0, 0, 0})
692 {
693 if (!style.backgroundTexture.name.empty())
694 {
695 auto *ctx = context();
696 auto *a = ctx ? ctx->assets : nullptr;
697 if (a)
698 {
699 TextureHandle h = a->getTexture(style.backgroundTexture.name);
700 if (h.valid())
701 {
702 const auto &tr = style.backgroundTexture;
703 return {h, NineSlice{tr.left, tr.top, tr.right, tr.bottom}};
704 }
705 }
706 }
707 return {fallbackTex, fallbackSlice};
708 }
709
710 // ---- Inline style setters ----
711
713 void setInlineBase(const Style &s)
714 {
715 style_.ensureInlineBase().overlay(s);
716 internal_.pendingTransition = 1;
717 }
718
725 {
726 internal_.pendingTransition = 1;
727 return style_.ensureInlineBase();
728 }
729
736 {
737 internal_.pendingTransition = 1;
738 return style_.ensureInlineDefaults();
739 }
740
741 // ---- Animation shortcuts ----
742
750 void addAnimation(const std::string &name, std::shared_ptr<UIAnimation> anim)
751 {
752 anim_.addImperative(name, std::move(anim));
753 }
754
759 void playAnimation(const std::string &name, bool playReverse = false)
760 {
761 anim_.play(*this, name, playReverse);
762 }
763
765 {
766 return anim_.hasActive(*this);
767 }
768
776 void addCssAnimation(const std::string &name)
777 {
778 auto *ctx = context();
779 anim_.addCss(name, ctx ? ctx->time : 0.0);
780 }
781
782 void stopCssAnimation(const std::string &name)
783 {
784 anim_.stopCss(name);
785 }
786
787 // ---- Virtual pass entry points ----
788
800 virtual Vec2 measure(float parent_w, float parent_h);
801
809 virtual void arrange(Rect space);
810
825 virtual void update(float dt, bool ancestorBlocked = false, bool scrolling = false);
826
838 virtual void draw(float parentOpacity = 1.0f);
839
855 bool ancestorBlocked = false,
856 const Rect *clipLocal = nullptr);
857
867 const DragPayload &payload,
868 const Layout *excludeSource,
869 const Layout *excludeGhost,
870 const Rect *clipLocal = nullptr);
871
879 void updateTree(float dt);
880
882 void runFrame(float dt);
883
886
887 // ---- Accessors ----
888
889 Rect getRect() const { return rect; }
890 Vec2 getMeasuredSize() const { return measuredSize; }
891 const ComputedStyle &getStyle() const { return style_.currentStyle; }
893 std::vector<const ThemeRule *> getMatchingRules() const;
894
896 UIContext *contextPtr() const { return ctx_; }
897
899 UIContext *context() const { return ctx_; }
900
903
906
908 Vec2 viewportSize() const { return ctx_ ? ctx_->viewport : Vec2{0.0f, 0.0f}; }
909
911 const Theme &theme() const
912 {
913 static const Theme kEmptyTheme{};
914 return ctx_ ? ctx_->theme : kEmptyTheme;
915 }
916
917 // ---- Public callback hooks ----
918
919 std::function<void()> onHoverEnter, onHoverExit, onPress, onRelease, onClick;
920
922 std::function<void()> onRightClick;
923
924 std::function<void(MouseButton)> onButtonPress;
925 std::function<void(MouseButton)> onButtonRelease;
926 std::function<void(MouseButton)> onButtonClick;
927
934 std::function<void()> onAnimationsFinished;
935
937 std::vector<std::shared_ptr<Layout>> children;
938
940 std::string nodeId;
941
943 std::string ref;
944
951 void setBackgroundTexture(TextureHandle tex, NineSlice np = {0, 0, 0, 0})
952 {
953 bgTexture = tex;
954 bgPatchInfo = np;
956 }
957
965 {
966 customEffect = shader;
967 hasShader = true;
969 }
970
980 {
981 if (layerCache_)
982 layerCache_->dirty = true;
983 auto p = parent.lock();
984 while (p)
985 {
986 if (p->layerCache_)
987 p->layerCache_->dirty = true;
988 p = p->parent.lock();
989 }
990 }
991
998
1004
1005 protected:
1007 // ---- Internal state ----
1008
1009 LayoutType type;
1010 bool hasShader{false};
1011 uint32_t lastViewportGen_{0};
1012 uint32_t relevantThemeVersion_{~0u};
1013 Rect rect{0, 0, 0, 0};
1014 Vec2 measuredSize{0, 0};
1015 float lastMeasureW_{-1.0f};
1016 float lastMeasureH_{-1.0f};
1017 float forcedMeasureW_{-1.0f};
1018 ScrollController scroll_;
1019
1020 NodeState state{};
1021 NodeConfig config{};
1022 NodeInternal internal_{};
1023 std::string styleTag;
1024 std::vector<std::string> styleClasses;
1025 StyleResolver style_;
1026 std::vector<std::pair<SimpleSelector::Kind, std::string_view>> relevantSymbols_;
1027
1028#if defined(_MSC_VER)
1029 [[msvc::no_unique_address]] InputController input_;
1030#else
1031 [[no_unique_address]] InputController input_;
1032#endif
1033
1034 TextureHandle bgTexture;
1035 NineSlice bgPatchInfo;
1036 EffectHandle customEffect;
1037 std::unique_ptr<std::string> effectName_;
1038 EffectHandle currentEffect_;
1039
1040 AnimationPlayer anim_;
1041
1042 std::weak_ptr<Layout> parent;
1043
1050 void markInheritanceDirty()
1051 {
1052 style_.invalidateCache();
1053 internal_.pendingTransition = 1;
1054 internal_.subtreeDirty = 1;
1055 for (auto &c : children)
1056 c->markInheritanceDirty();
1057 }
1058
1059 void markLayoutDirtyUpward()
1060 {
1061 internal_.layoutDirty = 1;
1062 internal_.subtreeDirty = 1;
1063 if (layerCache_)
1064 layerCache_->dirty = true;
1065 auto p = parent.lock();
1066 while (p)
1067 {
1068 p->internal_.layoutDirty = 1;
1069 p->internal_.subtreeDirty = 1;
1070 if (p->layerCache_)
1071 p->layerCache_->dirty = true;
1072 p = p->parent.lock();
1073 }
1074 }
1075
1076 void clearSubtreeInteractionOnHide();
1077
1079
1087 void invalidateIfRelevant(SimpleSelector::Kind kind, std::string_view name);
1088
1091
1092 void invalidateFollowingSiblings(SimpleSelector::Kind kind, std::string_view name);
1093 void invalidateFollowingSiblingsCache();
1094 void invalidateChildrenForSiblingRules();
1101 Style partStyle(const std::string &partName)
1102 {
1103 return style_.partFor(*this, partName);
1104 }
1105
1106 // ---- Subclass hooks ----
1107
1115 virtual Vec2 computeIntrinsicSize(float /*availW*/, float /*availH*/) { return {0, 0}; }
1116
1118 virtual void onLayout() {}
1119
1121 virtual void onUpdate(float /*dt*/) {}
1122
1124 virtual void onEnabledChanged(bool /*nowEnabled*/) {}
1125
1127 virtual void onCheckedChanged(bool /*nowChecked*/) {}
1128
1130 virtual void onDetachContext(UIContext * /*oldCtx*/) {}
1131
1139 {
1140 resolveEffectIfNeeded(style_.currentStyle);
1141 if (currentEffect_.valid())
1142 return currentEffect_;
1143 if (hasShader)
1144 return customEffect;
1145 return {};
1146 }
1147
1148 // ---- Render hooks ----
1149
1157 virtual void renderContent(float /*op*/, const ComputedStyle & /*style*/) {}
1158
1168 virtual void renderChrome(float op, const ComputedStyle &style);
1169
1171 virtual void onDescendantFocused(Layout * /*descendant*/) {}
1172
1173 // ---- Layout internals ----
1174
1184 void arrangeInto(Rect space);
1185
1191 {
1192 const Vec2 vp = viewportSize();
1193 Transform2D tr;
1194 tr.pivot = rect.center();
1195 tr.translate = {
1196 style.translateX.resolveSelfH(rect.width, rect.height, vp),
1197 style.translateY.resolveSelfV(rect.width, rect.height, vp)};
1198 tr.rotationDeg = style.rotation;
1199 tr.scale = style.scale;
1200 return tr;
1201 }
1202
1209 virtual void translateSubtree(float dx, float dy);
1210
1211 private:
1212 // ---- Private internals ----
1213
1214 Vec2 measureConstrainedW(float constrainedW, float parent_w, float parent_h);
1215
1217 void initStyleIfNeeded();
1218
1220 void cullRemovedChildren();
1221
1223 void recomputeDirty(bool wasPending, const ComputedStyle &styleBefore);
1224
1226 void resolveEffectIfNeeded(const ComputedStyle &style);
1227
1229 void drawWithStyle(const ComputedStyle &renderStyle, float parentOpacity);
1230
1232 void drawInline(const ComputedStyle &renderStyle, float globalOp);
1233
1243 void drawLayer(const ComputedStyle &renderStyle, float globalOp);
1244
1246 void drawChildren(float globalOp);
1247
1248 // ---- Flow helpers ----
1249
1251 void arrangeAbsoluteAndPortals(const Rect &inner);
1252
1262 void arrangeAbsolute(Layout *c, const ComputedStyle &cst, const Rect &in);
1263
1272 void arrangeVerticalFlow(const Rect &inner, float gapY);
1273
1275 void arrangeHorizontalFlow(const Rect &inner, float gapX);
1276
1284 void arrangeWrapFlow(const Rect &inner, float gapX, float gapY);
1285
1287 void arrangeStackFlow(const Rect &inner);
1288
1290 void arrangeGridFlow(const Rect &inner, float gapX, float gapY);
1291
1300 static float clampSafe(float v, float lo, float hi);
1301
1302 std::unique_ptr<std::vector<std::shared_ptr<void>>> retainedObjects_;
1303 UIContext *ctx_{nullptr};
1304
1313 struct LayerCache
1314 {
1315 TargetHandle target{};
1316 uint64_t poolGeneration{0};
1317 Rect srcRect{0, 0, 0, 0};
1318 int tw{0};
1319 int th{0};
1320 float lastRotation{0.0f};
1321 float lastScale{1.0f};
1322 float lastOpacity{1.0f};
1323 float lastRegionOffX{0.0f};
1324 float lastRegionOffY{0.0f};
1325 float lastDpiScale{1.0f};
1326 uint32_t lastViewportGen{0};
1327 uint32_t lastThemeVer{0};
1328 uint64_t fingerprint{0};
1329 uint64_t lastFingerprint{0};
1330 uint64_t lastUsedFrame{0};
1331 uint8_t stableFrames{0};
1332 bool premultiplied{false};
1333 bool dirty{true};
1334 };
1335
1342 void releaseLayerCache()
1343 {
1344 if (!layerCache_)
1345 return;
1346 if (layerCache_->target.valid())
1347 {
1348 if (auto *ctx = context())
1349 {
1350 auto &pool = ctx->targetPool;
1351 if (layerCache_->poolGeneration == pool.generation())
1352 pool.release(layerCache_->target);
1353 }
1354 layerCache_->target = {};
1355 }
1356 layerCache_->stableFrames = 0;
1357 layerCache_->dirty = true;
1358 layerCache_->premultiplied = false;
1359 }
1360
1362 void maybeEvictStaleLayerCache();
1363
1365 void appendSubtreeFingerprint(const Layout &layerRoot,
1366 const ComputedStyle &nodeStyle,
1367 bool isRoot,
1368 uint64_t &hash) const;
1369
1370 std::unique_ptr<LayerCache> layerCache_;
1371 std::unique_ptr<DragHandlers> dragHandlers_;
1372 };
1373
1395 template <typename Derived, typename Base = Layout>
1396 class TLayout : public Base
1397 {
1398 public:
1400 template <typename... Args>
1401 TLayout(Args &&...args) : Base(std::forward<Args>(args)...) {}
1402
1409 template <typename... Args>
1410 static std::shared_ptr<Derived> create(Args &&...args)
1411 {
1412 auto p = std::make_shared<Derived>(std::forward<Args>(args)...);
1413 static_cast<TLayout<Derived, Base> *>(p.get())->onBuild();
1414 return p;
1415 }
1416
1418 std::shared_ptr<Derived> cls(const std::string &name)
1419 {
1420 this->addClass(name);
1421 return self();
1422 }
1423
1424 std::shared_ptr<Derived> id(const std::string &node_id)
1425 {
1426 this->setId(node_id);
1427 return self();
1428 }
1429
1430 std::shared_ptr<Derived> withRef(const std::string &r)
1431 {
1432 this->setRef(r);
1433 return self();
1434 }
1435
1436 std::shared_ptr<Derived> size(Value w, Value h)
1437 {
1438 this->setSize(w, h);
1439 return self();
1440 }
1441
1442 std::shared_ptr<Derived> passThrough(bool p = true)
1443 {
1444 this->setPassThrough(p);
1445 return self();
1446 }
1447
1448 std::shared_ptr<Derived> with(std::shared_ptr<Layout> c)
1449 {
1450 this->addChild(std::move(c));
1451 return self();
1452 }
1453
1454 std::shared_ptr<Derived> self()
1455 {
1456 return std::static_pointer_cast<Derived>(this->shared_from_this());
1457 }
1458
1459 protected:
1461 virtual void onBuild() {}
1462 };
1463
1464 inline bool nodeMatchesAtom(const Layout *node,
1466 const std::string &name,
1467 const std::vector<std::pair<SimpleSelector::Kind, std::string>> &extras,
1468 bool reqHover,
1469 bool reqPressed,
1470 bool reqFocus,
1471 bool reqDisabled,
1472 bool reqChecked)
1473 {
1474 if (!node)
1475 return false;
1476
1477 if (reqHover && !node->isHoveredState())
1478 return false;
1479 if (reqPressed && !node->isPressedState())
1480 return false;
1481 if (reqFocus && !node->isFocusedState())
1482 return false;
1483 if (reqDisabled && !node->isDisabledState())
1484 return false;
1485 if (reqChecked && !node->isCheckedState())
1486 return false;
1487
1488 auto matchesComponent = [node](SimpleSelector::Kind k,
1489 const std::string &n) -> bool
1490 {
1492 return true;
1493 if (k == SimpleSelector::Kind::Tag)
1494 return node->getStyleTag() == n;
1495 if (k == SimpleSelector::Kind::Id)
1496 return node->nodeId == n;
1497 for (const auto &c : node->getStyleClasses())
1498 if (c == n)
1499 return true;
1500 return false;
1501 };
1502
1503 if (!matchesComponent(kind, name))
1504 return false;
1505
1506 for (const auto &[k, n] : extras)
1507 {
1508 if (!matchesComponent(k, n))
1509 return false;
1510 }
1511
1512 return true;
1513 }
1514
1518 inline bool nodeMatchesSimple(const Layout *node, const SimpleSelector &ss)
1519 {
1520 if (!nodeMatchesAtom(node, ss.kind, ss.name, ss.extras,
1521 ss.requireHover, ss.requirePressed, ss.requireFocus,
1522 ss.requireDisabled, ss.requireChecked))
1523 return false;
1524
1525 for (const auto &neg : ss.negations)
1526 {
1527 for (const auto &item : neg.items)
1528 {
1529 if (nodeMatchesAtom(node, item.kind, item.name, item.extras,
1530 item.requireHover, item.requirePressed, item.requireFocus,
1531 item.requireDisabled, item.requireChecked))
1532 return false;
1533 }
1534 }
1535
1536 return true;
1537 }
1538
1540 inline const Layout *previousStyleSibling(const Layout *node)
1541 {
1542 if (!node)
1543 return nullptr;
1544 auto parent = node->getParent();
1545 if (!parent)
1546 return nullptr;
1547 const auto &sibs = parent->children;
1548 for (size_t i = 0; i < sibs.size(); ++i)
1549 {
1550 if (sibs[i].get() == node)
1551 {
1552 while (i > 0)
1553 {
1554 --i;
1555 const Layout *prev = sibs[i].get();
1556 if (prev && prev->getStyleTag() != "EachAnchor")
1557 return prev;
1558 }
1559 return nullptr;
1560 }
1561 }
1562 return nullptr;
1563 }
1564
1565 inline bool matchSelectorChainAt(const std::vector<SimpleSelector> &chain,
1566 size_t idx,
1567 const Layout *node)
1568 {
1569 if (!node || !nodeMatchesSimple(node, chain[idx]))
1570 return false;
1571 if (idx == 0)
1572 return true;
1573
1574 switch (chain[idx].combinator)
1575 {
1577 {
1578 auto p = node->getParent();
1579 return p && matchSelectorChainAt(chain, idx - 1, p.get());
1580 }
1582 {
1583 auto p = node->getParent();
1584 while (p)
1585 {
1586 if (matchSelectorChainAt(chain, idx - 1, p.get()))
1587 return true;
1588 p = p->getParent();
1589 }
1590 return false;
1591 }
1593 {
1594 const Layout *prev = previousStyleSibling(node);
1595 return prev && matchSelectorChainAt(chain, idx - 1, prev);
1596 }
1598 {
1599 const Layout *prev = previousStyleSibling(node);
1600 while (prev)
1601 {
1602 if (matchSelectorChainAt(chain, idx - 1, prev))
1603 return true;
1604 prev = previousStyleSibling(prev);
1605 }
1606 return false;
1607 }
1608 }
1609 return false;
1610 }
1611
1615 inline bool ruleMatches(const ThemeRule &r, const Layout *node, Vec2 viewport)
1616 {
1617 if (r.chain.empty() || !node)
1618 return false;
1619 if (r.media.has_value() && !evaluateMedia(*r.media, viewport))
1620 return false;
1621 return matchSelectorChainAt(r.chain, r.chain.size() - 1, node);
1622 }
1623
1624}
Low-level animation types: imperative tracks, CSS keyframes, and the per-instance active animation st...
Per-node owner of imperative and CSS animation state.
Centralized standard library includes used throughout ZenitUI.
Hover / press / focus state and click-callback dispatch for one node.
Lightweight, replaceable logging facility used across ZenitUI.
@media query representation and evaluation.
Overflow handling, scrolling input, and scrollbar rendering for a node.
Pure data: the scroll offset, bounds, inertia, and drag anchors.
Fixed-capacity inline-storage vector with heap fallback.
Per-node style resolution, state transitions and per-part animations.
The Style / ComputedStyle pair and all style-related value types.
Global stylesheet storage and rule matching.
Per-application state: renderer, platform, pointer, focus, portals.
Small enumerations describing layout strategy and interaction state.
The base node type: tree, style, layout, input, scroll, render.
Definition Layout.hpp:154
void renderFrame()
Render the current state: beginFrame, draw, endFrame.
Style & getInlineBase()
Direct mutable access to the inline style.
Definition Layout.hpp:724
virtual void update(float dt, bool ancestorBlocked=false, bool scrolling=false)
Per-frame update: input, style, animation, then recurse into children.
bool moveChildBefore(const Layout *anchor, const Layout *child)
Reposition an existing direct child immediately before anchor (or at the end if anchor is not found) ...
void invalidateLayerCache()
Mark any cached off-screen filter layer on this node and its ancestors as dirty so it is re-baked on ...
Definition Layout.hpp:979
void arrangeInto(Rect space)
Dispatch to the layout-type-specific arrange helper.
std::shared_ptr< T > as()
static_pointer_cast helper returning shared_ptr<T>.
Definition Layout.hpp:196
void setRef(const std::string &r)
Set the node's @ref (used by UINode::ref / refAll).
Definition Layout.hpp:251
virtual void onCheckedChanged(bool)
Called from setChecked after the checked state changes.
Definition Layout.hpp:1127
std::string ref
@ref for UINode::ref / refAll lookup.
Definition Layout.hpp:943
void notifyDescendantFocused(Layout *descendant)
Notify the node that one of its descendants gained focus.
Definition Layout.hpp:493
void removeFromParent()
Request removal at the next culling pass.
Definition Layout.hpp:365
UIContext * contextPtr() const
Return the UIContext this node is attached to, or nullptr if unmounted.
Definition Layout.hpp:896
void scrollTo(float x, float y)
Set the scroll offset, clamped to the valid range.
Definition Layout.hpp:521
bool hasActiveAnimations() const
true if this node or any descendant is currently animating.
Definition Layout.hpp:764
const DragHandlers * dragHandlers() const noexcept
Non-allocating read access to Drag & Drop callbacks, or nullptr if none were set.
Definition Layout.hpp:611
bool hasClass(const std::string &className) const
true if the node has the given class.
bool hasId(const std::string &targetId) const
true if the node's nodeId equals targetId.
Definition Layout.hpp:243
void setShader(EffectHandle shader)
Set a custom shader effect applied to the node's content.
Definition Layout.hpp:964
std::shared_ptr< Layout > id(const std::string &node_id)
Fluent setId; returns shared_from_this().
Definition Layout.hpp:277
bool isAncestorOf(const Layout *other) const
true if this node is an ancestor of other.
Definition Layout.hpp:401
bool hasPointerCapture() const
true if this node currently holds the pointer capture.
Definition Layout.hpp:636
const Theme & theme() const
Return the stylesheet theme of this node's UIContext (or an empty theme if unmounted).
Definition Layout.hpp:911
bool isStackingContext() const
true if the node has a non-static position and a non-auto zIndex.
Definition Layout.hpp:496
Layout(LayoutType type=LayoutType::Stack)
Construct a node with the given layout strategy.
Definition Layout.hpp:163
void attachContext(UIContext *newCtx)
Attach this node and its subtree to newCtx.
std::function< void()> onRightClick
Right-click hook; fires on right-button press over the node.
Definition Layout.hpp:922
FontHandle resolveFont(const ComputedStyle &style, FontHandle fallback={}) const
Resolve a FontHandle from the node's style font stack.
Definition Layout.hpp:667
std::shared_ptr< Layout > cls(const std::string &className)
Fluent addClass; returns shared_from_this().
Definition Layout.hpp:271
virtual void onLayout()
Called after arrange assigns the node's rect.
Definition Layout.hpp:1118
virtual void onEnabledChanged(bool)
Called from setEnabled after the state change.
Definition Layout.hpp:1124
void snapStyleImmediate()
Immediately resolve style rules and clear pending transitions across this subtree so recycled nodes p...
std::function< void()> onAnimationsFinished
Called when the node had active local animations and now has none.
Definition Layout.hpp:934
Style partStyle(const std::string &partName)
Resolve the style for pseudo-element partName.
Definition Layout.hpp:1101
void setPortal(bool p)
Enable or disable portal rendering for this node.
Definition Layout.hpp:586
std::string nodeId
#id for selector matching and UINode::find.
Definition Layout.hpp:940
Transform2D currentTransform(const ComputedStyle &style) const
Compute the current transform from the style's translateX/translateY/rotation/scale.
Definition Layout.hpp:1190
void addCssAnimation(const std::string &name)
Manually start a CSS animation by name.
Definition Layout.hpp:776
void setInlineBase(const Style &s)
Overlay s onto the node's inline style (highest priority).
Definition Layout.hpp:713
virtual void renderChrome(float op, const ComputedStyle &style)
Draw the node's background, border, and shadow.
std::vector< const ThemeRule * > getMatchingRules() const
Return the stylesheet theme of the active UIContext.
void capturePointer()
Capture the pointer: all subsequent input events go to this node.
Definition Layout.hpp:620
void retainObject(std::shared_ptr< void > obj)
Retain an arbitrary type-erased object for the lifetime of this node.
Definition Layout.hpp:383
void invalidateIfRelevant(SimpleSelector::Kind kind, std::string_view name)
Propagate a class/tag change to descendants that may match it.
void setStyleTag(const std::string &t)
Set the node's style tag.
Style & getInlineDefaults()
Direct mutable access to the inline defaults (lowest-priority inline).
Definition Layout.hpp:735
void detachContext()
Detach this node and its subtree from its current UIContext.
Layout * hitTestDroppable(Vec2 p, const DragPayload &payload, const Layout *excludeSource, const Layout *excludeGhost, const Rect *clipLocal=nullptr)
Hit-test a point against droppable nodes during an active drag (§5.22b).
virtual Vec2 computeIntrinsicSize(float, float)
Compute the intrinsic size, excluding padding and border.
Definition Layout.hpp:1115
virtual void onDetachContext(UIContext *)
Called from detachContext() right before clearing ctx_.
Definition Layout.hpp:1130
bool scrollIntoView(float margin=0.0f)
Scroll the nearest scrolling ancestor so that this node's rect becomes visible, respecting margin.
void setChecked(bool c)
Set the :checked pseudo-class state.
Definition Layout.hpp:447
std::vector< std::shared_ptr< Layout > > children
Children of this node.
Definition Layout.hpp:937
std::shared_ptr< Layout > with(std::shared_ptr< Layout > child)
Fluent addChild; returns shared_from_this().
Definition Layout.hpp:289
bool removeChild(const Layout *child)
Synchronously detach a single direct child, clearing its parent pointer.
virtual void renderContent(float, const ComputedStyle &)
Draw the node's content (text, images, custom geometry).
Definition Layout.hpp:1157
UIContext * context() const
Return the UIContext this node is attached to, or nullptr if unmounted.
Definition Layout.hpp:899
void runFrame(float dt)
Run one full frame: update, measure, arrange.
void addClass(const std::string &className)
Add a class name to the node's style class list.
virtual ~Layout()
Destroy the node and clean up framework-side references.
Definition Layout.hpp:183
virtual void translateSubtree(float dx, float dy)
Translate the subtree (children and their descendants) by (dx, dy).
void setBackgroundTexture(TextureHandle tex, NineSlice np={0, 0, 0, 0})
Override the background texture with a direct handle.
Definition Layout.hpp:951
virtual Layout * contentTarget()
Return the node that receives children when built from markup.
Definition Layout.hpp:356
std::shared_ptr< Layout > size(Value w, Value h)
Fluent setSize; returns shared_from_this().
Definition Layout.hpp:283
virtual void draw(float parentOpacity=1.0f)
Draw the node and its children.
Vec2 viewportSize() const
Return the logical viewport size of this node's UIContext (or {0, 0} if unmounted).
Definition Layout.hpp:908
void insertChildBefore(const Layout *anchor, std::shared_ptr< Layout > child)
Insert child immediately before anchor (or append if anchor is not found).
virtual void removeAllChildren()
Detach every child immediately, clearing their parent pointers.
Layout * hitTest(Vec2 p, bool ancestorBlocked=false, const Rect *clipLocal=nullptr)
Hit-test a point against this subtree.
bool scrollIntoView(const Rect &subRect, float margin=0.0f)
Scroll the nearest scrolling ancestor so that subRect becomes visible, respecting margin.
void playAnimation(const std::string &name, bool playReverse=false)
Start (or restart) the imperative animation named name.
Definition Layout.hpp:759
EffectHandle resolveActiveEffect()
Resolve the currently active effect handle.
Definition Layout.hpp:1138
void addAnimation(const std::string &name, std::shared_ptr< UIAnimation > anim)
Register an imperative animation under name.
Definition Layout.hpp:750
void invalidateStyleCacheRecursive()
Mark the whole subtree as needing style re-resolution.
void setEnabled(bool e)
Enable or disable the node.
ResolvedBgTexture resolveBgTexture(const ComputedStyle &style, TextureHandle fallbackTex={}, NineSlice fallbackSlice={0, 0, 0, 0})
Resolve the background texture from the style, falling back to explicit parameters if the style has n...
Definition Layout.hpp:688
void addChild(std::shared_ptr< Layout > child)
Append child to this node's child list.
Definition Layout.hpp:302
void updateTree(float dt)
Root-of-tree update: refresh pointer state and recurse.
virtual void onUpdate(float)
Called every frame from update, after input dispatch.
Definition Layout.hpp:1121
virtual void arrange(Rect space)
Assign a screen rect to this node and lay out its children.
void setSize(Value w, Value h)
Convenience: set explicit width and height.
Definition Layout.hpp:260
void stopCssAnimation(const std::string &name)
Mark the named CSS animation as finished.
Definition Layout.hpp:782
void setId(const std::string &node_id)
Set the node's #id (used in selectors and by UINode::find).
void setVisible(bool v)
Show or hide the node (display: none semantics).
void removeClass(const std::string &className)
Remove a class name; no-op if absent.
DragHandlers & drag()
Access Drag & Drop callbacks for this node, allocating storage lazily on first call.
Definition Layout.hpp:603
bool isScrollContainer() const
true if either overflow axis is non-visible.
Definition Layout.hpp:507
void releasePointer()
Release the pointer capture if this node owns it.
Definition Layout.hpp:626
int getZIndex() const
Effective zIndex; returns 0 for the "auto" case.
Definition Layout.hpp:501
virtual Vec2 measure(float parent_w, float parent_h)
Compute the intrinsic size given available space.
void resetInteractionState()
Reset transient interaction state (hovered, pressed, focused, capture, and current UIState) across th...
void clearStyleClasses()
Remove every class name.
virtual void onDescendantFocused(Layout *)
Called on ancestors when a descendant gains focus.
Definition Layout.hpp:1171
void beginTransition()
Restart the current style transition from the current value.
Definition Layout.hpp:476
std::shared_ptr< Derived > self()
Return shared_from_this() statically cast to Derived.
Definition Layout.hpp:1454
std::shared_ptr< Derived > id(const std::string &node_id)
Fluent setId; returns typed shared_ptr<Derived>.
Definition Layout.hpp:1424
virtual void onBuild()
Hook: called once after create() finishes constructing the object.
Definition Layout.hpp:1461
std::shared_ptr< Derived > size(Value w, Value h)
Fluent setSize; returns typed shared_ptr<Derived>.
Definition Layout.hpp:1436
TLayout(Args &&...args)
Forward constructor arguments to Base.
Definition Layout.hpp:1401
std::shared_ptr< Derived > passThrough(bool p=true)
Fluent setPassThrough; returns typed shared_ptr<Derived>.
Definition Layout.hpp:1442
std::shared_ptr< Derived > withRef(const std::string &r)
Fluent setRef; returns typed shared_ptr<Derived>.
Definition Layout.hpp:1430
std::shared_ptr< Derived > cls(const std::string &name)
Fluent addClass; returns typed shared_ptr<Derived>.
Definition Layout.hpp:1418
static std::shared_ptr< Derived > create(Args &&...args)
Construct a shared_ptr<Derived> and call onBuild().
Definition Layout.hpp:1410
std::shared_ptr< Derived > with(std::shared_ptr< Layout > c)
Fluent addChild; returns typed shared_ptr<Derived>.
Definition Layout.hpp:1448
Per-context stylesheet: rules, keyframes, and root style.
Definition Theme.hpp:164
const Layout * previousStyleSibling(const Layout *node)
Return the immediately preceding non-sentinel sibling of node, or nullptr.
Definition Layout.hpp:1540
bool nodeMatchesSimple(const Layout *node, const SimpleSelector &ss)
true if node matches the primary selector, all extras, and none of its :not() clauses.
Definition Layout.hpp:1518
bool ruleMatches(const ThemeRule &r, const Layout *node, Vec2 viewport)
true if node matches the full rule selector chain ( , >, +, ~, :not()).
Definition Layout.hpp:1615
LayoutType
Positioning strategy applied to a Layout node's direct children.
Definition UIEnums.hpp:29
MouseButton
Mouse buttons tracked by the input system.
Definition CoreTypes.hpp:361
@ Vertical
Children flow top-to-bottom (column flex semantics).
Definition UIEnums.hpp:31
@ Stack
Children overlap each other; Z-order controls paint order.
Definition UIEnums.hpp:30
@ Grid
2D CSS-style grid layout (grid-template-columns / grid-template-rows).
Definition UIEnums.hpp:33
@ Horizontal
Children flow left-to-right (row flex semantics).
Definition UIEnums.hpp:32
bool evaluateMedia(const MediaQuery &q, Vec2 viewport)
Evaluate a MediaQuery against a viewport size.
Definition Media.hpp:49
@ GeneralSibling
A ~ B (any preceding sibling).
Definition Style.hpp:625
@ AdjacentSibling
A + B (immediately preceding sibling).
Definition Style.hpp:624
@ Descendant
A B (any ancestor).
Definition Style.hpp:622
@ Child
A > B (direct parent).
Definition Style.hpp:623
Per-node animation state and operations.
Definition AnimationPlayer.hpp:74
Dense style: every property has a concrete value.
Definition Style.hpp:1036
Lazily allocated Drag & Drop callbacks owned by Layout (§5.22).
Definition Layout.hpp:128
Opaque user payload carried during an active drag-and-drop operation.
Definition UIContext.hpp:698
Opaque handle to a shader/effect owned by the asset provider.
Definition CoreTypes.hpp:142
Opaque handle to a font loaded by TextEngine.
Definition CoreTypes.hpp:135
Stateless per-node input dispatcher.
Definition InputController.hpp:45
Result of resolveBgTexture: a texture plus its nine-slice insets.
Definition Layout.hpp:678
Nine-slice inset values for scalable textures.
Definition CoreTypes.hpp:163
Static configuration bits: interaction behaviour, render behaviour.
Definition Layout.hpp:86
uint32_t blocksRaycast
Stops hit-testing even when not interactive.
Definition Layout.hpp:88
uint32_t interactive
Receives pointer hover/click events.
Definition Layout.hpp:87
uint32_t portal
Rendered at the root above clip rects.
Definition Layout.hpp:95
uint32_t visible
Visibility (false behaves like display: none).
Definition Layout.hpp:90
uint32_t draggable
Can initiate a drag-and-drop gesture on press + move.
Definition Layout.hpp:97
uint32_t focusable
Can acquire keyboard focus and participate in Tab cycle.
Definition Layout.hpp:91
uint32_t droppable
Can accept drops during an active drag-and-drop gesture.
Definition Layout.hpp:98
uint32_t updateWhenDisabled
Still runs onUpdate while disabled.
Definition Layout.hpp:94
uint32_t focusScope
Traps Tab focus cycling inside this subtree.
Definition Layout.hpp:92
uint32_t enabled
Enabled state (false triggers :disabled).
Definition Layout.hpp:89
uint32_t passThrough
Forwards press/click events to ancestor nodes.
Definition Layout.hpp:96
uint32_t keyboardActivates
Enter / Space trigger onClick while focused.
Definition Layout.hpp:93
Transient bookkeeping bits used by the layout / style / culling passes.
Definition Layout.hpp:109
uint32_t wantsRemoval
Deferred removal requested via removeFromParent().
Definition Layout.hpp:114
uint32_t pressedInChain
Reserved press-chain tracking flag.
Definition Layout.hpp:115
uint32_t hadLocalAnimationsLast
Active local animations in the previous frame.
Definition Layout.hpp:113
uint32_t layoutDirty
Structural layout change forces re-measure.
Definition Layout.hpp:117
uint32_t hadRemovedChildren
At least one child was removed since last measure.
Definition Layout.hpp:116
uint32_t pendingTransition
Style must be re-resolved on next update.
Definition Layout.hpp:112
uint32_t styleInitialized
Initial style resolution has run at least once.
Definition Layout.hpp:111
uint32_t subtreeDirty
Subtree needs re-measure/re-arrange.
Definition Layout.hpp:110
Per-frame interaction flags derived from pointer / keyboard state.
Definition Layout.hpp:68
uint32_t pressed
Primary mouse button is pressed on this node.
Definition Layout.hpp:70
uint32_t hovered
Pointer is currently inside the node.
Definition Layout.hpp:69
uint32_t focused
Node currently holds keyboard focus.
Definition Layout.hpp:71
uint32_t checked
Toggle / Checkbox checked state (:checked).
Definition Layout.hpp:72
Axis-aligned rectangle in screen coordinates.
Definition CoreTypes.hpp:46
Per-node overflow, scrolling and scrollbar state machine.
Definition ScrollController.hpp:51
One component of a CSS selector chain.
Definition Style.hpp:632
Kind
Definition Style.hpp:634
@ Any
Universal selector * or implicit base for standalone :not(...) / :hover.
Definition Style.hpp:638
Resolves, caches, and transitions the style of a single node.
Definition StyleResolver.hpp:36
Sparse style: every property is Opt<T>, unset by default.
Definition Style.hpp:932
Opaque handle to an off-screen render target.
Definition CoreTypes.hpp:155
Opaque handle to a GPU/software texture owned by the asset provider.
Definition CoreTypes.hpp:127
A single selector-plus-declarations entry in the stylesheet.
Definition Theme.hpp:148
2D affine transform stored as pivot + translate + rotation + scale.
Definition CoreTypes.hpp:178
Per-instance UI context: backends, theme, text engine, frame state, and routing.
Definition UIContext.hpp:725
8-byte tagged length expression:
Definition Unit.hpp:58
2D vector with component-wise arithmetic.
Definition CoreTypes.hpp:25