docs
Loading...
Searching...
No Matches
Container.h
Go to the documentation of this file.
1///
2/// Copyright (C) 2026 Ultralight, Inc. All rights reserved.
3/// A license is required for commercial use. https://ultralig.ht
4///
5#pragma once
8
9#include <concepts>
10#include <utility>
11
12namespace ultralight {
13
14struct DividerStyle;
15
16///
17/// A builder element (see `<AppCore/layout/Builder.h>`): anything that can append itself to
18/// a container.
19///
20template <typename T>
21concept LayoutBuildable = requires(const T& spec, Container& parent) { spec.ApplyTo(parent); };
22
23///
24/// A layout node that organizes child nodes into a row or column.
25///
26/// Containers form the rows and columns of an AppCore window's layout tree. The window's root
27/// layout is a container that fills the entire window, and adding child rows or columns divides
28/// that space into a hierarchy of panes.
29///
30/// Each child can be a Panel that hosts a View, or another Container that splits space further. The
31/// library recalculates child sizes automatically whenever the window resizes or moves between
32/// displays with different scale factors.
33///
34/// The following example creates a resizable row with a sidebar and a content pane:
35///
36/// ```
37/// RefPtr<Container> body =
38/// window->layout()->AddRow({ .key = "body", .resizable = true });
39/// RefPtr<Panel> sidebar =
40/// body->AddPanel({ .key = "sidebar", .size = "240px", .min_size = "160px" });
41/// RefPtr<Panel> content = body->AddPanel({ .key = "content" });
42///
43/// sidebar->view()->LoadURL("file:///sidebar.html");
44/// content->view()->LoadURL("file:///content.html");
45/// ```
46///
47/// ## Sizing Children
48///
49/// A container divides space along its main axis by first subtracting its padding and any gaps
50/// between children. It satisfies pixel sizes first, gives percentage sizes their shares of the
51/// free space left after pixel-sized children, and divides what remains among flexible children
52/// according to their flex factors. A child created without an explicit size defaults to one flex
53/// share (`1fr`). For what each size unit means, see Size and Length.
54///
55/// Containers also accept `gap` to separate adjacent children and `padding` to inset them from all
56/// four edges (both in logical pixels).
57///
58/// ## Resizable Containers
59///
60/// Setting `resizable = true` on a container places draggable dividers between its direct children.
61/// Dragging a divider resizes the panes on either side.
62///
63/// You can constrain how panes resize during a drag:
64///
65/// - **Set `min_size` to prevent a pane from collapsing.**
66/// - **Set `fixed = true` to keep a child's size constant.**
67///
68/// Double-clicking a divider resets both neighboring children to their declared sizes.
69///
70/// You can customize divider appearance by passing a DividerStyle to SetDividerStyle().
71///
72/// ## Finding Children
73///
74/// Assigning a `key` in a child's creation options lets you look up that node across the
75/// container's subtree with Find(), FindPanel(), or FindContainer(). If multiple descendants share
76/// the same key, the lookup returns the newest match.
77///
78/// ## Reserving Space for Drawing
79///
80/// An empty container reserves space in the layout without hosting a View or rendering web content.
81///
82/// To track the container's bounds as the window resizes, register a layout change listener:
83///
84/// ```
85/// RefPtr<Container> viewport = body->AddColumn({ .key = "viewport" });
86///
87/// // The callback runs while viewport_tracker_ is kept.
88/// viewport_tracker_ = viewport->OnLayoutChange([](LayoutNode& node) {
89/// ResizeViewport(node.device_bounds());
90/// });
91/// ```
92///
93/// ## Overriding Child Layout
94///
95/// Call SetLayoutOverride() to install a layout delegate that positions direct children manually
96/// with LayoutNode::SetBounds().
97///
98/// The delegate runs when the container's size changes, after SetNeedsLayout(), or when the
99/// display scale changes. It also runs when its children change, or when a child's options change.
100///
101/// Moving a container while keeping its size shifts its children with it-- the delegate does not
102/// run.
103///
104/// Layout may happen during a geometry read anywhere in your app, or at the next frame.
105///
106/// @see LayoutNode, PanelOptions, ContainerOptions, Size, DividerStyle, Container::Build(),
107/// Window::BuildLayout()
108///
110 public:
111 ///
112 /// Create a panel with a new View (window-default view configuration).
113 ///
114 /// @param options The panel's declared options.
115 ///
116 /// @param position Where to insert the panel (default: append at the end).
117 ///
118 /// @return Returns the new panel (see LayoutNode if this container was removed).
119 ///
120 virtual RefPtr<Panel> AddPanel(const PanelOptions& options = {},
121 InsertPosition position = {}) = 0;
122
123 ///
124 /// Create a panel with a caller-supplied ViewConfig.
125 ///
126 /// The fields describing the hosting window are filled in from the window for you. Every
127 /// other field is yours:
128 ///
129 /// - `initial_device_scale` (the window's scale)
130 /// - `display_id` (the window's display)
131 /// - `is_accelerated` (whether the window composites on the GPU)
132 ///
133 /// To host a deliberately CPU-rendered View on a GPU window, create the View with
134 /// Renderer::CreateView() and use AdoptPanel().
135 ///
136 /// @param options The panel's declared options.
137 ///
138 /// @param view_config The configuration for the new View. The window-describing fields
139 /// listed above are overwritten.
140 ///
141 /// @param position Where to insert the panel (default: append at the end).
142 ///
143 /// @return Returns the new panel (see LayoutNode if this container was removed).
144 ///
145 virtual RefPtr<Panel> AddPanel(const PanelOptions& options, const ViewConfig& view_config,
146 InsertPosition position = {}) = 0;
147
148 ///
149 /// Create a panel that adopts an existing View (including a View created through a
150 /// Session).
151 ///
152 /// The panel takes a reference to the View and resizes it to the panel's bounds.
153 ///
154 /// @param view The View to host.
155 ///
156 /// @param options The panel's declared options.
157 ///
158 /// @param position Where to insert the panel (default: append at the end).
159 ///
160 /// @return Returns the new panel (see LayoutNode if this container was removed).
161 ///
162 /// @note The panel replaces the View's editor listener with its own (see Panel).
163 ///
164 virtual RefPtr<Panel> AdoptPanel(RefPtr<View> view, const PanelOptions& options = {},
165 InsertPosition position = {}) = 0;
166
167 ///
168 /// Adopt an existing View (shorthand for AdoptPanel()).
169 ///
170 /// @param view The View to host.
171 ///
172 /// @param options The panel's declared options.
173 ///
174 /// @param position Where to insert the panel (default: append at the end).
175 ///
176 /// @return Returns the new panel (see LayoutNode if this container was removed).
177 ///
178 template <typename ViewRef>
179 requires std::convertible_to<ViewRef&&, RefPtr<View>>
180 RefPtr<Panel> AddPanel(ViewRef&& view, const PanelOptions& options = {},
181 InsertPosition position = {}) {
182 return AdoptPanel(RefPtr<View>(std::forward<ViewRef>(view)), options, position);
183 }
184
185 ///
186 /// Create a child row container.
187 ///
188 /// @param options The container's declared options.
189 ///
190 /// @param position Where to insert the container (default: append at the end).
191 ///
192 /// @return Returns the new container (see LayoutNode if this container was removed).
193 ///
194 virtual RefPtr<Container> AddRow(const ContainerOptions& options = {},
195 InsertPosition position = {}) = 0;
196
197 ///
198 /// Create a child column container.
199 ///
200 /// @param options The container's declared options.
201 ///
202 /// @param position Where to insert the container (default: append at the end).
203 ///
204 /// @return Returns the new container (see LayoutNode if this container was removed).
205 ///
206 virtual RefPtr<Container> AddColumn(const ContainerOptions& options = {},
207 InsertPosition position = {}) = 0;
208
209 ///
210 /// Remove a direct child (and, for a container child, its whole subtree) from the tree.
211 ///
212 /// Removal detaches the child and drops each removed panel's reference to its View. A View
213 /// the application holds a RefPtr to survives removal and can be adopted into another
214 /// panel or window. For what removed handles do afterwards, see LayoutNode.
215 ///
216 /// @param node The direct child to remove.
217 ///
218 /// @return Returns whether or not the node was a direct child and was removed.
219 ///
220 virtual bool Remove(RefPtr<LayoutNode> node) = 0;
221
222 ///
223 /// Remove every child. Equivalent to Remove() on each child in turn.
224 ///
225 virtual void RemoveAll() = 0;
226
227 ///
228 /// Reorder a direct child within this container.
229 ///
230 /// A node from a different container (or window) is a no-op with a warning. A position
231 /// anchor that is not a direct child falls back to the end, also with a warning.
232 ///
233 /// @param node The direct child to move.
234 ///
235 /// @param position The new position (default: move to the end).
236 ///
237 /// @return Returns whether or not the node was reordered.
238 ///
239 virtual bool Move(RefPtr<LayoutNode> node, InsertPosition position = {}) = 0;
240
241 ///
242 /// Get the number of children.
243 ///
244 virtual int child_count() const = 0;
245
246 ///
247 /// Get the child at an index.
248 ///
249 /// @param index The zero-based index within this container's child list.
250 ///
251 /// @return Returns the child, or null when the index is out of range.
252 ///
253 virtual RefPtr<LayoutNode> child_at(int index) const = 0;
254
255 ///
256 /// Find a descendant by key.
257 ///
258 /// @param key The key to look for.
259 ///
260 /// @return Returns the matching node, or null when nothing matches. With duplicate keys
261 /// the most recently created match wins.
262 ///
263 virtual RefPtr<LayoutNode> Find(const String& key) = 0;
264
265 ///
266 /// Find a descendant panel by key.
267 ///
268 /// @param key The key to look for.
269 ///
270 /// @return Returns the matching panel, or null when nothing matches or the match is not a
271 /// panel.
272 ///
273 virtual RefPtr<Panel> FindPanel(const String& key) = 0;
274
275 ///
276 /// Find a descendant container by key.
277 ///
278 /// @param key The key to look for.
279 ///
280 /// @return Returns the matching container, or null when nothing matches or the match is
281 /// not a container.
282 ///
284
285 ///
286 /// Override this container's layout with a layout delegate.
287 ///
288 /// The delegate runs when the container's size changes, after SetNeedsLayout(), or when the
289 /// display scale changes. It also runs when children are added, removed, moved, shown, or hidden,
290 /// and when a child's options change.
291 ///
292 /// Moving a container while keeping its size shifts its children with it-- the delegate does
293 /// not run.
294 ///
295 /// Layout happens during a geometry read anywhere in your app, or at the next frame.
296 ///
297 /// The delegate never runs while the container has no children.
298 ///
299 /// If the delegate reads application state, call SetNeedsLayout() when that state changes.
300 /// Otherwise, the delegate will not see the change.
301 ///
302 /// The same inputs must produce the same placement-- the delegate may run more often than
303 /// strictly needed.
304 ///
305 /// The delegate positions direct children with LayoutNode::SetBounds():
306 ///
307 /// ```
308 /// grid->SetLayoutOverride([](Container& c, const Rect& content_box) {
309 /// float x = content_box.x(), y = content_box.y(), w = content_box.width();
310 /// c.child_at(0)->SetBounds(Rect::FromXYWH(x, y, w, 40));
311 /// c.child_at(1)->SetBounds(
312 /// Rect::FromXYWH(x, y + 40, w, content_box.height() - 40));
313 /// });
314 /// ```
315 ///
316 /// `content_box` is the container's content box (inside its padding) in container-local
317 /// logical pixels.
318 ///
319 /// Placed rectangles are snapped and clipped to this box.
320 ///
321 /// A placed rectangle persists until the delegate places that child again-- the delegate may
322 /// place only what changed.
323 ///
324 /// Children that the delegate has never placed occupy no region.
325 ///
326 /// Inside the delegate, the container and its ancestors already have their new geometry.
327 ///
328 /// The container's own children keep their previous placement until the delegate returns.
329 /// Other nodes in the tree may still hold their previous layout.
330 ///
331 /// Place children from `content_box`.
332 ///
333 /// Changing the tree from inside the delegate is allowed. The change applies at the next
334 /// layout.
335 ///
336 /// If a delegate changes its own container or an ancestor on every run, the window never
337 /// settles-- the library logs a warning.
338 ///
339 /// Setting a new delegate replaces the existing one, and every child resets to never-placed.
340 ///
341 /// Replacing the delegate destroys the previous delegate's user data. If replaced from inside
342 /// the delegate, destruction is deferred until the delegate returns.
343 ///
344 /// @param callback The delegate to install. Pass nullptr to restore ordinary
345 /// layout.
346 ///
347 /// @param user_data Passed back to the delegate on every run (can be nullptr).
348 ///
349 /// @param destroy_user_data Called once when the delegate drops `user_data` (can be
350 /// nullptr).
351 ///
352 /// @warning Do not pump the event loop, open modal dialogs, or close the window from inside the
353 /// delegate.
354 ///
355 /// \parblock
356 /// @note `resizable` is ignored (with a warning) while a container has a layout delegate.
357 /// Dividers only exist between children that the container itself lays out.
358 /// \endparblock
359 ///
360 /// \parblock
361 /// @note Callbacks must not let exceptions propagate.
362 /// \endparblock
363 ///
364 virtual void SetLayoutOverride(LayoutOverrideCallback callback, void* user_data = nullptr,
365 LayoutDestroyUserDataCallback destroy_user_data = nullptr) = 0;
366
367 ///
368 /// Whether or not this container has a layout delegate installed.
369 ///
370 virtual bool HasLayoutOverride() const = 0;
371
372 ///
373 /// Mark this container's layout stale.
374 ///
375 /// Its layout override (or, without one, its track placement) runs again at the next layout--
376 /// either on the next geometry read or at the next frame.
377 ///
378 /// Call this when application state read by a layout override changes.
379 ///
380 /// This has no effect on a removed container.
381 ///
382 /// @see SetLayoutOverride()
383 ///
384 virtual void SetNeedsLayout() = 0;
385
386 ///
387 /// Set this container's divider style (see `<AppCore/layout/DividerStyle.h>`).
388 ///
389 /// Fields left unset fall back to the window's style (Window::SetDividerStyle()), then to
390 /// the built-in defaults.
391 ///
392 /// @param style The style to apply. A default-constructed style clears the override.
393 ///
394 virtual void SetDividerStyle(const DividerStyle& style) = 0;
395
396 ///
397 /// Install a layout delegate (invocable form).
398 ///
399 /// @param callback Any invocable. It may take `(Container&, const Rect&)` (the container
400 /// and its content box), or just `(const Rect&)`.
401 ///
402 template <typename Callback>
403 requires std::invocable<Callback&, Container&, const Rect&>
404 || std::invocable<Callback&, const Rect&>
405 void SetLayoutOverride(Callback callback) {
406 auto* holder = new Callback(std::move(callback));
407 LayoutOverrideCallback trampoline = [](void* user_data, Container* container,
408 Rect content_box) {
409 auto& cb = *static_cast<Callback*>(user_data);
410 if constexpr (std::invocable<Callback&, Container&, const Rect&>)
411 cb(*container, content_box);
412 else
413 cb(content_box);
414 };
415 SetLayoutOverride(trampoline, holder,
416 [](void* user_data) { delete static_cast<Callback*>(user_data); });
417 }
418
419 ///
420 /// Iterator over a container's children (a forward range of RefPtr<LayoutNode>).
421 ///
423 public:
425 using difference_type = int;
426
427 ChildIterator() = default;
428 ChildIterator(const Container* container, int index) : container_(container), index_(index) {}
429
430 RefPtr<LayoutNode> operator*() const { return container_->child_at(index_); }
432 ++index_;
433 return *this;
434 }
436 ChildIterator prev = *this;
437 ++index_;
438 return prev;
439 }
440 friend bool operator==(const ChildIterator&, const ChildIterator&) = default;
441
442 private:
443 const Container* container_ = nullptr;
444 int index_ = 0;
445 };
446
447 ///
448 /// A range over the container's children:
449 ///
450 /// ```
451 /// for (RefPtr<LayoutNode> child : container->children()) { ... }
452 /// ```
453 ///
454 /// The range reads through child_at(), so mutating the child list while iterating skews
455 /// the walk. Collect handles first when a loop mutates.
456 ///
458 public:
459 ChildRange(const Container* container, int count) : container_(container), count_(count) {}
460 ChildIterator begin() const { return ChildIterator(container_, 0); }
461 ChildIterator end() const { return ChildIterator(container_, count_); }
462
463 private:
464 const Container* container_;
465 int count_;
466 };
467
468 ///
469 /// Get a forward range over the children.
470 ///
471 ChildRange children() const { return ChildRange(this, child_count()); }
472
473 ///
474 /// Append builder elements (see `<AppCore/layout/Builder.h>`) to this container.
475 ///
476 /// Build **appends**, so calling twice appends twice. For a fresh start, call RemoveAll()
477 /// first.
478 ///
479 /// @param children The builder elements to append, in order.
480 ///
481 /// @return Returns this container, so the builder line composes with follow-up calls.
482 ///
483 template <typename... Children>
484 requires(LayoutBuildable<Children> && ...)
486 (children.ApplyTo(*this), ...);
487 return RefPtr<Container>(this);
488 }
489
490 protected:
491 virtual ~Container();
492};
493
496 if (!p)
497 return nullptr;
498 int i = index();
499 return i < 0 ? nullptr : p->child_at(i + 1);
500}
501
504 if (!p)
505 return nullptr;
506 int i = index();
507 return i <= 0 ? nullptr : p->child_at(i - 1);
508}
509
510} // namespace ultralight
#define AExport
Definition Defines.h:41
Iterator over a container's children (a forward range of RefPtr<LayoutNode>).
Definition Container.h:422
int difference_type
Definition Container.h:425
RefPtr< LayoutNode > value_type
Definition Container.h:424
friend bool operator==(const ChildIterator &, const ChildIterator &)=default
ChildIterator & operator++()
Definition Container.h:431
ChildIterator operator++(int)
Definition Container.h:435
RefPtr< LayoutNode > operator*() const
Definition Container.h:430
ChildIterator(const Container *container, int index)
Definition Container.h:428
A range over the container's children:
Definition Container.h:457
ChildIterator end() const
Definition Container.h:461
ChildRange(const Container *container, int count)
Definition Container.h:459
ChildIterator begin() const
Definition Container.h:460
A layout node that organizes child nodes into a row or column.
Definition Container.h:109
virtual bool Move(RefPtr< LayoutNode > node, InsertPosition position={})=0
Reorder a direct child within this container.
virtual RefPtr< Container > AddColumn(const ContainerOptions &options={}, InsertPosition position={})=0
Create a child column container.
virtual RefPtr< Panel > AdoptPanel(RefPtr< View > view, const PanelOptions &options={}, InsertPosition position={})=0
Create a panel that adopts an existing View (including a View created through a Session).
virtual void SetNeedsLayout()=0
Mark this container's layout stale.
virtual RefPtr< Panel > FindPanel(const String &key)=0
Find a descendant panel by key.
virtual bool Remove(RefPtr< LayoutNode > node)=0
Remove a direct child (and, for a container child, its whole subtree) from the tree.
virtual void SetLayoutOverride(LayoutOverrideCallback callback, void *user_data=nullptr, LayoutDestroyUserDataCallback destroy_user_data=nullptr)=0
Override this container's layout with a layout delegate.
virtual RefPtr< LayoutNode > child_at(int index) const =0
Get the child at an index.
virtual RefPtr< Panel > AddPanel(const PanelOptions &options, const ViewConfig &view_config, InsertPosition position={})=0
Create a panel with a caller-supplied ViewConfig.
virtual RefPtr< LayoutNode > Find(const String &key)=0
Find a descendant by key.
void SetLayoutOverride(Callback callback)
Install a layout delegate (invocable form).
Definition Container.h:405
RefPtr< Panel > AddPanel(ViewRef &&view, const PanelOptions &options={}, InsertPosition position={})
Adopt an existing View (shorthand for AdoptPanel()).
Definition Container.h:180
ChildRange children() const
Get a forward range over the children.
Definition Container.h:471
virtual bool HasLayoutOverride() const =0
Whether or not this container has a layout delegate installed.
virtual RefPtr< Panel > AddPanel(const PanelOptions &options={}, InsertPosition position={})=0
Create a panel with a new View (window-default view configuration).
virtual void SetDividerStyle(const DividerStyle &style)=0
Set this container's divider style (see <AppCore/layout/DividerStyle.h>).
virtual void RemoveAll()=0
Remove every child.
virtual RefPtr< Container > FindContainer(const String &key)=0
Find a descendant container by key.
RefPtr< Container > Build(Children... children)
Append builder elements (see <AppCore/layout/Builder.h>) to this container.
Definition Container.h:485
virtual RefPtr< Container > AddRow(const ContainerOptions &options={}, InsertPosition position={})=0
Create a child row container.
virtual int child_count() const =0
Get the number of children.
Base class for Panels and Containers in a window layout tree.
Definition LayoutNode.h:118
virtual RefPtr< Container > parent() const =0
Get the node's parent container (null at the root or when detached).
RefPtr< LayoutNode > next_sibling() const
Get the sibling after this node (null at the end, at the root, or when detached).
Definition Container.h:494
virtual int index() const =0
Get the node's index within its parent (-1 when detached).
RefPtr< LayoutNode > previous_sibling() const
Get the sibling before this node (null at the start, at the root, or when detached).
Definition Container.h:502
virtual String key() const =0
Get the node's key (empty if unkeyed).
A nullable smart pointer.
Definition RefPtr.h:126
Unicode string container with conversions for UTF-8, UTF-16, and UTF-32.
Definition String.h:31
A builder element (see <AppCore/layout/Builder.h>): anything that can append itself to a container.
Definition Container.h:21
Root namespace for every public Ultralight type, function, and enumeration.
void(*) LayoutOverrideCallback(void *user_data, Container *container, Rect content_box)
Layout delegate, called to place a container's children yourself.
Definition Callback.h:92
void(*) LayoutDestroyUserDataCallback(void *user_data)
Destroy hook for a callback registration's user data.
Definition Callback.h:27
Configuration options for a row or column container.
Definition Options.h:265
Line thickness, colors, and grab width for draggable pane dividers.
Definition DividerStyle.h:47
Position relative to an existing sibling in a container.
Definition Options.h:348
Configuration options for a panel in a row or column.
Definition Options.h:182
Float Rectangle Helper.
Definition Geometry.h:416
View-specific configuration settings.
Definition View.h:100