From 0001e249fd33d8efa7d35c2e76e79094386bdb8a Mon Sep 17 00:00:00 2001 From: Sander van Rossen Date: Fri, 4 Dec 2026 12:09:45 +0100 Subject: [PATCH 1/9] Build dialogs on the public API, with a context the app owns (#350) There is no extension registry in GUIApplication any more. The dialogs live in namespace tachyon::dialogs: their controls take the app and a dialogs::Context the app owns, and the app calls dialogs::EndGUI last in OnGUI and dialogs::Cleanup before its own cleanup. Their styles refresh when GUIApplication::StylesGeneration changes. --- CHANGELOG.md | 12 +- docs/contributing/writing-controls.md | 56 +++--- docs/controls/buttons-and-toggles.md | 9 +- docs/controls/other-controls.md | 81 +++++---- docs/controls/tooltips-and-dialogs.md | 132 +++++++++----- docs/controls/trees-and-grids.md | 2 +- docs/controls/windows-and-layout.md | 4 +- examples/showcase/application.cpp | 81 +++++---- examples/showcase/application.h | 6 +- examples/showcase/capture.cpp | 4 +- examples/showcase/panel_files.cpp | 16 +- examples/showcase/panel_hierarchy.cpp | 20 +-- examples/showcase/panel_inspector.cpp | 12 +- examples/showcase/panel_misc.cpp | 12 +- examples/showcase/progress_demos.cpp | 34 ++-- examples/showcase/settings_theme.cpp | 8 +- src/CMakeLists.txt | 3 +- src/gui_controls/gui_app_extension.h | 66 ------- src/gui_controls/gui_application.cpp | 49 +---- src/gui_controls/gui_application.h | 34 +--- ..._dialogs_extension.cpp => gui_dialogs.cpp} | 155 ++++++++-------- src/gui_dialogs/gui_dialogs.h | 145 ++++++++++----- src/gui_dialogs/gui_dialogs_internal.h | 67 +------ src/gui_dialogs/gui_message_dialog.cpp | 18 +- src/gui_dialogs/gui_message_dialog_types.h | 2 +- src/gui_dialogs/gui_notification_types.h | 2 +- src/gui_dialogs/gui_notifications.cpp | 38 ++-- src/gui_dialogs/gui_progress.cpp | 78 ++++---- src/gui_dialogs/gui_progress_types.h | 2 +- tests/CMakeLists.txt | 1 - tests/app_extension_test.cpp | 118 ------------ tests/controls_notifications_test.cpp | 119 ++++++------ tests/gpu/gpu_message_dialog_test.cpp | 16 +- tests/gpu/gpu_theme_crossfade_test.cpp | 3 +- tests/message_dialog_test.cpp | 31 ++-- tests/progress_composites_test.cpp | 170 +++++++++--------- tests/progress_test.cpp | 58 +++--- tests/redraw_test.cpp | 7 +- tests/static_id_release_test.cpp | 11 +- tests/theme_variables_test.cpp | 7 +- 40 files changed, 760 insertions(+), 929 deletions(-) delete mode 100644 src/gui_controls/gui_app_extension.h rename src/gui_dialogs/{gui_dialogs_extension.cpp => gui_dialogs.cpp} (60%) delete mode 100644 tests/app_extension_test.cpp diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ea2e1fb..4d4d77b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,8 +15,8 @@ Notable changes per release. Releases are tagged `vX.Y.Z`; the version lives in - The package installs third-party headers only for the libraries its public headers include (SDL3, VMA, D3D12 Memory Allocator). The privately linked ones (HarfBuzz, skribidi, SheenBidi, libunibreak, budoux, nanosvg, vk-bootstrap) are there as library files alone, without headers or package configs. - The file system, file icons and file thumbnails (`IFileSystem`, `MemoryFileSystem`, `FileIcons`, `FileThumbnails`) moved out of `gui_controls` into the examples (`examples/app_controls`, as ``): they serve one kind of app. The showcase's Files panel uses them from there. - Drag and drop is part of `gui_core`: `MakeDragSourceHandler` and `MakeDropTargetHandler` moved to `gui_core/input/gui_drag_drop.h` (still included by `gui_controls/gui_default_handlers.h`). `DispatchToElementChain` carries drag events and drops from other applications up from the element under the pointer, one path for both. -- Extensions: a library of controls on top of `gui_controls` keeps its state per application in an `AppExtension` (`app.Extension()`, `gui_controls/gui_app_extension.h`), with hooks for theme loads, the frame and cleanup. Its controls are free functions that take the app. `ScheduleFrameAt`, `CloseOnPressOutside`, `RetireWindow`, `AppColorStyle`, `ButtonGroupItemStyle`, `NoteButtonGroupItem`, `LastStatusBar` and `GUITheme::VariableColor` are public for them. -- Dialogs are the first extension, `gui_dialogs` (`TachyonUI::gui_dialogs`, ``): `MessageDialog`, `ShowToast`, `FindToast`, `DismissToast`, `Toasts`, `Banner`, `BusyButton` and the progress controls (`ProgressBar`, `IndeterminateProgressBar`, `Spinner`, `CircularProgress`, `Skeleton`, `TaskProgress`, `ProgressSteps`, `StatusProgress`, `BackgroundTasks`) are free functions now, the app first: `ShowToast(app, desc)`, or `ShowToast(*this, desc)` inside an app class. Their styles moved from `GUITheme` to `GetDialogStyles(app)`. +- Extensions: a library of controls on top of `gui_controls` has its own namespace and is built on the public API: its controls are free functions that take the app and a context of the library's own, which the app owns, and the app calls the library's frame and cleanup functions itself. `ScheduleFrameAt`, `CloseOnPressOutside`, `RetireWindow`, `AppColorStyle`, `ButtonGroupItemStyle`, `NoteButtonGroupItem`, `LastStatusBar`, `StylesGeneration` and `GUITheme::VariableColor` are public for them. +- Dialogs are the first extension, `gui_dialogs` (`TachyonUI::gui_dialogs`, ``, namespace `tachyon::dialogs`): `MessageDialog`, `ShowToast`, `FindToast`, `DismissToast`, `Toasts`, `Banner`, `BusyButton` and the progress controls (`ProgressBar`, `IndeterminateProgressBar`, `Spinner`, `CircularProgress`, `Skeleton`, `TaskProgress`, `ProgressSteps`, `StatusProgress`, `BackgroundTasks`) are free functions now, taking the app and a `dialogs::Context` the app owns: `dialogs::ShowToast(app, dialogContext, desc)`. The app calls `dialogs::EndGUI` last in `OnGUI` and `dialogs::Cleanup` before its own cleanup. Their styles moved from `GUITheme` to `dialogs::GetStyles(app, dialogContext)`. - No files or DLLs to ship: the shaders, the default themes and the fonts are built into the library (`TACHYON_EMBED_RESOURCES`), and the bundled SDL3 is linked statically. `SetResourceRoot` is only needed for an app's own themes and fonts; a file there replaces the built-in one of the same name. - Resource files must be named in their exact case on every platform. The built-in themes and fonts are no longer found by a name in another case on Windows. `SetPathCaseCheck` compares the paths of the theme, font, icon and shader files the library opens with their names on disk: debug builds log a wrong case, `PathCaseCheck::Fail` refuses the file as Linux would, and the test programs run with it. `FindPathCaseMismatch` and `CheckPathCase` do the same for an app's own files. A test checks every resource path in the source and docs against the files on disk, and that no two files differ only in case. See [Resource paths](docs/contributing/resource-paths.md). - `GraphicsContext::SetShaderDirectory` is gone; `VulkanGraphicsContext::SetShaderDirectory` loads shaders from disk instead of the built-in ones. The package no longer installs `shaders_compiled/`. @@ -135,7 +135,7 @@ Notable changes per release. Releases are tagged `vX.Y.Z`; the version lives in - Node view: Fit and Home frame the selected nodes, or all of them when none is selected. `FrameSelectedNodes` and `FrameNodes(view, indices)` join `FrameAllNodes`. - Showcase: the node view's canvas menu has its view items after a separator ("Frame all", or "Frame selection", and "Show curved wires" / "Show grid aligned wires"); the settings' font size is a smaller / size / larger control, "Motion" is "Animations", with a tooltip, the undo levels are on General, and the Advanced and About pages are gone. - Layout presets: named arrangements of a document's panels. `LayoutPresets` holds the app's built-in ones (`AddBuiltIn`) and the ones the user saved (`Save`, `Remove`), and the preset each file type opens with (`SetForFileType`, `ForFileType`); `PersistLayoutPresets` keeps the saved ones and the file types. `SaveDockLayout` writes a layout's dock tree as text, and `ApplyDockLayout` lays a layout out as such a tree says, making the panels it lacks through a callback and closing the ones the tree doesn't name. -- `MessageDialogDesc::input`: a text field in the dialog, for a name to give; Enter in it chooses the default button. +- `dialogs::MessageDialogDesc::input`: a text field in the dialog, for a name to give; Enter in it chooses the default button. - `BeginDropdownMenu`: a menu trigger that stays a dropdown, with its arrow, inside a menu bar or title bar, and isn't one of the bar's menus. Its theme style, `menu-bar-dropdown`, is flat like the bar's menus, with the small arrow on the right. - `GridViewVirtualState::onOpen`: called when an item is double-clicked, or with the selected one on Enter. - `DocumentBar` and `DocumentPanels`: the two parts of `Documents`, to place apart, such as the tabs in the title bar (`theme.titleBarDocumentsStyleRef`) and the menus under them. "N open" stays a dropdown in a title bar. @@ -147,7 +147,7 @@ Notable changes per release. Releases are tagged `vX.Y.Z`; the version lives in - `GradientF`: a gradient of float colors for data such as a gradient map: up to 64 stops, colors over 1 (HDR) kept, each stop blending to the next linearly, smoothly or in a step (`StopInterpolation`), in any of the color spaces a `Gradient` blends in. `Sample`, `WriteTo` (float, or clamped 8-bit), and `From` / `ToGradient`. `GradientField` edits one: the editor takes its stops and colors, and has each stop's blend to the next. `Gradient` is unchanged and blends as before, with the same code. `ColorStyle::ToVisualStyle`, `StyleManager::CreateColorStyle` / `UpdateColorStyle` take a row of pixels as a gradient's ramp (`GradientManager::AcquireRowPixels`). - Allocation hooks also take the memory of the text and SVG libraries (HarfBuzz, skribidi, SheenBidi, nanosvg) while the app lives. A `SkribidiTextSystem` made with hooks routes them itself. Data HarfBuzz keeps until the process ends (its Unicode tables, the languages it has seen) is made on the C heap where it can be, so a short-lived `TrackingAllocator` sees nothing live after `Cleanup`. A host's own HarfBuzz (`TACHYON_SYSTEM_HARFBUZZ`) keeps its own allocator. - Progress and loading controls: `ProgressBar` (failed in the error color, a 4px small style), `IndeterminateProgressBar` (a soft segment sliding along), `Spinner` in three sizes, `CircularProgress` with its percentage, and `Skeleton` placeholders with a shine that stops under reduced motion. `BusyButton` shows a spinner and "Saving..." in place of its icon and text, keeps its width and ignores clicks while busy. `CustomDrawContext::RenderArc` draws part of a ring with round ends. `ElementFlags::Animated` marks an element that moves every frame, so a `BeginCached` scope holding one is rebuilt. The showcase's Misc panel shows them all. -- Task progress built on those, each taking a `ProgressTask` (name, value, `TaskState`, note, detail, cancel and retry callbacks): `TaskProgress` (name and percent over the bar, a cancel button and a detail line; failed with an error icon, the reason and Retry; done as one line with a check and the time taken), `ProgressSteps` (a glyph per step: check, spinner, dashed ring; a small bar under the running one), `StatusProgress` (spinner, name, 120px bar and count, for a status bar) and `BackgroundTasks` (a "3 tasks" pill opening a popover of the tasks with their bars and cancel buttons). A paused task's bar is in the warning color. New palette colors `--error-text` and `--on-ok`. +- Task progress built on those, each taking a `dialogs::ProgressTask` (name, value, `dialogs::TaskState`, note, detail, cancel and retry callbacks): `TaskProgress` (name and percent over the bar, a cancel button and a detail line; failed with an error icon, the reason and Retry; done as one line with a check and the time taken), `ProgressSteps` (a glyph per step: check, spinner, dashed ring; a small bar under the running one), `StatusProgress` (spinner, name, 120px bar and count, for a status bar) and `BackgroundTasks` (a "3 tasks" pill opening a popover of the tasks with their bars and cancel buttons). A paused task's bar is in the warning color. New palette colors `--error-text` and `--on-ok`. - Runtime accent color: `SetAccent` replaces the palette's accent without a new palette file, with a color for dark palettes and one for light ones (`AccentColors`), and crossfades to it. The colors derived from it follow, at the palettes' own amounts: `--accent-soft`, `--bg-menu-hover`, `--selection`, `--caret`, `--divider-hover`, `--focus-ring`, `--selected-ring`. `kAccentPresets` has the design's Blue, Teal, Violet and Orange. `GUITheme::IsLight` tells a light palette from a dark one. The showcase's Settings > Appearance has an Accent dropdown. - Node view frames (`NodeView::frames`, `NodeFrame`): titled, tinted boxes behind a group of nodes and their wires. Dragging the title moves the frame, the frames inside it and their nodes; the right and bottom edges resize it; a double-click on the title renames it (`RenameFrame`); `onFrameContextMenu` builds its menu. They select as nodes do (`selectedFrameIDs`) and change through edits (`NodeViewEdit::frameChanges`, `frames`), so they undo. A collapsed frame is drawn as one node, with a row for each wire crossing its edge, and hides what it held when it collapsed; the chevron on its title or Enter toggles it (`CollapseFrameEdit`). Helpers `AddFrameEdit`, `RemoveFramesEdit`, `FrameAroundNodes`, `NodesInFrame`, `FrameTitleAtCanvasPos`. The minimap shows them. The showcase's node graph starts with a frame, and its menus put nodes in a frame, add a frame, rename, tint, collapse and delete one, and add nodes of four kinds. - Node view: a wire's lane dragged between two nodes, one above the other, goes round them both (above or below) as well as between them, as it already could for nodes side by side; one let go inside a node goes to its nearer edge. @@ -256,7 +256,7 @@ Notable changes per release. Releases are tagged `vX.Y.Z`; the version lives in - Property help: a label's dotted underline sits 1px under the text's line instead of 3px, inside it, so it shows in a label group and on a label only as tall as its text; it was cut off there (the Inspector's labels). - Showcase: the Inspector shows each kind of tooltip: Cast shadows with property help, a disabled Publish that says why, and an Opacity out of its range with its error. The captures take the shortcut chip (Curves' Frame all), the help, the disabled and the error tooltips. - Progress steps: each step is a line, its 18px glyph level with its name and its note or percent at the line's end; the running step's bar runs from under its name to the end, with its `detail` under it ("Lightmap atlas, about 1 min left"), and a failed step says "failed" (`progress-step-header`, `progress-step-error`). The glyph was 16px and the bar and note sat beside the name. -- Progress: `SpinnerSize::Large` is 18px (was 24px) and `CircularProgress` 36px (was 40px), as the design has them. Retry has a turning arrow (`theme.retryIcon`), and the background tasks' pill a chevron pointing where its popover opens. A background task with `ProgressTask::onPause` has a pause button while it runs and a resume button while it's paused (`task-progress-pause`). The tasks' popover opens again after the OS closed it; the pill did nothing then. +- Progress: `dialogs::SpinnerSize::Large` is 18px (was 24px) and `CircularProgress` 36px (was 40px), as the design has them. Retry has a turning arrow (`theme.retryIcon`), and the background tasks' pill a chevron pointing where its popover opens. A background task with `dialogs::ProgressTask::onPause` has a pause button while it runs and a resume button while it's paused (`task-progress-pause`). The tasks' popover opens again after the OS closed it; the pill did nothing then. - Dialog primary buttons draw their icon in the text's color (`--on-accent`), so a busy one's spinner shows on the accent. - Showcase: progress shows where the work happens, not in the Misc panel. A Build panel runs a build's steps, with Cancel and a Build button busy while it builds; the status bar shows the indexing and, at its far right, the background tasks' pill, where the paused upload can be resumed; the frame time moved left, after the GPU, and the theme's path is gone; the Files panel's toolbar imports a file, its tile showing a ring; the viewport shows its shaders compiling at startup; the hierarchy's props load and its terrain streams in. Captures hold each at a moment, and take the Build panel and the tasks' popover from the status bar. - Reorderable: in a group that wraps, the dashed gap an item will drop into is on the row (or column) it lands in; it stayed on the row the item came from, outlining another item. @@ -265,7 +265,7 @@ Notable changes per release. Releases are tagged `vX.Y.Z`; the version lives in - Color picker: New sits over Original, each named beside its half; the value range is in the footer after the format ("sRGB · 8-bit · 0–255"), still a click to switch. The swatches start as the design's palette of twelve; `SetColorSwatches` / `ColorSwatches` set and read them, and `AddRecentColor` adds to the recent colors. - Gradient editor: the table lists Color, Alpha and Location (a `GradientF`'s adds each stop's Blend); the footer's hint is gone. The preset in use is ringed for an 8-bit gradient too: its stops, kept in 1/65535ths, didn't match the preset's exactly. - Showcase: the Inspector's color and gradient rows are Tint and Sky ramp, so the picker and the editor say what they edit; the gradient starts as the Sky preset, and the picker has recent colors. -- Toasts: in a window with a status bar, the stack sits above it instead of over it. `ToastDesc::icon` gives a toast its own icon in place of its severity's (an upload's up arrow). +- Toasts: in a window with a status bar, the stack sits above it instead of over it. `dialogs::ToastDesc::icon` gives a toast its own icon in place of its severity's (an upload's up arrow). - Showcase: quitting with unsaved documents asks "Save changes before closing?", each document listed with a check box and its color dot, and saves only those checked (Don't save, Cancel, Save all). Quitting with nothing unsaved but work running asks "Quit Test?", listing the work and how far each is, with Don't ask again. Deleting several hierarchy objects asks first, listing them, with Don't ask again this session. Opening a compiled shader in the Files panel says it couldn't, with its details and Copy details. File > Reload from disk asks about a modified document (Keep mine, Reload). The demo toasts are six, so two fold into "+2 earlier", and the upload's has an up arrow. Captures take each of these questions. - Menus: a destructive item's row is tinted with the error color when hovered (`menu-item-row-destructive`). An item that opens a submenu stays lit while the submenu is open, its arrow brighter. The control or row a context menu was opened on looks hovered while the menu is open. - Timeline: the lanes menu's shortcuts read as the command system writes them ("Delete", "Ctrl A"). diff --git a/docs/contributing/writing-controls.md b/docs/contributing/writing-controls.md index d183a959..7532c8fe 100644 --- a/docs/contributing/writing-controls.md +++ b/docs/contributing/writing-controls.md @@ -973,45 +973,51 @@ A pen on a tablet or pen display drives the pointer as a mouse does. ## Controls outside GUIApplication A library of controls on top of `gui_controls` (such as `gui_dialogs`), or an app's own, -can't add members to `GUIApplication`. Its controls are free functions that take the app. +can't add members to `GUIApplication`. Its controls are free functions in a namespace of its +own, and they take the app. -- The app comes first; the rest is as a member control's would be: +- The app comes first, then the library's context; the rest is as a member control's + would be: ```cpp - void Rating(GUIApplication& app, ID id, int& stars, LayoutOverride&& constraints = {}); + ratings::Rating(*this, ratingContext, ratingID, stars); // in your app class ``` -- What it keeps from frame to frame, and its styles, live in an `AppExtension` - (`gui_controls/gui_app_extension.h`): one per app, made the first time - `app.Extension()` asks for it, kept until `Cleanup`. +- What it keeps from frame to frame, and its styles, are a plain struct the app owns and + passes to each of its controls: a context. The library knows nothing of where it's kept. +- What has to happen once a frame, or at cleanup, are functions the app calls itself, at + the right point: the end of `OnGUI`, before its own `Cleanup`. ```cpp - class Ratings : public AppExtension + namespace ratings { - public: - explicit Ratings(GUIApplication& app) : AppExtension(app) {} - void OnStylesLoaded() override { starStyle = app.theme.GetStyle("rating-star"); } - StyleRef starStyle{}; - }; + struct Context + { + StyleRef starStyle{}; + uint32_t stylesGeneration = 0; + }; + + void Rating(GUIApplication& app, Context& context, ID id, int& stars, LayoutOverride&& constraints = {}); + void EndGUI(GUIApplication& app, Context& context); // last in OnGUI + void Cleanup(GUIApplication& app, Context& context); // before GUIApplication::Cleanup + } + ``` + +- Styles come from the theme by their CSS classes. A theme load clears every `StyleRef`, so + look them up again when `app.StylesGeneration()` changes: - void Rating(GUIApplication& app, ID id, int& stars, LayoutOverride&& constraints) + ```cpp + if (context.stylesGeneration != app.StylesGeneration()) { - Ratings& ratings = app.Extension(); - app.BeginHorizontal(id, std::move(constraints)); - ... + context.starStyle = app.theme.GetStyle("rating-star"); + context.stylesGeneration = app.StylesGeneration(); } ``` -- Its hooks run with the app, in the order the extensions were made: - - `OnStylesLoaded`: after each theme load, which clears every `StyleRef`; look the - extension's styles up here by their CSS classes - - `OnPostConstruct`: every element of the frame is declared, before layout - - `OnEndFrame`: drop the state of controls no longer built - - `OnCleanup`: give back static IDs and close windows, before the extension is destroyed -- A lambda that runs later (an event handler, a post-layout callback) captures `&app` and - gets the extension again inside, rather than holding on to it. +- A lambda that runs later (an event handler, a post-layout callback) holds a pointer to + the context, which lives as long as the app. - What a control inside `GUIApplication` uses that isn't otherwise public is in the - Extensions group of `gui_application.h`: + "For controls outside GUIApplication" group of `gui_application.h`: - `ScheduleFrameAt`: a frame at a later time, for a control that changes by itself - `CloseOnPressOutside`: a popover that closes on a press elsewhere - `RetireWindow`: close a popup window whose state went diff --git a/docs/controls/buttons-and-toggles.md b/docs/controls/buttons-and-toggles.md index 669085ce..0120a832 100644 --- a/docs/controls/buttons-and-toggles.md +++ b/docs/controls/buttons-and-toggles.md @@ -58,8 +58,9 @@ EndHorizontal(); A button that can show it's at work, for example while a save runs. -- It's in the dialogs library, with the other progress controls: link - `TachyonUI::gui_dialogs`, include ``, and pass the app first. +- It's in the dialogs library, with the other progress controls: `dialogs::BusyButton`, + with the app and a `dialogs::Context` first. See + [Message dialogs](tooltips-and-dialogs.md#message-dialogs) for the setup. - While `busy` is `false` it's an ordinary [Button](#button). - While `busy` is `true`: - a turning spinner takes the place of its icon @@ -70,7 +71,7 @@ A button that can show it's at work, for example while a save runs. - it returns `false` ```cpp -bool BusyButton(GUIApplication& app, ID id, const GUIContent& content, bool busy, std::string_view busyText, +bool dialogs::BusyButton(GUIApplication& app, Context& context, ID id, const GUIContent& content, bool busy, std::string_view busyText, std::function onClick, StyleRef style, LayoutOverride&& constraints = {}); ``` @@ -78,7 +79,7 @@ You decide when it's busy, so pass a flag your own work sets and clears: ```cpp // member: bool saving -BusyButton(*this, saveID, { saveIcon, "Save" }, saving, "Saving...", [this] { saving = true; StartSave(); }); +dialogs::BusyButton(*this, dialogContext, saveID, { saveIcon, "Save" }, saving, "Saving...", [this] { saving = true; StartSave(); }); ``` ```cpp diff --git a/docs/controls/other-controls.md b/docs/controls/other-controls.md index 576d316a..1f8df4b9 100644 --- a/docs/controls/other-controls.md +++ b/docs/controls/other-controls.md @@ -49,18 +49,17 @@ EndStatusBar(); Controls that show work is under way. None of them take clicks. -- These are in the dialogs library, not in `GUIApplication`: - - link `TachyonUI::gui_dialogs` and include `` - - each is a free function whose first argument is the app: inside your app class that's - `*this`, elsewhere your app object +- These are in the dialogs library, not in `GUIApplication`: link `TachyonUI::gui_dialogs`, + and keep a `dialogs::Context` in your app. See + [Message dialogs](tooltips-and-dialogs.md#message-dialogs) for the setup. + - each takes the app, then the context: ```cpp - ProgressBar(*this, 0.5f); // in OnGUI - ProgressBar(app, 0.5f); // anywhere else + dialogs::ProgressBar(*this, dialogContext, 0.5f); // in your app class ``` - - their styles are in `GetDialogStyles(app)`, for example - `GetDialogStyles(*this).progressBarSmallStyleRef` + - their styles are in `dialogs::GetStyles(app, dialogContext)`, for example + `dialogs::GetStyles(*this, dialogContext).progressBarSmallStyleRef` - A value is a fraction from 0 to 1. Values outside that range are clamped, and NaN counts as 0. - The moving ones (the indeterminate bar, the spinner and the skeleton's shine) move by @@ -75,25 +74,25 @@ Controls that show work is under way. None of them take clicks. A bar filled `value` of the way, for work whose length you know. ```cpp -void ProgressBar(GUIApplication& app, ID id, float value, bool failed, StyleRef style, LayoutOverride&& constraints = {}); +void dialogs::ProgressBar(GUIApplication& app, Context& context, ID id, float value, bool failed, StyleRef style, LayoutOverride&& constraints = {}); ``` - `failed` fills it in the error color instead, for work that stopped part way. - The theme's bar is 6px high. - - `GetDialogStyles(*this).progressBarSmallStyleRef` is 4px high, for lists and status bars. + - `dialogs::GetStyles(*this, dialogContext).progressBarSmallStyleRef` is 4px high, for lists and status bars. - It fills the width it's given. - Give it a width when it shares a row. ```cpp -ProgressBar(*this, float(filesDone) / float(fileCount)); +dialogs::ProgressBar(*this, dialogContext, float(filesDone) / float(fileCount)); ``` ```cpp -ProgressBar(*this, bakeID, bakeDone, bakeFailed, GetDialogStyles(*this).progressBarStyleRef); +dialogs::ProgressBar(*this, dialogContext, bakeID, bakeDone, bakeFailed, dialogs::GetStyles(*this, dialogContext).progressBarStyleRef); ``` ```cpp -ProgressBar(*this, indexID, indexDone, false, GetDialogStyles(*this).progressBarSmallStyleRef, LayoutOverride::Auto().Width(120)); +dialogs::ProgressBar(*this, dialogContext, indexID, indexDone, false, dialogs::GetStyles(*this, dialogContext).progressBarSmallStyleRef, LayoutOverride::Auto().Width(120)); ``` Classes: @@ -109,12 +108,12 @@ A bar for work whose length you don't know. - It takes the same bar styles as ProgressBar. ```cpp -void IndeterminateProgressBar(GUIApplication& app, ID id, StyleRef style, LayoutOverride&& constraints = {}); +void dialogs::IndeterminateProgressBar(GUIApplication& app, Context& context, ID id, StyleRef style, LayoutOverride&& constraints = {}); ``` ```cpp Text("Compiling shaders..."); -IndeterminateProgressBar(*this); +dialogs::IndeterminateProgressBar(*this, dialogContext); ``` Classes: `progress-bar` (the track), `progress-segment` (the sliding segment). @@ -124,19 +123,19 @@ Classes: `progress-bar` (the track), `progress-segment` (the sliding segment). A faint ring with an arc going round it, a turn every 0.8 s. ```cpp -void Spinner(GUIApplication& app, ID id, SpinnerSize size = SpinnerSize::Medium, LayoutOverride&& constraints = {}); +void dialogs::Spinner(GUIApplication& app, Context& context, ID id, dialogs::SpinnerSize size = dialogs::SpinnerSize::Medium, LayoutOverride&& constraints = {}); ``` -- `SpinnerSize::Small`, `Medium` and `Large` are 12, 16 and 18px across. +- `dialogs::SpinnerSize::Small`, `Medium` and `Large` are 12, 16 and 18px across. - A width or height in `constraints` overrides the size. - The ring scales to fit the space it gets. -- The colors are `GetDialogStyles(*this).progressTrackColor` (the ring) and `GetDialogStyles(*this).progressArcColor` (the +- The colors are `dialogs::GetStyles(*this, dialogContext).progressTrackColor` (the ring) and `dialogs::GetStyles(*this, dialogContext).progressArcColor` (the arc). - These come from `--line-subtle` and `--accent` in the theme. ```cpp BeginHorizontal(); -Spinner(*this, SpinnerSize::Small); +dialogs::Spinner(*this, dialogContext, dialogs::SpinnerSize::Small); Text("Loading preview"); EndHorizontal(); ``` @@ -147,14 +146,14 @@ A ring that fills clockwise from the top as `value` grows, with the percentage i middle. ```cpp -void CircularProgress(GUIApplication& app, ID id, float value, StyleRef style, LayoutOverride&& constraints = {}); +void dialogs::CircularProgress(GUIApplication& app, Context& context, ID id, float value, StyleRef style, LayoutOverride&& constraints = {}); ``` - The percentage is rounded down, so it only shows 100 once the work is done. - The theme's is 36px across. ```cpp -CircularProgress(*this, uploadDone); +dialogs::CircularProgress(*this, dialogContext, uploadDone); ``` Class: `circular-progress`. @@ -170,15 +169,15 @@ across it every 1.5 s. - Under reduced motion it doesn't shine. ```cpp -void Skeleton(GUIApplication& app, ID id, StyleRef style, LayoutOverride&& constraints = {}); +void dialogs::Skeleton(GUIApplication& app, Context& context, ID id, StyleRef style, LayoutOverride&& constraints = {}); ``` ```cpp if (!profileLoaded) { BeginHorizontal(); - Skeleton(*this, LayoutOverride::Auto().Size(14, 14)); // the avatar - Skeleton(*this, LayoutOverride::Auto().Width(160)); // the name + dialogs::Skeleton(*this, dialogContext, LayoutOverride::Auto().Size(14, 14)); // the avatar + dialogs::Skeleton(*this, dialogContext, LayoutOverride::Auto().Width(160)); // the name EndHorizontal(); } ``` @@ -190,14 +189,14 @@ Classes: ### ProgressTask -The controls below show a piece of work described by a `ProgressTask`. You fill one in +The controls below show a piece of work described by a `dialogs::ProgressTask`. You fill one in every frame from your own state. | Field | What it's for | | --- | --- | | `name` | What the work is: "Importing character.fbx" | | `value` | How much is done, 0 to 1. Below 0 when you can't tell: the bar slides instead | -| `state` | `TaskState::Pending`, `Running` (the default), `Paused`, `Failed` or `Done` | +| `state` | `dialogs::TaskState::Pending`, `Running` (the default), `Paused`, `Failed` or `Done` | | `note` | A short text beside the name: "2.1 s", "1,240 / 3,800". Empty shows the percent while running | | `detail` | A line under the bar: "12.4 MB of 19.3 MB". Once failed, why it failed | | `onCancel` | Set it to get a cancel button while the work runs or is paused | @@ -208,7 +207,7 @@ every frame from your own state. - `Paused` draws the bar in the warning color and says "paused". ```cpp -ProgressTask task{ .name = "Exporting level", .value = exportDone, .detail = exportDetail, +dialogs::ProgressTask task{ .name = "Exporting level", .value = exportDone, .detail = exportDetail, .onCancel = [this] { exporter.Cancel(); } }; ``` @@ -217,7 +216,7 @@ ProgressTask task{ .name = "Exporting level", .value = exportDone, .detail = exp A piece of work in full, for a panel or a dialog. ```cpp -void TaskProgress(GUIApplication& app, ID id, const ProgressTask& task, LayoutOverride&& constraints = {}); +void dialogs::TaskProgress(GUIApplication& app, Context& context, ID id, const dialogs::ProgressTask& task, LayoutOverride&& constraints = {}); ``` - Running or paused: @@ -232,17 +231,17 @@ void TaskProgress(GUIApplication& app, ID id, const ProgressTask& task, LayoutOv - Done: one line with a check, the name and the note, such as how long it took. No bar. ```cpp -TaskProgress(*this, ProgressTask{ .name = "Importing character.fbx", .value = importDone, +dialogs::TaskProgress(*this, dialogContext, dialogs::ProgressTask{ .name = "Importing character.fbx", .value = importDone, .detail = "12.4 MB of 19.3 MB", .onCancel = [this] { CancelImport(); } }); ``` ```cpp -TaskProgress(*this, ProgressTask{ .name = "Bake failed at 73%", .value = 0.73f, .state = TaskState::Failed, +dialogs::TaskProgress(*this, dialogContext, dialogs::ProgressTask{ .name = "Bake failed at 73%", .value = 0.73f, .state = dialogs::TaskState::Failed, .detail = bakeError, .onRetry = [this] { StartBake(); } }); ``` ```cpp -TaskProgress(*this, ProgressTask{ .name = "Import complete", .state = TaskState::Done, .note = "2.1 s" }); +dialogs::TaskProgress(*this, dialogContext, dialogs::ProgressTask{ .name = "Import complete", .state = dialogs::TaskState::Done, .note = "2.1 s" }); ``` Classes: @@ -259,7 +258,7 @@ Classes: The steps of a longer job, one per row. ```cpp -void ProgressSteps(GUIApplication& app, ID id, std::span steps, LayoutOverride&& constraints = {}); +void dialogs::ProgressSteps(GUIApplication& app, Context& context, ID id, std::span steps, LayoutOverride&& constraints = {}); ``` - Each step's line starts with an 18px glyph for its state: @@ -274,13 +273,13 @@ void ProgressSteps(GUIApplication& app, ID id, std::span ste - its `detail`, such as "Lightmap atlas, about 1 min left" ```cpp -const ProgressTask steps[] = { - { .name = "Compile scripts", .state = TaskState::Done, .note = "4.2 s" }, - { .name = "Bake lighting", .value = 0.42f, .state = TaskState::Running, +const dialogs::ProgressTask steps[] = { + { .name = "Compile scripts", .state = dialogs::TaskState::Done, .note = "4.2 s" }, + { .name = "Bake lighting", .value = 0.42f, .state = dialogs::TaskState::Running, .detail = "Lightmap atlas, about 1 min left" }, - { .name = "Package assets", .state = TaskState::Pending }, + { .name = "Package assets", .state = dialogs::TaskState::Pending }, }; -ProgressSteps(*this, steps); +dialogs::ProgressSteps(*this, dialogContext, steps); ``` Classes: `progress-steps`, `progress-step`, `progress-step-header` (a step's line), @@ -294,12 +293,12 @@ A piece of work in a [status bar](#status-bar): a 12px spinner while it runs, it 120px bar and its note or percent. ```cpp -void StatusProgress(GUIApplication& app, ID id, const ProgressTask& task, LayoutOverride&& constraints = {}); +void dialogs::StatusProgress(GUIApplication& app, Context& context, ID id, const dialogs::ProgressTask& task, LayoutOverride&& constraints = {}); ``` ```cpp BeginStatusBar(); -StatusProgress(*this, ProgressTask{ .name = "Indexing assets", .value = indexed, .note = indexCount }); +dialogs::StatusProgress(*this, dialogContext, dialogs::ProgressTask{ .name = "Indexing assets", .value = indexed, .note = indexCount }); EndStatusBar(); ``` @@ -313,7 +312,7 @@ in the background. - Its chevron points up, where the popover opens, and down while it's open. ```cpp -bool BackgroundTasks(GUIApplication& app, ID id, std::span tasks, LayoutOverride&& constraints = {}); +bool dialogs::BackgroundTasks(GUIApplication& app, Context& context, ID id, std::span tasks, LayoutOverride&& constraints = {}); ``` - A click on the pill opens the popover above it, and another click closes it. @@ -327,7 +326,7 @@ bool BackgroundTasks(GUIApplication& app, ID id, std::span t ```cpp BeginStatusBar(); StatusText("Ready", LayoutOverride::Auto().FlexGrow(1)); -BackgroundTasks(*this, backgroundTasksID, backgroundTasks); // member: std::vector +dialogs::BackgroundTasks(*this, dialogContext, backgroundTasksID, backgroundTasks); // member: std::vector EndStatusBar(); ``` diff --git a/docs/controls/tooltips-and-dialogs.md b/docs/controls/tooltips-and-dialogs.md index d65a09ed..50986c6f 100644 --- a/docs/controls/tooltips-and-dialogs.md +++ b/docs/controls/tooltips-and-dialogs.md @@ -200,16 +200,50 @@ automatic: there's nothing to declare. ## Message dialogs -Message dialogs, toasts and banners are in the dialogs library, not in `GUIApplication`: - -- link `TachyonUI::gui_dialogs` and include `` -- each is a free function whose first argument is the app: inside your app class that's - `*this`, elsewhere your app object - - ```cpp - ShowToast(*this, ToastDesc{ .title = "Saved" }); // in your app class - ShowToast(app, ToastDesc{ .title = "Saved" }); // anywhere else - ``` +Message dialogs, toasts and banners are in the dialogs library, not in `GUIApplication`. +So are the progress controls and `BusyButton`. + +- Link `TachyonUI::gui_dialogs` and include ``. +- They're in namespace `tachyon::dialogs`, as are their types (`dialogs::ToastDesc`, + `dialogs::MessageDialogDesc`). +- What they keep from frame to frame (the toasts shown, a dialog's dimmed windows, their + styles) is a `dialogs::Context` your app owns, for example a member of your app class. + - Each dialog function takes the app first, then the context: + + ```cpp + dialogs::ShowToast(*this, dialogContext, dialogs::ToastDesc{ .title = "Saved" }); // in your app class + dialogs::ShowToast(app, dialogContext, dialogs::ToastDesc{ .title = "Saved" }); // anywhere else + ``` + + - Call `dialogs::EndGUI` last in `OnGUI`, every frame. It brings the toasts over the rest + of their window, dims the windows under a message dialog, and drops what dialogs no + longer built held. + - Call `dialogs::Cleanup` before the app's own cleanup, to give back what the dialogs + hold. + + ```cpp + class MyApp : public tachyon::GUIApplication + { + tachyon::dialogs::Context dialogContext; + + void OnGUI() override + { + // ... the windows, with their dialogs + tachyon::dialogs::EndGUI(*this, dialogContext); + } + + void Cleanup() override + { + tachyon::dialogs::Cleanup(*this, dialogContext); + GUIApplication::Cleanup(); + } + }; + ``` + + - Don't name the context `dialogs`: it would hide the namespace, and `dialogs::ShowToast` + would no longer compile. + - Their styles are in `dialogs::GetStyles(app, dialogContext)`, looked up again after + each theme load. ### MessageDialog @@ -217,7 +251,7 @@ A message dialog asks the user a question, with a button for each answer, such a "Cancel" and "Quit". ```cpp -int MessageDialog(GUIApplication& app, ID id, const MessageDialogDesc& desc, StyleRef style); +int dialogs::MessageDialog(GUIApplication& app, Context& context, ID id, const dialogs::MessageDialogDesc& desc, StyleRef style); ``` - It's centered, and modal: the user can't use the rest of the app until they answer. @@ -231,12 +265,12 @@ Keyboard: - Alt plus a button's first letter chooses that button. - The default button starts with the focus. Tab cycles through the dialog. -| `MessageDialogDesc` field | Meaning | +| `dialogs::MessageDialogDesc` field | Meaning | | --- | --- | -| `icon` | `MessageIcon::Warning`, `Quit`, `Question`, `Info` or `Error` | +| `icon` | `dialogs::MessageIcon::Warning`, `Quit`, `Question`, `Info` or `Error` | | `title` | The question | | `message` | One or two sentences on what happens; a long one wraps beside the icon | -| `buttons` | Span of `MessageButton`: `label`, `kind` (`Secondary`, `Primary`, `Danger`), `alignLeft` | +| `buttons` | Span of `dialogs::MessageButton`: `label`, `kind` (`Secondary`, `Primary`, `Danger`), `alignLeft` | | `defaultButton` | | | `cancelButton` | -1 means the default button | | `items` | Affected items, each with an optional color dot, note and checkbox | @@ -250,12 +284,12 @@ The CSS classes: - `dialog-button`, `dialog-button-primary` and `dialog-button-danger` for the buttons ```cpp -static constexpr MessageButton kButtons[] = { +static constexpr dialogs::MessageButton kButtons[] = { { .label = "Cancel" }, - { .label = "Quit", .kind = MessageButtonKind::Danger }, + { .label = "Quit", .kind = dialogs::MessageButtonKind::Danger }, }; -const int choice = MessageDialog(*this, quitDialogID, MessageDialogDesc{ - .icon = MessageIcon::Quit, .title = "Quit?", .message = "Unsaved edits will be lost.", +const int choice = dialogs::MessageDialog(*this, dialogContext, quitDialogID, dialogs::MessageDialogDesc{ + .icon = dialogs::MessageIcon::Quit, .title = "Quit?", .message = "Unsaved edits will be lost.", .buttons = kButtons, .defaultButton = 0, .cancelButton = 0 }); if (choice == 1) applicationQuit = true; if (choice >= 0) asking = false; @@ -265,16 +299,16 @@ A dialog that lists the affected files and offers "Don't ask again": ```cpp // members: bool asking; bool dontAskAgain; bool saveScene = true -const MessageDialogItem affected[] = { +const dialogs::MessageDialogItem affected[] = { { .name = "Forest.level", .meta = "12 edits", .checked = &saveScene }, }; -static constexpr MessageButton kSaveButtons[] = { +static constexpr dialogs::MessageButton kSaveButtons[] = { { .label = "Don't save", .alignLeft = true }, { .label = "Cancel" }, - { .label = "Save", .kind = MessageButtonKind::Primary }, + { .label = "Save", .kind = dialogs::MessageButtonKind::Primary }, }; -const int answer = MessageDialog(*this, MessageDialogDesc{ - .icon = MessageIcon::Warning, .title = "Save changes before closing?", +const int answer = dialogs::MessageDialog(*this, dialogContext, dialogs::MessageDialogDesc{ + .icon = dialogs::MessageIcon::Warning, .title = "Save changes before closing?", .buttons = kSaveButtons, .defaultButton = 2, .cancelButton = 1, .items = affected, .dontAskAgain = &dontAskAgain }); if (answer >= 0) asking = false; @@ -284,12 +318,12 @@ A dialog that asks for a name: ```cpp // members: bool naming; std::string layoutName -static constexpr MessageButton kNameButtons[] = { +static constexpr dialogs::MessageButton kNameButtons[] = { { .label = "Cancel" }, - { .label = "Save", .kind = MessageButtonKind::Primary }, + { .label = "Save", .kind = dialogs::MessageButtonKind::Primary }, }; -const int answer = MessageDialog(*this, MessageDialogDesc{ - .icon = MessageIcon::Question, .title = "Save this layout as?", +const int answer = dialogs::MessageDialog(*this, dialogContext, dialogs::MessageDialogDesc{ + .icon = dialogs::MessageIcon::Question, .title = "Save this layout as?", .message = "Saved layouts can be picked for any document.", .buttons = kNameButtons, .defaultButton = 1, .cancelButton = 0, .input = &layoutName }); if (answer == 1) presets.Save(layoutName, SaveDockLayout(document.layout)); @@ -304,14 +338,14 @@ A toast is a short message that pops up in a corner of the window and goes away itself, such as "Build succeeded". It doesn't interrupt the user. ```cpp -ToastID ShowToast(GUIApplication& app, ToastDesc desc); -ToastDesc* FindToast(GUIApplication& app, ToastID toast); -void DismissToast(GUIApplication& app, ToastID toast); -void Toasts(GUIApplication& app); +dialogs::ToastID dialogs::ShowToast(GUIApplication& app, Context& context, dialogs::ToastDesc desc); +dialogs::ToastDesc* dialogs::FindToast(GUIApplication& app, Context& context, dialogs::ToastID toast); +void dialogs::DismissToast(GUIApplication& app, Context& context, dialogs::ToastID toast); +void dialogs::Toasts(GUIApplication& app, Context& context); ``` - `ShowToast` adds a toast. -- Call `Toasts(app)` last in a window. It draws the toasts: +- Call `dialogs::Toasts(app, dialogContext)` last in a window. It draws the toasts: - in the bottom-right corner, 16 px from the edges - or, in a window with a status bar (`BeginStatusBar`), 16 px above it, so it stays readable - over the content @@ -321,20 +355,20 @@ void Toasts(GUIApplication& app); - An error toast stays until it's dismissed, by its close button or by `DismissToast`. - Others go after about 6 s, counted only while the pointer isn't over them. - A toast with a `progress` below 1 stays. -- `FindToast` returns the toast's `ToastDesc`, to update its progress, body or title. It +- `FindToast` returns the toast's `dialogs::ToastDesc`, to update its progress, body or title. It returns null once the toast is gone. - Clicking an action runs it, and dismisses the toast. - The body wraps. The title is one line, cut short with an ellipsis, with the full text in a tooltip. - Set `age` to show how long ago it happened ("4 min"). -| `ToastDesc` field | Meaning | +| `dialogs::ToastDesc` field | Meaning | | --- | --- | -| `severity` | `Severity::Info`, `Success`, `Warning`, `Error`: icon and circle color | +| `severity` | `dialogs::Severity::Info`, `Success`, `Warning`, `Error`: icon and circle color | | `title`, `body` | | | `monospaceBody` | For code or file locations | | `progress` | Optional bar, 0 to 1 | -| `actions` | `ToastAction` list (`label`, `onClick`); the first uses the link color | +| `actions` | `dialogs::ToastAction` list (`label`, `onClick`); the first uses the link color | | `icon` | In place of the severity's icon, such as an up arrow for an upload; the circle keeps the severity's color | The CSS classes: @@ -349,7 +383,7 @@ The CSS classes: - `toast-earlier` ```cpp -ShowToast(*this, ToastDesc{ .severity = Severity::Error, .title = "Shader compile failed", +dialogs::ShowToast(*this, dialogContext, dialogs::ToastDesc{ .severity = dialogs::Severity::Error, .title = "Shader compile failed", .body = "Terrain.shader:118", .monospaceBody = true, .actions = { { "Show log", [this] { ShowLog(); } } } }); ``` @@ -357,21 +391,21 @@ ShowToast(*this, ToastDesc{ .severity = Severity::Error, .title = "Shader compil A toast with a progress bar, updated every frame, and drawn last in the window: ```cpp -// Once: member ToastID uploadToast -uploadToast = ShowToast(*this, ToastDesc{ .title = "Uploading build", .progress = 0.0f }); +// Once: member dialogs::ToastID uploadToast +uploadToast = dialogs::ShowToast(*this, dialogContext, dialogs::ToastDesc{ .title = "Uploading build", .progress = 0.0f }); // Each frame, inside the window: -if (ToastDesc* upload = FindToast(*this, uploadToast)) +if (dialogs::ToastDesc* upload = dialogs::FindToast(*this, dialogContext, uploadToast)) { upload->progress = uploadDone; // member: float uploadDone, 0 to 1 if (uploadDone >= 1.0f) upload->title = "Uploaded build"; } -Toasts(*this); +dialogs::Toasts(*this, dialogContext); ``` ```cpp -Button("Cancel upload", [this] { DismissToast(*this, uploadToast); }); +Button("Cancel upload", [this] { dialogs::DismissToast(*this, dialogContext, uploadToast); }); ``` ### Banner @@ -379,13 +413,13 @@ Button("Cancel upload", [this] { DismissToast(*this, uploadToast); }); A banner is a message across the top of a panel, tinted in the color of its severity. ```cpp -void Banner(GUIApplication& app, ID id, Severity severity, const GUIContent& message, std::span actions = {}, +void dialogs::Banner(GUIApplication& app, Context& context, ID id, dialogs::Severity severity, const GUIContent& message, std::span actions = {}, LayoutOverride&& constraints = {}); ``` - Its icon is `message.icon`, or else the severity's icon. - Its actions sit on the right. Each is one of: - - `BannerActionKind::Primary`: an accent button + - `dialogs::BannerActionKind::Primary`: an accent button - `Secondary`: a plain button - `Link` - The CSS classes: @@ -394,16 +428,16 @@ void Banner(GUIApplication& app, ID id, Severity severity, const GUIContent& mes - `banner-primary`, `banner-secondary` and `banner-link` ```cpp -const BannerAction actions[] = { +const dialogs::BannerAction actions[] = { { "Discard", [this] { Discard(); } }, - { "Save", [this] { Save(); }, BannerActionKind::Primary }, + { "Save", [this] { Save(); }, dialogs::BannerActionKind::Primary }, }; -Banner(*this, idManager.AllocateDynamicID("unsaved"), Severity::Warning, "Scene has unsaved changes", actions); +dialogs::Banner(*this, dialogContext, idManager.AllocateDynamicID("unsaved"), dialogs::Severity::Warning, "Scene has unsaved changes", actions); ``` ```cpp -const BannerAction links[] = { { "Learn more", [this] { showHelp = true; }, BannerActionKind::Link } }; -Banner(*this, Severity::Info, "This project uses an older file format.", links); +const dialogs::BannerAction links[] = { { "Learn more", [this] { showHelp = true; }, dialogs::BannerActionKind::Link } }; +dialogs::Banner(*this, dialogContext, dialogs::Severity::Info, "This project uses an older file format.", links); ``` --- diff --git a/docs/controls/trees-and-grids.md b/docs/controls/trees-and-grids.md index 92f3605c..0534c242 100644 --- a/docs/controls/trees-and-grids.md +++ b/docs/controls/trees-and-grids.md @@ -231,7 +231,7 @@ for (const FileEntry& entry : files.List("TachyonUI")) names.push_back(entry.isFolder ? entry.name + "/" : entry.name); std::string error; if (!files.Move("TachyonUI/notes.txt", "Archive", error)) - ShowToast(*this, ToastDesc{ .severity = Severity::Error, .title = "Can't move it", .body = error }); + dialogs::ShowToast(*this, dialogContext, dialogs::ToastDesc{ .severity = dialogs::Severity::Error, .title = "Can't move it", .body = error }); ``` `FileIcons` (`app_controls/gui_file_icons.h`) gets the OS icon for a file or folder. diff --git a/docs/controls/windows-and-layout.md b/docs/controls/windows-and-layout.md index eecac695..01c4a955 100644 --- a/docs/controls/windows-and-layout.md +++ b/docs/controls/windows-and-layout.md @@ -71,8 +71,8 @@ if (editorOpen) askingToClose = true; if (askingToClose) { - static constexpr MessageButton kButtons[] = { { .label = "Cancel" }, { .label = "Close" } }; - const int choice = MessageDialog(*this, MessageDialogDesc{ .title = "Close the editor?", .buttons = kButtons }); + static constexpr dialogs::MessageButton kButtons[] = { { .label = "Cancel" }, { .label = "Close" } }; + const int choice = dialogs::MessageDialog(*this, dialogContext, dialogs::MessageDialogDesc{ .title = "Close the editor?", .buttons = kButtons }); if (choice == 1) editorOpen = false; if (choice >= 0) askingToClose = false; } diff --git a/examples/showcase/application.cpp b/examples/showcase/application.cpp index 46fde286..292068b3 100644 --- a/examples/showcase/application.cpp +++ b/examples/showcase/application.cpp @@ -164,6 +164,7 @@ namespace tachyon void Application::Cleanup() { + dialogs::Cleanup(*this, dialogContext); if (pastedImage != nullptr && graphicsContext != nullptr) { graphicsContext->UnregisterImage(pastedImageIndex); @@ -1529,14 +1530,14 @@ namespace tachyon if (!unsaved.empty()) { // The unsaved documents, each checked to be saved, in its type's color. - static constexpr MessageButton kButtons[] = { + static constexpr dialogs::MessageButton kButtons[] = { { .label = "Don't save", .alignLeft = true }, { .label = "Cancel" }, - { .label = "Save all", .kind = MessageButtonKind::Primary }, + { .label = "Save all", .kind = dialogs::MessageButtonKind::Primary }, }; std::vector names; names.reserve(unsaved.size()); - std::vector items; + std::vector items; for (const Document* document : unsaved) { names.push_back(document->name + document->extension); @@ -1547,8 +1548,8 @@ namespace tachyon const std::string message = unsaved.size() == 1 ? std::format("{} has unsaved changes. Changes you don't save are lost.", names[0]) : std::format("{} documents have unsaved changes. Changes you don't save are lost.", unsaved.size()); - choice = MessageDialog(*this, showcase.exitDialogID, MessageDialogDesc{ - .icon = MessageIcon::Warning, .title = "Save changes before closing?", .message = message, .buttons = kButtons, + choice = dialogs::MessageDialog(*this, dialogContext, showcase.exitDialogID, dialogs::MessageDialogDesc{ + .icon = dialogs::MessageIcon::Warning, .title = "Save changes before closing?", .message = message, .buttons = kButtons, .defaultButton = 2, .cancelButton = 1, .items = items }); if (choice == 2) for (Document* document : unsaved) @@ -1559,9 +1560,9 @@ namespace tachyon else { // Nothing unsaved: the work still running, which quitting stops. - static constexpr MessageButton kButtons[] = { + static constexpr dialogs::MessageButton kButtons[] = { { .label = "Cancel" }, - { .label = "Quit", .kind = MessageButtonKind::Danger }, + { .label = "Quit", .kind = dialogs::MessageButtonKind::Danger }, }; const std::vector running = RunningWork(); if (running.empty()) @@ -1570,13 +1571,13 @@ namespace tachyon showcase.exitRequested = false; return; } - std::vector items; + std::vector items; for (const RunningTask& task : running) items.push_back({ .name = task.name, .meta = task.state }); const std::string message = running.size() == 1 ? "A background task is still running. Quitting stops it." : std::format("{} background tasks are still running. Quitting stops them.", running.size()); - choice = MessageDialog(*this, showcase.exitDialogID, MessageDialogDesc{ - .icon = MessageIcon::Quit, .title = "Quit Test?", .message = message, .buttons = kButtons, + choice = dialogs::MessageDialog(*this, dialogContext, showcase.exitDialogID, dialogs::MessageDialogDesc{ + .icon = dialogs::MessageIcon::Quit, .title = "Quit Test?", .message = message, .buttons = kButtons, .defaultButton = 0, .cancelButton = 0, .items = items, .dontAskAgain = &showcase.quitDontAsk }); if (choice == 1) applicationQuit = true; else if (choice == 0) showcase.quitDontAsk = false; // asked to stay: it asks again next time @@ -1830,15 +1831,15 @@ namespace tachyon const std::string_view message = existing && existing->builtIn ? "A built-in layout has that name. Built-in layouts can't be replaced." : existing ? "It replaces the saved layout of that name." : "Saved layouts can be picked for any document."; - static constexpr MessageButton kButtons[] = { + static constexpr dialogs::MessageButton kButtons[] = { { .label = "Cancel" }, - { .label = "Save", .kind = MessageButtonKind::Primary }, + { .label = "Save", .kind = dialogs::MessageButtonKind::Primary }, }; - const int choice = MessageDialog(*this, showcase.layoutNameDialogID, MessageDialogDesc{ - .icon = MessageIcon::Question, .title = "Save this layout as?", .message = message, + const int choice = dialogs::MessageDialog(*this, dialogContext, showcase.layoutNameDialogID, dialogs::MessageDialogDesc{ + .icon = dialogs::MessageIcon::Question, .title = "Save this layout as?", .message = message, .buttons = kButtons, .defaultButton = 1, .cancelButton = 0, .input = &showcase.layoutNameInput }); if (choice == 1 && !showcase.layoutPresets.Save(name, SaveDockLayout(document->layout))) - ShowToast(*this, ToastDesc{ .severity = Severity::Warning, .title = "Layout not saved", + dialogs::ShowToast(*this, dialogContext, dialogs::ToastDesc{ .severity = dialogs::Severity::Warning, .title = "Layout not saved", .body = name.empty() ? std::string("It needs a name.") : std::format("\"{}\" is a built-in layout.", name) }); if (choice >= 0) showcase.namingLayoutDocument = ID::Invalid(); @@ -1988,26 +1989,26 @@ namespace tachyon void Application::ShowDemoToasts() { // Shown again: the last ones make way. - for (const ToastID toast : showcase.demoToasts) - DismissToast(*this, toast); + for (const dialogs::ToastID toast : showcase.demoToasts) + dialogs::DismissToast(*this, dialogContext, toast); showcase.demoToasts.clear(); // Two older ones, folded into "+2 earlier" under the four shown. - showcase.demoToasts.push_back(ShowToast(*this, ToastDesc{ .severity = Severity::Success, .title = "Lightmaps baked", .body = "Forest.level · 6 atlases", + showcase.demoToasts.push_back(dialogs::ShowToast(*this, dialogContext, dialogs::ToastDesc{ .severity = dialogs::Severity::Success, .title = "Lightmaps baked", .body = "Forest.level · 6 atlases", .age = 12.0f * 60.0f })); - showcase.demoToasts.push_back(ShowToast(*this, ToastDesc{ .severity = Severity::Info, .title = "Autosaved", .body = "Forest.level, Terrain.mat", + showcase.demoToasts.push_back(dialogs::ShowToast(*this, dialogContext, dialogs::ToastDesc{ .severity = dialogs::Severity::Info, .title = "Autosaved", .body = "Forest.level, Terrain.mat", .age = 10.0f * 60.0f })); - showcase.demoToasts.push_back(ShowToast(*this, ToastDesc{ .severity = Severity::Success, .title = "Build succeeded", .body = "Windows x64 \u00B7 1 m 42 s", + showcase.demoToasts.push_back(dialogs::ShowToast(*this, dialogContext, dialogs::ToastDesc{ .severity = dialogs::Severity::Success, .title = "Build succeeded", .body = "Windows x64 \u00B7 1 m 42 s", .actions = { { "Open folder", {} }, { "Run", {} } }, .age = 4.0f * 60.0f })); - showcase.demoToasts.push_back(ShowToast(*this, ToastDesc{ .severity = Severity::Error, .title = "Shader compile failed", + showcase.demoToasts.push_back(dialogs::ShowToast(*this, dialogContext, dialogs::ToastDesc{ .severity = dialogs::Severity::Error, .title = "Shader compile failed", .body = "Terrain.shader:118 \u2014 undeclared identifier 'uv2'", .monospaceBody = true, .actions = { { "Show log", {} }, { "Copy error", {} } }, .age = 2.0f * 60.0f })); - showcase.demoToasts.push_back(ShowToast(*this, ToastDesc{ .severity = Severity::Warning, .title = "3 textures exceed 4K", .body = "They will be downscaled on import.", + showcase.demoToasts.push_back(dialogs::ShowToast(*this, dialogContext, dialogs::ToastDesc{ .severity = dialogs::Severity::Warning, .title = "3 textures exceed 4K", .body = "They will be downscaled on import.", .actions = { { "Review", {} }, { "Ignore", {} } }, .age = 60.0f })); showcase.uploadStart = guiStateManager.Interaction().GetFrameTime(); - showcase.uploadToast = ShowToast(*this, ToastDesc{ .severity = Severity::Info, .title = "Uploading build", + showcase.uploadToast = dialogs::ShowToast(*this, dialogContext, dialogs::ToastDesc{ .severity = dialogs::Severity::Info, .title = "Uploading build", .body = "build-0.8.3-win64.zip \u00B7 0%", .progress = 0.0f, .actions = { { "Cancel", {} } }, .icon = showcase.uploadIcon }); showcase.demoToasts.push_back(showcase.uploadToast); @@ -2016,7 +2017,7 @@ namespace tachyon // The upload's progress, over about 20 s. void Application::UpdateDemoToasts() { - ToastDesc* upload = FindToast(*this, showcase.uploadToast); + dialogs::ToastDesc* upload = dialogs::FindToast(*this, dialogContext, showcase.uploadToast); if (!upload || !upload->progress) return; const float done = std::min(1.0f, (guiStateManager.Interaction().GetFrameTime() - showcase.uploadStart) / 20.0f); @@ -2112,7 +2113,7 @@ namespace tachyon RenderStatusBar(); EmitFloatingDockWindows(window.documents); if (!showcase.mainWindowOpen) - Toasts(*this); // in the first document window while the main one is closed + dialogs::Toasts(*this, dialogContext); // in the first document window while the main one is closed } EndWindow(); } @@ -2151,13 +2152,13 @@ namespace tachyon showcase.reloadDocument = nullptr; // closed or saved meanwhile return; } - static constexpr MessageButton kButtons[] = { + static constexpr dialogs::MessageButton kButtons[] = { { .label = "Keep mine" }, - { .label = "Reload", .kind = MessageButtonKind::Primary }, + { .label = "Reload", .kind = dialogs::MessageButtonKind::Primary }, }; const std::string title = std::format("Reload {}{}?", document->name, document->extension); - const int choice = MessageDialog(*this, showcase.reloadDialogID, MessageDialogDesc{ - .icon = MessageIcon::Question, .title = title, + const int choice = dialogs::MessageDialog(*this, dialogContext, showcase.reloadDialogID, dialogs::MessageDialogDesc{ + .icon = dialogs::MessageIcon::Question, .title = title, .message = "Reloading replaces the open version with the one on disk; its unsaved changes will be lost.", .buttons = kButtons, .defaultButton = 1, .cancelButton = 0 }); if (choice == 1) @@ -2174,13 +2175,13 @@ namespace tachyon if (showcase.openErrorFile.empty() || window != showcase.openErrorWindow) return; // Copy details copies them and leaves the error up; OK closes it. - static constexpr MessageButton kButtons[] = { + static constexpr dialogs::MessageButton kButtons[] = { { .label = "Copy details" }, - { .label = "OK", .kind = MessageButtonKind::Primary }, + { .label = "OK", .kind = dialogs::MessageButtonKind::Primary }, }; const std::string title = std::format("Couldn't open {}", showcase.openErrorFile); - const int choice = MessageDialog(*this, showcase.openErrorDialogID, MessageDialogDesc{ - .icon = MessageIcon::Error, .title = title, + const int choice = dialogs::MessageDialog(*this, dialogContext, showcase.openErrorDialogID, dialogs::MessageDialogDesc{ + .icon = dialogs::MessageIcon::Error, .title = title, .message = "It's a compiled shader, which the showcase has no reader for.", .buttons = kButtons, .defaultButton = 1, .cancelButton = 1, .details = showcase.openErrorDetails }); if (choice == 0 && clipboard) @@ -2201,14 +2202,14 @@ namespace tachyon showcase.closingDocument = nullptr; return; } - static constexpr MessageButton kButtons[] = { - { .label = "Discard", .kind = MessageButtonKind::Danger, .alignLeft = true }, + static constexpr dialogs::MessageButton kButtons[] = { + { .label = "Discard", .kind = dialogs::MessageButtonKind::Danger, .alignLeft = true }, { .label = "Cancel" }, - { .label = "Save", .kind = MessageButtonKind::Primary }, + { .label = "Save", .kind = dialogs::MessageButtonKind::Primary }, }; const std::string title = std::format("Close {}{}?", document->name, document->extension); - const int choice = MessageDialog(*this, showcase.closeDocumentDialogID, MessageDialogDesc{ - .icon = MessageIcon::Warning, .title = title, .message = "It has unsaved changes. Closing it without saving discards them.", + const int choice = dialogs::MessageDialog(*this, dialogContext, showcase.closeDocumentDialogID, dialogs::MessageDialogDesc{ + .icon = dialogs::MessageIcon::Warning, .title = title, .message = "It has unsaved changes. Closing it without saving discards them.", .buttons = kButtons, .defaultButton = 2, .cancelButton = 1 }); if (choice == 2) SaveShowcaseDocument(*document); @@ -2357,6 +2358,7 @@ namespace tachyon if (!m_captureDir.empty()) { RenderCapture(); + dialogs::EndGUI(*this, dialogContext); return; } auto&& sizeConstraints = LayoutOverride::FixedSize(1700, 900); @@ -2404,7 +2406,7 @@ namespace tachyon EmitFloatingDockWindows(showcase.documents); EmitViewportFloatingToolbars(); UpdateDemoToasts(); - Toasts(*this); + dialogs::Toasts(*this, dialogContext); } else { // BeginWindow returned false - window is closing @@ -2414,5 +2416,6 @@ namespace tachyon } } RenderDocumentWindows(); + dialogs::EndGUI(*this, dialogContext); } } diff --git a/examples/showcase/application.h b/examples/showcase/application.h index a3831a11..f2963230 100644 --- a/examples/showcase/application.h +++ b/examples/showcase/application.h @@ -685,8 +685,8 @@ namespace tachyon DocumentSet* closingSet = nullptr; // the set it's in std::vector> documentWindows; // documents dragged out bool mainWindowOpen = true; - ToastID uploadToast = 0; // the demo upload, its progress moving - std::vector demoToasts; // the demo's toasts, taken away when shown again + dialogs::ToastID uploadToast = 0; // the demo upload, its progress moving + std::vector demoToasts; // the demo's toasts, taken away when shown again float uploadStart = 0.0f; // when it started, frame time in seconds bool inspectorUnsaved = true; // the Inspector's banners bool inspectorReadOnly = true; @@ -745,6 +745,8 @@ namespace tachyon } void OnGUI() override; + /// The dialogs' state: toasts, message dialogs, progress. + dialogs::Context dialogContext; private: // Settings pages (panel_settings.cpp). InitSettingsPages() runs once after diff --git a/examples/showcase/capture.cpp b/examples/showcase/capture.cpp index 75e07387..e2ff1983 100644 --- a/examples/showcase/capture.cpp +++ b/examples/showcase/capture.cpp @@ -262,7 +262,7 @@ namespace tachyon { case CaptureTarget::ColorSwatch: match = element.styleRef == theme.colorSwatchStyleRef; break; case CaptureTarget::GradientSwatch: match = element.styleRef == theme.gradientSwatchStyleRef; break; - case CaptureTarget::TasksPill: match = element.styleRef == GetDialogStyles(*this).tasksPillStyleRef; break; + case CaptureTarget::TasksPill: match = element.styleRef == dialogs::GetStyles(*this, dialogContext).tasksPillStyleRef; break; case CaptureTarget::Invalid: match = element.eventHandler && (element.state & ElementState::Invalid) != ElementState::None; break; case CaptureTarget::DockButton: case CaptureTarget::Text: @@ -590,7 +590,7 @@ namespace tachyon if (shot.act == CaptureAct::Toasts) { UpdateDemoToasts(); - Toasts(*this); + dialogs::Toasts(*this, dialogContext); } } else if (shot.scene == CaptureScene::Document) diff --git a/examples/showcase/panel_files.cpp b/examples/showcase/panel_files.cpp index 3242a529..caac7f71 100644 --- a/examples/showcase/panel_files.cpp +++ b/examples/showcase/panel_files.cpp @@ -335,7 +335,7 @@ namespace tachyon std::string error; if (!p.files->Move(path, folder, error)) { - ShowToast(*this, ToastDesc{ .severity = Severity::Error, .title = "Can't move \"" + std::string(FileName(path)) + "\"", .body = error }); + dialogs::ShowToast(*this, dialogContext, dialogs::ToastDesc{ .severity = dialogs::Severity::Error, .title = "Can't move \"" + std::string(FileName(path)) + "\"", .body = error }); return; } FolderMoved(path, JoinPath(folder, FileName(path))); @@ -358,7 +358,7 @@ namespace tachyon if (p.files->Rename(path, name, error)) FolderMoved(path, JoinPath(ParentPath(path), name)); else - ShowToast(*this, ToastDesc{ .severity = Severity::Error, .title = "Can't rename \"" + std::string(FileName(path)) + "\"", .body = error }); + dialogs::ShowToast(*this, dialogContext, dialogs::ToastDesc{ .severity = dialogs::Severity::Error, .title = "Can't rename \"" + std::string(FileName(path)) + "\"", .body = error }); } // Back to the file system's names, the refused ones too. p.treeDirty = true; @@ -513,7 +513,7 @@ namespace tachyon refused += (refused.empty() ? "" : "\n") + error; } if (!refused.empty()) - ShowToast(*this, ToastDesc{ .severity = Severity::Warning, + dialogs::ShowToast(*this, dialogContext, dialogs::ToastDesc{ .severity = dialogs::Severity::Warning, .title = "Not added to " + (folder.empty() ? p.rootName : std::string(FileName(folder))), .body = refused }); } @@ -737,8 +737,8 @@ namespace tachyon const LayoutOverride block = LayoutOverride{}.Width(Pixels{ styleManager.Px(200) }).NoGrow().NoShrink(); const ID importID = idManager.AllocateDynamicID("filesImportProgress"); if (progress.importCancelledAt >= 0.0f) - TaskProgress(*this, importID, ProgressTask{ .name = "Import cancelled", .value = imported / ProgressDemos::kImportSecs, - .state = TaskState::Failed, + dialogs::TaskProgress(*this, dialogContext, importID, dialogs::ProgressTask{ .name = "Import cancelled", .value = imported / ProgressDemos::kImportSecs, + .state = dialogs::TaskState::Failed, .onRetry = [this] { progress.importStart = guiStateManager.Interaction().GetFrameTime(); progress.importCancelledAt = -1.0f; @@ -746,13 +746,13 @@ namespace tachyon LayoutOverride(block)); else if (imported < ProgressDemos::kImportSecs) { - TaskProgress(*this, importID, ProgressTask{ .name = "Importing character.fbx", .value = imported / ProgressDemos::kImportSecs, + dialogs::TaskProgress(*this, dialogContext, importID, dialogs::ProgressTask{ .name = "Importing character.fbx", .value = imported / ProgressDemos::kImportSecs, .onCancel = [this] { progress.importCancelledAt = ImportElapsed(); } }, LayoutOverride(block)); } else { - TaskProgress(*this, importID, ProgressTask{ .name = "Import complete", .state = TaskState::Done, .note = "6.0 s" }, + dialogs::TaskProgress(*this, dialogContext, importID, dialogs::ProgressTask{ .name = "Import complete", .state = dialogs::TaskState::Done, .note = "6.0 s" }, LayoutOverride(block)); } } @@ -814,7 +814,7 @@ namespace tachyon BeginVertical(itemID, filesImportTileStyleRef, LayoutOverride{}.Size(Pixels{ std::max(cellW, int(p.gridScrollState.cellStretchedW)) }, Pixels{ cellH })); BeginVertical(idManager.AllocateDynamicID("filesImportWell"), filesImportWellStyleRef); - CircularProgress(*this, idManager.AllocateDynamicID("filesImportRing"), imported / ProgressDemos::kImportSecs); + dialogs::CircularProgress(*this, dialogContext, idManager.AllocateDynamicID("filesImportRing"), imported / ProgressDemos::kImportSecs); EndVertical(); Text(idManager.AllocateDynamicID("filesImportName"), "character.fbx", filesImportNameStyleRef); EndVertical(); diff --git a/examples/showcase/panel_hierarchy.cpp b/examples/showcase/panel_hierarchy.cpp index 5e63bea0..8442bcfb 100644 --- a/examples/showcase/panel_hierarchy.cpp +++ b/examples/showcase/panel_hierarchy.cpp @@ -347,15 +347,15 @@ namespace tachyon const size_t count = showcase.deleteNodes.size(); const std::string title = std::format("Delete {} objects?", count); const std::string label = std::format("Delete {} objects", count); - const MessageButton buttons[] = { + const dialogs::MessageButton buttons[] = { { .label = "Cancel" }, - { .label = label, .kind = MessageButtonKind::Danger }, + { .label = label, .kind = dialogs::MessageButtonKind::Danger }, }; - std::vector items; + std::vector items; for (const std::string& name : showcase.deleteNames) items.push_back({ .name = name }); - const int choice = MessageDialog(*this, showcase.deleteDialogID, MessageDialogDesc{ - .icon = MessageIcon::Warning, .title = title, + const int choice = dialogs::MessageDialog(*this, dialogContext, showcase.deleteDialogID, dialogs::MessageDialogDesc{ + .icon = dialogs::MessageIcon::Warning, .title = title, .message = "They're removed from the scene, with everything under them. This can't be undone.", .buttons = buttons, .defaultButton = 0, .cancelButton = 0, .items = items, .dontAskAgain = &showcase.deleteDontAsk }); if (choice == 1 && p) @@ -660,8 +660,8 @@ namespace tachyon LayoutOverride{}.FlexGrow(1)); RegisterElement(Element{ .id = idManager.AllocateDynamicID("indent"), .styleRef = theme.emptyHorzStyleRef }, LayoutOverride::Auto().Width(Pixels{ indent }).NoShrink()); - Skeleton(*this, idManager.AllocateDynamicID("icon"), LayoutOverride::Auto().Size(Pixels{ styleManager.Px(13) }, Pixels{ styleManager.Px(13) })); - Skeleton(*this, idManager.AllocateDynamicID("name"), LayoutOverride::Auto().Width(Pixels{ width }).Height(Pixels{ styleManager.Px(8) })); + dialogs::Skeleton(*this, dialogContext, idManager.AllocateDynamicID("icon"), LayoutOverride::Auto().Size(Pixels{ styleManager.Px(13) }, Pixels{ styleManager.Px(13) })); + dialogs::Skeleton(*this, dialogContext, idManager.AllocateDynamicID("name"), LayoutOverride::Auto().Width(Pixels{ width }).Height(Pixels{ styleManager.Px(8) })); EndHorizontal(); }); return; @@ -696,7 +696,7 @@ namespace tachyon // While something streams in, a column at the end says so on its row. // As wide as "streaming", its spinner and the room around them. const int32_t streamingWidth = textSystem->GetTextMeasurement(textSystem->RegisterText( - tachyon::ID::Invalid(), "streaming", GetDialogStyles(*this).taskProgressDetailStyleRef, tachyon::ElementState::None)).maxWidth + tachyon::ID::Invalid(), "streaming", dialogs::GetStyles(*this, dialogContext).taskProgressDetailStyleRef, tachyon::ElementState::None)).maxWidth + styleManager.Px(12 + 6 + 8 + 4); cols[2].column = TableColumn{ .header = {}, .initialWidth = streamingWidth, .minWidth = streamingWidth, @@ -707,8 +707,8 @@ namespace tachyon Cell([this, here] { if (!here) return; BeginHorizontal(idManager.AllocateDynamicID("streaming"), hierarchyStreamingStyleRef, LayoutOverride{}.FlexGrow(1)); - Text(idManager.AllocateDynamicID("streamingText"), "streaming", GetDialogStyles(*this).taskProgressDetailStyleRef); - Spinner(*this, idManager.AllocateDynamicID("streamingSpinner"), SpinnerSize::Small); + Text(idManager.AllocateDynamicID("streamingText"), "streaming", dialogs::GetStyles(*this, dialogContext).taskProgressDetailStyleRef); + dialogs::Spinner(*this, dialogContext, idManager.AllocateDynamicID("streamingSpinner"), dialogs::SpinnerSize::Small); EndHorizontal(); }); }; diff --git a/examples/showcase/panel_inspector.cpp b/examples/showcase/panel_inspector.cpp index 92de0ffb..efacbb46 100644 --- a/examples/showcase/panel_inspector.cpp +++ b/examples/showcase/panel_inspector.cpp @@ -417,19 +417,19 @@ namespace tachyon // ---- Banners: what the user should know about the object ------------- if (showcase.inspectorUnsaved) { - const BannerAction actions[] = { + const dialogs::BannerAction actions[] = { { "Discard", [this] { showcase.inspectorUnsaved = false; } }, - { "Save", [this] { showcase.inspectorUnsaved = false; }, BannerActionKind::Primary }, + { "Save", [this] { showcase.inspectorUnsaved = false; }, dialogs::BannerActionKind::Primary }, }; - Banner(*this, idManager.AllocateDynamicID("inspectorUnsaved"), Severity::Warning, "Scene has unsaved changes", actions, + dialogs::Banner(*this, dialogContext, idManager.AllocateDynamicID("inspectorUnsaved"), dialogs::Severity::Warning, "Scene has unsaved changes", actions, tachyon::LayoutOverride::Auto().NoShrink()); } if (showcase.inspectorReadOnly) { - const BannerAction actions[] = { - { "Make editable", [this] { showcase.inspectorReadOnly = false; }, BannerActionKind::Link }, + const dialogs::BannerAction actions[] = { + { "Make editable", [this] { showcase.inspectorReadOnly = false; }, dialogs::BannerActionKind::Link }, }; - Banner(*this, idManager.AllocateDynamicID("inspectorReadOnly"), Severity::Info, + dialogs::Banner(*this, dialogContext, idManager.AllocateDynamicID("inspectorReadOnly"), dialogs::Severity::Info, { showcase.visibilityLockIcon, "Read-only \u2014 this asset comes from a package" }, actions, tachyon::LayoutOverride::Auto().NoShrink()); } diff --git a/examples/showcase/panel_misc.cpp b/examples/showcase/panel_misc.cpp index 7f914dff..1eae9fed 100644 --- a/examples/showcase/panel_misc.cpp +++ b/examples/showcase/panel_misc.cpp @@ -35,7 +35,7 @@ namespace tachyon { const ClipboardImage image{ MiscPanel::kPictureWidth, MiscPanel::kPictureHeight, misc.picturePixels }; if (!clipboard || !clipboard->SetImage(image)) - ShowToast(*this, ToastDesc{ .severity = Severity::Warning, .title = "Image not copied", .body = "This clipboard takes no images." }); + dialogs::ShowToast(*this, dialogContext, dialogs::ToastDesc{ .severity = dialogs::Severity::Warning, .title = "Image not copied", .body = "This clipboard takes no images." }); } void Application::PasteImage() @@ -43,7 +43,7 @@ namespace tachyon const ClipboardImage image = clipboard ? clipboard->GetImage() : ClipboardImage{}; if (image.Empty()) { - ShowToast(*this, ToastDesc{ .severity = Severity::Info, .title = "No image to paste", .body = "The clipboard holds no image." }); + dialogs::ShowToast(*this, dialogContext, dialogs::ToastDesc{ .severity = dialogs::Severity::Info, .title = "No image to paste", .body = "The clipboard holds no image." }); return; } ShowPastedImage(image.rgba.data(), uint2{ image.width, image.height }); @@ -56,7 +56,7 @@ namespace tachyon FileThumbnails::Picture picture; if (!reader || !reader(std::filesystem::path(reinterpret_cast(path.c_str())), 512, picture) || picture.rgba.empty()) { - ShowToast(*this, ToastDesc{ .severity = Severity::Info, .title = "No image to paste", + dialogs::ShowToast(*this, dialogContext, dialogs::ToastDesc{ .severity = dialogs::Severity::Info, .title = "No image to paste", .body = "That file has no picture to show." }); return; } @@ -69,7 +69,7 @@ namespace tachyon ImageFormat::R8G8B8A8, Sampler::LinearClampToEdge, true); if (created == nullptr) { - ShowToast(*this, ToastDesc{ .severity = Severity::Error, .title = "Image not pasted", + dialogs::ShowToast(*this, dialogContext, dialogs::ToastDesc{ .severity = dialogs::Severity::Error, .title = "Image not pasted", .body = std::format("A {} x {} image can't be made here.", size.x, size.y) }); return; } @@ -351,8 +351,8 @@ namespace tachyon // Still loading: a skeleton for the picture and for the name. BeginVertical(idManager.AllocateDynamicID("thumbLoading"), misc.thumbTile); - Skeleton(*this, idManager.AllocateDynamicID("thumbSkeleton"), misc.thumbLoading); - Skeleton(*this, idManager.AllocateDynamicID("nameSkeleton"), LayoutOverride::FixedSize(52, 8)); + dialogs::Skeleton(*this, dialogContext, idManager.AllocateDynamicID("thumbSkeleton"), misc.thumbLoading); + dialogs::Skeleton(*this, dialogContext, idManager.AllocateDynamicID("nameSkeleton"), LayoutOverride::FixedSize(52, 8)); EndVertical(); // A file with no picture to show: the image icon on the well. diff --git a/examples/showcase/progress_demos.cpp b/examples/showcase/progress_demos.cpp index a9e6b6fd..9048e909 100644 --- a/examples/showcase/progress_demos.cpp +++ b/examples/showcase/progress_demos.cpp @@ -94,19 +94,19 @@ namespace tachyon const bool running = BuildRunning(); // Each step done, under way, or still to come; cancelled, the one under way says so. - ProgressTask steps[std::size(kBuildSteps)]; + dialogs::ProgressTask steps[std::size(kBuildSteps)]; std::string notes[std::size(kBuildSteps)], details[std::size(kBuildSteps)]; float stepStart = 0.0f; for (size_t i = 0; i < std::size(kBuildSteps); ++i) { const BuildStep& step = kBuildSteps[i]; const float stepEnd = stepStart + step.seconds; - ProgressTask& task = steps[i]; + dialogs::ProgressTask& task = steps[i]; task.name = step.name; - task.state = TaskState::Pending; + task.state = dialogs::TaskState::Pending; if (at >= stepEnd) { - task.state = TaskState::Done; + task.state = dialogs::TaskState::Done; notes[i] = std::format("{:.1f} s", step.seconds); } else if (at >= stepStart) @@ -115,7 +115,7 @@ namespace tachyon notes[i] = "cancelled"; else { - task.state = TaskState::Running; + task.state = dialogs::TaskState::Running; task.value = (at - stepStart) / step.seconds; const int left = int(std::ceil(stepEnd - at)); if (i == 2) details[i] = std::format("Lightmap atlas, about {} s left", left); @@ -133,7 +133,7 @@ namespace tachyon Text(idManager.AllocateDynamicID("buildConfig"), "Development", buildSubtitleStyleRef); EndHorizontal(); - ProgressSteps(*this, idManager.AllocateDynamicID("buildSteps"), steps); + dialogs::ProgressSteps(*this, dialogContext, idManager.AllocateDynamicID("buildSteps"), steps); // Cancel while it runs; Build, busy while it runs, keeping its width. BeginHorizontal(idManager.AllocateDynamicID("buildFooter"), buildFooterStyleRef); @@ -141,7 +141,7 @@ namespace tachyon Button(idManager.AllocateDynamicID("buildCancel"), "Cancel", [this] { progress.buildCancelledAt = BuildElapsed(); }, theme.dialogButtonStyleRef); if (!running) EndDisabled(); - BusyButton(*this, idManager.AllocateDynamicID("buildRun"), { showcase.panelBuildIcon, "Build" }, running, "Building", + dialogs::BusyButton(*this, dialogContext, idManager.AllocateDynamicID("buildRun"), { showcase.panelBuildIcon, "Build" }, running, "Building", [this] { progress.buildStart = guiStateManager.Interaction().GetFrameTime(); progress.buildCancelledAt = -1.0f; @@ -177,7 +177,7 @@ namespace tachyon const std::string count = std::format("{} / 3,800", int(std::clamp(indexed, 0.0f, 1.0f) * 3800.0f)); // The background tasks: those running, and the paused upload. - std::vector tasks; + std::vector tasks; if (BuildRunning()) tasks.push_back({ .name = "Build Windows player", .value = BuildElapsed() / kBuildSecs, .onCancel = [this] { progress.buildCancelledAt = BuildElapsed(); } }); @@ -185,30 +185,30 @@ namespace tachyon const bool uploading = progress.uploadResumedAt >= 0.0f && !progress.held; const float uploaded = uploading ? progress.uploadDone + ProgressElapsed(progress.uploadResumedAt, 0.0f) / ProgressDemos::kUploadSecs : progress.uploadDone; - const ProgressTask background[] = { + const dialogs::ProgressTask background[] = { { .name = "Indexing assets", .value = indexed }, { .name = "Generate thumbnails", .value = thumbs }, - { .name = "Upload build", .value = uploaded, .state = uploading ? TaskState::Running : TaskState::Paused, + { .name = "Upload build", .value = uploaded, .state = uploading ? dialogs::TaskState::Running : dialogs::TaskState::Paused, .onPause = [this, uploading, uploaded] { progress.uploadDone = uploaded; progress.uploadResumedAt = uploading ? -1.0f : guiStateManager.Interaction().GetFrameTime(); } }, }; - const ProgressTask* shown = nullptr; // the status bar's: the first background one running + const dialogs::ProgressTask* shown = nullptr; // the status bar's: the first background one running for (int i = 0; i < 3; ++i) { if (progress.backgroundCancelled[i] || background[i].value >= 1.0f) continue; tasks.push_back(background[i]); tasks.back().onCancel = [this, i] { progress.backgroundCancelled[i] = true; }; - if (shown == nullptr && background[i].state == TaskState::Running) + if (shown == nullptr && background[i].state == dialogs::TaskState::Running) shown = &background[i]; } if (shown != nullptr) - StatusProgress(*this, idManager.AllocateDynamicID("statusTask"), - ProgressTask{ .name = shown->name, .value = shown->value, .note = shown == &background[0] ? std::string_view(count) : std::string_view{} }); - BackgroundTasks(*this, idManager.AllocateDynamicID("statusTasks"), tasks); + dialogs::StatusProgress(*this, dialogContext, idManager.AllocateDynamicID("statusTask"), + dialogs::ProgressTask{ .name = shown->name, .value = shown->value, .note = shown == &background[0] ? std::string_view(count) : std::string_view{} }); + dialogs::BackgroundTasks(*this, dialogContext, idManager.AllocateDynamicID("statusTasks"), tasks); } void Application::RenderViewportBusy(ID viewportID, int32_t width) @@ -216,12 +216,12 @@ namespace tachyon if (!ShadersCompiling() || width <= 0) return; // Along the view's top edge, and centered under it, the pill naming the work. - IndeterminateProgressBar(*this, idManager.AllocateDynamicID("viewportBusyBar"), viewportBusyBarStyleRef, + dialogs::IndeterminateProgressBar(*this, dialogContext, idManager.AllocateDynamicID("viewportBusyBar"), viewportBusyBarStyleRef, LayoutOverride{}.Width(Pixels{ width }).Anchored(viewportID, AnchorPlacement::InsideTopLeft)); BeginHorizontal(idManager.AllocateDynamicID("viewportBusy"), viewportBusyPillStyleRef, LayoutOverride{}.Anchored(viewportID, AnchorPlacement::InsideTop | AnchorPlacement::CenterHorz, { 0, int16_t(styleManager.Px(12)) })); - Spinner(*this, idManager.AllocateDynamicID("viewportBusySpinner"), SpinnerSize::Small); + dialogs::Spinner(*this, dialogContext, idManager.AllocateDynamicID("viewportBusySpinner"), dialogs::SpinnerSize::Small); Text(idManager.AllocateDynamicID("viewportBusyText"), "Compiling shaders", viewportBusyTextStyleRef); EndHorizontal(); } diff --git a/examples/showcase/settings_theme.cpp b/examples/showcase/settings_theme.cpp index 01dc92a8..20f64f41 100644 --- a/examples/showcase/settings_theme.cpp +++ b/examples/showcase/settings_theme.cpp @@ -99,14 +99,14 @@ namespace tachyon if (editor.confirmReset && changed) { - static constexpr MessageButton kButtons[] = { - { .label = "Reset", .kind = MessageButtonKind::Danger }, + static constexpr dialogs::MessageButton kButtons[] = { + { .label = "Reset", .kind = dialogs::MessageButtonKind::Danger }, { .label = "Cancel" }, }; const std::string title = std::format("Reset {} theme?", themeName); const std::string message = std::format("The colors and sizes you changed go back to the {} theme's own.", themeName); - const int choice = MessageDialog(*this, editor.resetDialogID, MessageDialogDesc{ - .icon = MessageIcon::Question, .title = title, .message = message, .buttons = kButtons, + const int choice = dialogs::MessageDialog(*this, dialogContext, editor.resetDialogID, dialogs::MessageDialogDesc{ + .icon = dialogs::MessageIcon::Question, .title = title, .message = message, .buttons = kButtons, .defaultButton = 1, .cancelButton = 1 }); if (choice == 0) ClearThemeVariables(); diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index d88e8ea4..fffde251 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -474,7 +474,6 @@ list(APPEND GUI_CONTROLS_FILES gui_controls/gui_application.h gui_controls/gui_application_internal.h gui_controls/gui_application.cpp - gui_controls/gui_app_extension.h gui_controls/gui_content.h gui_controls/gui_widget_state_types.h gui_controls/gui_node_view_types.h @@ -591,7 +590,7 @@ add_library(TachyonUI::gui_controls ALIAS gui_controls) set(GUI_DIALOGS_FILES gui_dialogs/gui_dialogs.h gui_dialogs/gui_dialogs_internal.h - gui_dialogs/gui_dialogs_extension.cpp + gui_dialogs/gui_dialogs.cpp gui_dialogs/gui_message_dialog_types.h gui_dialogs/gui_message_dialog.cpp gui_dialogs/gui_notification_types.h diff --git a/src/gui_controls/gui_app_extension.h b/src/gui_controls/gui_app_extension.h deleted file mode 100644 index 920f407c..00000000 --- a/src/gui_controls/gui_app_extension.h +++ /dev/null @@ -1,66 +0,0 @@ -#pragma once - -// Extensions: what a library of controls outside GUIApplication keeps per application. A -// control there is a free function that takes the app; its state and its theme parts live in -// an AppExtension the app makes on first use (GUIApplication::Extension) and keeps until -// Cleanup, running its hooks along with the app's frames and theme loads. -// -// class Dialogs : public AppExtension -// { -// public: -// explicit Dialogs(GUIApplication& app) : AppExtension(app) {} -// void OnStylesLoaded() override { toastStyle = app.theme.GetStyle("toast"); } -// StyleRef toastStyle{}; -// std::vector toasts; -// }; -// -// void ShowToast(GUIApplication& app, ToastDesc desc) -// { -// app.Extension().toasts.push_back(...); -// } - -#include - -namespace tachyon -{ - class GUIApplication; - - /// The per-application part of a library of controls: derive from it, with a constructor - /// that takes the GUIApplication&, and get it with GUIApplication::Extension(). Its hooks - /// run in the order the extensions were made. - class AppExtension - { - public: - explicit AppExtension(GUIApplication& owner) : app(owner) {} - virtual ~AppExtension() = default; - AppExtension(const AppExtension&) = delete; - AppExtension& operator=(const AppExtension&) = delete; - - /// The styles have loaded: at the theme's first load, after every reload (which - /// clears every StyleRef and color style), and when the extension is made after - /// either. Look up the extension's styles here (theme.GetStyle with its CSS classes). - virtual void OnStylesLoaded() {} - /// Every element of the frame is declared, before layout: for moving or drawing over - /// what the frame built. `frameTimeSecs` is the frame's time. - virtual void OnPostConstruct(float frameTimeSecs) { (void)frameTimeSecs; } - /// The frame is over: for dropping the state of controls no longer built. - virtual void OnEndFrame() {} - /// The app is cleaning up, with its windows and ID manager still there: for giving - /// back static IDs and closing windows. The extension is destroyed after. - virtual void OnCleanup() {} - - GUIApplication& app; ///< the application this belongs to - }; - - namespace detail - { - /// A number for each extension type, the same in every application of the process. - size_t NextAppExtensionSlot(); - template - size_t AppExtensionSlot() - { - static const size_t slot = NextAppExtensionSlot(); - return slot; - } - } -} diff --git a/src/gui_controls/gui_application.cpp b/src/gui_controls/gui_application.cpp index 7610ba56..cf5abb56 100644 --- a/src/gui_controls/gui_application.cpp +++ b/src/gui_controls/gui_application.cpp @@ -10,7 +10,6 @@ #include #include -#include #include #include #include @@ -292,39 +291,6 @@ namespace tachyon m_gridItemRenameByID.clear(); }); m_frame.OnEndFrame([this](FrameContext&) { PruneStaleControlState(); }); - // The extensions', after the app's own. An extension made during a frame's construction - // takes part from that frame's post-construct on. - m_frame.OnPostConstruct([this](FrameContext& ctx) - { - for (size_t i = 0; i < m_extensionOrder.size(); ++i) // a hook may make another - m_extensionOrder[i]->OnPostConstruct(ctx.elapsedTimeSecs); - }); - m_frame.OnEndFrame([this](FrameContext&) - { - for (size_t i = 0; i < m_extensionOrder.size(); ++i) - m_extensionOrder[i]->OnEndFrame(); - }); - } - - void GUIApplication::AddExtension(size_t slot, std::unique_ptr extension) - { - AppExtension* made = extension.get(); - m_extensions[slot] = std::move(extension); - m_extensionOrder.push_back(made); - if (m_stylesLoaded) - made->OnStylesLoaded(); - } - - void GUIApplication::CleanupExtensions() - { - for (size_t i = 0; i < m_extensionOrder.size(); ++i) - m_extensionOrder[i]->OnCleanup(); - for (size_t i = m_extensionOrder.size(); i-- > 0; ) - for (std::unique_ptr& owned : m_extensions) - if (owned.get() == m_extensionOrder[i]) - owned.reset(); - m_extensionOrder.clear(); - m_extensions.clear(); } void GUIApplication::RetireWindow(ID windowID) @@ -425,12 +391,6 @@ namespace tachyon }); } - size_t detail::NextAppExtensionSlot() - { - static std::atomic next{ 0 }; - return next.fetch_add(1, std::memory_order_relaxed); - } - GUIApplication::~GUIApplication() { // This class's Cleanup: a derived one's members are gone by now. @@ -440,8 +400,6 @@ namespace tachyon void GUIApplication::ReleaseOwnIDs() { - // The extensions give back theirs first, while the windows and the rest they use are here. - CleanupExtensions(); // Torn-off windows: their panels are hidden and destroyed with them, and their IDs and // trees' go back. while (!m_floatingDockWindows.empty()) @@ -471,8 +429,6 @@ namespace tachyon // The IDs it made for itself go back while what holds them is still here. if (m_initialized) ReleaseOwnIDs(); - else - CleanupExtensions(); // A theme switch still crossfading holds images of its windows. if (graphicsContext != nullptr) EndThemeCrossfade(); @@ -515,12 +471,9 @@ namespace tachyon m_loadedThemePath = m_themePath; m_loadedFontScale = m_globalFontScale; m_loadedAccent = m_accent; - m_stylesLoaded = true; - for (size_t i = 0; i < m_extensionOrder.size(); ++i) // a hook may make another - m_extensionOrder[i]->OnStylesLoaded(); + ++m_stylesGeneration; return {}; } - m_stylesLoaded = false; TACHYON_LOG_ERROR(kLogApp, "could not load theme {}", m_themePath); return Error{ ErrorCode::ParseFailed, "could not load theme " + m_themePath }; } diff --git a/src/gui_controls/gui_application.h b/src/gui_controls/gui_application.h index 242d3689..c98d160c 100644 --- a/src/gui_controls/gui_application.h +++ b/src/gui_controls/gui_application.h @@ -5,7 +5,6 @@ #include #include #include -#include #include #include #include @@ -87,7 +86,6 @@ #include #include #include -#include namespace tachyon { @@ -2841,24 +2839,15 @@ namespace tachyon ///@} - /// @name Extensions - /// A library of controls outside GUIApplication keeps its state per application in an - /// AppExtension (gui_app_extension.h). + /// @name For controls outside GUIApplication + /// A library of controls on top of this one (gui_dialogs, say) or an app's own: + /// what they need from the app that a member control reaches directly. ///@{ - /// This application's T, made with T(*this) on first use and kept until Cleanup; its - /// hooks run from then on. T derives from AppExtension. - template - T& Extension() - { - static_assert(std::is_base_of_v, "an extension derives from AppExtension"); - const size_t slot = detail::AppExtensionSlot(); - if (slot >= m_extensions.size()) - m_extensions.resize(slot + 1); - if (!m_extensions[slot]) - AddExtension(slot, std::make_unique(*this)); - return static_cast(*m_extensions[slot]); - } + /// Counts the times the styles loaded: at the theme's first load and after every + /// reload, which clears every StyleRef and color style. A control outside the app that + /// keeps styles of its own looks them up again when this changes. + uint32_t StylesGeneration() const { return m_stylesGeneration; } /// A color style of `owner`'s own for a color the app gives (and may change any frame): /// changed in place while `owner` asks for it each frame, freed the frame after it @@ -2897,14 +2886,7 @@ namespace tachyon /// the library's own code and the tests. friend class GUIApplicationInternals; - /// The extensions by AppExtensionSlot (null for a type this app hasn't used), and in - /// the order they were made, which their hooks run in. - std::vector> m_extensions; - std::vector m_extensionOrder; - bool m_stylesLoaded = false; ///< InitializeStyles succeeded last time it ran - void AddExtension(size_t slot, std::unique_ptr extension); - /// Runs each extension's OnCleanup, then destroys them, the newest first. - void CleanupExtensions(); + uint32_t m_stylesGeneration = 0; ///< StylesGeneration /// Segmented's body: `pick` writes a clicked segment's index to the caller's value. bool SegmentedImpl(ID id, int selected, std::span options, diff --git a/src/gui_dialogs/gui_dialogs_extension.cpp b/src/gui_dialogs/gui_dialogs.cpp similarity index 60% rename from src/gui_dialogs/gui_dialogs_extension.cpp rename to src/gui_dialogs/gui_dialogs.cpp index 35e0a462..70646ac8 100644 --- a/src/gui_dialogs/gui_dialogs_extension.cpp +++ b/src/gui_dialogs/gui_dialogs.cpp @@ -7,9 +7,9 @@ #include #include -namespace tachyon +namespace tachyon::dialogs { - void DialogStyles::Load(GUITheme& theme, StyleManager& styleManager) + void Styles::Load(GUITheme& theme, StyleManager& styleManager) { messageBoxStyleRef = theme.GetStyle("message-box"); messageBoxCloseStyleRef = theme.GetStyle("message-box-close"); @@ -97,97 +97,102 @@ namespace tachyon } } - const DialogStyles& GetDialogStyles(GUIApplication& app) { return Dialogs(app).styles; } - - void DialogsExtension::OnStylesLoaded() - { - styles.Load(app.theme, app.styleManager); - // The reload cleared every color style, the scrims' with them. - for (auto& [window, scrim] : scrims) - scrim.color = VisualColorStyleIndex::Invalid; - } - - void DialogsExtension::OnPostConstruct(float frameTimeSecs) + namespace { // The toasts over everything their window built, wherever in it Toasts was called; a // modal's scrim, after them, still dims them. - BringToastsToFront(); - // Scrims go over windows once everything in them is declared. - DrawScrims(frameTimeSecs); - } + void BringToastsToFront(GUIApplication& app, Context& context) + { + if (!std::exchange(context.toastsBuilt, false)) + return; + ElementRef stack = app.elementStorage.FindElementRefByID(context.toastStackID); + if (!app.elementStorage.IsValidRef(stack)) + return; + // Its window's last child, so the pointer finds it first; then drawn last. + const IndexRange siblings = app.elementStorage.GetChildRange(app.elementStorage.GetParentRef(stack)); + if (!siblings.Empty() && stack.index + 1 < siblings.end) + { + if (app.elementStorage.MoveChild(stack.depth, siblings.begin, stack.index - siblings.begin, + siblings.end - 1 - siblings.begin) == ElementStorageResult::Success) + { + app.windowRegistry.ApplyElementMove(app.elementStorage.LastMove()); + stack = app.elementStorage.FindElementRefByID(context.toastStackID); + } + } + if (app.elementStorage.IsValidRef(stack)) + app.windowRegistry.MoveSubtreeToEnd(stack); + } - void DialogsExtension::BringToastsToFront() - { - if (!std::exchange(toastsBuilt, false)) - return; - ElementRef stack = app.elementStorage.FindElementRefByID(toastStackID); - if (!app.elementStorage.IsValidRef(stack)) - return; - // Its window's last child, so the pointer finds it first; then drawn last. - const IndexRange siblings = app.elementStorage.GetChildRange(app.elementStorage.GetParentRef(stack)); - if (!siblings.Empty() && stack.index + 1 < siblings.end) + void DrawScrims(GUIApplication& app, Context& context, float now) { - if (app.elementStorage.MoveChild(stack.depth, siblings.begin, stack.index - siblings.begin, - siblings.end - 1 - siblings.begin) == ElementStorageResult::Success) + // Each dimmed window's scrim fades in (or out, after its dialog closed) over 120 ms, + // eased out, drawn over everything in the window. + constexpr float kFadeSecs = 0.12f; + const float step = context.scrimTime < 0.0f ? 0.0f : std::max(0.0f, now - context.scrimTime) / kFadeSecs; + context.scrimTime = now; + for (auto it = context.scrims.begin(); it != context.scrims.end(); ) { - app.windowRegistry.ApplyElementMove(app.elementStorage.LastMove()); - stack = app.elementStorage.FindElementRefByID(toastStackID); + Context::ScrimFade& scrim = it->second; + const bool wanted = std::exchange(scrim.wanted, false); + scrim.amount = std::clamp(scrim.amount + (wanted ? step : -step), 0.0f, 1.0f); + const ElementRef owner = app.windowRegistry.GetWindowRef(it->first); + if ((scrim.amount <= 0.0f && !wanted) || !app.elementStorage.IsValidRef(owner)) + { + if (scrim.color != VisualColorStyleIndex::Invalid) + app.styleManager.DestroyColorStyle(scrim.color); + it = context.scrims.erase(it); + continue; + } + const float eased = 1.0f - (1.0f - scrim.amount) * (1.0f - scrim.amount) * (1.0f - scrim.amount); + if (eased > 0.0f) + { + SetColorStyle(app.styleManager, scrim.color, color4f{ app.theme.scrim.r / 255.0f, app.theme.scrim.g / 255.0f, + app.theme.scrim.b / 255.0f, app.theme.scrim.a / 255.0f * eased }); + VERIFY(app.elementStorage.AddCustomDrawAfter(owner, [color = scrim.color](CustomDrawContext& ctx) + { ctx.RenderQuad(ctx.ElementRect(), color); })); + } + ++it; } } - if (app.elementStorage.IsValidRef(stack)) - app.windowRegistry.MoveSubtreeToEnd(stack); } - void DialogsExtension::OnEndFrame() + Context& Prepare(GUIApplication& app, Context& context) { - busyButtonWidths.EndFrame(); - tasksPopovers.EndFrame([this](ID, TasksPopover& popover) { app.RetireWindow(popover.windowID); return true; }); + if (context.stylesGeneration != app.StylesGeneration()) + { + context.styles.Load(app.theme, app.styleManager); + context.stylesGeneration = app.StylesGeneration(); + // The load cleared every color style, the scrims' with them. + for (auto& [window, scrim] : context.scrims) + scrim.color = VisualColorStyleIndex::Invalid; + } + return context; } - void DialogsExtension::OnCleanup() + const Styles& GetStyles(GUIApplication& app, Context& context) { return Prepare(app, context).styles; } + + void EndGUI(GUIApplication& app, Context& context) { - auto release = [this](ID& id) { + Prepare(app, context); + BringToastsToFront(app, context); + // Scrims go over windows once everything in them is declared. + DrawScrims(app, context, app.guiStateManager.Interaction().GetFrameTime()); + context.busyButtonWidths.EndFrame(); + context.tasksPopovers.EndFrame([&app](ID, Context::TasksPopover& popover) { app.RetireWindow(popover.windowID); return true; }); + } + + void Cleanup(GUIApplication& app, Context& context) + { + auto release = [&app](ID& id) { if (id != ID::Invalid() && id.GetMode() == IDMode::Static) app.idManager.ReleaseStaticID(id); id = ID::Invalid(); }; - for (ShownToast& toast : toasts) + for (Context::ShownToast& toast : context.toasts) release(toast.id); - toasts.clear(); - release(toastStackID); - tasksPopovers.ForEach([&](ID, TasksPopover& popover) { release(popover.windowID); }); - tasksPopovers.Clear(); - } - - void DialogsExtension::DrawScrims(float now) - { - // Each dimmed window's scrim fades in (or out, after its dialog closed) over 120 ms, - // eased out, drawn over everything in the window. - constexpr float kFadeSecs = 0.12f; - const float step = scrimTime < 0.0f ? 0.0f : std::max(0.0f, now - scrimTime) / kFadeSecs; - scrimTime = now; - for (auto it = scrims.begin(); it != scrims.end(); ) - { - ScrimFade& scrim = it->second; - const bool wanted = std::exchange(scrim.wanted, false); - scrim.amount = std::clamp(scrim.amount + (wanted ? step : -step), 0.0f, 1.0f); - const ElementRef owner = app.windowRegistry.GetWindowRef(it->first); - if ((scrim.amount <= 0.0f && !wanted) || !app.elementStorage.IsValidRef(owner)) - { - if (scrim.color != VisualColorStyleIndex::Invalid) - app.styleManager.DestroyColorStyle(scrim.color); - it = scrims.erase(it); - continue; - } - const float eased = 1.0f - (1.0f - scrim.amount) * (1.0f - scrim.amount) * (1.0f - scrim.amount); - if (eased > 0.0f) - { - SetColorStyle(app.styleManager, scrim.color, color4f{ app.theme.scrim.r / 255.0f, app.theme.scrim.g / 255.0f, - app.theme.scrim.b / 255.0f, app.theme.scrim.a / 255.0f * eased }); - VERIFY(app.elementStorage.AddCustomDrawAfter(owner, [color = scrim.color](CustomDrawContext& ctx) - { ctx.RenderQuad(ctx.ElementRect(), color); })); - } - ++it; - } + context.toasts.clear(); + release(context.toastStackID); + context.tasksPopovers.ForEach([&](ID, Context::TasksPopover& popover) { release(popover.windowID); }); + context.tasksPopovers.Clear(); } } diff --git a/src/gui_dialogs/gui_dialogs.h b/src/gui_dialogs/gui_dialogs.h index dd1f9ea3..7df975dc 100644 --- a/src/gui_dialogs/gui_dialogs.h +++ b/src/gui_dialogs/gui_dialogs.h @@ -1,30 +1,35 @@ #pragma once // Dialogs: message boxes, toasts and banners, and progress (bars, spinners, tasks). A library -// of its own on gui_controls: each control is a free function that takes the application, -// and keeps its state in the app's DialogsExtension. +// of its own on gui_controls, in namespace tachyon::dialogs: each control is a free function +// that takes the application, and keeps what it needs from frame to frame in the app. // -// if (int choice = MessageDialog(app, desc); choice >= 0) +// if (int choice = dialogs::MessageDialog(app, context, desc); choice >= 0) // ... -// ShowToast(app, ToastDesc{ .severity = Severity::Success, .title = "Saved" }); +// dialogs::ShowToast(app, context, dialogs::ToastDesc{ .severity = dialogs::Severity::Success, .title = "Saved" }); #include #include #include #include +#include + +#include #include #include #include #include +#include +#include -namespace tachyon +namespace tachyon::dialogs { /// @addtogroup controls /// @{ /// The dialogs' styles, looked up by their CSS classes each time the styles load. - struct DialogStyles + struct Styles { StyleRef messageBoxStyleRef {}; ///< MessageDialog: the window StyleRef messageBoxCloseStyleRef {}; ///< MessageDialog: the close button, top right @@ -111,17 +116,69 @@ namespace tachyon void Load(GUITheme& theme, StyleManager& styleManager); }; - /// The dialogs' styles in `app`'s theme. - const DialogStyles& GetDialogStyles(GUIApplication& app); + /// What the dialogs keep from frame to frame, the app's to own (a member of its app class, + /// say) and pass to each of them. It holds no pointer to the app. + struct Context + { + Styles styles; + uint32_t stylesGeneration = 0; ///< the app's StylesGeneration the styles were looked up at + + /// A BusyButton's width while it wasn't busy, kept while it is. + RecentIDMap busyButtonWidths; + + /// BackgroundTasks' popover, per pill. + struct TasksPopover + { + ID windowID = ID::Invalid(); + bool open = false; + }; + RecentIDMap tasksPopovers; + + /// A toast shown: what it says, when it came and went, and its elements' parent ID. + struct ShownToast + { + ToastID handle = 0; + ToastDesc desc; + ID id = ID::Invalid(); ///< static, released when it's gone + float shownAt = 0.0f; ///< frame time, seconds + float leftAt = -1.0f; ///< when it started going; negative while it stays + float shownFor = 0.0f; ///< seconds it has been shown without the pointer over the stack + }; + std::vector toasts; + ToastID nextToast = 0; + float toastsTime = -1.0f; ///< the frame time Toasts last ran at + bool toastsExpanded = false; ///< "+N earlier" clicked: every toast shown + ID toastStackID = ID::Invalid(); + bool toastsBuilt = false; ///< built this frame: moved over its window after construction + + std::vector mnemonicStyles; ///< this frame's underlined mnemonic letters (MessageDialog) + + /// Windows dimmed under a modal dialog, by window ID: fading in while wanted, out after. + struct ScrimFade { float amount = 0.0f; bool wanted = false; VisualColorStyleIndex color = VisualColorStyleIndex::Invalid; }; + std::unordered_map scrims; + float scrimTime = -1.0f; + }; + + /// The dialogs' styles in `app`'s theme, looked up again after each theme load. + const Styles& GetStyles(GUIApplication& app, Context& context); + + /// After everything the frame builds: brings the toasts over the rest of their window, + /// draws the scrims that dim windows under a message dialog, and drops the state of + /// dialogs no longer built. Call it last in OnGUI, every frame. + void EndGUI(GUIApplication& app, Context& context); + + /// Gives back what the dialogs hold (static IDs, popover windows). Call it before + /// GUIApplication::Cleanup, while the app's windows are still there. + void Cleanup(GUIApplication& app, Context& context); /// A button at work: a spinner in place of its icon and `busyText` ("Saving...") in /// place of its text, as wide as it was before, and clicks ignored. While `busy` is /// false it's an ordinary Button; empty `busyText` keeps the text. - bool BusyButton(GUIApplication& app, ID id, const GUIContent& content, bool busy, std::string_view busyText, + bool BusyButton(GUIApplication& app, Context& context, ID id, const GUIContent& content, bool busy, std::string_view busyText, std::function onClick, StyleRef style, LayoutOverride&& constraints = {}); /// As above, in the theme's button style. - inline bool BusyButton(GUIApplication& app, ID id, const GUIContent& content, bool busy, std::string_view busyText, - std::function onClick, LayoutOverride&& constraints = {}) { return BusyButton(app, id, content, busy, busyText, std::move(onClick), app.theme.controls->button, std::move(constraints)); } + inline bool BusyButton(GUIApplication& app, Context& context, ID id, const GUIContent& content, bool busy, std::string_view busyText, + std::function onClick, LayoutOverride&& constraints = {}) { return BusyButton(app, context, id, content, busy, busyText, std::move(onClick), app.theme.controls->button, std::move(constraints)); } /// @name Progress and loading @@ -132,71 +189,71 @@ namespace tachyon /// A bar `value` (0 to 1, clamped) of the way full; `failed` fills it in the error /// color, for work that stopped. The theme's bar is 6px high; progressBarSmallStyleRef's /// is 4px, for lists and the status bar. - void ProgressBar(GUIApplication& app, ID id, float value, bool failed, StyleRef style, LayoutOverride&& constraints = {}); + void ProgressBar(GUIApplication& app, Context& context, ID id, float value, bool failed, StyleRef style, LayoutOverride&& constraints = {}); /// As above, not failed, in the theme's bar style. - inline void ProgressBar(GUIApplication& app, ID id, float value, LayoutOverride&& constraints = {}) { ProgressBar(app, id, value, false, GetDialogStyles(app).progressBarStyleRef, std::move(constraints)); } + inline void ProgressBar(GUIApplication& app, Context& context, ID id, float value, LayoutOverride&& constraints = {}) { ProgressBar(app, context, id, value, false, GetStyles(app, context).progressBarStyleRef, std::move(constraints)); } /// As above, with the call site as the ID. - inline void ProgressBar(GUIApplication& app, float value, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { ProgressBar(app, app.idManager.AllocateDynamicID(site), value, false, GetDialogStyles(app).progressBarStyleRef, std::move(constraints)); } + inline void ProgressBar(GUIApplication& app, Context& context, float value, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { ProgressBar(app, context, app.idManager.AllocateDynamicID(site), value, false, GetStyles(app, context).progressBarStyleRef, std::move(constraints)); } /// A bar for work of unknown length: a segment with soft ends slides along it, from /// start to end every 1.2 s. - void IndeterminateProgressBar(GUIApplication& app, ID id, StyleRef style, LayoutOverride&& constraints = {}); + void IndeterminateProgressBar(GUIApplication& app, Context& context, ID id, StyleRef style, LayoutOverride&& constraints = {}); /// As above, in the theme's bar style. - inline void IndeterminateProgressBar(GUIApplication& app, ID id, LayoutOverride&& constraints = {}) { IndeterminateProgressBar(app, id, GetDialogStyles(app).progressBarStyleRef, std::move(constraints)); } + inline void IndeterminateProgressBar(GUIApplication& app, Context& context, ID id, LayoutOverride&& constraints = {}) { IndeterminateProgressBar(app, context, id, GetStyles(app, context).progressBarStyleRef, std::move(constraints)); } /// As above, with the call site as the ID. - inline void IndeterminateProgressBar(GUIApplication& app, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { IndeterminateProgressBar(app, app.idManager.AllocateDynamicID(site), GetDialogStyles(app).progressBarStyleRef, std::move(constraints)); } + inline void IndeterminateProgressBar(GUIApplication& app, Context& context, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { IndeterminateProgressBar(app, context, app.idManager.AllocateDynamicID(site), GetStyles(app, context).progressBarStyleRef, std::move(constraints)); } /// A ring with an arc going round it, a turn every 0.8 s, in the theme's track and /// accent colors: work under way. 12, 16 or 18px across unless `constraints` say. - void Spinner(GUIApplication& app, ID id, SpinnerSize size = SpinnerSize::Medium, LayoutOverride&& constraints = {}); + void Spinner(GUIApplication& app, Context& context, ID id, SpinnerSize size = SpinnerSize::Medium, LayoutOverride&& constraints = {}); /// As above, with the call site as the ID. - inline void Spinner(GUIApplication& app, SpinnerSize size = SpinnerSize::Medium, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { Spinner(app, app.idManager.AllocateDynamicID(site), size, std::move(constraints)); } + inline void Spinner(GUIApplication& app, Context& context, SpinnerSize size = SpinnerSize::Medium, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { Spinner(app, context, app.idManager.AllocateDynamicID(site), size, std::move(constraints)); } /// A ring filled `value` (0 to 1, clamped) of the way round, clockwise from the top, /// the percentage in its middle. The theme's is 36px across. - void CircularProgress(GUIApplication& app, ID id, float value, StyleRef style, LayoutOverride&& constraints = {}); + void CircularProgress(GUIApplication& app, Context& context, ID id, float value, StyleRef style, LayoutOverride&& constraints = {}); /// As above, in the theme's style. - inline void CircularProgress(GUIApplication& app, ID id, float value, LayoutOverride&& constraints = {}) { CircularProgress(app, id, value, GetDialogStyles(app).circularProgressStyleRef, std::move(constraints)); } + inline void CircularProgress(GUIApplication& app, Context& context, ID id, float value, LayoutOverride&& constraints = {}) { CircularProgress(app, context, id, value, GetStyles(app, context).circularProgressStyleRef, std::move(constraints)); } /// As above, with the call site as the ID. - inline void CircularProgress(GUIApplication& app, float value, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { CircularProgress(app, app.idManager.AllocateDynamicID(site), value, GetDialogStyles(app).circularProgressStyleRef, std::move(constraints)); } + inline void CircularProgress(GUIApplication& app, Context& context, float value, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { CircularProgress(app, context, app.idManager.AllocateDynamicID(site), value, GetStyles(app, context).circularProgressStyleRef, std::move(constraints)); } /// A placeholder bar where content is still loading, sized as the content it stands /// for (give it a width), with a shine sweeping across it every 1.5 s; still with /// reduced motion. - void Skeleton(GUIApplication& app, ID id, StyleRef style, LayoutOverride&& constraints = {}); + void Skeleton(GUIApplication& app, Context& context, ID id, StyleRef style, LayoutOverride&& constraints = {}); /// As above, in the theme's style. - inline void Skeleton(GUIApplication& app, ID id, LayoutOverride&& constraints = {}) { Skeleton(app, id, GetDialogStyles(app).skeletonStyleRef, std::move(constraints)); } + inline void Skeleton(GUIApplication& app, Context& context, ID id, LayoutOverride&& constraints = {}) { Skeleton(app, context, id, GetStyles(app, context).skeletonStyleRef, std::move(constraints)); } /// As above, with the call site as the ID. - inline void Skeleton(GUIApplication& app, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { Skeleton(app, app.idManager.AllocateDynamicID(site), GetDialogStyles(app).skeletonStyleRef, std::move(constraints)); } + inline void Skeleton(GUIApplication& app, Context& context, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { Skeleton(app, context, app.idManager.AllocateDynamicID(site), GetStyles(app, context).skeletonStyleRef, std::move(constraints)); } /// A piece of work in full: its name and percent (or `note`) over its bar, a cancel /// button when `onCancel` is set, and `detail` under it. Failed: the error icon, the bar /// in the error color, the reason in error text and a Retry button when `onRetry` is /// set, with a turning arrow. Done: a check, the name and `note` (how long it took) on one line. - void TaskProgress(GUIApplication& app, ID id, const ProgressTask& task, LayoutOverride&& constraints = {}); + void TaskProgress(GUIApplication& app, Context& context, ID id, const ProgressTask& task, LayoutOverride&& constraints = {}); /// As above, with the call site as the ID. - inline void TaskProgress(GUIApplication& app, const ProgressTask& task, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { TaskProgress(app, app.idManager.AllocateDynamicID(site), task, std::move(constraints)); } + inline void TaskProgress(GUIApplication& app, Context& context, const ProgressTask& task, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { TaskProgress(app, context, app.idManager.AllocateDynamicID(site), task, std::move(constraints)); } /// The steps of a longer job, one a row: a glyph for its state (a check once done, a /// spinner while running, a dashed ring while pending, a cross and "failed" once failed), /// its name, and its `note` (or percent) at the end of the line; under the running one, a /// small bar and its `detail`, in line with the names. - void ProgressSteps(GUIApplication& app, ID id, std::span steps, LayoutOverride&& constraints = {}); + void ProgressSteps(GUIApplication& app, Context& context, ID id, std::span steps, LayoutOverride&& constraints = {}); /// As above, with the call site as the ID. - inline void ProgressSteps(GUIApplication& app, std::span steps, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { ProgressSteps(app, app.idManager.AllocateDynamicID(site), steps, std::move(constraints)); } + inline void ProgressSteps(GUIApplication& app, Context& context, std::span steps, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { ProgressSteps(app, context, app.idManager.AllocateDynamicID(site), steps, std::move(constraints)); } /// A piece of work in a status bar: a small spinner, its name, a 120px bar and its /// `note` ("1,240 / 3,800") or percent. - void StatusProgress(GUIApplication& app, ID id, const ProgressTask& task, LayoutOverride&& constraints = {}); + void StatusProgress(GUIApplication& app, Context& context, ID id, const ProgressTask& task, LayoutOverride&& constraints = {}); /// As above, with the call site as the ID. - inline void StatusProgress(GUIApplication& app, const ProgressTask& task, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { StatusProgress(app, app.idManager.AllocateDynamicID(site), task, std::move(constraints)); } + inline void StatusProgress(GUIApplication& app, Context& context, const ProgressTask& task, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { StatusProgress(app, context, app.idManager.AllocateDynamicID(site), task, std::move(constraints)); } /// A "3 tasks" pill with a chevron, for a status bar, that opens a popover listing `tasks`: each with its /// name, a small bar, its percent or state and a cancel button when `onCancel` is set. /// Shows nothing while `tasks` is empty. Returns whether the popover is open. - bool BackgroundTasks(GUIApplication& app, ID id, std::span tasks, LayoutOverride&& constraints = {}); + bool BackgroundTasks(GUIApplication& app, Context& context, ID id, std::span tasks, LayoutOverride&& constraints = {}); /// As above, with the call site as the ID. - inline bool BackgroundTasks(GUIApplication& app, std::span tasks, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return BackgroundTasks(app, app.idManager.AllocateDynamicID(site), tasks, std::move(constraints)); } + inline bool BackgroundTasks(GUIApplication& app, Context& context, std::span tasks, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return BackgroundTasks(app, context, app.idManager.AllocateDynamicID(site), tasks, std::move(constraints)); } ///@} @@ -204,35 +261,35 @@ namespace tachyon /// A modal question with verb buttons, centered. Call it every frame while asking; it /// returns the index of the button chosen (once, on the frame after), else -1. Esc and /// the close button choose desc.cancelButton; Alt + a button's first letter chooses it. - int MessageDialog(GUIApplication& app, ID id, const MessageDialogDesc& desc, StyleRef style); + int MessageDialog(GUIApplication& app, Context& context, ID id, const MessageDialogDesc& desc, StyleRef style); /// As above, in the theme's message box style. - inline int MessageDialog(GUIApplication& app, ID id, const MessageDialogDesc& desc) { return MessageDialog(app, id, desc, GetDialogStyles(app).messageBoxStyleRef); } + inline int MessageDialog(GUIApplication& app, Context& context, ID id, const MessageDialogDesc& desc) { return MessageDialog(app, context, id, desc, GetStyles(app, context).messageBoxStyleRef); } /// As above, with the call site as the ID. - inline int MessageDialog(GUIApplication& app, const MessageDialogDesc& desc, StyleRef style, std::source_location site = std::source_location::current()) { return MessageDialog(app, app.idManager.AllocateDynamicID(site), desc, style); } + inline int MessageDialog(GUIApplication& app, Context& context, const MessageDialogDesc& desc, StyleRef style, std::source_location site = std::source_location::current()) { return MessageDialog(app, context, app.idManager.AllocateDynamicID(site), desc, style); } /// As above, with the call site as the ID, in the theme's message box style. - inline int MessageDialog(GUIApplication& app, const MessageDialogDesc& desc, std::source_location site = std::source_location::current()) { return MessageDialog(app, app.idManager.AllocateDynamicID(site), desc, GetDialogStyles(app).messageBoxStyleRef); } + inline int MessageDialog(GUIApplication& app, Context& context, const MessageDialogDesc& desc, std::source_location site = std::source_location::current()) { return MessageDialog(app, context, app.idManager.AllocateDynamicID(site), desc, GetStyles(app, context).messageBoxStyleRef); } /// Shows a toast in the corner of the window that builds Toasts. Errors stay until /// dismissed; the rest go after about 6 s (not while the pointer is over the toasts, nor /// while a progress bar is short of 1). - ToastID ShowToast(GUIApplication& app, ToastDesc desc); + ToastID ShowToast(GUIApplication& app, Context& context, ToastDesc desc); /// A shown toast's description, to change (its progress, its body); null once it's gone. /// A change outside a frame shows at the next one: call RequestRedraw after it. - ToastDesc* FindToast(GUIApplication& app, ToastID toast); + ToastDesc* FindToast(GUIApplication& app, Context& context, ToastID toast); /// Takes a toast away, as its close button does. - void DismissToast(GUIApplication& app, ToastID toast); + void DismissToast(GUIApplication& app, Context& context, ToastID toast); /// The toasts, in the current window's bottom-right corner over what's built before; /// call it last in the window. The newest is nearest the corner; ones past the fourth /// fold into a "+N earlier" pill, which shows them all. - void Toasts(GUIApplication& app); + void Toasts(GUIApplication& app, Context& context); /// A banner across the top of a panel: the message (`message.icon`, else the /// severity's) on the severity's tint, then `actions`, right-aligned. - void Banner(GUIApplication& app, ID id, Severity severity, const GUIContent& message, std::span actions = {}, + void Banner(GUIApplication& app, Context& context, ID id, Severity severity, const GUIContent& message, std::span actions = {}, LayoutOverride&& constraints = {}); /// As above, with the call site as the ID. - inline void Banner(GUIApplication& app, Severity severity, const GUIContent& message, std::span actions = {}, + inline void Banner(GUIApplication& app, Context& context, Severity severity, const GUIContent& message, std::span actions = {}, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) - { Banner(app, app.idManager.AllocateDynamicID(site), severity, message, actions, std::move(constraints)); } + { Banner(app, context, app.idManager.AllocateDynamicID(site), severity, message, actions, std::move(constraints)); } /// @} } diff --git a/src/gui_dialogs/gui_dialogs_internal.h b/src/gui_dialogs/gui_dialogs_internal.h index ddeb67ce..66783384 100644 --- a/src/gui_dialogs/gui_dialogs_internal.h +++ b/src/gui_dialogs/gui_dialogs_internal.h @@ -1,69 +1,12 @@ #pragma once -// Not installed: the dialogs' state in each application, for the dialogs' own code and tests. +// Not installed: what the dialogs' own code shares. #include -#include - -#include -#include -#include - -namespace tachyon +namespace tachyon::dialogs { - class DialogsExtension : public AppExtension - { - public: - explicit DialogsExtension(GUIApplication& owner) : AppExtension(owner) {} - - void OnStylesLoaded() override; - void OnPostConstruct(float frameTimeSecs) override; - void OnEndFrame() override; - void OnCleanup() override; - - DialogStyles styles; - - /// A BusyButton's width while it wasn't busy, kept while it is. - RecentIDMap busyButtonWidths; - - /// BackgroundTasks' popover, per pill. - struct TasksPopover - { - ID windowID = ID::Invalid(); - bool open = false; - }; - RecentIDMap tasksPopovers; - - /// A toast shown: what it says, when it came and went, and its elements' parent ID. - struct ShownToast - { - ToastID handle = 0; - ToastDesc desc; - ID id = ID::Invalid(); ///< static, released when it's gone - float shownAt = 0.0f; ///< frame time, seconds - float leftAt = -1.0f; ///< when it started going; negative while it stays - float shownFor = 0.0f; ///< seconds it has been shown without the pointer over the stack - }; - std::vector toasts; - ToastID nextToast = 0; - float toastsTime = -1.0f; ///< the frame time Toasts last ran at - bool toastsExpanded = false; ///< "+N earlier" clicked: every toast shown - ID toastStackID = ID::Invalid(); - bool toastsBuilt = false; ///< built this frame: moved over its window after construction - - std::vector mnemonicStyles; ///< this frame's underlined mnemonic letters (MessageDialog) - - /// Windows dimmed under a modal dialog, by window ID: fading in while wanted, out after. - struct ScrimFade { float amount = 0.0f; bool wanted = false; VisualColorStyleIndex color = VisualColorStyleIndex::Invalid; }; - std::unordered_map scrims; - float scrimTime = -1.0f; - void DrawScrims(float now); - - private: - void BringToastsToFront(); - }; - - /// `app`'s dialogs, made on first use. - inline DialogsExtension& Dialogs(GUIApplication& app) { return app.Extension(); } + /// `context`, with its styles looked up again when the app's styles loaded since: what + /// each dialog does first. + Context& Prepare(GUIApplication& app, Context& context); } diff --git a/src/gui_dialogs/gui_message_dialog.cpp b/src/gui_dialogs/gui_message_dialog.cpp index b0c61912..857d5e4c 100644 --- a/src/gui_dialogs/gui_message_dialog.cpp +++ b/src/gui_dialogs/gui_message_dialog.cpp @@ -6,7 +6,7 @@ // MessageDialog: a modal question with verb buttons (see MessageDialogDesc). -namespace tachyon +namespace tachyon::dialogs { namespace { @@ -25,9 +25,9 @@ namespace tachyon } } - int MessageDialog(GUIApplication& app, ID id, const MessageDialogDesc& desc, StyleRef style) + int MessageDialog(GUIApplication& app, Context& context, ID id, const MessageDialogDesc& desc, StyleRef style) { - DialogsExtension& d = Dialogs(app); + Context& d = Prepare(app, context); auto& store = app.guiStateManager.GetElementDataStore(); auto& state = store.GetOrCreate(id); if (state.choice >= 0) @@ -121,12 +121,12 @@ namespace tachyon // Severity icon | title, message and extras. app.BeginHorizontal(app.idManager.AllocateDynamicID("message_box_body"), d.styles.messageBoxBodyStyleRef, LayoutOverride{}.NoShrink()); { - static constexpr struct { StyleRef DialogStyles::* style; IconID GUITheme::* icon; } kIcons[] = { - { &DialogStyles::messageBoxWarningStyleRef, &GUITheme::alertIcon }, // Warning - { &DialogStyles::messageBoxWarningStyleRef, &GUITheme::powerIcon }, // Quit - { &DialogStyles::messageBoxQuestionStyleRef, &GUITheme::questionIcon }, // Question - { &DialogStyles::messageBoxQuestionStyleRef, &GUITheme::infoIcon }, // Info - { &DialogStyles::messageBoxErrorStyleRef, &GUITheme::errorIcon }, // Error + static constexpr struct { StyleRef Styles::* style; IconID GUITheme::* icon; } kIcons[] = { + { &Styles::messageBoxWarningStyleRef, &GUITheme::alertIcon }, // Warning + { &Styles::messageBoxWarningStyleRef, &GUITheme::powerIcon }, // Quit + { &Styles::messageBoxQuestionStyleRef, &GUITheme::questionIcon }, // Question + { &Styles::messageBoxQuestionStyleRef, &GUITheme::infoIcon }, // Info + { &Styles::messageBoxErrorStyleRef, &GUITheme::errorIcon }, // Error }; const auto& kind = kIcons[std::min(size_t(desc.icon), std::size(kIcons) - 1)]; app.RegisterElement(Element{ .id = app.idManager.AllocateDynamicID("message_box_icon"), .iconID = app.theme.*kind.icon, diff --git a/src/gui_dialogs/gui_message_dialog_types.h b/src/gui_dialogs/gui_message_dialog_types.h index ee09c82c..70df241d 100644 --- a/src/gui_dialogs/gui_message_dialog_types.h +++ b/src/gui_dialogs/gui_message_dialog_types.h @@ -9,7 +9,7 @@ #include #include -namespace tachyon +namespace tachyon::dialogs { /// @addtogroup controls /// @{ diff --git a/src/gui_dialogs/gui_notification_types.h b/src/gui_dialogs/gui_notification_types.h index 3e6145ff..67653a77 100644 --- a/src/gui_dialogs/gui_notification_types.h +++ b/src/gui_dialogs/gui_notification_types.h @@ -12,7 +12,7 @@ // Telling the user something without a dialog: toasts in a window's corner, banners at the // top of a panel. -namespace tachyon +namespace tachyon::dialogs { /// @addtogroup controls /// @{ diff --git a/src/gui_dialogs/gui_notifications.cpp b/src/gui_dialogs/gui_notifications.cpp index 8b46f457..aebbef95 100644 --- a/src/gui_dialogs/gui_notifications.cpp +++ b/src/gui_dialogs/gui_notifications.cpp @@ -8,7 +8,7 @@ #include #include -namespace tachyon +namespace tachyon::dialogs { // --------------------------------------------------------------------------- @@ -59,10 +59,10 @@ namespace tachyon } } - ToastID ShowToast(GUIApplication& app, ToastDesc desc) + ToastID ShowToast(GUIApplication& app, Context& context, ToastDesc desc) { - DialogsExtension& d = Dialogs(app); - DialogsExtension::ShownToast toast; + Context& d = Prepare(app, context); + Context::ShownToast toast; toast.handle = ++d.nextToast; toast.desc = std::move(desc); toast.id = app.idManager.CreateStaticID(); @@ -72,19 +72,19 @@ namespace tachyon return d.toasts.back().handle; } - ToastDesc* FindToast(GUIApplication& app, ToastID toast) + ToastDesc* FindToast(GUIApplication& app, Context& context, ToastID toast) { - DialogsExtension& d = Dialogs(app); - for (DialogsExtension::ShownToast& shown : d.toasts) + Context& d = Prepare(app, context); + for (Context::ShownToast& shown : d.toasts) if (shown.handle == toast && shown.leftAt < 0.0f) return &shown.desc; return nullptr; } - void DismissToast(GUIApplication& app, ToastID toast) + void DismissToast(GUIApplication& app, Context& context, ToastID toast) { - DialogsExtension& d = Dialogs(app); - for (DialogsExtension::ShownToast& shown : d.toasts) + Context& d = Prepare(app, context); + for (Context::ShownToast& shown : d.toasts) if (shown.handle == toast && shown.leftAt < 0.0f) { shown.leftAt = app.guiStateManager.Interaction().GetFrameTime(); @@ -92,9 +92,9 @@ namespace tachyon } } - void Toasts(GUIApplication& app) + void Toasts(GUIApplication& app, Context& context) { - DialogsExtension& d = Dialogs(app); + Context& d = Prepare(app, context); const float now = app.guiStateManager.Interaction().GetFrameTime(); const float dt = d.toastsTime < 0.0f ? 0.0f : std::max(0.0f, now - d.toastsTime); const float lastToasts = d.toastsTime; @@ -108,7 +108,7 @@ namespace tachyon // Gone once slid out; the ones that go by themselves count down while not hovered. for (size_t i = d.toasts.size(); i-- > 0; ) { - DialogsExtension::ShownToast& toast = d.toasts[i]; + Context::ShownToast& toast = d.toasts[i]; if (toast.leftAt >= 0.0f && (reduced || now - toast.leftAt >= kToastOutSecs)) { app.idManager.ReleaseStaticID(toast.id); @@ -157,11 +157,11 @@ namespace tachyon if (folded > 0) app.Button(app.idManager.AllocateDynamicID("earlier"), "+" + std::to_string(folded) + " earlier", - [&app] { Dialogs(app).toastsExpanded = true; }, d.styles.toastEarlierStyleRef, LayoutOverride{}.NoGrow().NoShrink()); + [state = &context] { state->toastsExpanded = true; }, d.styles.toastEarlierStyleRef, LayoutOverride{}.NoGrow().NoShrink()); for (int i = folded; i < count; ++i) { - DialogsExtension::ShownToast& toast = d.toasts[size_t(i)]; + Context::ShownToast& toast = d.toasts[size_t(i)]; const ToastDesc& desc = toast.desc; const ToastID handle = toast.handle; @@ -223,14 +223,14 @@ namespace tachyon // An action does its thing, and the toast goes. auto onClick = desc.actions[a].onClick; app.Button(app.idManager.AllocateDynamicID("action"), desc.actions[a].label, - [&app, handle, onClick] { if (onClick) onClick(); DismissToast(app, handle); }, + [&app, state = &context, handle, onClick] { if (onClick) onClick(); DismissToast(app, *state, handle); }, a == 0 ? d.styles.toastActionStyleRef : d.styles.toastActionSecondaryStyleRef); } app.EndHorizontal(); } app.EndVertical(); - app.Button(app.idManager.AllocateDynamicID("dismiss"), app.theme.tabCloseIcon, [&app, handle] { DismissToast(app, handle); }, + app.Button(app.idManager.AllocateDynamicID("dismiss"), app.theme.tabCloseIcon, [&app, state = &context, handle] { DismissToast(app, *state, handle); }, d.styles.toastDismissStyleRef); app.SetTooltip("Dismiss"); @@ -246,10 +246,10 @@ namespace tachyon d.toastsBuilt = app.elementStorage.IsValidRef(stackRef); } - void Banner(GUIApplication& app, ID id, Severity severity, const GUIContent& message, std::span actions, + void Banner(GUIApplication& app, Context& context, ID id, Severity severity, const GUIContent& message, std::span actions, LayoutOverride&& constraints) { - DialogsExtension& d = Dialogs(app); + Context& d = Prepare(app, context); const int s = std::clamp(int(severity), 0, 3); app.BeginHorizontal(id, d.styles.bannerStyleRefs[s], std::move(constraints)); [[maybe_unused]] const bool pushed = app.idManager.PushParent(id); diff --git a/src/gui_dialogs/gui_progress.cpp b/src/gui_dialogs/gui_progress.cpp index 9a6a06fc..b8b00f29 100644 --- a/src/gui_dialogs/gui_progress.cpp +++ b/src/gui_dialogs/gui_progress.cpp @@ -8,7 +8,7 @@ #include #include -namespace tachyon +namespace tachyon::dialogs { // --------------------------------------------------------------------------- @@ -80,22 +80,22 @@ namespace tachyon } } - static void TaskBar(GUIApplication& app, ID id, const ProgressTask& task, StyleRef trackStyle, LayoutOverride&& constraints); - static void StepGlyph(GUIApplication& app, ID id, TaskState state); + static void TaskBar(GUIApplication& app, Context& context, ID id, const ProgressTask& task, StyleRef trackStyle, LayoutOverride&& constraints); + static void StepGlyph(GUIApplication& app, Context& context, ID id, TaskState state); - void ProgressBar(GUIApplication& app, ID id, float value, bool failed, StyleRef style, LayoutOverride&& constraints) + void ProgressBar(GUIApplication& app, Context& context, ID id, float value, bool failed, StyleRef style, LayoutOverride&& constraints) { - TaskBar(app, id, ProgressTask{ .value = Clamped01(value), .state = failed ? TaskState::Failed : TaskState::Running }, + TaskBar(app, context, id, ProgressTask{ .value = Clamped01(value), .state = failed ? TaskState::Failed : TaskState::Running }, style, std::move(constraints)); } - static void TaskBar(GUIApplication& app, ID id, const ProgressTask& task, StyleRef trackStyle, LayoutOverride&& constraints) + static void TaskBar(GUIApplication& app, Context& context, ID id, const ProgressTask& task, StyleRef trackStyle, LayoutOverride&& constraints) { - DialogsExtension& d = Dialogs(app); + Context& d = Prepare(app, context); // Under way with no telling how far: the sliding segment. if (task.state == TaskState::Running && task.value < 0.0f) { - IndeterminateProgressBar(app, id, trackStyle, std::move(constraints)); + IndeterminateProgressBar(app, context, id, trackStyle, std::move(constraints)); return; } const ElementRef track = app.RegisterElement(Element{ .id = id, .styleRef = trackStyle, .flags = ElementFlags::NoInput }, @@ -114,9 +114,9 @@ namespace tachyon })); } - void IndeterminateProgressBar(GUIApplication& app, ID id, StyleRef style, LayoutOverride&& constraints) + void IndeterminateProgressBar(GUIApplication& app, Context& context, ID id, StyleRef style, LayoutOverride&& constraints) { - DialogsExtension& d = Dialogs(app); + Context& d = Prepare(app, context); const ElementRef track = app.RegisterElement(Element{ .id = id, .styleRef = style, .flags = ElementFlags::NoInput | ElementFlags::Animated }, std::move(constraints)); @@ -133,9 +133,9 @@ namespace tachyon })); } - void Spinner(GUIApplication& app, ID id, SpinnerSize size, LayoutOverride&& constraints) + void Spinner(GUIApplication& app, Context& context, ID id, SpinnerSize size, LayoutOverride&& constraints) { - DialogsExtension& d = Dialogs(app); + Context& d = Prepare(app, context); const SpinnerMetrics metrics = MetricsOf(size); const int32_t side = app.styleManager.Px(metrics.size); if (!constraints.HasFixedWidth()) @@ -162,9 +162,9 @@ namespace tachyon })); } - void CircularProgress(GUIApplication& app, ID id, float value, StyleRef style, LayoutOverride&& constraints) + void CircularProgress(GUIApplication& app, Context& context, ID id, float value, StyleRef style, LayoutOverride&& constraints) { - DialogsExtension& d = Dialogs(app); + Context& d = Prepare(app, context); const float done = Clamped01(value); const std::string percent = std::to_string(WholePercent(done)); const ElementRef ref = app.RegisterElement(Element{ .id = id, .styleRef = style, .flags = ElementFlags::NoInput }, @@ -185,9 +185,9 @@ namespace tachyon })); } - void Skeleton(GUIApplication& app, ID id, StyleRef style, LayoutOverride&& constraints) + void Skeleton(GUIApplication& app, Context& context, ID id, StyleRef style, LayoutOverride&& constraints) { - DialogsExtension& d = Dialogs(app); + Context& d = Prepare(app, context); const bool shines = !app.IsReducedMotion(); const ElementRef ref = app.RegisterElement(Element{ .id = id, .styleRef = style, .flags = ElementFlags::NoInput | (shines ? ElementFlags::Animated : ElementFlags::None) }, @@ -207,16 +207,16 @@ namespace tachyon })); } - bool BusyButton(GUIApplication& app, ID id, const GUIContent& content, bool busy, std::string_view busyText, + bool BusyButton(GUIApplication& app, Context& context, ID id, const GUIContent& content, bool busy, std::string_view busyText, std::function onClick, StyleRef style, LayoutOverride&& constraints) { - DialogsExtension& d = Dialogs(app); + Context& d = Prepare(app, context); if (!busy) { const bool clicked = app.Button(id, content, std::move(onClick), style, std::move(constraints)); // Its width, kept once it's busy. if (const ElementRef ref = app.elementStorage.FindElementRefByID(id); ref.IsValid()) - VERIFY(app.elementStorage.AddPostLayout(ref, [&app, id](PostLayoutContext& ctx) { Dialogs(app).busyButtonWidths[id] = ctx.ElementRect().w; })); + VERIFY(app.elementStorage.AddPostLayout(ref, [state = &context, id](PostLayoutContext& ctx) { state->busyButtonWidths[id] = ctx.ElementRect().w; })); return clicked; } @@ -244,9 +244,9 @@ namespace tachyon // the pill and popover listing the tasks running in the background. // --------------------------------------------------------------------------- - void TaskProgress(GUIApplication& app, ID id, const ProgressTask& task, LayoutOverride&& constraints) + void TaskProgress(GUIApplication& app, Context& context, ID id, const ProgressTask& task, LayoutOverride&& constraints) { - DialogsExtension& d = Dialogs(app); + Context& d = Prepare(app, context); app.BeginVertical(id, d.styles.taskProgressStyleRef, std::move(constraints)); [[maybe_unused]] const bool pushed = app.idManager.PushParent(id); @@ -282,7 +282,7 @@ namespace tachyon // Done, it's one line: the check, the name and how long it took. if (!done) { - TaskBar(app, app.idManager.AllocateDynamicID("bar"), task, d.styles.progressBarStyleRef, LayoutOverride{}); + TaskBar(app, context, app.idManager.AllocateDynamicID("bar"), task, d.styles.progressBarStyleRef, LayoutOverride{}); if (!task.detail.empty()) app.Text(app.idManager.AllocateDynamicID("detail"), task.detail, failed ? d.styles.taskProgressErrorStyleRef : d.styles.taskProgressDetailStyleRef); @@ -293,12 +293,12 @@ namespace tachyon app.EndVertical(); } - static void StepGlyph(GUIApplication& app, ID id, TaskState state) + static void StepGlyph(GUIApplication& app, Context& context, ID id, TaskState state) { - DialogsExtension& d = Dialogs(app); + Context& d = Prepare(app, context); if (state == TaskState::Running) { - Spinner(app, id, SpinnerSize::Large); + Spinner(app, context, id, SpinnerSize::Large); return; } const StyleRef style = state == TaskState::Done ? d.styles.progressStepDoneStyleRef @@ -311,9 +311,9 @@ namespace tachyon app.RegisterElement(Element{ .id = id, .iconID = icon, .styleRef = style, .flags = ElementFlags::NoInput }, LayoutOverride{}); } - void ProgressSteps(GUIApplication& app, ID id, std::span steps, LayoutOverride&& constraints) + void ProgressSteps(GUIApplication& app, Context& context, ID id, std::span steps, LayoutOverride&& constraints) { - DialogsExtension& d = Dialogs(app); + Context& d = Prepare(app, context); app.BeginVertical(id, d.styles.progressStepsStyleRef, std::move(constraints)); [[maybe_unused]] const bool pushed = app.idManager.PushParent(id); const ID rowsID = steps.empty() ? ID::Invalid() : app.idManager.AllocateRangedID(uint32_t(steps.size()), "steps"); @@ -326,7 +326,7 @@ namespace tachyon // One line: the glyph, the name, and its note or percent at the end. app.BeginHorizontal(app.idManager.AllocateDynamicID("header"), d.styles.progressStepHeaderStyleRef); - StepGlyph(app, app.idManager.AllocateDynamicID("glyph"), step.state); + StepGlyph(app, context, app.idManager.AllocateDynamicID("glyph"), step.state); app.Text(app.idManager.AllocateDynamicID("name"), step.name, step.state == TaskState::Pending ? d.styles.progressStepPendingStyleRef : d.styles.progressStepNameStyleRef); if (step.state == TaskState::Failed && step.note.empty()) @@ -339,7 +339,7 @@ namespace tachyon if (step.state == TaskState::Running) { app.BeginVertical(app.idManager.AllocateDynamicID("body"), d.styles.progressStepBodyStyleRef); - TaskBar(app, app.idManager.AllocateDynamicID("bar"), step, d.styles.progressBarSmallStyleRef, LayoutOverride{}); + TaskBar(app, context, app.idManager.AllocateDynamicID("bar"), step, d.styles.progressBarSmallStyleRef, LayoutOverride{}); if (!step.detail.empty()) app.Text(app.idManager.AllocateDynamicID("detail"), step.detail, d.styles.taskProgressDetailStyleRef); app.EndVertical(); @@ -354,16 +354,16 @@ namespace tachyon app.EndVertical(); } - void StatusProgress(GUIApplication& app, ID id, const ProgressTask& task, LayoutOverride&& constraints) + void StatusProgress(GUIApplication& app, Context& context, ID id, const ProgressTask& task, LayoutOverride&& constraints) { - DialogsExtension& d = Dialogs(app); + Context& d = Prepare(app, context); app.BeginHorizontal(id, d.styles.statusProgressStyleRef, std::move(constraints)); [[maybe_unused]] const bool pushed = app.idManager.PushParent(id); if (task.state == TaskState::Running) - Spinner(app, app.idManager.AllocateDynamicID("spinner"), SpinnerSize::Small); + Spinner(app, context, app.idManager.AllocateDynamicID("spinner"), SpinnerSize::Small); // Short of room, the bar gives way and the name is read in full. app.StatusText(app.idManager.AllocateDynamicID("name"), task.name, app.theme.statusTextStyleRef, LayoutOverride{}.NoShrink()); - TaskBar(app, app.idManager.AllocateDynamicID("bar"), task, d.styles.progressBarSmallStyleRef, + TaskBar(app, context, app.idManager.AllocateDynamicID("bar"), task, d.styles.progressBarSmallStyleRef, LayoutOverride{}.FlexBasis(Pixels{ app.styleManager.Px(120) }).NoGrow().FlexShrink(1).MinWidth(Pixels{ app.styleManager.Px(32) })); if (const std::string state = StateText(task); !state.empty()) app.StatusText(app.idManager.AllocateDynamicID("state"), state, app.theme.statusTextMonoStyleRef); @@ -372,10 +372,10 @@ namespace tachyon app.EndHorizontal(); } - bool BackgroundTasks(GUIApplication& app, ID id, std::span tasks, LayoutOverride&& constraints) + bool BackgroundTasks(GUIApplication& app, Context& context, ID id, std::span tasks, LayoutOverride&& constraints) { - DialogsExtension& d = Dialogs(app); - DialogsExtension::TasksPopover& popover = d.tasksPopovers[id]; + Context& d = Prepare(app, context); + Context::TasksPopover& popover = d.tasksPopovers[id]; if (tasks.empty()) { popover.open = false; @@ -391,12 +391,12 @@ namespace tachyon const std::string label = tasks.size() == 1 ? "1 task" : std::to_string(tasks.size()) + " tasks"; // Its chevron points where the list opens, and back while it's open. app.Button(id, GUIContent{ popover.open ? app.theme.dropdownArrowIcon : app.theme.dropdownArrowUpIcon, label }, - [&app, id] { Dialogs(app).tasksPopovers[id].open = !Dialogs(app).tasksPopovers[id].open; }, d.styles.tasksPillStyleRef, + [state = &context, id] { state->tasksPopovers[id].open = !state->tasksPopovers[id].open; }, d.styles.tasksPillStyleRef, std::move(constraints)); if (!popover.open) return false; // A press anywhere but on it or the pill closes it; the pill toggles it itself. - app.CloseOnPressOutside(popover.windowID, id, [&app, id] { Dialogs(app).tasksPopovers[id].open = false; }); + app.CloseOnPressOutside(popover.windowID, id, [state = &context, id] { state->tasksPopovers[id].open = false; }); // Above the pill, its right edge on the pill's: a status bar is at the bottom. It // takes no focus, so the keyboard stays where it was. @@ -424,7 +424,7 @@ namespace tachyon [[maybe_unused]] const bool inRow = app.idManager.PushParent(rowID); app.BeginVertical(app.idManager.AllocateDynamicID("body"), d.styles.tasksRowBodyStyleRef); app.Text(app.idManager.AllocateDynamicID("name"), task.name, d.styles.taskProgressNameStyleRef); - TaskBar(app, app.idManager.AllocateDynamicID("bar"), task, d.styles.progressBarSmallStyleRef, LayoutOverride{}); + TaskBar(app, context, app.idManager.AllocateDynamicID("bar"), task, d.styles.progressBarSmallStyleRef, LayoutOverride{}); app.EndVertical(); std::string state = StateText(task); if (state.empty()) diff --git a/src/gui_dialogs/gui_progress_types.h b/src/gui_dialogs/gui_progress_types.h index 714013e7..cc54ce17 100644 --- a/src/gui_dialogs/gui_progress_types.h +++ b/src/gui_dialogs/gui_progress_types.h @@ -4,7 +4,7 @@ #include #include -namespace tachyon +namespace tachyon::dialogs { /// @addtogroup app /// @{ diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 735189b6..bab8edf7 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -72,7 +72,6 @@ list(APPEND GUI_CORE_TEST_FILES popup_escape_test.cpp label_group_alignment_test.cpp drag_drop_test.cpp - app_extension_test.cpp file_drop_test.cpp in_app_drag_test.cpp pen_input_test.cpp diff --git a/tests/app_extension_test.cpp b/tests/app_extension_test.cpp deleted file mode 100644 index 86af7635..00000000 --- a/tests/app_extension_test.cpp +++ /dev/null @@ -1,118 +0,0 @@ -// Extensions: state and hooks a library outside GUIApplication keeps per application -// (GUIApplication::Extension), made on first use and run along with the app's frames, -// theme loads and cleanup. - -#include - -#include "headless_gui_app.h" - -#include - -#include -#include - -namespace -{ - using namespace tachyon; - using GUITest::HeadlessGUIApp; - - // What the extensions did, in order, across every app in a test. - std::vector& Calls() - { - static std::vector calls; - return calls; - } - - class Recorder : public AppExtension - { - public: - explicit Recorder(GUIApplication& app) : AppExtension(app) { Calls().push_back("made"); } - ~Recorder() override { Calls().push_back("destroyed"); } - - void OnStylesLoaded() override - { - // Looked up here, as an extension's own styles are. - buttonStyle = app.theme.GetStyle("button"); - Calls().push_back("styles"); - } - void OnPostConstruct(float) override { Calls().push_back("post-construct"); } - void OnEndFrame() override { Calls().push_back("end-frame"); } - void OnCleanup() override { Calls().push_back("cleanup"); } - - StyleRef buttonStyle{}; - int value = 0; - }; - - class Other : public AppExtension - { - public: - explicit Other(GUIApplication& app) : AppExtension(app) {} - }; - - class AppExtensionTest : public ::testing::Test - { - protected: - void SetUp() override { Calls().clear(); } - }; - - TEST_F(AppExtensionTest, OneObjectPerTypeAndApp) - { - HeadlessGUIApp a, b; - ASSERT_TRUE(a.Initialize()); - ASSERT_TRUE(b.Initialize()); - Recorder& first = a.Extension(); - first.value = 7; - EXPECT_EQ(&a.Extension(), &first); - EXPECT_EQ(a.Extension().value, 7); - EXPECT_NE(&b.Extension(), &first); - EXPECT_EQ(b.Extension().value, 0); - EXPECT_NE(static_cast(&a.Extension()), static_cast(&first)); - EXPECT_EQ(&first.app, &a); - } - - TEST_F(AppExtensionTest, MadeOnFirstUseWithTheStylesAlreadyLoaded) - { - HeadlessGUIApp app; - ASSERT_TRUE(app.Initialize()); - EXPECT_TRUE(Calls().empty()); - const Recorder& recorder = app.Extension(); - EXPECT_EQ(Calls(), (std::vector{ "made", "styles" })); - EXPECT_EQ(recorder.buttonStyle, app.theme.GetStyle("button")); - } - - TEST_F(AppExtensionTest, MadeBeforeTheStylesLoadGetsThemWhenTheyDo) - { - HeadlessGUIApp app; - GUIApplication::InitializeOptions options; - options.loadStyles = false; - ASSERT_TRUE(app.Initialize(options)); - app.Extension(); - EXPECT_EQ(Calls(), (std::vector{ "made" })); - ASSERT_TRUE(app.InitializeStyles()); - EXPECT_EQ(Calls(), (std::vector{ "made", "styles" })); - } - - TEST_F(AppExtensionTest, RunsWithEachFrame) - { - HeadlessGUIApp app; - ASSERT_TRUE(app.Initialize()); - app.Extension(); - Calls().clear(); - app.Frame([] {}); - EXPECT_EQ(Calls(), (std::vector{ "post-construct", "end-frame" })); - } - - TEST_F(AppExtensionTest, CleanedUpAndDestroyedWithTheApp) - { - HeadlessGUIApp app; - ASSERT_TRUE(app.Initialize()); - app.Extension(); - Calls().clear(); - app.Cleanup(); - EXPECT_EQ(Calls(), (std::vector{ "cleanup", "destroyed" })); - // Used again after cleanup, it's a new one. - Calls().clear(); - app.Extension(); - EXPECT_EQ(Calls().front(), "made"); - } -} diff --git a/tests/controls_notifications_test.cpp b/tests/controls_notifications_test.cpp index 95035b30..a16d4724 100644 --- a/tests/controls_notifications_test.cpp +++ b/tests/controls_notifications_test.cpp @@ -21,11 +21,12 @@ namespace tachyon { protected: HeadlessGUIApp app; + dialogs::Context dialogContext; const int2 windowSize{ 1200, 800 }; std::function content; // built before the toasts void SetUp() override { ASSERT_TRUE(app.Initialize()); } - void TearDown() override { app.Cleanup(); } + void TearDown() override { dialogs::Cleanup(app, dialogContext); app.Cleanup(); } void Frame() { @@ -33,8 +34,9 @@ namespace tachyon app.BeginRootWindow(windowSize, ElementFlags::None, app.theme.mainWindowStyleRef); if (content) content(); - tachyon::Toasts(app); + tachyon::dialogs::Toasts(app, dialogContext); app.EndRootWindow(); + dialogs::EndGUI(app, dialogContext); }); } // Time passes, a frame at a time. @@ -61,15 +63,15 @@ namespace tachyon std::vector Toasts() { std::vector rects; - for (const ID id : FindAllByStyle(GetDialogStyles(app).toastStyleRef)) + for (const ID id : FindAllByStyle(dialogs::GetStyles(app, dialogContext).toastStyleRef)) rects.push_back(app.GetElementRect(id)); return rects; } bool Shown(std::string_view title) const { return app.FindByText(title) != ID::Invalid(); } - ToastID Show(std::string title, Severity severity = Severity::Info) + dialogs::ToastID Show(std::string title, dialogs::Severity severity = dialogs::Severity::Info) { - return ShowToast(app, ToastDesc{ .severity = severity, .title = std::move(title) }); + return dialogs::ShowToast(app, dialogContext, dialogs::ToastDesc{ .severity = severity, .title = std::move(title) }); } }; @@ -118,10 +120,10 @@ namespace tachyon // Its own icon in place of its severity's; the circle keeps the severity's color. TEST_F(NotificationsTest, AToastCanHaveItsOwnIcon) { - ShowToast(app, ToastDesc{ .severity = Severity::Info, .title = "Uploading build", .icon = app.theme.addIcon }); + dialogs::ShowToast(app, dialogContext, dialogs::ToastDesc{ .severity = dialogs::Severity::Info, .title = "Uploading build", .icon = app.theme.addIcon }); Show("Plain"); Wait(300); - const std::vector circles = FindAllByStyle(GetDialogStyles(app).toastCircleStyleRefs[int(Severity::Info)]); + const std::vector circles = FindAllByStyle(dialogs::GetStyles(app, dialogContext).toastCircleStyleRefs[int(dialogs::Severity::Info)]); ASSERT_EQ(circles.size(), 2u); const auto iconOf = [&](ID id) { return app.elementStorage.GetElementUnsafe(app.elementStorage.FindElementRefByID(id)).iconID; }; EXPECT_EQ(iconOf(circles[0]), app.theme.addIcon); @@ -146,9 +148,9 @@ namespace tachyon // A button filling the window under it: the click goes to the toast. int under = 0; content = [&] { app.Button("Under", [&] { ++under; }, LayoutOverride{}.FlexGrow(1)); }; - Show("On top", Severity::Error); + Show("On top", dialogs::Severity::Error); Wait(300); - const std::vector dismiss = FindAllByStyle(GetDialogStyles(app).toastDismissStyleRef); + const std::vector dismiss = FindAllByStyle(dialogs::GetStyles(app, dialogContext).toastDismissStyleRef); ASSERT_EQ(dismiss.size(), 1u); app.ClickAt(app.CenterOf(dismiss[0])); Wait(300); @@ -156,17 +158,18 @@ namespace tachyon EXPECT_EQ(under, 0); // Built before the window's content, the toasts are still over it. - Show("Before", Severity::Error); + Show("Before", dialogs::Severity::Error); auto frameToastsFirst = [&] { app.Frame([&] { app.BeginRootWindow(windowSize, ElementFlags::None, app.theme.mainWindowStyleRef); - tachyon::Toasts(app); + tachyon::dialogs::Toasts(app, dialogContext); content(); app.EndRootWindow(); + dialogs::EndGUI(app, dialogContext); }); }; for (int i = 0; i < 6; ++i) { app.AdvanceTime(50); frameToastsFirst(); } - const std::vector again = FindAllByStyle(GetDialogStyles(app).toastDismissStyleRef); + const std::vector again = FindAllByStyle(dialogs::GetStyles(app, dialogContext).toastDismissStyleRef); ASSERT_EQ(again.size(), 1u); app.ClickAt(app.CenterOf(again[0])); for (int i = 0; i < 6; ++i) { app.AdvanceTime(50); frameToastsFirst(); } @@ -176,10 +179,10 @@ namespace tachyon TEST_F(NotificationsTest, OnlyErrorsStay) { - Show("Info", Severity::Info); - Show("Done", Severity::Success); - Show("Careful", Severity::Warning); - Show("Failed", Severity::Error); + Show("Info", dialogs::Severity::Info); + Show("Done", dialogs::Severity::Success); + Show("Careful", dialogs::Severity::Warning); + Show("Failed", dialogs::Severity::Error); Wait(5800); EXPECT_TRUE(Shown("Info")) << "still there before 6 s"; Wait(600); @@ -195,8 +198,8 @@ namespace tachyon // A toast about something earlier says when it happened, and still stays its 6 s. TEST_F(NotificationsTest, AnEarlierToastSaysWhenItHappened) { - ShowToast(app, ToastDesc{ .title = "Built", .age = 4.0f * 60.0f + 10.0f }); - ShowToast(app, ToastDesc{ .title = "Old", .age = 2.0f * 3600.0f }); + dialogs::ShowToast(app, dialogContext, dialogs::ToastDesc{ .title = "Built", .age = 4.0f * 60.0f + 10.0f }); + dialogs::ShowToast(app, dialogContext, dialogs::ToastDesc{ .title = "Old", .age = 2.0f * 3600.0f }); Wait(300); EXPECT_TRUE(Shown("4 min")); EXPECT_TRUE(Shown("2 h")); @@ -222,31 +225,31 @@ namespace tachyon TEST_F(NotificationsTest, AProgressBarKeepsItUntilDone) { - const ToastID upload = ShowToast(app, ToastDesc{ .title = "Uploading", .body = "build.zip", .progress = 0.48f }); + const dialogs::ToastID upload = dialogs::ShowToast(app, dialogContext, dialogs::ToastDesc{ .title = "Uploading", .body = "build.zip", .progress = 0.48f }); Wait(7000, 200); ASSERT_TRUE(Shown("Uploading")); - ToastDesc* desc = FindToast(app, upload); + dialogs::ToastDesc* desc = dialogs::FindToast(app, dialogContext, upload); ASSERT_NE(desc, nullptr); - EXPECT_EQ(FindAllByStyle(GetDialogStyles(app).toastProgressStyleRef).size(), 1u); + EXPECT_EQ(FindAllByStyle(dialogs::GetStyles(app, dialogContext).toastProgressStyleRef).size(), 1u); desc->progress = 1.0f; Wait(7000, 200); EXPECT_FALSE(Shown("Uploading")); - EXPECT_EQ(FindToast(app, upload), nullptr) << "gone"; + EXPECT_EQ(dialogs::FindToast(app, dialogContext, upload), nullptr) << "gone"; } TEST_F(NotificationsTest, ItsCloseButtonAndDismissToastTakeItAway) { - Show("Failed", Severity::Error); - const ToastID other = Show("Also failed", Severity::Error); + Show("Failed", dialogs::Severity::Error); + const dialogs::ToastID other = Show("Also failed", dialogs::Severity::Error); Wait(300); - const std::vector dismiss = FindAllByStyle(GetDialogStyles(app).toastDismissStyleRef); + const std::vector dismiss = FindAllByStyle(dialogs::GetStyles(app, dialogContext).toastDismissStyleRef); ASSERT_EQ(dismiss.size(), 2u); app.ClickAt(app.CenterOf(dismiss[0])); Wait(300); EXPECT_FALSE(Shown("Failed")); EXPECT_TRUE(Shown("Also failed")); - DismissToast(app, other); - EXPECT_EQ(FindToast(app, other), nullptr) << "going: no longer to change"; + dialogs::DismissToast(app, dialogContext, other); + EXPECT_EQ(dialogs::FindToast(app, dialogContext, other), nullptr) << "going: no longer to change"; Wait(300); EXPECT_TRUE(Toasts().empty()); } @@ -254,11 +257,11 @@ namespace tachyon TEST_F(NotificationsTest, AnActionRunsAndTheToastGoes) { int opened = 0, ran = 0; - ShowToast(app, ToastDesc{ .severity = Severity::Success, .title = "Build succeeded", .body = "Windows x64", + dialogs::ShowToast(app, dialogContext, dialogs::ToastDesc{ .severity = dialogs::Severity::Success, .title = "Build succeeded", .body = "Windows x64", .actions = { { "Open folder", [&] { ++opened; } }, { "Run", [&] { ++ran; } } } }); Wait(300); - EXPECT_EQ(FindAllByStyle(GetDialogStyles(app).toastActionStyleRef).size(), 1u) << "the first in the link color"; - EXPECT_EQ(FindAllByStyle(GetDialogStyles(app).toastActionSecondaryStyleRef).size(), 1u); + EXPECT_EQ(FindAllByStyle(dialogs::GetStyles(app, dialogContext).toastActionStyleRef).size(), 1u) << "the first in the link color"; + EXPECT_EQ(FindAllByStyle(dialogs::GetStyles(app, dialogContext).toastActionSecondaryStyleRef).size(), 1u); app.ClickAt(app.CenterOf(app.FindByText("Run"))); Wait(300); EXPECT_EQ(ran, 1); @@ -269,7 +272,7 @@ namespace tachyon TEST_F(NotificationsTest, MoreThanFourFoldIntoAPill) { for (int i = 0; i < 6; ++i) - Show("Toast " + std::to_string(i), Severity::Error); + Show("Toast " + std::to_string(i), dialogs::Severity::Error); Wait(300); EXPECT_EQ(Toasts().size(), 4u); EXPECT_FALSE(Shown("Toast 0")); @@ -285,12 +288,12 @@ namespace tachyon EXPECT_EQ(app.FindByText("+2 earlier"), ID::Invalid()); // Down to four, it folds again when more come. - for (const ID id : FindAllByStyle(GetDialogStyles(app).toastDismissStyleRef)) + for (const ID id : FindAllByStyle(dialogs::GetStyles(app, dialogContext).toastDismissStyleRef)) if (id != ID::Invalid()) { app.ClickAt(app.CenterOf(id)); Wait(300); break; } - for (const ID id : FindAllByStyle(GetDialogStyles(app).toastDismissStyleRef)) + for (const ID id : FindAllByStyle(dialogs::GetStyles(app, dialogContext).toastDismissStyleRef)) if (id != ID::Invalid()) { app.ClickAt(app.CenterOf(id)); Wait(300); break; } ASSERT_EQ(Toasts().size(), 4u); - Show("Toast 6", Severity::Error); + Show("Toast 6", dialogs::Severity::Error); Wait(300); EXPECT_EQ(Toasts().size(), 4u); EXPECT_NE(app.FindByText("+1 earlier"), ID::Invalid()); @@ -298,7 +301,7 @@ namespace tachyon TEST_F(NotificationsTest, ItSlidesInFromTheRightAndOut) { - const ToastID toast = Show("Sliding", Severity::Error); + const dialogs::ToastID toast = Show("Sliding", dialogs::Severity::Error); app.AdvanceTime(20); Frame(); const int32_t settledX = windowSize.x - app.styleManager.Px(16) - app.styleManager.Px(380); @@ -307,7 +310,7 @@ namespace tachyon Wait(300); EXPECT_EQ(Toasts().at(0).x, settledX); - DismissToast(app, toast); + dialogs::DismissToast(app, dialogContext, toast); app.AdvanceTime(40); Frame(); ASSERT_EQ(Toasts().size(), 1u) << "going, not gone"; @@ -319,25 +322,25 @@ namespace tachyon TEST_F(NotificationsTest, WithReducedMotionItDoesntSlide) { app.SetReducedMotion(true); - const ToastID toast = Show("Still", Severity::Error); + const dialogs::ToastID toast = Show("Still", dialogs::Severity::Error); app.AdvanceTime(20); Frame(); EXPECT_EQ(Toasts().at(0).x, windowSize.x - app.styleManager.Px(16) - app.styleManager.Px(380)); - DismissToast(app, toast); + dialogs::DismissToast(app, dialogContext, toast); Frame(); EXPECT_TRUE(Toasts().empty()); } TEST_F(NotificationsTest, AMonospaceBodyForCode) { - ShowToast(app, ToastDesc{ .severity = Severity::Error, .title = "Shader compile failed", + dialogs::ShowToast(app, dialogContext, dialogs::ToastDesc{ .severity = dialogs::Severity::Error, .title = "Shader compile failed", .body = "Terrain.shader:118", .monospaceBody = true }); - ShowToast(app, ToastDesc{ .severity = Severity::Warning, .title = "3 textures exceed 4K", .body = "Downscaled on import." }); + dialogs::ShowToast(app, dialogContext, dialogs::ToastDesc{ .severity = dialogs::Severity::Warning, .title = "3 textures exceed 4K", .body = "Downscaled on import." }); Wait(300); - EXPECT_EQ(FindAllByStyle(GetDialogStyles(app).toastBodyMonoStyleRef).size(), 1u); - EXPECT_EQ(FindAllByStyle(GetDialogStyles(app).toastBodyStyleRef).size(), 1u); - EXPECT_EQ(FindAllByStyle(GetDialogStyles(app).toastCircleStyleRefs[int(Severity::Error)]).size(), 1u); - EXPECT_EQ(FindAllByStyle(GetDialogStyles(app).toastCircleStyleRefs[int(Severity::Warning)]).size(), 1u); + EXPECT_EQ(FindAllByStyle(dialogs::GetStyles(app, dialogContext).toastBodyMonoStyleRef).size(), 1u); + EXPECT_EQ(FindAllByStyle(dialogs::GetStyles(app, dialogContext).toastBodyStyleRef).size(), 1u); + EXPECT_EQ(FindAllByStyle(dialogs::GetStyles(app, dialogContext).toastCircleStyleRefs[int(dialogs::Severity::Error)]).size(), 1u); + EXPECT_EQ(FindAllByStyle(dialogs::GetStyles(app, dialogContext).toastCircleStyleRefs[int(dialogs::Severity::Warning)]).size(), 1u); } // A long body wraps onto as many lines as it takes, inside the toast; a long title @@ -346,13 +349,13 @@ namespace tachyon { const std::string longBody = "Terrain.shader:118 - undeclared identifier uv2 in the vertex stage of the terrain pass"; const std::string longTitle = "Shader compile failed in every one of the twelve terrain material variants"; - ShowToast(app, ToastDesc{ .severity = Severity::Error, .title = longTitle, .body = longBody, .monospaceBody = true }); - ShowToast(app, ToastDesc{ .severity = Severity::Error, .title = "Short", .body = "One line." }); + dialogs::ShowToast(app, dialogContext, dialogs::ToastDesc{ .severity = dialogs::Severity::Error, .title = longTitle, .body = longBody, .monospaceBody = true }); + dialogs::ShowToast(app, dialogContext, dialogs::ToastDesc{ .severity = dialogs::Severity::Error, .title = "Short", .body = "One line." }); Wait(300); const std::vector toasts = Toasts(); ASSERT_EQ(toasts.size(), 2u); - const IntRect body = app.GetElementRect(FindAllByStyle(GetDialogStyles(app).toastBodyMonoStyleRef).at(0)); - const IntRect shortBody = app.GetElementRect(FindAllByStyle(GetDialogStyles(app).toastBodyStyleRef).at(0)); + const IntRect body = app.GetElementRect(FindAllByStyle(dialogs::GetStyles(app, dialogContext).toastBodyMonoStyleRef).at(0)); + const IntRect shortBody = app.GetElementRect(FindAllByStyle(dialogs::GetStyles(app, dialogContext).toastBodyStyleRef).at(0)); EXPECT_LE(body.x + body.w, toasts[0].x + toasts[0].w - app.styleManager.Px(12)) << "inside the toast"; EXPECT_GE(body.h, 2 * shortBody.h) << "on more than one line"; EXPECT_GT(toasts[0].h, toasts[1].h) << "the toast grows with it"; @@ -372,15 +375,15 @@ namespace tachyon int saved = 0, discarded = 0, editable = 0; const ID warning = app.idManager.CreateStaticID(); const ID info = app.idManager.CreateStaticID(); - const BannerAction actions[] = { + const dialogs::BannerAction actions[] = { { "Discard", [&] { ++discarded; } }, - { "Save", [&] { ++saved; }, BannerActionKind::Primary }, + { "Save", [&] { ++saved; }, dialogs::BannerActionKind::Primary }, }; - const BannerAction link[] = { { "Make editable", [&] { ++editable; }, BannerActionKind::Link } }; + const dialogs::BannerAction link[] = { { "Make editable", [&] { ++editable; }, dialogs::BannerActionKind::Link } }; content = [&] { app.BeginVertical(LayoutOverride{}.Width(480)); - Banner(app, warning, Severity::Warning, "Scene has unsaved changes", actions); - Banner(app, info, Severity::Info, "Read-only", link); + dialogs::Banner(app, dialogContext, warning, dialogs::Severity::Warning, "Scene has unsaved changes", actions); + dialogs::Banner(app, dialogContext, info, dialogs::Severity::Info, "Read-only", link); app.EndVertical(); }; Frame(); @@ -391,11 +394,11 @@ namespace tachyon const IntRect save = app.GetElementRect(app.FindByText("Save")); EXPECT_EQ(save.x + save.w, banner.x + banner.w - app.styleManager.Px(12)) << "right-aligned, inside the padding"; EXPECT_LT(app.GetElementRect(app.FindByText("Discard")).x, save.x); - EXPECT_EQ(FindAllByStyle(GetDialogStyles(app).bannerStyleRefs[int(Severity::Warning)]).size(), 1u); - EXPECT_EQ(FindAllByStyle(GetDialogStyles(app).bannerMessageStyleRefs[int(Severity::Info)]).size(), 1u); - EXPECT_EQ(FindAllByStyle(GetDialogStyles(app).bannerPrimaryStyleRef).size(), 1u); - EXPECT_EQ(FindAllByStyle(GetDialogStyles(app).bannerSecondaryStyleRef).size(), 1u); - EXPECT_EQ(FindAllByStyle(GetDialogStyles(app).bannerLinkStyleRef).size(), 1u); + EXPECT_EQ(FindAllByStyle(dialogs::GetStyles(app, dialogContext).bannerStyleRefs[int(dialogs::Severity::Warning)]).size(), 1u); + EXPECT_EQ(FindAllByStyle(dialogs::GetStyles(app, dialogContext).bannerMessageStyleRefs[int(dialogs::Severity::Info)]).size(), 1u); + EXPECT_EQ(FindAllByStyle(dialogs::GetStyles(app, dialogContext).bannerPrimaryStyleRef).size(), 1u); + EXPECT_EQ(FindAllByStyle(dialogs::GetStyles(app, dialogContext).bannerSecondaryStyleRef).size(), 1u); + EXPECT_EQ(FindAllByStyle(dialogs::GetStyles(app, dialogContext).bannerLinkStyleRef).size(), 1u); app.ClickAt(app.CenterOf(app.FindByText("Save"))); Frame(); diff --git a/tests/gpu/gpu_message_dialog_test.cpp b/tests/gpu/gpu_message_dialog_test.cpp index 10f3eb2b..241c81b3 100644 --- a/tests/gpu/gpu_message_dialog_test.cpp +++ b/tests/gpu/gpu_message_dialog_test.cpp @@ -24,23 +24,25 @@ namespace struct Laid { std::string text; IntRect rect; }; std::vector texts; // each text in the dialog, where it was laid out int frame = 0; + dialogs::Context dialogContext; void OnGUI() override { - static constexpr MessageButton kButtons[] = { - { .label = "Discard", .kind = MessageButtonKind::Danger, .alignLeft = true }, + static constexpr dialogs::MessageButton kButtons[] = { + { .label = "Discard", .kind = dialogs::MessageButtonKind::Danger, .alignLeft = true }, { .label = "Cancel" }, - { .label = "Save All", .kind = MessageButtonKind::Primary }, + { .label = "Save All", .kind = dialogs::MessageButtonKind::Primary }, }; const std::string names[] = { "Desert.level", "Forest.level" }; - const MessageDialogItem items[] = { { .name = names[0] }, { .name = names[1] } }; + const dialogs::MessageDialogItem items[] = { { .name = names[0] }, { .name = names[1] } }; if (BeginWindow(windowID, "Owner", theme.windowStyleRef, LayoutOverride{}.Size(900, 600))) { - (void)MessageDialog(*this, dialogID, MessageDialogDesc{ - .icon = MessageIcon::Quit, .title = "Quit Test?", .message = kMessage, + (void)dialogs::MessageDialog(*this, dialogContext, dialogID, dialogs::MessageDialogDesc{ + .icon = dialogs::MessageIcon::Quit, .title = "Quit Test?", .message = kMessage, .buttons = kButtons, .defaultButton = 2, .cancelButton = 1, .items = items }); } EndWindow(); + dialogs::EndGUI(*this, dialogContext); if (++frame >= 12) { dialogOS = windowManager->GetWindowRect(dialogID); @@ -85,6 +87,7 @@ namespace DialogApp app; if (!app.Start()) { + dialogs::Cleanup(app, app.dialogContext); app.Cleanup(); GTEST_SKIP() << "no GPU device available"; } @@ -107,6 +110,7 @@ namespace EXPECT_LE(message->rect.x + message->rect.w, app.dialogLaid.x + app.dialogLaid.w) << "and stays inside the dialog"; const auto item = std::find_if(app.texts.begin(), app.texts.end(), [](const auto& t) { return t.text == "Desert.level"; }); EXPECT_GE(item->rect.h, title->rect.h * 3 / 4) << "an item's name as tall as text"; + dialogs::Cleanup(app, app.dialogContext); app.Cleanup(); } } diff --git a/tests/gpu/gpu_theme_crossfade_test.cpp b/tests/gpu/gpu_theme_crossfade_test.cpp index 8fa955d3..4c55a9ef 100644 --- a/tests/gpu/gpu_theme_crossfade_test.cpp +++ b/tests/gpu/gpu_theme_crossfade_test.cpp @@ -28,6 +28,7 @@ namespace std::optional accentTo; // set: switch only the accent ID barID = ID::Invalid(); // valid: a full ProgressBar in the window uint32_t barColor = 0; // its middle at the end, 0x00RRGGBB + dialogs::Context dialogContext; IntRect barRect {}; // where the last layout put it uint32_t before = 0, justAfter = 0, settled = 0; // window background, 0x00RRGGBB bool crossfadingJustAfter = false, crossfadingAtEnd = true; @@ -80,7 +81,7 @@ namespace { if (barID != ID::Invalid()) { - ProgressBar(*this, barID, 1.0f, false, GetDialogStyles(*this).progressBarStyleRef, LayoutOverride{}.Width(Pixels{ 160 })); + dialogs::ProgressBar(*this, dialogContext, barID, 1.0f, false, dialogs::GetStyles(*this, dialogContext).progressBarStyleRef, LayoutOverride{}.Width(Pixels{ 160 })); // Laid out once the frame is built; noted then. VERIFY(elementStorage.AddPostLayout(elementStorage.FindElementRefByID(barID), [this](PostLayoutContext& ctx) { barRect = ctx.ElementRect(); })); diff --git a/tests/message_dialog_test.cpp b/tests/message_dialog_test.cpp index 0fb27de4..c4547429 100644 --- a/tests/message_dialog_test.cpp +++ b/tests/message_dialog_test.cpp @@ -26,20 +26,21 @@ namespace // One frame asking (or not); returns what MessageDialog returned. int Emit(bool asking = true) { - static constexpr MessageButton kButtons[] = { + static constexpr dialogs::MessageButton kButtons[] = { { .label = "Cancel" }, - { .label = "Quit", .kind = MessageButtonKind::Danger }, + { .label = "Quit", .kind = dialogs::MessageButtonKind::Danger }, }; int choice = -1; app.Frame([&] { app.BeginRootWindow({ 1200, 800 }); app.Button(aboveID, "Above", [] {}); if (asking) - choice = MessageDialog(app, dialogID, MessageDialogDesc{ - .icon = MessageIcon::Quit, .title = "Quit Test?", .message = "Running tasks will be stopped.", + choice = dialogs::MessageDialog(app, dialogContext, dialogID, dialogs::MessageDialogDesc{ + .icon = dialogs::MessageIcon::Quit, .title = "Quit Test?", .message = "Running tasks will be stopped.", .buttons = kButtons, .defaultButton = 0, .cancelButton = 0 }); app.Button(belowID, "Below", [] {}); app.EndRootWindow(); + dialogs::EndGUI(app, dialogContext); }); return choice; } @@ -56,6 +57,7 @@ namespace } HeadlessGUIApp app; + dialogs::Context dialogContext; ID dialogID = ID::Invalid(); ID aboveID = ID::Invalid(); ID belowID = ID::Invalid(); @@ -88,7 +90,7 @@ namespace { Emit(); Emit(); - const ID close = FindByStyle(GetDialogStyles(app).messageBoxCloseStyleRef); + const ID close = FindByStyle(dialogs::GetStyles(app, dialogContext).messageBoxCloseStyleRef); ASSERT_NE(close, ID::Invalid()); app.mouseWindow = dialogID; // the dialog is a window of its own app.InjectMouseMove(app.CenterOf(close)); @@ -125,16 +127,17 @@ namespace // Esc cancels wherever the focus is in the dialog. TEST_F(MessageDialogTest, TabReachesTheDialogsOtherControls) { - static constexpr MessageButton kButtons[] = { { .label = "Cancel" }, { .label = "Quit" } }; + static constexpr dialogs::MessageButton kButtons[] = { { .label = "Cancel" }, { .label = "Quit" } }; bool dontAsk = false; int choice = -1; auto emit = [&] { app.Frame([&] { app.BeginRootWindow({ 1200, 800 }); - choice = MessageDialog(app, dialogID, MessageDialogDesc{ + choice = dialogs::MessageDialog(app, dialogContext, dialogID, dialogs::MessageDialogDesc{ .title = "Quit Test?", .message = "Running tasks will be stopped.", .buttons = kButtons, .defaultButton = 0, .cancelButton = 0, .dontAskAgain = &dontAsk, .details = "Task 3 of 5" }); app.EndRootWindow(); + dialogs::EndGUI(app, dialogContext); }); }; app.activeWindow = dialogID; // the modal dialog has the keyboard @@ -176,16 +179,17 @@ namespace // Enter chooses the default button. TEST_F(MessageDialogTest, ItsTextFieldTakesTypingAndEnterChooses) { - static constexpr MessageButton kButtons[] = { { .label = "Cancel" }, { .label = "Save", .kind = MessageButtonKind::Primary } }; + static constexpr dialogs::MessageButton kButtons[] = { { .label = "Cancel" }, { .label = "Save", .kind = dialogs::MessageButtonKind::Primary } }; std::string name = "My"; int choice = -1; auto emit = [&] { app.Frame([&] { app.BeginRootWindow({ 1200, 800 }); - choice = MessageDialog(app, dialogID, MessageDialogDesc{ + choice = dialogs::MessageDialog(app, dialogContext, dialogID, dialogs::MessageDialogDesc{ .title = "Save this layout as?", .message = "Saved layouts can be picked for any document.", .buttons = kButtons, .defaultButton = 1, .cancelButton = 0, .input = &name }); app.EndRootWindow(); + dialogs::EndGUI(app, dialogContext); }); }; app.activeWindow = dialogID; @@ -231,17 +235,18 @@ namespace // hold them. TEST_F(MessageDialogTest, ItsMessageAndItemsFitInIt) { - static constexpr MessageButton kButtons[] = { { .label = "Discard", .alignLeft = true }, { .label = "Cancel" }, { .label = "Save All" } }; + static constexpr dialogs::MessageButton kButtons[] = { { .label = "Discard", .alignLeft = true }, { .label = "Cancel" }, { .label = "Save All" } }; const std::string names[] = { "Desert.level", "Forest.level" }; - const MessageDialogItem items[] = { { .name = names[0] }, { .name = names[1] } }; + const dialogs::MessageDialogItem items[] = { { .name = names[0] }, { .name = names[1] } }; auto emit = [&] { app.Frame([&] { app.BeginRootWindow({ 1200, 800 }); - (void)MessageDialog(app, dialogID, MessageDialogDesc{ - .icon = MessageIcon::Quit, .title = "Quit Test?", + (void)dialogs::MessageDialog(app, dialogContext, dialogID, dialogs::MessageDialogDesc{ + .icon = dialogs::MessageIcon::Quit, .title = "Quit Test?", .message = "These documents have unsaved changes. Quitting without saving discards them.", .buttons = kButtons, .defaultButton = 2, .cancelButton = 1, .items = items }); app.EndRootWindow(); + dialogs::EndGUI(app, dialogContext); }); }; for (int i = 0; i < 4; ++i) emit(); diff --git a/tests/progress_composites_test.cpp b/tests/progress_composites_test.cpp index db34a1a5..cd42e2ab 100644 --- a/tests/progress_composites_test.cpp +++ b/tests/progress_composites_test.cpp @@ -27,9 +27,10 @@ namespace tachyon { protected: HeadlessGUIApp app; + dialogs::Context dialogContext; void SetUp() override { ASSERT_TRUE(app.Initialize()); } - void TearDown() override { app.Cleanup(); } + void TearDown() override { dialogs::Cleanup(app, dialogContext); app.Cleanup(); } void Frame(const std::function& build) { @@ -37,6 +38,7 @@ namespace tachyon app.BeginRootWindow(); build(); app.EndRootWindow(); + dialogs::EndGUI(app, dialogContext); }); } @@ -93,7 +95,7 @@ namespace tachyon int cancels = 0; auto frame = [&] { Frame([&] { - TaskProgress(app, task, ProgressTask{ .name = "Importing character.fbx", .value = 0.648f, + dialogs::TaskProgress(app, dialogContext, task, dialogs::ProgressTask{ .name = "Importing character.fbx", .value = 0.648f, .detail = "12.4 MB of 19.3 MB", .onCancel = [&] { ++cancels; } }, LayoutOverride{}.Width(Pixels{ 300 })); }); @@ -104,12 +106,12 @@ namespace tachyon ASSERT_TRUE(name != ID::Invalid()); ASSERT_TRUE(percent != ID::Invalid()) << "rounded down"; ASSERT_TRUE(detail != ID::Invalid()); - EXPECT_EQ(ElementOf(name).styleRef, GetDialogStyles(app).taskProgressNameStyleRef); - EXPECT_EQ(ElementOf(percent).styleRef, GetDialogStyles(app).taskProgressPercentStyleRef); - EXPECT_EQ(ElementOf(detail).styleRef, GetDialogStyles(app).taskProgressDetailStyleRef); - const std::vector cancel = WithStyle(GetDialogStyles(app).taskProgressCancelStyleRef); + EXPECT_EQ(ElementOf(name).styleRef, dialogs::GetStyles(app, dialogContext).taskProgressNameStyleRef); + EXPECT_EQ(ElementOf(percent).styleRef, dialogs::GetStyles(app, dialogContext).taskProgressPercentStyleRef); + EXPECT_EQ(ElementOf(detail).styleRef, dialogs::GetStyles(app, dialogContext).taskProgressDetailStyleRef); + const std::vector cancel = WithStyle(dialogs::GetStyles(app, dialogContext).taskProgressCancelStyleRef); ASSERT_EQ(cancel.size(), 1u); - const std::vector bars = WithStyle(GetDialogStyles(app).progressBarStyleRef); + const std::vector bars = WithStyle(dialogs::GetStyles(app, dialogContext).progressBarStyleRef); ASSERT_EQ(bars.size(), 1u); // One row over the bar, the detail under it. @@ -123,7 +125,7 @@ namespace tachyon EXPECT_EQ(b.w, 300); const Fill fill = FillOf(bars[0]); EXPECT_EQ(fill.w, 194); - EXPECT_EQ(fill.style, SlotOf(GetDialogStyles(app).progressFillStyleRef)); + EXPECT_EQ(fill.style, SlotOf(dialogs::GetStyles(app, dialogContext).progressFillStyleRef)); Click(cancel[0]); frame(); @@ -135,31 +137,31 @@ namespace tachyon // nothing known the bar slides and there's no percent. TEST_F(ProgressCompositesTest, ATaskShowsANoteOrPausedOrSlides) { - ProgressTask task{ .name = "Export", .value = 0.5f, .note = "about 3 s left" }; - Frame([&] { TaskProgress(app, task); }); + dialogs::ProgressTask task{ .name = "Export", .value = 0.5f, .note = "about 3 s left" }; + Frame([&] { dialogs::TaskProgress(app, dialogContext, task); }); ASSERT_TRUE(app.FindByText("about 3 s left") != ID::Invalid()); - EXPECT_EQ(ElementOf(app.FindByText("about 3 s left")).styleRef, GetDialogStyles(app).taskProgressNoteStyleRef); + EXPECT_EQ(ElementOf(app.FindByText("about 3 s left")).styleRef, dialogs::GetStyles(app, dialogContext).taskProgressNoteStyleRef); EXPECT_FALSE(app.FindByText("50%") != ID::Invalid()); - EXPECT_TRUE(WithStyle(GetDialogStyles(app).taskProgressCancelStyleRef).empty()) << "no cancel without onCancel"; + EXPECT_TRUE(WithStyle(dialogs::GetStyles(app, dialogContext).taskProgressCancelStyleRef).empty()) << "no cancel without onCancel"; task.note = {}; - task.state = TaskState::Paused; - Frame([&] { TaskProgress(app, task); }); + task.state = dialogs::TaskState::Paused; + Frame([&] { dialogs::TaskProgress(app, dialogContext, task); }); EXPECT_TRUE(app.FindByText("paused") != ID::Invalid()); - EXPECT_EQ(FillOf(WithStyle(GetDialogStyles(app).progressBarStyleRef).at(0)).style, SlotOf(GetDialogStyles(app).progressFillPausedStyleRef)); + EXPECT_EQ(FillOf(WithStyle(dialogs::GetStyles(app, dialogContext).progressBarStyleRef).at(0)).style, SlotOf(dialogs::GetStyles(app, dialogContext).progressFillPausedStyleRef)); - task.state = TaskState::Running; + task.state = dialogs::TaskState::Running; task.value = -1.0f; - Frame([&] { TaskProgress(app, task); }); - const std::vector bars = WithStyle(GetDialogStyles(app).progressBarStyleRef); + Frame([&] { dialogs::TaskProgress(app, dialogContext, task); }); + const std::vector bars = WithStyle(dialogs::GetStyles(app, dialogContext).progressBarStyleRef); ASSERT_EQ(bars.size(), 1u); EXPECT_TRUE(Animated(bars[0])) << "sliding"; EXPECT_FALSE(app.FindByText("0%") != ID::Invalid()); // Only running work slides: paused with nothing known, it's an empty bar. - task.state = TaskState::Paused; - Frame([&] { TaskProgress(app, task); }); - const ID paused = WithStyle(GetDialogStyles(app).progressBarStyleRef).at(0); + task.state = dialogs::TaskState::Paused; + Frame([&] { dialogs::TaskProgress(app, dialogContext, task); }); + const ID paused = WithStyle(dialogs::GetStyles(app, dialogContext).progressBarStyleRef).at(0); EXPECT_FALSE(Animated(paused)); EXPECT_EQ(FillOf(paused).w, 0); } @@ -171,8 +173,8 @@ namespace tachyon int retries = 0, cancels = 0; auto frame = [&] { Frame([&] { - TaskProgress(app, app.idManager.AllocateDynamicID("bake"), - ProgressTask{ .name = "Bake failed at 73%", .value = 0.73f, .state = TaskState::Failed, + dialogs::TaskProgress(app, dialogContext, app.idManager.AllocateDynamicID("bake"), + dialogs::ProgressTask{ .name = "Bake failed at 73%", .value = 0.73f, .state = dialogs::TaskState::Failed, .note = "1:02", .detail = "Out of GPU memory", .onCancel = [&] { ++cancels; }, .onRetry = [&] { ++retries; } }, LayoutOverride{}.Width(Pixels{ 200 })); @@ -181,19 +183,19 @@ namespace tachyon frame(); const ID name = app.FindByText("Bake failed at 73%"); ASSERT_TRUE(name != ID::Invalid()); - EXPECT_EQ(ElementOf(name).styleRef, GetDialogStyles(app).taskProgressFailedStyleRef); + EXPECT_EQ(ElementOf(name).styleRef, dialogs::GetStyles(app, dialogContext).taskProgressFailedStyleRef); EXPECT_EQ(IconOf(name), app.theme.invalidIcon); - EXPECT_EQ(ElementOf(app.FindByText("Out of GPU memory")).styleRef, GetDialogStyles(app).taskProgressErrorStyleRef); + EXPECT_EQ(ElementOf(app.FindByText("Out of GPU memory")).styleRef, dialogs::GetStyles(app, dialogContext).taskProgressErrorStyleRef); EXPECT_FALSE(app.FindByText("73%") != ID::Invalid()); EXPECT_FALSE(app.FindByText("1:02") != ID::Invalid()) << "Retry in place of the note"; - EXPECT_TRUE(WithStyle(GetDialogStyles(app).taskProgressCancelStyleRef).empty()); - const Fill fill = FillOf(WithStyle(GetDialogStyles(app).progressBarStyleRef).at(0)); + EXPECT_TRUE(WithStyle(dialogs::GetStyles(app, dialogContext).taskProgressCancelStyleRef).empty()); + const Fill fill = FillOf(WithStyle(dialogs::GetStyles(app, dialogContext).progressBarStyleRef).at(0)); EXPECT_EQ(fill.w, 146); - EXPECT_EQ(fill.style, SlotOf(GetDialogStyles(app).progressFillFailedStyleRef)); + EXPECT_EQ(fill.style, SlotOf(dialogs::GetStyles(app, dialogContext).progressFillFailedStyleRef)); const ID retry = app.FindByText("Retry"); ASSERT_TRUE(retry != ID::Invalid()); - EXPECT_EQ(ElementOf(retry).styleRef, GetDialogStyles(app).taskProgressRetryStyleRef); + EXPECT_EQ(ElementOf(retry).styleRef, dialogs::GetStyles(app, dialogContext).taskProgressRetryStyleRef); EXPECT_EQ(IconOf(retry), app.theme.retryIcon) << "the refresh arrow before Retry"; Click(retry); frame(); @@ -206,17 +208,17 @@ namespace tachyon TEST_F(ProgressCompositesTest, ADoneTaskIsOneLineWithACheck) { Frame([&] { - TaskProgress(app, ProgressTask{ .name = "Import complete", .value = 1.0f, .state = TaskState::Done, + dialogs::TaskProgress(app, dialogContext, dialogs::ProgressTask{ .name = "Import complete", .value = 1.0f, .state = dialogs::TaskState::Done, .note = "2.1 s", .detail = "not shown", .onCancel = [] {} }); }); const ID name = app.FindByText("Import complete"); ASSERT_TRUE(name != ID::Invalid()); - EXPECT_EQ(ElementOf(name).styleRef, GetDialogStyles(app).taskProgressDoneStyleRef); + EXPECT_EQ(ElementOf(name).styleRef, dialogs::GetStyles(app, dialogContext).taskProgressDoneStyleRef); EXPECT_EQ(IconOf(name), app.theme.menuCheckIcon); - EXPECT_EQ(ElementOf(app.FindByText("2.1 s")).styleRef, GetDialogStyles(app).taskProgressNoteStyleRef); - EXPECT_TRUE(WithStyle(GetDialogStyles(app).progressBarStyleRef).empty()); + EXPECT_EQ(ElementOf(app.FindByText("2.1 s")).styleRef, dialogs::GetStyles(app, dialogContext).taskProgressNoteStyleRef); + EXPECT_TRUE(WithStyle(dialogs::GetStyles(app, dialogContext).progressBarStyleRef).empty()); EXPECT_FALSE(app.FindByText("not shown") != ID::Invalid()); - EXPECT_TRUE(WithStyle(GetDialogStyles(app).taskProgressCancelStyleRef).empty()); + EXPECT_TRUE(WithStyle(dialogs::GetStyles(app, dialogContext).taskProgressCancelStyleRef).empty()); } // --------------------------------------------------------------------- @@ -226,38 +228,38 @@ namespace tachyon // A glyph a step, a small bar under the running one only, and each note or percent. TEST_F(ProgressCompositesTest, StepsShowWhereEachIs) { - const ProgressTask steps[] = { - { .name = "Compile scripts", .state = TaskState::Done, .note = "4.2 s" }, - { .name = "Bake lighting", .value = 0.42f, .state = TaskState::Running }, - { .name = "Package assets", .value = 0.5f, .state = TaskState::Pending }, - { .name = "Upload", .state = TaskState::Paused }, - { .name = "Notify", .state = TaskState::Failed }, + const dialogs::ProgressTask steps[] = { + { .name = "Compile scripts", .state = dialogs::TaskState::Done, .note = "4.2 s" }, + { .name = "Bake lighting", .value = 0.42f, .state = dialogs::TaskState::Running }, + { .name = "Package assets", .value = 0.5f, .state = dialogs::TaskState::Pending }, + { .name = "Upload", .state = dialogs::TaskState::Paused }, + { .name = "Notify", .state = dialogs::TaskState::Failed }, }; - Frame([&] { ProgressSteps(app, steps, LayoutOverride{}.Width(Pixels{ 300 })); }); + Frame([&] { dialogs::ProgressSteps(app, dialogContext, steps, LayoutOverride{}.Width(Pixels{ 300 })); }); - const std::vector done = WithStyle(GetDialogStyles(app).progressStepDoneStyleRef); + const std::vector done = WithStyle(dialogs::GetStyles(app, dialogContext).progressStepDoneStyleRef); ASSERT_EQ(done.size(), 1u); EXPECT_EQ(ElementOf(done[0]).iconID, app.theme.boldCheckIcon); - const std::vector failed = WithStyle(GetDialogStyles(app).progressStepFailedStyleRef); + const std::vector failed = WithStyle(dialogs::GetStyles(app, dialogContext).progressStepFailedStyleRef); ASSERT_EQ(failed.size(), 1u); EXPECT_EQ(ElementOf(failed[0]).iconID, app.theme.boldCrossIcon); - EXPECT_EQ(WithStyle(GetDialogStyles(app).progressStepWaitingStyleRef).size(), 1u); - EXPECT_EQ(WithStyle(GetDialogStyles(app).progressStepPausedStyleRef).size(), 1u); + EXPECT_EQ(WithStyle(dialogs::GetStyles(app, dialogContext).progressStepWaitingStyleRef).size(), 1u); + EXPECT_EQ(WithStyle(dialogs::GetStyles(app, dialogContext).progressStepPausedStyleRef).size(), 1u); - EXPECT_EQ(ElementOf(app.FindByText("Package assets")).styleRef, GetDialogStyles(app).progressStepPendingStyleRef); - EXPECT_EQ(ElementOf(app.FindByText("Bake lighting")).styleRef, GetDialogStyles(app).progressStepNameStyleRef); - EXPECT_EQ(ElementOf(app.FindByText("Upload")).styleRef, GetDialogStyles(app).progressStepNameStyleRef); + EXPECT_EQ(ElementOf(app.FindByText("Package assets")).styleRef, dialogs::GetStyles(app, dialogContext).progressStepPendingStyleRef); + EXPECT_EQ(ElementOf(app.FindByText("Bake lighting")).styleRef, dialogs::GetStyles(app, dialogContext).progressStepNameStyleRef); + EXPECT_EQ(ElementOf(app.FindByText("Upload")).styleRef, dialogs::GetStyles(app, dialogContext).progressStepNameStyleRef); EXPECT_TRUE(app.FindByText("4.2 s") != ID::Invalid()); EXPECT_TRUE(app.FindByText("42%") != ID::Invalid()); EXPECT_TRUE(app.FindByText("paused") != ID::Invalid()); EXPECT_FALSE(app.FindByText("50%") != ID::Invalid()) << "a percent only while running"; const ID failedText = app.FindByText("failed"); ASSERT_TRUE(failedText != ID::Invalid()) << "a failed step says so"; - EXPECT_EQ(ElementOf(failedText).styleRef, GetDialogStyles(app).progressStepErrorStyleRef); + EXPECT_EQ(ElementOf(failedText).styleRef, dialogs::GetStyles(app, dialogContext).progressStepErrorStyleRef); // The running step's spinner, left of its name, and its bar under the name. const ID name = app.FindByText("Bake lighting"); - const std::vector bars = WithStyle(GetDialogStyles(app).progressBarSmallStyleRef); + const std::vector bars = WithStyle(dialogs::GetStyles(app, dialogContext).progressBarSmallStyleRef); ASSERT_EQ(bars.size(), 1u); EXPECT_GE(app.GetElementRect(bars[0]).y, app.GetElementRect(name).y + app.GetElementRect(name).h); EXPECT_EQ(app.GetElementRect(bars[0]).x, app.GetElementRect(name).x); @@ -281,18 +283,18 @@ namespace tachyon // detail under that. TEST_F(ProgressCompositesTest, StepsLineUpInColumns) { - const ProgressTask steps[] = { - { .name = "Compile scripts", .state = TaskState::Done, .note = "4.2 s" }, - { .name = "Bake lighting", .value = 0.42f, .state = TaskState::Running, .detail = "Lightmap atlas, about 1 min left" }, - { .name = "Package", .state = TaskState::Pending }, + const dialogs::ProgressTask steps[] = { + { .name = "Compile scripts", .state = dialogs::TaskState::Done, .note = "4.2 s" }, + { .name = "Bake lighting", .value = 0.42f, .state = dialogs::TaskState::Running, .detail = "Lightmap atlas, about 1 min left" }, + { .name = "Package", .state = dialogs::TaskState::Pending }, }; const ID list = app.idManager.CreateStaticID(); - Frame([&] { ProgressSteps(app, list, steps, LayoutOverride{}.Width(Pixels{ 300 })); }); - Frame([&] { ProgressSteps(app, list, steps, LayoutOverride{}.Width(Pixels{ 300 })); }); + Frame([&] { dialogs::ProgressSteps(app, dialogContext, list, steps, LayoutOverride{}.Width(Pixels{ 300 })); }); + Frame([&] { dialogs::ProgressSteps(app, dialogContext, list, steps, LayoutOverride{}.Width(Pixels{ 300 })); }); const IntRect all = app.GetElementRect(list); auto middle = [](IntRect r) { return r.y * 2 + r.h; }; // twice the middle, kept whole - const IntRect doneGlyph = app.GetElementRect(WithStyle(GetDialogStyles(app).progressStepDoneStyleRef).at(0)); + const IntRect doneGlyph = app.GetElementRect(WithStyle(dialogs::GetStyles(app, dialogContext).progressStepDoneStyleRef).at(0)); const IntRect doneName = app.GetElementRect(app.FindByText("Compile scripts")); const IntRect doneNote = app.GetElementRect(app.FindByText("4.2 s")); EXPECT_NEAR(middle(doneGlyph), middle(doneName), 2) << "the glyph level with its name"; @@ -303,13 +305,13 @@ namespace tachyon const IntRect percent = app.GetElementRect(app.FindByText("42%")); EXPECT_NEAR(middle(percent), middle(name), 2); EXPECT_EQ(percent.x + percent.w, all.x + all.w) << "the percent at the end"; - const IntRect bar = app.GetElementRect(WithStyle(GetDialogStyles(app).progressBarSmallStyleRef).at(0)); + const IntRect bar = app.GetElementRect(WithStyle(dialogs::GetStyles(app, dialogContext).progressBarSmallStyleRef).at(0)); EXPECT_EQ(bar.x, name.x) << "the bar from under the name"; EXPECT_EQ(bar.x + bar.w, all.x + all.w) << "to the end"; EXPECT_GE(bar.y, name.y + name.h); const ID detail = app.FindByText("Lightmap atlas, about 1 min left"); ASSERT_TRUE(detail != ID::Invalid()); - EXPECT_EQ(ElementOf(detail).styleRef, GetDialogStyles(app).taskProgressDetailStyleRef); + EXPECT_EQ(ElementOf(detail).styleRef, dialogs::GetStyles(app, dialogContext).taskProgressDetailStyleRef); EXPECT_EQ(app.GetElementRect(detail).x, name.x); EXPECT_GE(app.GetElementRect(detail).y, bar.y + bar.h); @@ -323,10 +325,10 @@ namespace tachyon TEST_F(ProgressCompositesTest, AStatusBarTaskHasASpinnerABarAndACount) { - ProgressTask task{ .name = "Indexing assets", .value = 0.33f, .note = "1,240 / 3,800" }; + dialogs::ProgressTask task{ .name = "Indexing assets", .value = 0.33f, .note = "1,240 / 3,800" }; Frame([&] { app.BeginStatusBar(); - StatusProgress(app, task); + dialogs::StatusProgress(app, dialogContext, task); app.EndStatusBar(); }); const ID name = app.FindByText("Indexing assets"), count = app.FindByText("1,240 / 3,800"); @@ -334,7 +336,7 @@ namespace tachyon ASSERT_TRUE(count != ID::Invalid()); EXPECT_EQ(ElementOf(name).styleRef, app.theme.statusTextStyleRef); EXPECT_EQ(ElementOf(count).styleRef, app.theme.statusTextMonoStyleRef); - const std::vector bars = WithStyle(GetDialogStyles(app).progressBarSmallStyleRef); + const std::vector bars = WithStyle(dialogs::GetStyles(app, dialogContext).progressBarSmallStyleRef); ASSERT_EQ(bars.size(), 1u); EXPECT_EQ(app.GetElementRect(bars[0]).w, app.styleManager.Px(120)); EXPECT_EQ(app.GetElementRect(bars[0]).h, app.styleManager.Px(4)); @@ -354,50 +356,50 @@ namespace tachyon EXPECT_EQ(spinner.w, app.styleManager.Px(12)); EXPECT_LT(spinner.x, app.GetElementRect(name).x); - task.state = TaskState::Paused; + task.state = dialogs::TaskState::Paused; task.note = {}; Frame([&] { app.BeginStatusBar(); - StatusProgress(app, task); + dialogs::StatusProgress(app, dialogContext, task); app.EndStatusBar(); }); EXPECT_TRUE(spinners().empty()) << "no spinner while paused"; EXPECT_TRUE(app.FindByText("paused") != ID::Invalid()); // Done, the bar is full, whatever the value says. - task.state = TaskState::Done; + task.state = dialogs::TaskState::Done; Frame([&] { app.BeginStatusBar(); - StatusProgress(app, task); + dialogs::StatusProgress(app, dialogContext, task); app.EndStatusBar(); }); - EXPECT_EQ(FillOf(WithStyle(GetDialogStyles(app).progressBarSmallStyleRef).at(0)).w, app.styleManager.Px(120)); + EXPECT_EQ(FillOf(WithStyle(dialogs::GetStyles(app, dialogContext).progressBarSmallStyleRef).at(0)).w, app.styleManager.Px(120)); } // In a status bar too narrow for all of it, the bar gives way, not the task's name: // the name is read in full and the bar keeps a little of itself. TEST_F(ProgressCompositesTest, ANarrowStatusBarShrinksTheBarNotTheName) { - const ProgressTask task{ .name = "Indexing assets", .value = 0.5f, .note = "1,885 / 3,800" }; + const dialogs::ProgressTask task{ .name = "Indexing assets", .value = 0.5f, .note = "1,885 / 3,800" }; auto draw = [&](int width) { Frame([&] { app.BeginStatusBar(LayoutOverride{}.Width(Pixels{ width }).NoGrow()); - StatusProgress(app, task); + dialogs::StatusProgress(app, dialogContext, task); app.EndStatusBar(); }); Frame([&] { app.BeginStatusBar(LayoutOverride{}.Width(Pixels{ width }).NoGrow()); - StatusProgress(app, task); + dialogs::StatusProgress(app, dialogContext, task); app.EndStatusBar(); }); }; draw(800); const int32_t fullName = app.GetElementRect(app.FindByText("Indexing assets")).w; - const int32_t fullBar = app.GetElementRect(WithStyle(GetDialogStyles(app).progressBarSmallStyleRef).at(0)).w; + const int32_t fullBar = app.GetElementRect(WithStyle(dialogs::GetStyles(app, dialogContext).progressBarSmallStyleRef).at(0)).w; draw(260); const int32_t name = app.GetElementRect(app.FindByText("Indexing assets")).w; - const int32_t bar = app.GetElementRect(WithStyle(GetDialogStyles(app).progressBarSmallStyleRef).at(0)).w; + const int32_t bar = app.GetElementRect(WithStyle(dialogs::GetStyles(app, dialogContext).progressBarSmallStyleRef).at(0)).w; EXPECT_EQ(name, fullName) << "the name in full"; EXPECT_LT(bar, fullBar) << "the bar gave way"; EXPECT_GE(bar, app.styleManager.Px(32)) << "and kept a little of itself"; @@ -413,10 +415,10 @@ namespace tachyon { const ID pill = app.idManager.CreateStaticID(); int cancelled = -1; - std::vector tasks = { + std::vector tasks = { { .name = "Bake lighting", .value = 0.42f, .onCancel = [&] { cancelled = 0; } }, { .name = "Generate thumbnails", .value = 0.78f, .onCancel = [&] { cancelled = 1; } }, - { .name = "Upload build", .value = 0.15f, .state = TaskState::Paused }, + { .name = "Upload build", .value = 0.15f, .state = dialogs::TaskState::Paused }, }; bool open = false; ID closeWindow = ID::Invalid(); // set: that window closed as the OS would, next frame @@ -432,14 +434,14 @@ namespace tachyon app.EndVertical(); app.BeginStatusBar(); app.StatusText("Ready", LayoutOverride::Auto().FlexGrow(1)); - open = BackgroundTasks(app, pill, tasks); + open = dialogs::BackgroundTasks(app, dialogContext, pill, tasks); app.EndStatusBar(); app.EndVertical(); }); }; frame(); EXPECT_EQ(app.TextOf(pill), "3 tasks"); - EXPECT_EQ(ElementOf(pill).styleRef, GetDialogStyles(app).tasksPillStyleRef); + EXPECT_EQ(ElementOf(pill).styleRef, dialogs::GetStyles(app, dialogContext).tasksPillStyleRef); EXPECT_EQ(IconOf(pill), app.theme.dropdownArrowUpIcon) << "a chevron pointing where it opens"; EXPECT_FALSE(open); EXPECT_FALSE(app.FindByText("Background tasks") != ID::Invalid()); @@ -453,15 +455,15 @@ namespace tachyon EXPECT_TRUE(app.FindByText("2 running") != ID::Invalid()); for (const char* text : { "Bake lighting", "Generate thumbnails", "Upload build", "42%", "78%", "paused" }) EXPECT_TRUE(app.FindByText(text) != ID::Invalid()) << text; - const std::vector bars = WithStyle(GetDialogStyles(app).progressBarSmallStyleRef); + const std::vector bars = WithStyle(dialogs::GetStyles(app, dialogContext).progressBarSmallStyleRef); ASSERT_EQ(bars.size(), 3u); - EXPECT_EQ(FillOf(bars[2]).style, SlotOf(GetDialogStyles(app).progressFillPausedStyleRef)); - const std::vector cancels = WithStyle(GetDialogStyles(app).taskProgressCancelStyleRef); + EXPECT_EQ(FillOf(bars[2]).style, SlotOf(dialogs::GetStyles(app, dialogContext).progressFillPausedStyleRef)); + const std::vector cancels = WithStyle(dialogs::GetStyles(app, dialogContext).taskProgressCancelStyleRef); ASSERT_EQ(cancels.size(), 2u) << "none for the task without onCancel"; // Above the pill, its right edge on the pill's. const IntRect p = app.GetElementRect(pill); - const std::vector popover = WithStyle(GetDialogStyles(app).tasksPopoverStyleRef); + const std::vector popover = WithStyle(dialogs::GetStyles(app, dialogContext).tasksPopoverStyleRef); ASSERT_EQ(popover.size(), 1u); const IntRect w = app.GetElementRect(popover[0]); EXPECT_LE(w.y + w.h, p.y) << "popover " << w.x << "," << w.y << " " << w.w << "x" << w.h @@ -514,12 +516,12 @@ namespace tachyon frame(); frame(); ASSERT_TRUE(open); - const std::vector pauses = WithStyle(GetDialogStyles(app).taskProgressPauseStyleRef); + const std::vector pauses = WithStyle(dialogs::GetStyles(app, dialogContext).taskProgressPauseStyleRef); ASSERT_EQ(pauses.size(), 2u); EXPECT_EQ(IconOf(pauses[0]), app.theme.timelinePauseIcon) << "running: pause"; EXPECT_EQ(IconOf(pauses[1]), app.theme.timelinePlayIcon) << "paused: resume"; - EXPECT_LT(app.GetElementRect(pauses[0]).x, app.GetElementRect(WithStyle(GetDialogStyles(app).taskProgressCancelStyleRef).at(0)).x); - app.mouseWindow = WithStyle(GetDialogStyles(app).tasksPopoverStyleRef).at(0); + EXPECT_LT(app.GetElementRect(pauses[0]).x, app.GetElementRect(WithStyle(dialogs::GetStyles(app, dialogContext).taskProgressCancelStyleRef).at(0)).x); + app.mouseWindow = WithStyle(dialogs::GetStyles(app, dialogContext).tasksPopoverStyleRef).at(0); Click(pauses[1]); frame(); frame(); @@ -535,7 +537,7 @@ namespace tachyon frame(); frame(); ASSERT_TRUE(open); - closeWindow = WithStyle(GetDialogStyles(app).tasksPopoverStyleRef).at(0); + closeWindow = WithStyle(dialogs::GetStyles(app, dialogContext).tasksPopoverStyleRef).at(0); frame(); EXPECT_FALSE(open); diff --git a/tests/progress_test.cpp b/tests/progress_test.cpp index 7565690d..24a86f78 100644 --- a/tests/progress_test.cpp +++ b/tests/progress_test.cpp @@ -136,9 +136,10 @@ namespace tachyon { protected: HeadlessGUIApp app; + dialogs::Context dialogContext; void SetUp() override { ASSERT_TRUE(app.Initialize()); } - void TearDown() override { app.Cleanup(); } + void TearDown() override { dialogs::Cleanup(app, dialogContext); app.Cleanup(); } // Runs the custom draw of `id`'s element into a fresh stub renderer. StubGUIRenderer Draw(ID id) @@ -181,15 +182,16 @@ namespace tachyon auto frame = [&] { app.Frame([&] { app.BeginRootWindow(); - ProgressBar(app, bar, value, failed, GetDialogStyles(app).progressBarStyleRef, LayoutOverride{}.Width(Pixels{ 200 })); + dialogs::ProgressBar(app, dialogContext, bar, value, failed, dialogs::GetStyles(app, dialogContext).progressBarStyleRef, LayoutOverride{}.Width(Pixels{ 200 })); app.EndRootWindow(); + dialogs::EndGUI(app, dialogContext); }); }; frame(); const IntRect track = app.GetElementRect(bar); EXPECT_EQ(track.w, 200); EXPECT_EQ(track.h, app.styleManager.Px(6)); - EXPECT_EQ(app.elementStorage.GetElementUnsafe(app.elementStorage.FindElementRefByID(bar)).styleRef, GetDialogStyles(app).progressBarStyleRef); + EXPECT_EQ(app.elementStorage.GetElementUnsafe(app.elementStorage.FindElementRefByID(bar)).styleRef, dialogs::GetStyles(app, dialogContext).progressBarStyleRef); EXPECT_EQ(FlagsOf(bar) & ElementFlags::Animated, ElementFlags::None) << "it stays still"; StubGUIRenderer renderer = Draw(bar); @@ -197,7 +199,7 @@ namespace tachyon EXPECT_EQ(renderer.boxes[0].w, 50); EXPECT_EQ(renderer.boxes[0].h, track.h); EXPECT_EQ(renderer.boxes[0].x, 0) << "from the start"; - EXPECT_EQ(renderer.boxStyles[0], SlotOf(GetDialogStyles(app).progressFillStyleRef)); + EXPECT_EQ(renderer.boxStyles[0], SlotOf(dialogs::GetStyles(app, dialogContext).progressFillStyleRef)); for (const auto& [v, width] : { std::pair{ 2.0f, 200 }, std::pair{ 1.0f, 200 }, std::pair{ 0.501f, 100 } }) { @@ -219,7 +221,7 @@ namespace tachyon frame(); renderer = Draw(bar); ASSERT_EQ(renderer.boxes.size(), 1u); - EXPECT_EQ(renderer.boxStyles[0], SlotOf(GetDialogStyles(app).progressFillFailedStyleRef)) << "in the error color"; + EXPECT_EQ(renderer.boxStyles[0], SlotOf(dialogs::GetStyles(app, dialogContext).progressFillFailedStyleRef)) << "in the error color"; EXPECT_EQ(renderer.boxes[0].w, 146); } @@ -228,8 +230,9 @@ namespace tachyon const ID bar = app.idManager.CreateStaticID(); app.Frame([&] { app.BeginRootWindow(); - ProgressBar(app, bar, 0.5f, false, GetDialogStyles(app).progressBarSmallStyleRef, LayoutOverride{}.Width(Pixels{ 120 })); + dialogs::ProgressBar(app, dialogContext, bar, 0.5f, false, dialogs::GetStyles(app, dialogContext).progressBarSmallStyleRef, LayoutOverride{}.Width(Pixels{ 120 })); app.EndRootWindow(); + dialogs::EndGUI(app, dialogContext); }); EXPECT_EQ(app.GetElementRect(bar).h, app.styleManager.Px(4)); EXPECT_EQ(Draw(bar).boxes.at(0).w, 60); @@ -243,8 +246,9 @@ namespace tachyon auto frame = [&] { app.Frame([&] { app.BeginRootWindow(); - IndeterminateProgressBar(app, bar, LayoutOverride{}.Width(Pixels{ 200 })); + dialogs::IndeterminateProgressBar(app, dialogContext, bar, LayoutOverride{}.Width(Pixels{ 200 })); app.EndRootWindow(); + dialogs::EndGUI(app, dialogContext); }); }; frame(); @@ -254,7 +258,7 @@ namespace tachyon StubGUIRenderer renderer = Draw(bar); ASSERT_EQ(renderer.boxes.size(), 1u); EXPECT_EQ(renderer.boxes[0], (IntRect{ -length, 0, length, track.h })) << "just before the start"; - EXPECT_EQ(renderer.boxStyles[0], SlotOf(GetDialogStyles(app).progressSegmentStyleRef)); + EXPECT_EQ(renderer.boxStyles[0], SlotOf(dialogs::GetStyles(app, dialogContext).progressSegmentStyleRef)); const int32_t round = track.h / 2; EXPECT_EQ(renderer.boxClips[0], (IntRect{ round, 0, 200 - 2 * round, track.h })) << "the straight part"; @@ -277,11 +281,12 @@ namespace tachyon auto frame = [&] { app.Frame([&] { app.BeginRootWindow(); - Spinner(app, small, SpinnerSize::Small); - Spinner(app, medium); - Spinner(app, large, SpinnerSize::Large); - Spinner(app, sized, SpinnerSize::Medium, LayoutOverride{}.Size(Pixels{ 32 }, Pixels{ 32 })); + dialogs::Spinner(app, dialogContext, small, dialogs::SpinnerSize::Small); + dialogs::Spinner(app, dialogContext, medium); + dialogs::Spinner(app, dialogContext, large, dialogs::SpinnerSize::Large); + dialogs::Spinner(app, dialogContext, sized, dialogs::SpinnerSize::Medium, LayoutOverride{}.Size(Pixels{ 32 }, Pixels{ 32 })); app.EndRootWindow(); + dialogs::EndGUI(app, dialogContext); }); }; frame(); @@ -298,9 +303,9 @@ namespace tachyon EXPECT_FLOAT_EQ(center.x, float(app.styleManager.Px(16)) * 0.5f); EXPECT_FLOAT_EQ(renderer.circles[0].radius, 6.5f * scale); EXPECT_FLOAT_EQ(renderer.circles[0].style.lineWidth, 2.0f * scale); - EXPECT_EQ(renderer.circles[0].style.colorStyleIndex, GetDialogStyles(app).progressTrackColor); + EXPECT_EQ(renderer.circles[0].style.colorStyleIndex, dialogs::GetStyles(app, dialogContext).progressTrackColor); ASSERT_FALSE(renderer.triangles.empty()); - EXPECT_EQ(renderer.triangles[0].color, GetDialogStyles(app).progressArcColor); + EXPECT_EQ(renderer.triangles[0].color, dialogs::GetStyles(app, dialogContext).progressArcColor); const float outer = (6.5f + 1.0f) * scale; EXPECT_TRUE(HasPointNear(renderer, { center.x, center.y - outer })) << "from the top"; EXPECT_TRUE(HasPointNear(renderer, { center.x + outer, center.y })) << "a quarter round"; @@ -327,8 +332,9 @@ namespace tachyon auto frame = [&] { app.Frame([&] { app.BeginRootWindow(); - CircularProgress(app, ring, value); + dialogs::CircularProgress(app, dialogContext, ring, value); app.EndRootWindow(); + dialogs::EndGUI(app, dialogContext); }); }; frame(); @@ -367,8 +373,9 @@ namespace tachyon auto frame = [&] { app.Frame([&] { app.BeginRootWindow(); - Skeleton(app, bar, LayoutOverride{}.Width(Pixels{ 140 })); + dialogs::Skeleton(app, dialogContext, bar, LayoutOverride{}.Width(Pixels{ 140 })); app.EndRootWindow(); + dialogs::EndGUI(app, dialogContext); }); }; frame(); @@ -380,7 +387,7 @@ namespace tachyon ASSERT_EQ(renderer.boxes.size(), 1u); const int32_t band = std::max(70, rect.h * 4); EXPECT_EQ(renderer.boxes[0], (IntRect{ -band, 0, band, rect.h })); - EXPECT_EQ(renderer.boxStyles[0], SlotOf(GetDialogStyles(app).skeletonShineStyleRef)); + EXPECT_EQ(renderer.boxStyles[0], SlotOf(dialogs::GetStyles(app, dialogContext).skeletonShineStyleRef)); EXPECT_EQ(renderer.boxClips[0], (IntRect{ rect.h / 2, 0, 140 - rect.h, rect.h })); app.AdvanceTime(750); @@ -391,8 +398,9 @@ namespace tachyon const ID shortBar = app.idManager.CreateStaticID(); app.Frame([&] { app.BeginRootWindow(); - Skeleton(app, shortBar, LayoutOverride{}.Width(Pixels{ 30 })); + dialogs::Skeleton(app, dialogContext, shortBar, LayoutOverride{}.Width(Pixels{ 30 })); app.EndRootWindow(); + dialogs::EndGUI(app, dialogContext); }); EXPECT_EQ(Draw(shortBar).boxes.at(0).w, app.GetElementRect(shortBar).h * 4); @@ -417,10 +425,11 @@ namespace tachyon app.BeginRootWindow(); // A row it shares with a button that grows into the room left over too. app.BeginHorizontal(row, app.theme.emptyHorzStyleRef, LayoutOverride{}.Width(Pixels{ 600 })); - BusyButton(app, button, { app.theme.menuCheckIcon, "Save" }, busy, "Saving everything to disk...", [&] { ++clicks; }); + dialogs::BusyButton(app, dialogContext, button, { app.theme.menuCheckIcon, "Save" }, busy, "Saving everything to disk...", [&] { ++clicks; }); app.Button(other, "Cancel", [] {}); app.EndHorizontal(); app.EndRootWindow(); + dialogs::EndGUI(app, dialogContext); }); }; auto iconOf = [&] { @@ -474,8 +483,9 @@ namespace tachyon auto frame = [&](LayoutOverride constraints) { app.Frame([&] { app.BeginRootWindow(); - BusyButton(app, button, "Export", busy, {}, [] {}, std::move(constraints)); + dialogs::BusyButton(app, dialogContext, button, "Export", busy, {}, [] {}, std::move(constraints)); app.EndRootWindow(); + dialogs::EndGUI(app, dialogContext); }); }; frame({}); @@ -489,8 +499,9 @@ namespace tachyon const ID fresh = app.idManager.CreateStaticID(); app.Frame([&] { app.BeginRootWindow(); - BusyButton(app, fresh, "Go", true, "Going...", [] {}); + dialogs::BusyButton(app, dialogContext, fresh, "Go", true, "Going...", [] {}); app.EndRootWindow(); + dialogs::EndGUI(app, dialogContext); }); EXPECT_GT(app.GetElementRect(fresh).w, 0); } @@ -530,12 +541,13 @@ namespace tachyon { ++runs; if (moving) - Spinner(app, bar); + dialogs::Spinner(app, dialogContext, bar); else - ProgressBar(app, bar, 0.5f); + dialogs::ProgressBar(app, dialogContext, bar, 0.5f); } app.EndCached(); app.EndRootWindow(); + dialogs::EndGUI(app, dialogContext); }); }; frame(); diff --git a/tests/redraw_test.cpp b/tests/redraw_test.cpp index 811dc44e..0949e1ca 100644 --- a/tests/redraw_test.cpp +++ b/tests/redraw_test.cpp @@ -195,6 +195,7 @@ namespace tachyon class RedrawApp : public GUIApplicationInternals { public: + dialogs::Context dialogContext; ID windowID = ID::Invalid(); ID buttonID = ID::Invalid(); ID textID = ID::Invalid(); // has a tooltip, and no hover look of its own @@ -225,7 +226,7 @@ namespace tachyon if (cached) EndCached(); if (spinner) - Spinner(*this, idManager.AllocateDynamicID("spinner")); + dialogs::Spinner(*this, dialogContext, idManager.AllocateDynamicID("spinner")); if (still) RegisterElement(Element{ .id = idManager.AllocateDynamicID("still"), .styleRef = theme.emptyHorzStyleRef, .flags = ElementFlags::NoInput | ElementFlags::Animated }, @@ -416,11 +417,11 @@ namespace tachyon TEST_F(RedrawTest, AToastAsksForAFrame) { app.Settle(); - const ToastID toast = ShowToast(app, ToastDesc{ .title = "Saved" }); + const dialogs::ToastID toast = dialogs::ShowToast(app, app.dialogContext, dialogs::ToastDesc{ .title = "Saved" }); EXPECT_TRUE(app.NeedsFrame()); app.Settle(); EXPECT_FALSE(app.NeedsFrame()); - DismissToast(app, toast); + dialogs::DismissToast(app, app.dialogContext, toast); EXPECT_TRUE(app.NeedsFrame()); } diff --git a/tests/static_id_release_test.cpp b/tests/static_id_release_test.cpp index 35d8869f..a8aa3796 100644 --- a/tests/static_id_release_test.cpp +++ b/tests/static_id_release_test.cpp @@ -19,8 +19,9 @@ namespace tachyon { protected: HeadlessGUIApp app; + dialogs::Context dialogContext; void SetUp() override { ASSERT_TRUE(app.Initialize()); } - void TearDown() override { app.Cleanup(); } + void TearDown() override { dialogs::Cleanup(app, dialogContext); app.Cleanup(); } }; // A panel CreatePanel made an ID for goes with that ID when its tab is closed; one given @@ -56,6 +57,7 @@ namespace tachyon app.BeginDockingContainer(containerID, &layout, LayoutOverride{}.Size(800, 600)); app.EndDockingContainer(); app.EndRootWindow(); + dialogs::EndGUI(app, dialogContext); }); ASSERT_GT(app.idManager.GetStaticIDCount(), before + 3) << "test setup: the tree has IDs"; @@ -86,11 +88,12 @@ namespace tachyon // torn-off windows) goes back at Cleanup: none is left. TEST_F(StaticIDReleaseTest, CleanupGivesBackTheApplicationsOwnIDs) { - ShowToast(app, { .title = "Saved" }); + dialogs::ShowToast(app, dialogContext, { .title = "Saved" }); app.Frame([&] { app.BeginRootWindow(); - Toasts(app); + dialogs::Toasts(app, dialogContext); app.EndRootWindow(); + dialogs::EndGUI(app, dialogContext); }); const ID trigger = app.idManager.CreateStaticID(); (void)app.menuManager.PopupWindowFor(trigger, app.idManager); @@ -107,7 +110,7 @@ namespace tachyon app.m_floatingDockWindows.push_back(std::move(fw)); ASSERT_GT(app.idManager.GetStaticIDCount(), 0u); - app.Cleanup(); + dialogs::Cleanup(app, dialogContext); app.Cleanup(); EXPECT_EQ(app.idManager.GetStaticIDCount(), 0u); EXPECT_TRUE(app.m_floatingDockWindows.empty()); } diff --git a/tests/theme_variables_test.cpp b/tests/theme_variables_test.cpp index 6c8df76e..a71075b2 100644 --- a/tests/theme_variables_test.cpp +++ b/tests/theme_variables_test.cpp @@ -309,6 +309,7 @@ namespace tachyon { protected: HeadlessGUIApp app; + dialogs::Context dialogContext; void SetUp() override { ASSERT_TRUE(app.Initialize()); Frame(); } void TearDown() override { app.Cleanup(); } @@ -361,7 +362,7 @@ namespace tachyon }; const VisualColorStyle panel = background("dock-leaf"); // --bg-panel const VisualColorStyle header = background("table-header-section"); // --bg-panel too - const VisualColorStyle arc = *app.styleManager.GetVisualColorStyle(GetDialogStyles(app).progressArcColor); // --accent + const VisualColorStyle arc = *app.styleManager.GetVisualColorStyle(dialogs::GetStyles(app, dialogContext).progressArcColor); // --accent const VisualColorStyle input = *app.styleManager.GetVisualColorStyle(app.theme.alphaTrackColor); // --alpha-track const uint32_t generation = app.styleManager.Generation(); @@ -369,10 +370,10 @@ namespace tachyon EXPECT_FALSE(background("dock-leaf") == panel); EXPECT_TRUE(background("dock-leaf") == background("table-header-section")) << "one variable, one fill"; EXPECT_FALSE(background("table-header-section") == header); - EXPECT_TRUE(*app.styleManager.GetVisualColorStyle(GetDialogStyles(app).progressArcColor) == arc) << "the accent's stays"; + EXPECT_TRUE(*app.styleManager.GetVisualColorStyle(dialogs::GetStyles(app, dialogContext).progressArcColor) == arc) << "the accent's stays"; app.SetThemeVariable("--accent", "#FF0000"); - EXPECT_FALSE(*app.styleManager.GetVisualColorStyle(GetDialogStyles(app).progressArcColor) == arc) << "the theme's own from it"; + EXPECT_FALSE(*app.styleManager.GetVisualColorStyle(dialogs::GetStyles(app, dialogContext).progressArcColor) == arc) << "the theme's own from it"; EXPECT_TRUE(*app.styleManager.GetVisualColorStyle(app.theme.alphaTrackColor) == input); EXPECT_EQ(app.styleManager.Generation(), generation) << "without loading the theme"; } From 03bb6200d6d4ee5c9cd559250882560df3fb59b3 Mon Sep 17 00:00:00 2001 From: Sander van Rossen Date: Fri, 4 Dec 2026 13:20:21 +0100 Subject: [PATCH 2/9] Move the timeline and the viewport into the examples (#350) Timeline, TimelineEditor and Viewport serve one kind of app, so they leave the library for examples/app_controls, in namespace tachyon::app_controls, next to the file code. They are written on the public API: free functions that take the app and an app_controls::Context. Their styles moved to themes/app_controls.css and their style refs, icons and colors out of GUITheme. Their tests moved to app_controls_tests, which shares the headless test app with gui_core_tests through a small harness library. For them, GUITheme::RegisterDropdownParts and GUIApplication::RebuildCachedScopesAbove are public, and gui_core has ParseJsonObject, JsonFloat, JsonFloats and JsonFloatArray for saving a view's state. --- CHANGELOG.md | 1 + CMakeLists.txt | 2 +- docs/controls.md | 10 +- docs/controls/css-classes.md | 6 +- docs/controls/tabs-docking-toolbars.md | 2 +- docs/controls/timeline.md | 32 +- docs/controls/viewport.md | 20 +- examples/app_controls/CMakeLists.txt | 16 +- .../app_controls}/controls_timeline.cpp | 94 +-- .../controls_timeline_editor.cpp | 354 +++++------ .../app_controls}/controls_viewport.cpp | 112 ++-- examples/app_controls/gui_app_controls.cpp | 185 ++++++ examples/app_controls/gui_app_controls.h | 188 ++++++ examples/app_controls/gui_file_icons.cpp | 2 +- examples/app_controls/gui_file_icons.h | 5 +- examples/app_controls/gui_file_system.cpp | 2 +- examples/app_controls/gui_file_system.h | 2 +- examples/app_controls/gui_file_thumbnails.cpp | 2 +- examples/app_controls/gui_file_thumbnails.h | 5 +- .../app_controls}/gui_timeline_helpers.cpp | 5 +- .../app_controls}/gui_timeline_internal.h | 4 +- .../app_controls}/gui_timeline_types.h | 2 +- .../app_controls}/gui_viewport_helpers.cpp | 5 +- .../app_controls}/gui_viewport_types.h | 2 +- .../app_controls/tests/app_controls_test.h | 22 + .../tests/app_edit_id_release_test.cpp | 87 +++ .../tests/app_view_state_test.cpp | 65 ++ .../app_controls/tests/file_system_test.cpp | 2 +- .../tests/file_thumbnails_test.cpp | 2 +- .../tests}/timeline_editor_test.cpp | 80 ++- .../tests/timeline_focus_test.cpp | 113 ++++ .../tests}/timeline_internal_test.cpp | 4 +- .../app_controls/tests}/timeline_test.cpp | 48 +- .../tests}/timeline_two_views_test.cpp | 12 +- .../app_controls/tests}/viewport_test.cpp | 16 +- examples/showcase/application.cpp | 14 +- examples/showcase/application.h | 16 +- examples/showcase/panel_files.cpp | 66 +- examples/showcase/panel_misc.cpp | 4 +- examples/showcase/panel_timeline.cpp | 50 +- examples/showcase/panel_view.cpp | 30 +- examples/showcase/scene.h | 4 +- examples/showcase/scene_renderer.cpp | 10 +- examples/showcase/scene_renderer.h | 10 +- src/CMakeLists.txt | 8 - src/gui_controls/gui_application.h | 63 +- src/gui_controls/gui_theme.cpp | 93 +-- src/gui_controls/gui_theme.h | 83 +-- src/gui_controls/gui_view_state.cpp | 118 +--- src/gui_controls/gui_view_state.h | 9 - src/gui_core/gui_json.cpp | 37 ++ src/gui_core/gui_json.h | 13 + tests/CMakeLists.txt | 30 +- tests/controls_menu_test.cpp | 2 +- tests/edit_id_release_test.cpp | 72 --- tests/keyboard_focus_test.cpp | 16 +- tests/view_state_test.cpp | 45 +- workdirectory/themes/app_controls.css | 591 +++++++++++++++++ workdirectory/themes/styles.css | 592 +----------------- 59 files changed, 1925 insertions(+), 1560 deletions(-) rename {src/gui_controls => examples/app_controls}/controls_timeline.cpp (73%) rename {src/gui_controls => examples/app_controls}/controls_timeline_editor.cpp (81%) rename {src/gui_controls => examples/app_controls}/controls_viewport.cpp (83%) create mode 100644 examples/app_controls/gui_app_controls.cpp create mode 100644 examples/app_controls/gui_app_controls.h rename {src/gui_controls => examples/app_controls}/gui_timeline_helpers.cpp (98%) rename {src/gui_controls => examples/app_controls}/gui_timeline_internal.h (96%) rename {src/gui_controls => examples/app_controls}/gui_timeline_types.h (99%) rename {src/gui_controls => examples/app_controls}/gui_viewport_helpers.cpp (99%) rename {src/gui_controls => examples/app_controls}/gui_viewport_types.h (99%) create mode 100644 examples/app_controls/tests/app_controls_test.h create mode 100644 examples/app_controls/tests/app_edit_id_release_test.cpp create mode 100644 examples/app_controls/tests/app_view_state_test.cpp rename {tests => examples/app_controls/tests}/timeline_editor_test.cpp (93%) create mode 100644 examples/app_controls/tests/timeline_focus_test.cpp rename {tests => examples/app_controls/tests}/timeline_internal_test.cpp (96%) rename {tests => examples/app_controls/tests}/timeline_test.cpp (89%) rename {tests => examples/app_controls/tests}/timeline_two_views_test.cpp (91%) rename {tests => examples/app_controls/tests}/viewport_test.cpp (97%) create mode 100644 workdirectory/themes/app_controls.css diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d4d77b7..51c63ad9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ Notable changes per release. Releases are tagged `vX.Y.Z`; the version lives in - The backends are libraries of their own: `gui_backend_vulkan`, `gui_backend_d3d12`, `gui_backend_metal`, `gui_backend_sdlgpu` and `gui_backend_sdl` (windows and clipboard). `gui_core` and `gui_controls` hold none of them, so an app that sets its own backends links no SDL, Vulkan, VMA or D3D12MA. Apps link `TachyonUI::gui_backend_default` as well as `gui_controls` to get the built-in backends; without it and without a window backend set, `Initialize` fails and says which library to link. `RegisterGraphicsBackend`, `RegisterDefaultWindowBackend` and `RegisterDefaultClipboard` set the defaults; the `TACHYON_VULKAN`-style definitions come from `gui_backend_default` and the backend libraries. - The package installs third-party headers only for the libraries its public headers include (SDL3, VMA, D3D12 Memory Allocator). The privately linked ones (HarfBuzz, skribidi, SheenBidi, libunibreak, budoux, nanosvg, vk-bootstrap) are there as library files alone, without headers or package configs. - The file system, file icons and file thumbnails (`IFileSystem`, `MemoryFileSystem`, `FileIcons`, `FileThumbnails`) moved out of `gui_controls` into the examples (`examples/app_controls`, as ``): they serve one kind of app. The showcase's Files panel uses them from there. +- `Timeline`, `TimelineEditor` and `Viewport` moved out of the library into the examples (`examples/app_controls`, namespace `tachyon::app_controls`, with the file code): they serve one kind of app, and show how an app writes controls of its own on the public API. They take the app and an `app_controls::Context`: `app_controls::Timeline(*this, controlsContext, state, options)`. Their styles moved from `styles.css` to `themes/app_controls.css`, which an app adds to its style files, and from `GUITheme` to `app_controls::GetStyles`. `GUITheme::RegisterDropdownParts`, `GUIApplication::RebuildCachedScopesAbove` and the JSON helpers `ParseJsonObject`, `JsonFloat`, `JsonFloats` and `JsonFloatArray` are public for them. - Drag and drop is part of `gui_core`: `MakeDragSourceHandler` and `MakeDropTargetHandler` moved to `gui_core/input/gui_drag_drop.h` (still included by `gui_controls/gui_default_handlers.h`). `DispatchToElementChain` carries drag events and drops from other applications up from the element under the pointer, one path for both. - Extensions: a library of controls on top of `gui_controls` has its own namespace and is built on the public API: its controls are free functions that take the app and a context of the library's own, which the app owns, and the app calls the library's frame and cleanup functions itself. `ScheduleFrameAt`, `CloseOnPressOutside`, `RetireWindow`, `AppColorStyle`, `ButtonGroupItemStyle`, `NoteButtonGroupItem`, `LastStatusBar`, `StylesGeneration` and `GUITheme::VariableColor` are public for them. - Dialogs are the first extension, `gui_dialogs` (`TachyonUI::gui_dialogs`, ``, namespace `tachyon::dialogs`): `MessageDialog`, `ShowToast`, `FindToast`, `DismissToast`, `Toasts`, `Banner`, `BusyButton` and the progress controls (`ProgressBar`, `IndeterminateProgressBar`, `Spinner`, `CircularProgress`, `Skeleton`, `TaskProgress`, `ProgressSteps`, `StatusProgress`, `BackgroundTasks`) are free functions now, taking the app and a `dialogs::Context` the app owns: `dialogs::ShowToast(app, dialogContext, desc)`. The app calls `dialogs::EndGUI` last in `OnGUI` and `dialogs::Cleanup` before its own cleanup. Their styles moved from `GUITheme` to `dialogs::GetStyles(app, dialogContext)`. diff --git a/CMakeLists.txt b/CMakeLists.txt index 3688861e..e5831fb6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -169,7 +169,7 @@ if(TACHYON_INSTALL) install(FILES LICENSE THIRD_PARTY_NOTICES.txt DESTINATION share/TachyonUI) - set(_tachyon_resource_excludes PATTERN showcase.css EXCLUDE) + set(_tachyon_resource_excludes PATTERN showcase.css EXCLUDE PATTERN app_controls.css EXCLUDE) if(NOT TACHYON_FALLBACK_FONTS) list(APPEND _tachyon_resource_excludes PATTERN Noto-otf EXCLUDE) endif() diff --git a/docs/controls.md b/docs/controls.md index e7337b2c..a0960e79 100644 --- a/docs/controls.md +++ b/docs/controls.md @@ -34,7 +34,6 @@ results all controls share. | [Color and gradient fields](controls/color-and-gradient.md) | `ColorField`, `GradientField` and their pickers | | [Curves](controls/curves.md) | `CurveField` and its curve editor, `EvaluateCurve` | | [Plots](controls/plots.md) | `Plot`: histograms and other series, with handles (Levels) | -| [Viewport](controls/viewport.md) | `Viewport`: your 3D scene, its camera, and gizmos to move, rotate and scale | | [Menus](controls/menus.md) | Menus, menu items, menu bar, title bar, context menus | | [Tooltips and message dialogs](controls/tooltips-and-dialogs.md) | Tooltips, modal `MessageDialog` | | [Lists and reorderable groups](controls/lists.md) | List views, drag-to-reorder groups | @@ -42,11 +41,18 @@ results all controls share. | [Tree and grid views](controls/trees-and-grids.md) | `VirtualTreeView`, grid views, virtual grid views | | [Tabs, docking and toolbars](controls/tabs-docking-toolbars.md) | Tab bars, docking containers, toolbars, toolbar dock | | [Node view](controls/node-view.md) | `RenderNodeView` node graph editor | -| [Timeline](controls/timeline.md) | `Timeline` playback row, `TimelineEditor` animation editor, `AdvanceTimeline` | | [Other controls](controls/other-controls.md) | Breadcrumb, status bar, progress bars, spinners and skeletons, task progress and background tasks, command search, settings panel | | [Custom drawing](controls/custom-drawing.md) | Drawing shapes and text inside an element | | [Default CSS classes](controls/css-classes.md) | Each control's class when you pass no style | +Two more controls are example code rather than the library. They're in `examples/app_controls`, +and show how an app writes controls of its own; copy them, or use them as a model: + +| Page | Covers | +| --- | --- | +| [Viewport](controls/viewport.md) | `Viewport`: your 3D scene, its camera, and gizmos to move, rotate and scale | +| [Timeline](controls/timeline.md) | `Timeline` playback row, `TimelineEditor` animation editor, `AdvanceTimeline` | + ```cpp @@ -12,6 +13,7 @@ class MyApp : public tachyon::GUIApplication public: tachyon::Result Initialize(const InitializeOptions& options = {}) override; void OnGUI() override; + void Cleanup() override; CounterPanel counter; GreetingPanel greeting; @@ -19,7 +21,8 @@ public: private: tachyon::ID m_windowID = tachyon::ID::Invalid(); tachyon::ID m_dockID = tachyon::ID::Invalid(); - tachyon::DockingLayout m_layout; + tachyon::docking::DockingLayout m_layout; + tachyon::docking::Context m_docking; // docking's state: the panels' windows, drags }; ``` @@ -35,6 +38,7 @@ tachyon::Result MyApp::Initialize(const InitializeOptions& options) { if (tachyon::Result result = GUIApplication::Initialize(options); !result) return result; + docking::Install(*this, m_docking); // docking works at points of the frame OnGUI doesn't reach // The window and the dock layout keep their state between frames, so they get // IDs that stay the same: static IDs, made once. @@ -42,11 +46,11 @@ tachyon::Result MyApp::Initialize(const InitializeOptions& options) m_dockID = idManager.CreateStaticID(); const tachyon::IconID noIcon = tachyon::IconID::Invalid; - const tachyon::ID left = CreatePanel(m_layout.panels, "Counter", noIcon, [this] { counter.Draw(*this); }); - const tachyon::ID right = CreatePanel(m_layout.panels, "Greeting", noIcon, [this] { greeting.Draw(*this); }); - m_layout.root = tachyon::MakeSplit(tachyon::DockSplitMode::LeftPinned, 240, - tachyon::MakeLeaf({ left }), - tachyon::MakeLeaf({ right })); + const tachyon::ID left = docking::CreatePanel(*this, m_docking, m_layout.panels, "Counter", noIcon, [this] { counter.Draw(*this); }); + const tachyon::ID right = docking::CreatePanel(*this, m_docking, m_layout.panels, "Greeting", noIcon, [this] { greeting.Draw(*this); }); + m_layout.root = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 240, + docking::MakeLeaf({ left }), + docking::MakeLeaf({ right })); return {}; } ``` @@ -54,11 +58,28 @@ tachyon::Result MyApp::Initialize(const InitializeOptions& options) - The window and the dock layout remember their position, size and arrangement by ID. - So they need static IDs: IDs made once, which stay the same. - Call-site IDs, made from the file and line of a call, won't do here. +- Docking is a library of its own (`TachyonUI::gui_docking`, namespace `tachyon::docking`): + - its functions take the app, then a `docking::Context` the app owns (`m_docking` here) + - `docking::Install` hooks it into the frame, once, after `GUIApplication::Initialize` + - `my_app.cpp` shortens its name with `namespace docking = tachyon::docking;` - `CreatePanel` registers a dockable panel with a title and a draw callback. - The dock tree gives the counter a 240 px left column and the greeting the rest. - Users can drag tabs to rearrange the panels, or drag a tab out of the window to float its panel. +## Cleaning up + +Before the library cleans up, docking closes the windows of the panels that were floated: + + +```cpp +void MyApp::Cleanup() +{ + docking::Cleanup(*this, m_docking); // the floated panels' windows, before the library's own + GUIApplication::Cleanup(); +} +``` + ## Every frame @@ -68,9 +89,9 @@ void MyApp::OnGUI() if (BeginWindow(m_windowID, "My app", theme.mainWindowStyleRef, tachyon::LayoutOverride::FixedSize(640, 360).Centered())) { - BeginDockingContainer(m_dockID, &m_layout, tachyon::LayoutOverride::Auto()); - EndDockingContainer(); - EmitFloatingDockWindows(); + docking::BeginDockingContainer(*this, m_docking, m_dockID, &m_layout, tachyon::LayoutOverride::Auto()); + docking::EndDockingContainer(*this, m_docking); + docking::EmitFloatingDockWindows(*this, m_docking); } EndWindow(); } diff --git a/docs/tutorial/buttons.md b/docs/tutorial/buttons.md index 1dda4574..38440955 100644 --- a/docs/tutorial/buttons.md +++ b/docs/tutorial/buttons.md @@ -9,7 +9,7 @@ Each panel is a class: - Controls are members of `tachyon::GUIApplication`, so `Draw` takes the app. In `my_app.h`, after `#include `, -`#include ` and `#include `: +`#include ` and `#include `: ```cpp namespace my_app diff --git a/examples/app_controls/gui_app_controls.h b/examples/app_controls/gui_app_controls.h index 30e036f4..e6954aca 100644 --- a/examples/app_controls/gui_app_controls.h +++ b/examples/app_controls/gui_app_controls.h @@ -10,6 +10,7 @@ // app_controls::Timeline(*this, controlsContext, playback, options); #include +#include #include #include @@ -180,8 +181,8 @@ namespace tachyon::app_controls /// As above, with the call site as the ID. inline bool Viewport(GUIApplication& app, Context& context, ViewportView& view, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return Viewport(app, context, app.idManager.AllocateDynamicID(site), view, std::move(constraints)); } - /// A view's own state as text, for a panel to keep with its layout, and back (Panel::saveState and - /// Panel::restoreState). + /// A view's own state as text, for a panel to keep with its layout, and back (docking::Panel::saveState and + /// docking::Panel::restoreState). /// The part of a timeline in view and its zoom slider. std::string SaveViewState(const TimelineViewState& view); bool RestoreViewState(TimelineViewState& view, std::string_view state); diff --git a/examples/app_controls/tests/timeline_editor_test.cpp b/examples/app_controls/tests/timeline_editor_test.cpp index 27ed61b5..77d6326a 100644 --- a/examples/app_controls/tests/timeline_editor_test.cpp +++ b/examples/app_controls/tests/timeline_editor_test.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -24,6 +25,7 @@ namespace tachyon::app_controls { protected: HeadlessGUIApp app; + docking::Context dockingContext; mutable Context controlsContext; TimelineView view; ID editorID{}; @@ -38,6 +40,7 @@ namespace tachyon::app_controls { app.SetStyleFiles(kStyleFiles); ASSERT_TRUE(app.Initialize()); + docking::Install(app, dockingContext); editorID = app.idManager.CreateStaticID(); auto make = [&] { return app.idManager.CreateStaticID(); }; sphere = make(); position = make(); scale = make(); light = make(); intensity = make(); music = make(); events = make(); @@ -209,7 +212,7 @@ namespace tachyon::app_controls for (int i = 0; i < 2; ++i) app.Frame([&] { app.BeginRootWindow({ 1600, 900 }, ElementFlags::None, app.theme.mainWindowStyleRef); - app.BeginArea(panel, app.theme.dockContentStyleRef); + app.BeginArea(panel, docking::GetStyles(app, dockingContext).dockContentStyleRef); TimelineEditor(app, controlsContext, editorID, view, LayoutOverride{}.FlexGrow(1)); app.EndArea(); app.EndRootWindow(); diff --git a/examples/docking/CMakeLists.txt b/examples/docking/CMakeLists.txt index 8f392f28..902304f4 100644 --- a/examples/docking/CMakeLists.txt +++ b/examples/docking/CMakeLists.txt @@ -1 +1 @@ -tachyon_add_example(docking docking.cpp) +tachyon_add_example(docking docking.cpp LIBS gui_docking) diff --git a/examples/docking/docking.cpp b/examples/docking/docking.cpp index 8b034270..6d6fdeeb 100644 --- a/examples/docking/docking.cpp +++ b/examples/docking/docking.cpp @@ -3,7 +3,8 @@ #include #include -#include +#include +#include #include @@ -14,34 +15,40 @@ class DockingApp : public tachyon::GUIApplication { if (tachyon::Result result = GUIApplication::Initialize(options); !result) return result; + tachyon::docking::Install(*this, dockingContext); windowID = idManager.CreateStaticID(); dockID = idManager.CreateStaticID(); // Panels are created once; each draws its content in its callback. const tachyon::IconID noIcon = tachyon::IconID::Invalid; - const tachyon::ID scene = CreatePanel(layout.panels, "Scene", noIcon, [this] { ScenePanel(); }); - const tachyon::ID details = CreatePanel(layout.panels, "Details", noIcon, [this] { DetailsPanel(); }); - const tachyon::ID log = CreatePanel(layout.panels, "Log", noIcon, [this] { Text("Nothing logged yet."); }); - const tachyon::ID help = CreatePanel(layout.panels, "Help", noIcon, [this] { Text("Drag the tabs around."); }); + const tachyon::ID scene = tachyon::docking::CreatePanel(*this, dockingContext, layout.panels, "Scene", noIcon, [this] { ScenePanel(); }); + const tachyon::ID details = tachyon::docking::CreatePanel(*this, dockingContext, layout.panels, "Details", noIcon, [this] { DetailsPanel(); }); + const tachyon::ID log = tachyon::docking::CreatePanel(*this, dockingContext, layout.panels, "Log", noIcon, [this] { Text("Nothing logged yet."); }); + const tachyon::ID help = tachyon::docking::CreatePanel(*this, dockingContext, layout.panels, "Help", noIcon, [this] { Text("Drag the tabs around."); }); // Left column of 220 px, the rest split over a 150 px bottom row. - using tachyon::DockSplitMode; - layout.root = tachyon::MakeSplit(DockSplitMode::LeftPinned, 220, - tachyon::MakeLeaf({ scene }), - tachyon::MakeSplit(DockSplitMode::BottomPinned, 150, - tachyon::MakeLeaf({ details, help }), - tachyon::MakeLeaf({ log }))); + layout.root = tachyon::docking::MakeSplit(tachyon::docking::DockSplitMode::LeftPinned, 220, + tachyon::docking::MakeLeaf({ scene }), + tachyon::docking::MakeSplit(tachyon::docking::DockSplitMode::BottomPinned, 150, + tachyon::docking::MakeLeaf({ details, help }), + tachyon::docking::MakeLeaf({ log }))); return {}; } + void Cleanup() override + { + tachyon::docking::Cleanup(*this, dockingContext); + GUIApplication::Cleanup(); + } + void OnGUI() override { if (BeginWindow(windowID, "Docking", theme.mainWindowStyleRef, tachyon::LayoutOverride::FixedSize(900, 600).Centered())) { - BeginDockingContainer(dockID, &layout, tachyon::LayoutOverride::Auto()); - EndDockingContainer(); + tachyon::docking::BeginDockingContainer(*this, dockingContext, dockID, &layout, tachyon::LayoutOverride::Auto()); + tachyon::docking::EndDockingContainer(*this, dockingContext); // Panels dragged out of the window get their own OS windows, owned by this one. - EmitFloatingDockWindows(); + tachyon::docking::EmitFloatingDockWindows(*this, dockingContext); } EndWindow(); } @@ -64,7 +71,8 @@ class DockingApp : public tachyon::GUIApplication tachyon::ID windowID = tachyon::ID::Invalid(); tachyon::ID dockID = tachyon::ID::Invalid(); - tachyon::DockingLayout layout; + tachyon::docking::DockingLayout layout; + tachyon::docking::Context dockingContext; // docking's state: the panels' windows, drags int selected = 0; float scale = 1.0f; }; diff --git a/examples/showcase/CMakeLists.txt b/examples/showcase/CMakeLists.txt index 0df08d1b..820ffe28 100644 --- a/examples/showcase/CMakeLists.txt +++ b/examples/showcase/CMakeLists.txt @@ -83,7 +83,7 @@ tachyon_add_example(showcase "${PROJECT_SOURCE_DIR}/workdirectory/themes/styles.css" "${PROJECT_SOURCE_DIR}/workdirectory/themes/showcase.css" - LIBS gui_dialogs gui_curves gui_color gui_views gui_nodes tachyon_app_controls) + LIBS gui_dialogs gui_curves gui_color gui_views gui_nodes gui_docking tachyon_app_controls) tachyon_precompile_headers(showcase ) if(TACHYON_METAL) diff --git a/examples/showcase/application.cpp b/examples/showcase/application.cpp index 7ddfa692..f0339f7d 100644 --- a/examples/showcase/application.cpp +++ b/examples/showcase/application.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #endif #include @@ -43,6 +44,7 @@ namespace tachyon withFallbacks.fallbackFonts = "fonts/Noto-otf"; if (Result result = GUIApplication::Initialize(withFallbacks); !result) return result; + docking::Install(*this, dockingContext); // Application-specific resources and styles if (!InitializeShowcaseResources() || @@ -66,10 +68,10 @@ namespace tachyon PersistThemeVariables("themeVariables"); PersistShortcuts("shortcuts", commandManager); AddBuiltInLayouts(); - PersistLayoutPresets("layouts", showcase.layoutPresets); + docking::PersistLayoutPresets(*this, "layouts", showcase.layoutPresets); PersistWindow("main", showcase.windowLayoutID2); - PersistDocuments("documents", [this] { - std::vector windows; + docking::PersistDocuments(*this, dockingContext, "documents", [this] { + std::vector windows; if (showcase.mainWindowOpen) windows.push_back({ showcase.windowLayoutID2, &showcase.documents }); for (const auto& window : showcase.documentWindows) @@ -168,6 +170,7 @@ namespace tachyon { dialogs::Cleanup(*this, dialogContext); color::Cleanup(*this, colorContext); + docking::Cleanup(*this, dockingContext); if (pastedImage != nullptr && graphicsContext != nullptr) { graphicsContext->UnregisterImage(pastedImageIndex); @@ -176,10 +179,10 @@ namespace tachyon // The documents close, in every window: their panels are hidden and destroyed (the // Hierarchy panels' row IDs with them), and their IDs and trees' go back. - CloseAllDocuments(showcase.documents); + docking::CloseAllDocuments(*this, dockingContext, showcase.documents); for (const auto& window : showcase.documentWindows) - CloseAllDocuments(window->documents); - ReleaseDockingLayout(m_capture.layout); + docking::CloseAllDocuments(*this, dockingContext, window->documents); + docking::ReleaseDockingLayout(*this, dockingContext, m_capture.layout); // The undo history's steps give back the IDs of what only they still hold. commandManager.History().Clear(); @@ -1140,7 +1143,7 @@ namespace tachyon // Register icons from SVG { - // Document types: drawn in the tab's colors (stroke currentColor). + // docking::Document types: drawn in the tab's colors (stroke currentColor). auto documentIcon = [this](const char* name, const char* paths) { const std::string svg = std::string(R"()") @@ -1335,14 +1338,14 @@ namespace tachyon // Title bar with the main menu and the command search. Most items only log; // Theme and Zoom reload the theme and Exit ends the run loop. - void Application::RenderMainMenu(ID window, ID documentsID, DocumentSet& documents, bool withSearch) + void Application::RenderMainMenu(ID window, ID documentsID, docking::DocumentSet& documents, bool withSearch) { // The title bar: the application's mark, then the documents' tabs. BeginTitleBar(idManager.AllocateDynamicID("titleBar")); Text(idManager.AllocateDynamicID("appIcon"), "T", appIconStyleRef); - DocumentBar(documentsID, documents, theme.titleBarDocumentsStyleRef); + docking::DocumentBar(*this, dockingContext, documentsID, documents, docking::GetStyles(*this, dockingContext).titleBarDocumentsStyleRef); EndTitleBar(); - DocumentLine(documents); // across the window, in the active document's color + docking::DocumentLine(*this, dockingContext, documents); // across the window, in the active document's color // Under it, the menus, the command search and the layouts: they act on the active // document. @@ -1363,7 +1366,7 @@ namespace tachyon EndMenu(); // The open version again, from disk: asked first, as its changes would go. { - Document* active = documents.Active(); + docking::Document* active = documents.Active(); const bool modified = active != nullptr && active->dirty; if (!modified) BeginDisabled(); MenuItem({ showcase.syncIcon, "Reload from disk" }, [this, active, window] { @@ -1528,7 +1531,7 @@ namespace tachyon showcase.exitWindow = window; if (window != showcase.exitWindow) return; - const std::vector unsaved = showcase.exitForTasks ? std::vector{} : UnsavedDocuments(); + const std::vector unsaved = showcase.exitForTasks ? std::vector{} : UnsavedDocuments(); int choice = -1; if (!unsaved.empty()) { @@ -1541,7 +1544,7 @@ namespace tachyon std::vector names; names.reserve(unsaved.size()); std::vector items; - for (const Document* document : unsaved) + for (const docking::Document* document : unsaved) { names.push_back(document->name + document->extension); const auto checked = showcase.exitSave.try_emplace(document, true).first; @@ -1555,7 +1558,7 @@ namespace tachyon .icon = dialogs::MessageIcon::Warning, .title = "Save changes before closing?", .message = message, .buttons = kButtons, .defaultButton = 2, .cancelButton = 1, .items = items }); if (choice == 2) - for (Document* document : unsaved) + for (docking::Document* document : unsaved) if (showcase.exitSave[document]) SaveShowcaseDocument(*document); if (choice == 0 || choice == 2) applicationQuit = true; @@ -1592,10 +1595,10 @@ namespace tachyon showcase.exitSave.clear(); } } - std::vector Application::UnsavedDocuments() + std::vector Application::UnsavedDocuments() { - std::vector unsaved; - auto add = [&unsaved](DocumentSet& set) { + std::vector unsaved; + auto add = [&unsaved](docking::DocumentSet& set) { for (const auto& document : set.documents) if (document->dirty) unsaved.push_back(document.get()); }; @@ -1605,13 +1608,13 @@ namespace tachyon return unsaved; } - void Application::SaveShowcaseDocument(Document& document) + void Application::SaveShowcaseDocument(docking::Document& document) { document.dirty = false; TACHYON_LOG_INFO(kLogShowcase, "Saved {}{}", document.name, document.extension); } - ID Application::CreateShowcasePanel(DockingLayout& layout, std::string_view title) + ID Application::CreateShowcasePanel(docking::DockingLayout& layout, std::string_view title) { const ID id = MakeShowcasePanel(layout, title); const auto panel = layout.panels.find(id); @@ -1628,12 +1631,12 @@ namespace tachyon panel->second.onChanged = [this, data, id, alive] { for (const PanelOnData& other : m_panelsOnData) if (other.data == data && other.id != id && !other.alive.expired()) - InvalidatePanel(other.id); + docking::InvalidatePanel(*this, dockingContext, other.id); }; return id; } - ID Application::MakeShowcasePanel(DockingLayout& layout, std::string_view title) + ID Application::MakeShowcasePanel(docking::DockingLayout& layout, std::string_view title) { auto& panels = layout.panels; const std::string name(title); @@ -1642,7 +1645,7 @@ namespace tachyon return CreateViewportPanel(panels, name); if (title == "NodeView") return CreateNodeGraphPanel(panels, name); if (title == "StateMachine") return CreateStateMachinePanel(panels, name); - if (title == "BoxTest") return CreatePanel(panels, name, showcase.panelMiscIcon, [this] { RenderBoxTestPanel(); }); + if (title == "BoxTest") return docking::CreatePanel(*this, dockingContext, panels, name, showcase.panelMiscIcon, [this] { RenderBoxTestPanel(); }); if (title == "Inspector") return CreateInspectorPanel(panels, name); if (title == "Hierarchy") return CreateHierarchyPanel(panels, name); if (title == "Log") return CreateLogPanel(panels, name); @@ -1651,14 +1654,14 @@ namespace tachyon if (title == "Table") return CreateTablePanel(panels, name); if (title == "FrozenTable") return CreateFrozenTablePanel(panels, name); if (title == "Reorderable") return CreateReorderablePanel(panels, name); - if (title == "Build") return CreatePanel(panels, name, showcase.panelBuildIcon, [this] { RenderBuildPanel(); }); + if (title == "Build") return docking::CreatePanel(*this, dockingContext, panels, name, showcase.panelBuildIcon, [this] { RenderBuildPanel(); }); if (title == "Sketch") return CreateSketchPanel(panels, name); if (title == "Curves") { // Its playhead moves while the timeline plays: never cached. Its pan and zoom go with - // the layout (Panel::saveState). + // the layout (docking::Panel::saveState). auto view = std::make_shared(); - const ID id = CreatePanel(panels, name, curves::GetStyles(*this, curvesContext).curveBezierIcon, [this, view] { RenderCurvesPanel(*view); }); + const ID id = docking::CreatePanel(*this, dockingContext, panels, name, curves::GetStyles(*this, curvesContext).curveBezierIcon, [this, view] { RenderCurvesPanel(*view); }); panels[id].cacheSignature = []() -> std::optional { return std::nullopt; }; panels[id].saveState = [view] { return SaveViewState(*view); }; panels[id].restoreState = [view](std::string_view state) { (void)RestoreViewState(*view, state); }; @@ -1670,7 +1673,7 @@ namespace tachyon // goes with the layout. auto view = std::make_shared(); SetUpTimelineView(*view); - const ID id = CreatePanel(panels, name, theme.timelinePlayIcon, [this, view] { RenderTimelinePanel(*view); }); + const ID id = docking::CreatePanel(*this, dockingContext, panels, name, theme.timelinePlayIcon, [this, view] { RenderTimelinePanel(*view); }); panels[id].cacheSignature = []() -> std::optional { return std::nullopt; }; panels[id].saveState = [view] { return SaveViewState(*view); }; panels[id].restoreState = [view](std::string_view state) { (void)RestoreViewState(*view, state); }; @@ -1683,7 +1686,7 @@ namespace tachyon // Misc is still, so it's kept; while files are dragged over the app it's built every // frame, for its Paste image well to show the drag. auto view = std::make_shared(); - const ID id = CreatePanel(panels, name, showcase.panelMiscIcon, [this, view] { RenderMiscPanel(*view); }); + const ID id = docking::CreatePanel(*this, dockingContext, panels, name, showcase.panelMiscIcon, [this, view] { RenderMiscPanel(*view); }); panels[id].cacheSignature = [this]() -> std::optional { if (IsFileDragging()) return std::nullopt; @@ -1692,11 +1695,11 @@ namespace tachyon return id; } - void Application::FillDocument(Document& document, std::string_view main, std::string_view side) + void Application::FillDocument(docking::Document& document, std::string_view main, std::string_view side) { const ID mainID = CreateShowcasePanel(document.layout, main); const ID sideID = CreateShowcasePanel(document.layout, side); - document.layout.root = MakeSplit(DockSplitMode::RightPinned, 420, MakeLeaf({ mainID }), MakeLeaf({ sideID })); + document.layout.root = docking::MakeSplit(docking::DockSplitMode::RightPinned, 420, docking::MakeLeaf({ mainID }), docking::MakeLeaf({ sideID })); } namespace @@ -1720,7 +1723,7 @@ namespace tachyon void Application::AddBuiltInLayouts() { - LayoutPresets& presets = showcase.layoutPresets; + docking::LayoutPresets& presets = showcase.layoutPresets; // Every panel: the hierarchy left, the views in the middle, the tools right, the files // and the log along the bottom, which keeps its height as the window grows. presets.AddBuiltIn("Everything", @@ -1747,19 +1750,19 @@ namespace tachyon presets.SetForFileType(".mat", "Graph"); } - bool Application::ApplyLayoutPreset(Document& document, std::string_view name) + bool Application::ApplyLayoutPreset(docking::Document& document, std::string_view name) { - const LayoutPreset* preset = showcase.layoutPresets.Find(name); + const docking::LayoutPreset* preset = showcase.layoutPresets.Find(name); if (!preset) return false; - DockingLayout& layout = document.layout; - if (!ApplyDockLayout(layout, preset->tree, [this, &layout](std::string_view key) -> std::optional { + docking::DockingLayout& layout = document.layout; + if (!docking::ApplyDockLayout(*this, dockingContext, layout, preset->tree, [this, &layout](std::string_view key) -> std::optional { return CreateShowcasePanel(layout, key); })) return false; return true; } - Document* Application::FindShowcaseDocument(ID id) + docking::Document* Application::FindShowcaseDocument(ID id) { if (id == ID::Invalid()) return nullptr; @@ -1774,21 +1777,21 @@ namespace tachyon void Application::ApplyPendingLayout() { const ID id = std::exchange(showcase.pendingLayoutDocument, ID::Invalid()); - if (Document* document = FindShowcaseDocument(id); document && !ApplyLayoutPreset(*document, showcase.pendingLayoutName)) + if (docking::Document* document = FindShowcaseDocument(id); document && !ApplyLayoutPreset(*document, showcase.pendingLayoutName)) TACHYON_LOG_WARNING(kLogShowcase, "Layout \"{}\" not applied", showcase.pendingLayoutName); } - void Application::RenderLayoutMenu(DocumentSet& documents) + void Application::RenderLayoutMenu(docking::DocumentSet& documents) { - Document* const document = documents.Active(); + docking::Document* const document = documents.Active(); if (!document) return; - LayoutPresets& presets = showcase.layoutPresets; + docking::LayoutPresets& presets = showcase.layoutPresets; const ID documentID = document->id; if (BeginDropdownMenu(idManager.AllocateDynamicID("layoutMenu"), { showcase.layoutsIcon, "Layouts" })) { // Picked here, given before the documents are built next frame. - for (const LayoutPreset& preset : presets.All()) + for (const docking::LayoutPreset& preset : presets.All()) MenuItem(preset.name, [this, documentID, name = preset.name] { showcase.pendingLayoutDocument = documentID; showcase.pendingLayoutName = name; @@ -1800,11 +1803,11 @@ namespace tachyon showcase.layoutNameInput.clear(); }); - const bool anySaved = std::any_of(presets.All().begin(), presets.All().end(), [](const LayoutPreset& p) { return !p.builtIn; }); + const bool anySaved = std::any_of(presets.All().begin(), presets.All().end(), [](const docking::LayoutPreset& p) { return !p.builtIn; }); if (!anySaved) BeginDisabled(); if (BeginMenu(idManager.AllocateDynamicID("layoutMenuDelete"), "Delete layout")) { - for (const LayoutPreset& preset : presets.All()) + for (const docking::LayoutPreset& preset : presets.All()) if (!preset.builtIn) DestructiveMenuItem({ theme.deleteIcon, preset.name }, [this, name = preset.name] { (void)showcase.layoutPresets.Remove(name); @@ -1816,9 +1819,9 @@ namespace tachyon EndMenu(); } - void Application::AskLayoutName(DocumentSet& documents) + void Application::AskLayoutName(docking::DocumentSet& documents) { - Document* const document = FindShowcaseDocument(showcase.namingLayoutDocument); + docking::Document* const document = FindShowcaseDocument(showcase.namingLayoutDocument); if (!document) { showcase.namingLayoutDocument = ID::Invalid(); @@ -1830,7 +1833,7 @@ namespace tachyon std::string name = showcase.layoutNameInput; while (!name.empty() && name.back() == ' ') name.pop_back(); while (!name.empty() && name.front() == ' ') name.erase(name.begin()); - const LayoutPreset* existing = showcase.layoutPresets.Find(name); + const docking::LayoutPreset* existing = showcase.layoutPresets.Find(name); const std::string_view message = existing && existing->builtIn ? "A built-in layout has that name. Built-in layouts can't be replaced." : existing ? "It replaces the saved layout of that name." : "Saved layouts can be picked for any document."; @@ -1841,14 +1844,14 @@ namespace tachyon const int choice = dialogs::MessageDialog(*this, dialogContext, showcase.layoutNameDialogID, dialogs::MessageDialogDesc{ .icon = dialogs::MessageIcon::Question, .title = "Save this layout as?", .message = message, .buttons = kButtons, .defaultButton = 1, .cancelButton = 0, .input = &showcase.layoutNameInput }); - if (choice == 1 && !showcase.layoutPresets.Save(name, SaveDockLayout(document->layout))) + if (choice == 1 && !showcase.layoutPresets.Save(name, docking::SaveDockLayout(document->layout))) dialogs::ShowToast(*this, dialogContext, dialogs::ToastDesc{ .severity = dialogs::Severity::Warning, .title = "Layout not saved", .body = name.empty() ? std::string("It needs a name.") : std::format("\"{}\" is a built-in layout.", name) }); if (choice >= 0) showcase.namingLayoutDocument = ID::Invalid(); } - DocumentSet& Application::DocumentsOfWindow(ID windowID) + docking::DocumentSet& Application::DocumentsOfWindow(ID windowID) { for (const auto& window : showcase.documentWindows) if (window->windowID == windowID) @@ -1858,7 +1861,7 @@ namespace tachyon return showcase.documents; } - void Application::OpenFileAsDocument(DocumentSet& set, std::string_view fileName, IconID icon) + void Application::OpenFileAsDocument(docking::DocumentSet& set, std::string_view fileName, IconID icon) { const size_t dot = fileName.rfind('.'); const std::string name(fileName.substr(0, dot == 0 ? fileName.size() : dot)); @@ -1876,24 +1879,24 @@ namespace tachyon : extension == ".prefab" ? "prefab" : extension == ".anim" ? "animation" : ""; - Document& document = CreateShowcaseDocument(set, name, extension, kind); + docking::Document& document = CreateShowcaseDocument(set, name, extension, kind); if (kind.empty() && icon != IconID::Invalid) document.icon = icon; document.dirty = false; set.active = int(set.documents.size()) - 1; } - Document& Application::CreateShowcaseDocument(DocumentSet& set, std::string name, std::string extension, std::string kind) + docking::Document& Application::CreateShowcaseDocument(docking::DocumentSet& set, std::string name, std::string extension, std::string kind) { const IconID icon = kind == "material" ? showcase.documentMaterialIcon : kind == "layout" ? showcase.documentLayoutIcon : kind == "prefab" ? showcase.documentPrefabIcon : kind == "animation" ? showcase.documentAnimationIcon : showcase.documentLevelIcon; - Document& document = CreateDocument(set, name, std::move(extension), std::move(kind), icon); + docking::Document& document = docking::CreateDocument(*this, dockingContext, set, name, std::move(extension), std::move(kind), icon); // Each sample document has its own panels, or its file type's layout; one made with "+" a // viewport and an inspector. - const LayoutPreset* forType = showcase.layoutPresets.ForFileType(document.extension); + const docking::LayoutPreset* forType = showcase.layoutPresets.ForFileType(document.extension); if (name == "Forest") (void)ApplyLayoutPreset(document, "Everything"); else if (forType && ApplyLayoutPreset(document, forType->name)) {} else if (name == "Terrain") FillDocument(document, "NodeView", "Inspector"); @@ -1909,10 +1912,10 @@ namespace tachyon { // As they were when the showcase was last closed: each window with its documents, the // first in the main window. Else the samples. - std::vector saved = TakeSavedDocuments("documents"); + std::vector saved = docking::TakeSavedDocuments(dockingContext, "documents"); for (size_t w = 0; w < saved.size(); ++w) { - DocumentSet* set = &showcase.documents; + docking::DocumentSet* set = &showcase.documents; if (w > 0) { auto window = std::make_unique(); @@ -1921,18 +1924,18 @@ namespace tachyon // Its saved place, else a little in from the main window's corner. window->positioned = saved[w].rect.w > 0 && saved[w].rect.h > 0; window->spawnPosition = int2{ styleManager.Px(120), styleManager.Px(120) }; - RestoreWindowPlace(window->windowID, saved[w]); + docking::RestoreWindowPlace(*this, window->windowID, saved[w]); SetUpDocuments(window->documents); set = &window->documents; showcase.documentWindows.push_back(std::move(window)); } - for (const SavedDocument& document : saved[w].documents) + for (const docking::SavedDocument& document : saved[w].documents) { // A panel it was saved with that its kind's layout hasn't (a second Viewport, // say) is made again. - Document& made = CreateShowcaseDocument(*set, document.name, document.extension, document.kind); - DockingLayout& layout = made.layout; - (void)RestoreDocumentLayout(made, document, [this, &layout](std::string_view key) -> std::optional { + docking::Document& made = CreateShowcaseDocument(*set, document.name, document.extension, document.kind); + docking::DockingLayout& layout = made.layout; + (void)docking::RestoreDocumentLayout(*this, dockingContext, made, document, [this, &layout](std::string_view key) -> std::optional { return CreateShowcasePanel(layout, key); }); if (document.name.starts_with("Untitled ")) showcase.untitledCount = std::max(showcase.untitledCount, std::atoi(document.name.c_str() + 9)); @@ -1950,7 +1953,7 @@ namespace tachyon } // --panel and --float: in the Forest document, where it is. - Document* forest = nullptr; + docking::Document* forest = nullptr; for (const auto& document : showcase.documents.documents) if (document->name == "Forest") forest = document.get(); for (const auto& window : showcase.documentWindows) @@ -1958,10 +1961,10 @@ namespace tachyon if (document->name == "Forest") forest = document.get(); if (!forest) return; - DockingLayout& dock = forest->layout; + docking::DockingLayout& dock = forest->layout; // --panel: bring that panel to the front of its tab group. - auto selectStartPanel = [this, &dock](auto& self, DockNode* node) -> void { + auto selectStartPanel = [this, &dock](auto& self, docking::DockNode* node) -> void { if (!node) return; for (size_t t = 0; t < node->panelIds.size(); ++t) { @@ -1982,7 +1985,7 @@ namespace tachyon for (const auto& [id, panel] : dock.panels) if (panel.title == title) { - (void)FloatPanel(dock, id, floatAt); + (void)docking::FloatPanel(*this, dockingContext, dock, id, floatAt); floatAt += int2{ styleManager.Px(40), styleManager.Px(40) }; break; } @@ -2032,29 +2035,29 @@ namespace tachyon RequestRedrawIn(0.2f); // the next percent, while it uploads } - void Application::SetUpDocuments(DocumentSet& documents) + void Application::SetUpDocuments(docking::DocumentSet& documents) { - DocumentSet* const set = &documents; + docking::DocumentSet* const set = &documents; // A tab group's "+": every kind of panel, added as a tab there. - documents.newTabMenu = [this](DockingLayout& layout, ID leafNodeID) { + documents.newTabMenu = [this](docking::DockingLayout& layout, ID leafNodeID) { static constexpr std::string_view kPanels[] = { "Hierarchy", "Inspector", "Viewport", "NodeView", "StateMachine", "Files", "Log", "Timeline", "Curves", "Profiler", "Settings", "Build", "Table", "TreeTable", "FrozenTable", "Reorderable", "Sketch", "BoxTest", "Misc" }; for (const std::string_view title : kPanels) MenuItem(title, [this, &layout, leafNodeID, title] { - (void)AddPanelToLeaf(layout.root.get(), leafNodeID, CreateShowcasePanel(layout, title)); + (void)docking::AddPanelToLeaf(layout.root.get(), leafNodeID, CreateShowcasePanel(layout, title)); }); }; documents.onNew = [this, set] { - Document& created = CreateDocument(*set, std::format("Untitled {}", ++showcase.untitledCount), + docking::Document& created = docking::CreateDocument(*this, dockingContext, *set, std::format("Untitled {}", ++showcase.untitledCount), ".level", "level", showcase.documentLevelIcon); - const LayoutPreset* forType = showcase.layoutPresets.ForFileType(created.extension); + const docking::LayoutPreset* forType = showcase.layoutPresets.ForFileType(created.extension); if (!forType || !ApplyLayoutPreset(created, forType->name)) FillDocument(created, "Viewport", "Inspector"); set->active = int(set->documents.size()) - 1; }; // An unsaved document asks first; the dialog closes it (AskBeforeClosingDocument). - documents.onClose = [this, set](Document& document) { + documents.onClose = [this, set](docking::Document& document) { if (!document.dirty) return true; showcase.closingDocument = &document; @@ -2063,7 +2066,7 @@ namespace tachyon }; // Dropped off every bar: a main window of its own, its top left a little up and left // of where the tab was dropped, so the tab lands near the cursor. - documents.onTearOff = [this](std::unique_ptr document, int2 at) { + documents.onTearOff = [this](std::unique_ptr document, int2 at) { auto window = std::make_unique(); window->windowID = idManager.CreateStaticID(); window->documentsID = idManager.CreateStaticID(); @@ -2084,7 +2087,7 @@ namespace tachyon bool open = !window.documents.documents.empty(); if (open) { - const Document* document = window.documents.Active(); + const docking::Document* document = window.documents.Active(); const std::string title = document ? document->name + document->extension + " - Test" : std::string("Test"); auto constraints = LayoutOverride::FixedSize(1200, 760); if (!window.positioned) @@ -2112,9 +2115,9 @@ namespace tachyon TellOpenFailed(window.windowID); AskBeforeDeleting(window.windowID); AskLayoutName(window.documents); - DocumentPanels(window.documents); + docking::DocumentPanels(*this, dockingContext, window.documents); RenderStatusBar(); - EmitFloatingDockWindows(window.documents); + docking::EmitFloatingDockWindows(*this, dockingContext, window.documents); if (!showcase.mainWindowOpen) dialogs::Toasts(*this, dialogContext); // in the first document window while the main one is closed } @@ -2125,7 +2128,7 @@ namespace tachyon ++i; continue; } - DocumentSet* target = showcase.mainWindowOpen ? &showcase.documents : nullptr; + docking::DocumentSet* target = showcase.mainWindowOpen ? &showcase.documents : nullptr; for (size_t j = 0; j < showcase.documentWindows.size() && !target; ++j) if (j != i) target = &showcase.documentWindows[j]->documents; while (!window.documents.documents.empty()) @@ -2136,7 +2139,7 @@ namespace tachyon window.documents.documents.erase(window.documents.documents.begin()); } else - CloseDocument(window.documents, 0); + docking::CloseDocument(*this, dockingContext, window.documents, 0); } idManager.ReleaseStaticID(window.windowID); idManager.ReleaseStaticID(window.documentsID); @@ -2146,10 +2149,10 @@ namespace tachyon void Application::AskBeforeReloading(ID window) { - Document* const document = showcase.reloadDocument; + docking::Document* const document = showcase.reloadDocument; if (document == nullptr || window != showcase.reloadWindow) return; - const std::vector unsaved = UnsavedDocuments(); + const std::vector unsaved = UnsavedDocuments(); if (std::find(unsaved.begin(), unsaved.end(), document) == unsaved.end()) { showcase.reloadDocument = nullptr; // closed or saved meanwhile @@ -2193,9 +2196,9 @@ namespace tachyon showcase.openErrorFile.clear(); } - void Application::AskBeforeClosingDocument(DocumentSet& set) + void Application::AskBeforeClosingDocument(docking::DocumentSet& set) { - Document* const document = showcase.closingDocument; + docking::Document* const document = showcase.closingDocument; if (!document || showcase.closingSet != &set) return; auto& documents = set.documents; @@ -2217,7 +2220,7 @@ namespace tachyon if (choice == 2) SaveShowcaseDocument(*document); if (choice == 0 || choice == 2) - CloseDocument(set, int(it - documents.begin())); + docking::CloseDocument(*this, dockingContext, set, int(it - documents.begin())); if (choice >= 0) showcase.closingDocument = nullptr; } @@ -2378,7 +2381,7 @@ namespace tachyon if (showcase.mainWindowOpen) { // The window's title names the active document. - const Document* document = showcase.documents.Active(); + const docking::Document* document = showcase.documents.Active(); const std::string windowTitle = document ? document->name + document->extension + " - Test" : std::string("Test"); if (BeginWindow(showcase.windowLayoutID2, windowTitle, theme.mainWindowStyleRef, std::move(sizeConstraints.Centered()), ElementFlags::WindowUserControlled | ElementFlags::WindowIsCentered | ElementFlags::WindowCustomTitleBar @@ -2401,14 +2404,14 @@ namespace tachyon TellOpenFailed(showcase.windowLayoutID2); AskBeforeDeleting(showcase.windowLayoutID2); AskLayoutName(showcase.documents); - DocumentPanels(showcase.documents); + docking::DocumentPanels(*this, dockingContext, showcase.documents); RenderStatusBar(); // Must be emitted inside the main window's scope so main becomes // their OS owner; otherwise SDL's hidden helper owns them and they // die when it is torn down. The other windows emit their documents' own. - EmitFloatingDockWindows(showcase.documents); + docking::EmitFloatingDockWindows(*this, dockingContext, showcase.documents); EmitViewportFloatingToolbars(); UpdateDemoToasts(); dialogs::Toasts(*this, dialogContext); diff --git a/examples/showcase/application.h b/examples/showcase/application.h index 00ca102a..d1af5bbd 100644 --- a/examples/showcase/application.h +++ b/examples/showcase/application.h @@ -9,6 +9,7 @@ #include #include #include +#include #include "scene.h" #if TACHYON_VULKAN || TACHYON_D3D12 || TACHYON_SDLGPU || TACHYON_METAL @@ -91,7 +92,7 @@ namespace tachyon { ID windowID = ID::Invalid(); ID documentsID = ID::Invalid(); - DocumentSet documents; + docking::DocumentSet documents; int2 spawnPosition {}; // screen pixels, used on the first frame only bool positioned = false; // once true, the OS manages the position }; @@ -480,7 +481,7 @@ namespace tachyon bool exitRequested = false; // Exit with unsaved documents, or with work running: asking ID exitWindow = ID::Invalid(); // the window asking ID exitDialogID = ID::Invalid(); - std::unordered_map exitSave; // the unsaved documents: saved on Save all, checked + std::unordered_map exitSave; // the unsaved documents: saved on Save all, checked bool quitDontAsk = false; // quitting with work running doesn't ask again bool exitForTasks = false; // captures: the question about the work running, though documents are unsaved // Deleting several hierarchy objects: asking, about these, in that panel. @@ -496,7 +497,7 @@ namespace tachyon std::string openErrorDetails; ID openErrorWindow = ID::Invalid(); ID reloadDialogID = ID::Invalid(); - Document* reloadDocument = nullptr; + docking::Document* reloadDocument = nullptr; ID reloadWindow = ID::Invalid(); // Values bound by the node properties' renderBody lambdas. @@ -684,9 +685,9 @@ namespace tachyon // Documents, each with its own panels; the first holds the full DockingContainer demo ID documentsID { ID::Invalid() }; - DocumentSet documents; - Document* closingDocument = nullptr; // asked about its unsaved changes - DocumentSet* closingSet = nullptr; // the set it's in + docking::DocumentSet documents; + docking::Document* closingDocument = nullptr; // asked about its unsaved changes + docking::DocumentSet* closingSet = nullptr; // the set it's in std::vector> documentWindows; // documents dragged out bool mainWindowOpen = true; dialogs::ToastID uploadToast = 0; // the demo upload, its progress moving @@ -703,7 +704,7 @@ namespace tachyon // The title bar's layout picker: the built-in layouts, the saved ones, and the file // types' ones (kept in the saved UI state). - LayoutPresets layoutPresets; + docking::LayoutPresets layoutPresets; ID pendingLayoutDocument { ID::Invalid() }; // given pendingLayoutName next frame std::string pendingLayoutName; ID namingLayoutDocument { ID::Invalid() }; // "Save layout as...": asking for a name @@ -757,6 +758,8 @@ namespace tachyon views::Context viewsContext; /// The node views' state. nodes::Context nodesContext; + /// Docking's state: the panels' floating windows, tab and document drags. + docking::Context dockingContext; /// The curves' state: curve fields, the curve editor, plots. curves::Context curvesContext; /// The app-level controls' state: the timeline and the viewport. @@ -765,7 +768,7 @@ namespace tachyon private: // Settings pages (panel_settings.cpp). InitSettingsPages() runs once after // icon registration. Appearance mutates global state (theme, font scale). - ID CreateSettingsPanel(std::unordered_map& panels, std::string title); + ID CreateSettingsPanel(std::unordered_map& panels, std::string title); /// A Settings panel's pages, with static IDs of its own. void InitSettingsPages(SettingsView& view); void RenderSettingsAppearance(SettingsView& view); @@ -823,12 +826,12 @@ namespace tachyon /// Deletes `nodes` from `panel`'s tree; several, it asks first (unless told not to this session). void RequestHierarchyDelete(HierarchyPanel& panel, std::vector nodes); void AskBeforeDeleting(ID window); - ID CreateNodeGraphPanel(std::unordered_map& panels, std::string title); + ID CreateNodeGraphPanel(std::unordered_map& panels, std::string title); void RenderNodeViewPanel(NodeGraphPanel& panel); /// A nodes::NodeView panel's view of the graph: its menus, what its selection shows, its shortcuts. void SetUpNodeGraphView(nodes::NodeViewState& view); /// The StateMachine panel: the enemy's machine, or Combat's once opened; Step and Restart. - ID CreateStateMachinePanel(std::unordered_map& panels, std::string title); + ID CreateStateMachinePanel(std::unordered_map& panels, std::string title); void RenderStateMachinePanel(StateMachinePanel& panel); void SeedStateMachines(); /// Removes the machine's selected states (in `view`), their transitions with them, and @@ -899,26 +902,26 @@ namespace tachyon /// The title bar of `window`, with the tabs of `documents` (their bar is `documentsID`), /// and under it the menus for the active document; `withSearch` adds the command search /// (one window has it). - void RenderMainMenu(ID window, ID documentsID, DocumentSet& documents, bool withSearch = true); + void RenderMainMenu(ID window, ID documentsID, docking::DocumentSet& documents, bool withSearch = true); /// The title bar's layout picker for the active document of `documents`. - void RenderLayoutMenu(DocumentSet& documents); + void RenderLayoutMenu(docking::DocumentSet& documents); /// While "Save layout as..." waits, in the window asking: the name to save it as. - void AskLayoutName(DocumentSet& documents); + void AskLayoutName(docking::DocumentSet& documents); /// The layouts a document can be given; the file types' ones are set here, and may be /// changed by the saved UI state. void AddBuiltInLayouts(); /// Gives a document the layout of that name, making the panels it lacks. False when /// there's none of that name or it can't be applied. - bool ApplyLayoutPreset(Document& document, std::string_view name); + bool ApplyLayoutPreset(docking::Document& document, std::string_view name); /// The layout picked last frame, given to its document before the documents are built. void ApplyPendingLayout(); /// The document with that ID, in any window; null when it's gone. - Document* FindShowcaseDocument(ID id); + docking::Document* FindShowcaseDocument(ID id); /// The documents of the main window `windowID` is; the first open one's for another. - DocumentSet& DocumentsOfWindow(ID windowID); + docking::DocumentSet& DocumentsOfWindow(ID windowID); /// A file opened in `set` as a document (its type's layout, if it has one), or brought to /// the front when it's open already; `icon` for a type the showcase has none for. - void OpenFileAsDocument(DocumentSet& set, std::string_view fileName, IconID icon); + void OpenFileAsDocument(docking::DocumentSet& set, std::string_view fileName, IconID icon); /// State on the left, the active document in `documents`, frame time on the right. void RenderStatusBar(); /// The frame timings the status bar and the Profiler show, and whether they take new @@ -939,27 +942,27 @@ namespace tachyon void AskBeforeReloading(ID window); void TellOpenFailed(ID window); /// The documents with unsaved changes, in every window. - std::vector UnsavedDocuments(); + std::vector UnsavedDocuments(); /// Saves a document (the showcase only marks it saved). - void SaveShowcaseDocument(Document& document); + void SaveShowcaseDocument(docking::Document& document); /// A panel the showcase knows by its title ("Viewport", "Inspector", ...), added to /// `layout`. A change made in it rebuilds the other panels showing the same data. - ID CreateShowcasePanel(DockingLayout& layout, std::string_view title); + ID CreateShowcasePanel(docking::DockingLayout& layout, std::string_view title); /// Help > Show Notifications: a toast of each kind. void ShowDemoToasts(); /// Moves the demo upload's progress bar along. void UpdateDemoToasts(); /// A document of `kind` with its panels (the samples by name), added to `set`. - Document& CreateShowcaseDocument(DocumentSet& set, std::string name, std::string extension, std::string kind); + docking::Document& CreateShowcaseDocument(docking::DocumentSet& set, std::string name, std::string extension, std::string kind); /// On the first frame: the documents as they were saved, else the samples. void MakeShowcaseDocuments(); /// A document's panels: `main`, and `side` docked to its right. - void FillDocument(Document& document, std::string_view main, std::string_view side); + void FillDocument(docking::Document& document, std::string_view main, std::string_view side); /// While an unsaved document of `set` waits to close: asks whether to save or discard its changes. - void AskBeforeClosingDocument(DocumentSet& set); + void AskBeforeClosingDocument(docking::DocumentSet& set); /// A set's "+", its unsaved-changes question and its tear-off into a window of its own. - void SetUpDocuments(DocumentSet& documents); + void SetUpDocuments(docking::DocumentSet& documents); /// The windows documents were dragged out to, each with the main window's chrome. void RenderDocumentWindows(); /// `window` into `fullscreen` (Fullscreen or ExclusiveFullscreen), or out of fullscreen when in it. @@ -968,17 +971,17 @@ namespace tachyon ID FullscreenTarget() const; /// The panels with data of their own, each made with its own (and added to `panels`). - ID CreateFilesPanel(std::unordered_map& panels, std::string title); - ID CreateHierarchyPanel(std::unordered_map& panels, std::string title); - ID CreateInspectorPanel(std::unordered_map& panels, std::string title); - ID CreateLogPanel(std::unordered_map& panels, std::string title); - ID CreateViewportPanel(std::unordered_map& panels, std::string title); - ID CreateTablePanel(std::unordered_map& panels, std::string title); - ID CreateFrozenTablePanel(std::unordered_map& panels, std::string title); - ID CreateTreeTablePanel(std::unordered_map& panels, std::string title); - ID CreateSketchPanel(std::unordered_map& panels, std::string title); - ID CreateProfilerPanel(std::unordered_map& panels, std::string title); - ID CreateReorderablePanel(std::unordered_map& panels, std::string title); + ID CreateFilesPanel(std::unordered_map& panels, std::string title); + ID CreateHierarchyPanel(std::unordered_map& panels, std::string title); + ID CreateInspectorPanel(std::unordered_map& panels, std::string title); + ID CreateLogPanel(std::unordered_map& panels, std::string title); + ID CreateViewportPanel(std::unordered_map& panels, std::string title); + ID CreateTablePanel(std::unordered_map& panels, std::string title); + ID CreateFrozenTablePanel(std::unordered_map& panels, std::string title); + ID CreateTreeTablePanel(std::unordered_map& panels, std::string title); + ID CreateSketchPanel(std::unordered_map& panels, std::string title); + ID CreateProfilerPanel(std::unordered_map& panels, std::string title); + ID CreateReorderablePanel(std::unordered_map& panels, std::string title); void EnableFilesPanel(FilesPanel& panel); void DisableFilesPanel(FilesPanel& panel); @@ -1022,7 +1025,7 @@ namespace tachyon }; std::vector m_panelsOnData; /// The panel of `title`, made by its own Create...Panel. - ID MakeShowcasePanel(DockingLayout& layout, std::string_view title); + ID MakeShowcasePanel(docking::DockingLayout& layout, std::string_view title); std::vector m_startPanels; std::vector m_floatPanels; // --float: start in their own windows std::filesystem::path m_filesRoot; // --files @@ -1055,7 +1058,7 @@ namespace tachyon ID windowID = ID::Invalid(); ID areaID = ID::Invalid(); // the area the panel is in ID scrollID = ID::Invalid(); // the area paged through: the panel's that hides the most - DockingLayout layout; // holds the panel being captured + docking::DockingLayout layout; // holds the panel being captured ID panelID = ID::Invalid(); size_t theme = 0; size_t loadedTheme = size_t(-1); @@ -1068,7 +1071,7 @@ namespace tachyon ID targetID = ID::Invalid(); ID targetWindowID = ID::Invalid(); // the window it's in: the capture's, or one opened in it // A document window's documents, its own, made on first use. - DocumentSet documents; + docking::DocumentSet documents; ID documentsID = ID::Invalid(); // The States board's text fields and dropdowns, one per cell. std::vector stateTexts; diff --git a/examples/showcase/capture.cpp b/examples/showcase/capture.cpp index 88f36b4f..39bfe3b4 100644 --- a/examples/showcase/capture.cpp +++ b/examples/showcase/capture.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include @@ -388,9 +389,9 @@ namespace tachyon c.documents.active = 0; } RenderMainMenu(c.windowID, c.documentsID, c.documents, /*withSearch*/ false); - DocumentPanels(c.documents); + docking::DocumentPanels(*this, dockingContext, c.documents); RenderStatusBar(); - EmitFloatingDockWindows(c.documents); + docking::EmitFloatingDockWindows(*this, dockingContext, c.documents); } bool Application::CaptureReadPixels(IntRect& rect, std::vector& bgra) @@ -467,7 +468,7 @@ namespace tachyon } else if (which == "Reload") { - for (const std::unique_ptr& document : showcase.documents.documents) + for (const std::unique_ptr& document : showcase.documents.documents) if (document->dirty) { showcase.reloadDocument = document.get(); @@ -507,7 +508,7 @@ namespace tachyon if (shot.scene == CaptureScene::Panel && c.panelID == ID::Invalid()) { c.panelID = CreateShowcasePanel(c.layout, shot.panel); - if (Panel& panel = c.layout.panels[c.panelID]; panel.onEnable) + if (docking::Panel& panel = c.layout.panels[c.panelID]; panel.onEnable) panel.onEnable(); } if (shot.scene == CaptureScene::Main && !showcase.dockInitialized) @@ -528,12 +529,12 @@ namespace tachyon if (shot.act == CaptureAct::Dialog) CaptureOpenDialog(shot.text, c.windowID); if (shot.act == CaptureAct::Float) - if (Document* document = c.documents.Active()) + if (docking::Document* document = c.documents.Active()) for (const auto& [panelID, panel] : document->layout.panels) if (panel.title != "Viewport") { const int2 at = windowManager->GetWindowRect(c.windowID).position + int2{ styleManager.Px(700), styleManager.Px(160) }; - if (!FloatPanel(document->layout, panelID, at)) + if (!docking::FloatPanel(*this, dockingContext, document->layout, panelID, at)) TACHYON_LOG_ERROR(kLogCapture, "{}: couldn't float {}", shot.name, panel.title); break; } @@ -586,7 +587,7 @@ namespace tachyon AskBeforeDeleting(c.windowID); TellOpenFailed(c.windowID); AskBeforeReloading(c.windowID); - DocumentPanels(showcase.documents); + docking::DocumentPanels(*this, dockingContext, showcase.documents); RenderStatusBar(); if (shot.act == CaptureAct::Toasts) { @@ -596,11 +597,11 @@ namespace tachyon } else if (shot.scene == CaptureScene::Document) CaptureDocumentWindow(); - else if (BeginArea(c.areaID, theme.dockContentStyleRef, LayoutOverride{}.FlexGrow(1))) + else if (BeginArea(c.areaID, docking::GetStyles(*this, dockingContext).dockContentStyleRef, LayoutOverride{}.FlexGrow(1))) { if (shot.scene == CaptureScene::States) CaptureStatesBoard(); - else if (const Panel& panel = c.layout.panels[c.panelID]; panel.onPanelGUI) + else if (const docking::Panel& panel = c.layout.panels[c.panelID]; panel.onPanelGUI) panel.onPanelGUI(); EndArea(); } @@ -611,9 +612,9 @@ namespace tachyon auto nextShot = [&] { // A panel docked again is the tab shown where it lands: the first tabs, as before. if (shot.act == CaptureAct::Float) - if (Document* document = c.documents.Active()) + if (docking::Document* document = c.documents.Active()) { - auto first = [](auto& self, DockNode* node) -> void { + auto first = [](auto& self, docking::DockNode* node) -> void { if (node == nullptr) return; node->selectedTab = 0; self(self, node->first.get()); @@ -632,9 +633,9 @@ namespace tachyon if (c.panelID != ID::Invalid()) { // Hidden, as it was shown, by hand; then closed for good, its ID with it. - if (Panel& panel = c.layout.panels[c.panelID]; panel.onDisable) + if (docking::Panel& panel = c.layout.panels[c.panelID]; panel.onDisable) panel.onDisable(); - ClosePanel(c.layout, c.panelID); + docking::ClosePanel(*this, dockingContext, c.layout, c.panelID); c.panelID = ID::Invalid(); } c.frames = 0; diff --git a/examples/showcase/main.cpp b/examples/showcase/main.cpp index 6c89f242..20b51070 100644 --- a/examples/showcase/main.cpp +++ b/examples/showcase/main.cpp @@ -4,6 +4,7 @@ #if TACHYON_SDL #include +#include #endif #include @@ -33,7 +34,7 @@ int main(int argc, char* argv[]) // --files : the folder the Files panel shows (a copy: it's never written to); // the workdirectory without it. // --capture : saves every panel, in the dark and the light theme, as - // //.png, and quits. + // //.png, and quits. // --bench : draws every frame with the profiler on, prints each scope's mean // time per frame over frames, and quits. // --graphics : render with vulkan, d3d12, metal, sdlgpu or none (no GPU); the default backend diff --git a/examples/showcase/panel_console.cpp b/examples/showcase/panel_console.cpp index 63dfd901..fc079cba 100644 --- a/examples/showcase/panel_console.cpp +++ b/examples/showcase/panel_console.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -215,10 +216,10 @@ namespace tachyon } }; - ID Application::CreateLogPanel(std::unordered_map& panels, std::string title) + ID Application::CreateLogPanel(std::unordered_map& panels, std::string title) { auto panel = std::make_shared(); - return CreatePanel(panels, std::move(title), showcase.panelLogIcon, [this, panel] { RenderLogPanel(*panel); }, {}, + return docking::CreatePanel(*this, dockingContext, panels, std::move(title), showcase.panelLogIcon, [this, panel] { RenderLogPanel(*panel); }, {}, [this, panel] { EnableLogPanel(*panel); }); } diff --git a/examples/showcase/panel_files.cpp b/examples/showcase/panel_files.cpp index 59795f78..fc743a88 100644 --- a/examples/showcase/panel_files.cpp +++ b/examples/showcase/panel_files.cpp @@ -1,6 +1,7 @@ #include "application.h" #include #include +#include #include #include #include @@ -310,12 +311,12 @@ namespace tachyon } }; - ID Application::CreateFilesPanel(std::unordered_map& panels, std::string title) + ID Application::CreateFilesPanel(std::unordered_map& panels, std::string title) { auto panel = std::make_shared(); std::erase_if(m_filesPanels, [](const auto& p) { return p.expired(); }); // closed ones m_filesPanels.push_back(panel); - const ID id = CreatePanel(panels, std::move(title), showcase.panelFilesIcon, [this, panel] { RenderFilesPanel(*panel); }, {}, + const ID id = docking::CreatePanel(*this, dockingContext, panels, std::move(title), showcase.panelFilesIcon, [this, panel] { RenderFilesPanel(*panel); }, {}, [this, panel] { EnableFilesPanel(*panel); }, [this, panel] { DisableFilesPanel(*panel); }); // Rebuilt as an import goes on: its bar and its tile's ring show how far. panels[id].cacheSignature = [this]() -> std::optional { return ProgressLook(); }; diff --git a/examples/showcase/panel_hierarchy.cpp b/examples/showcase/panel_hierarchy.cpp index d31cbea0..8052c0a3 100644 --- a/examples/showcase/panel_hierarchy.cpp +++ b/examples/showcase/panel_hierarchy.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include #include @@ -259,11 +260,11 @@ namespace tachyon } }; - ID Application::CreateHierarchyPanel(std::unordered_map& panels, std::string title) + ID Application::CreateHierarchyPanel(std::unordered_map& panels, std::string title) { auto panel = std::make_shared(); panel->self = panel; - const ID id = CreatePanel(panels, std::move(title), showcase.panelHierarchyIcon, + const ID id = docking::CreatePanel(*this, dockingContext, panels, std::move(title), showcase.panelHierarchyIcon, [this, panel] { RenderHierarchyPanel(*panel); if (panel->treeHasFocus) focusedHierarchy = panel; diff --git a/examples/showcase/panel_inspector.cpp b/examples/showcase/panel_inspector.cpp index 562898f6..263cb473 100644 --- a/examples/showcase/panel_inspector.cpp +++ b/examples/showcase/panel_inspector.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -60,10 +61,10 @@ namespace tachyon } }; - ID Application::CreateInspectorPanel(std::unordered_map& panels, std::string title) + ID Application::CreateInspectorPanel(std::unordered_map& panels, std::string title) { auto panel = std::make_shared(idManager); - return CreatePanel(panels, std::move(title), showcase.panelInspectorIcon, [this, panel] { RenderInspectorPanel(*panel); }, {}, + return docking::CreatePanel(*this, dockingContext, panels, std::move(title), showcase.panelInspectorIcon, [this, panel] { RenderInspectorPanel(*panel); }, {}, [this, panel] { EnableInspectorPanel(*panel); }, [this, panel] { DisableInspectorPanel(*panel); }); } diff --git a/examples/showcase/panel_node_view.cpp b/examples/showcase/panel_node_view.cpp index 40a674b9..867df0b9 100644 --- a/examples/showcase/panel_node_view.cpp +++ b/examples/showcase/panel_node_view.cpp @@ -1,5 +1,6 @@ #include "application.h" #include +#include #include // AddNodeEdit, RemoveNodesEdit, GridLineNearest @@ -22,13 +23,13 @@ namespace tachyon nodes::NodeViewState view; }; - ID Application::CreateNodeGraphPanel(std::unordered_map& panels, std::string title) + ID Application::CreateNodeGraphPanel(std::unordered_map& panels, std::string title) { auto panel = std::make_shared(); SetUpNodeGraphView(panel->view); std::erase_if(m_nodeGraphPanels, [](const auto& p) { return p.expired(); }); // closed ones m_nodeGraphPanels.push_back(panel); - const ID id = CreatePanel(panels, std::move(title), showcase.panelNodeViewIcon, [this, panel] { RenderNodeViewPanel(*panel); }); + const ID id = docking::CreatePanel(*this, dockingContext, panels, std::move(title), showcase.panelNodeViewIcon, [this, panel] { RenderNodeViewPanel(*panel); }); // Its pan and zoom, kept with the layout. panels[id].saveState = [panel] { return SaveViewState(panel->view); }; panels[id].restoreState = [panel](std::string_view state) { (void)RestoreViewState(panel->view, state); }; diff --git a/examples/showcase/panel_profiler_tree.cpp b/examples/showcase/panel_profiler_tree.cpp index 57960850..45b3e978 100644 --- a/examples/showcase/panel_profiler_tree.cpp +++ b/examples/showcase/panel_profiler_tree.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -171,10 +172,10 @@ namespace tachyon } }; - ID Application::CreateProfilerPanel(std::unordered_map& panels, std::string title) + ID Application::CreateProfilerPanel(std::unordered_map& panels, std::string title) { auto panel = std::make_shared(idManager); - const ID id = CreatePanel(panels, std::move(title), showcase.panelProfilerIcon, [this, panel] { RenderProfilerTreePanel(*panel); }, {}, + const ID id = docking::CreatePanel(*this, dockingContext, panels, std::move(title), showcase.panelProfilerIcon, [this, panel] { RenderProfilerTreePanel(*panel); }, {}, [] { flameStylesInit = false; frameGraphStylesInit = false; }); panels[id].cacheSignature = []() -> std::optional { return Diagnostics::IsProfilingEnabled() ? std::nullopt : std::optional(0); }; @@ -517,7 +518,7 @@ namespace tachyon // a row; it's clipped (overflow:hidden), not scaled. Auto-size fits its rows again. tachyon::Element flameSizer{}; flameSizer.id = p.flameSizerID; - flameSizer.styleRef = theme.dockSizerVertStyleRef; + flameSizer.styleRef = docking::GetStyles(*this, dockingContext).dockSizerVertStyleRef; flameSizer.state = guiStateManager.GetCurrentState(flameSizer.id); const int rowUnits = int(std::ceil(float(rowH) / uiScale)); // rowH is pixels; p.flameHeight CSS px flameSizer.eventHandler = tachyon::MakeVerticalSizerHandler(guiStateManager, elementStorage, p.flameHeight, diff --git a/examples/showcase/panel_reorderable.cpp b/examples/showcase/panel_reorderable.cpp index ba764cf0..09c5d8b3 100644 --- a/examples/showcase/panel_reorderable.cpp +++ b/examples/showcase/panel_reorderable.cpp @@ -1,4 +1,5 @@ #include "application.h" +#include // // This file is for testing and prototyping a reorderable panel, which can be used for things like tab bars, lists, etc. @@ -46,10 +47,10 @@ namespace tachyon } } - ID Application::CreateReorderablePanel(std::unordered_map& panels, std::string title) + ID Application::CreateReorderablePanel(std::unordered_map& panels, std::string title) { auto panel = std::make_shared(idManager); - return CreatePanel(panels, std::move(title), showcase.panelMiscIcon, [this, panel] { RenderReorderablePanel(*panel); }); + return docking::CreatePanel(*this, dockingContext, panels, std::move(title), showcase.panelMiscIcon, [this, panel] { RenderReorderablePanel(*panel); }); } void Application::RenderReorderablePanel(ReorderablePanel& panel) diff --git a/examples/showcase/panel_settings.cpp b/examples/showcase/panel_settings.cpp index fd628ce4..0c604bcc 100644 --- a/examples/showcase/panel_settings.cpp +++ b/examples/showcase/panel_settings.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -50,12 +51,12 @@ namespace tachyon view.settings.treeWidth = 160; // narrower than the default page list } - ID Application::CreateSettingsPanel(std::unordered_map& panels, std::string title) + ID Application::CreateSettingsPanel(std::unordered_map& panels, std::string title) { auto view = std::make_shared(); view->ids = &idManager; InitSettingsPages(*view); - const ID id = CreatePanel(panels, std::move(title), showcase.panelSettingsIcon, [this, view] { views::RenderSettingsPanel(*this, viewsContext, view->settings); }); + const ID id = docking::CreatePanel(*this, dockingContext, panels, std::move(title), showcase.panelSettingsIcon, [this, view] { views::RenderSettingsPanel(*this, viewsContext, view->settings); }); // The page it shows, kept with the layout. panels[id].saveState = [view] { return SaveViewState(view->settings); }; panels[id].restoreState = [view](std::string_view state) { (void)RestoreViewState(view->settings, state); }; diff --git a/examples/showcase/panel_sketch.cpp b/examples/showcase/panel_sketch.cpp index b072aeb0..718d9781 100644 --- a/examples/showcase/panel_sketch.cpp +++ b/examples/showcase/panel_sketch.cpp @@ -1,5 +1,6 @@ #include "application.h" #include +#include #include #include @@ -66,10 +67,10 @@ namespace tachyon bool eraserTool = false; // the Eraser tool picked; a pen's eraser end erases either way }; - ID Application::CreateSketchPanel(std::unordered_map& panels, std::string title) + ID Application::CreateSketchPanel(std::unordered_map& panels, std::string title) { auto panel = std::make_shared(); - const ID id = CreatePanel(panels, std::move(title), showcase.panelMiscIcon, [this, panel] { RenderSketchPanel(*panel); }); + const ID id = docking::CreatePanel(*this, dockingContext, panels, std::move(title), showcase.panelMiscIcon, [this, panel] { RenderSketchPanel(*panel); }); // The pen's readout changes with every move: never cached. panels[id].cacheSignature = []() -> std::optional { return std::nullopt; }; return id; diff --git a/examples/showcase/panel_split_scroll.cpp b/examples/showcase/panel_split_scroll.cpp index 0eba129b..cf5ce04f 100644 --- a/examples/showcase/panel_split_scroll.cpp +++ b/examples/showcase/panel_split_scroll.cpp @@ -1,5 +1,6 @@ #include "application.h" #include +#include #include #include @@ -31,7 +32,7 @@ namespace tachyon std::vector columns; }; - ID Application::CreateFrozenTablePanel(std::unordered_map& panels, std::string title) + ID Application::CreateFrozenTablePanel(std::unordered_map& panels, std::string title) { auto panel = std::make_shared(); panel->columns = @@ -88,7 +89,7 @@ namespace tachyon if (from < to) std::rotate(columns->begin() + from, columns->begin() + from + 1, columns->begin() + to + 1); else std::rotate(columns->begin() + to, columns->begin() + from, columns->begin() + from + 1); }; - return CreatePanel(panels, std::move(title), showcase.panelMiscIcon, [this, panel] { RenderSplitScrollPanel(*panel); }); + return docking::CreatePanel(*this, dockingContext, panels, std::move(title), showcase.panelMiscIcon, [this, panel] { RenderSplitScrollPanel(*panel); }); } void Application::RenderSplitScrollPanel(FrozenTablePanel& panel) diff --git a/examples/showcase/panel_state_machine.cpp b/examples/showcase/panel_state_machine.cpp index 6e84fe24..d9ab73f0 100644 --- a/examples/showcase/panel_state_machine.cpp +++ b/examples/showcase/panel_state_machine.cpp @@ -2,6 +2,7 @@ #include #include +#include #include // AddTransitionEdit, SetInitialStateEdit, ... #include @@ -117,7 +118,7 @@ namespace tachyon bool combatOpen = false; // Combat's machine is the one shown }; - ID Application::CreateStateMachinePanel(std::unordered_map& panels, std::string title) + ID Application::CreateStateMachinePanel(std::unordered_map& panels, std::string title) { if (!showcase.stateMachinesSeeded) { @@ -157,7 +158,7 @@ namespace tachyon std::erase_if(m_stateMachinePanels, [](const auto& p) { return p.expired(); }); // closed ones m_stateMachinePanels.push_back(panel); - const ID id = CreatePanel(panels, std::move(title), showcase.panelNodeViewIcon, [this, panel] { RenderStateMachinePanel(*panel); }); + const ID id = docking::CreatePanel(*this, dockingContext, panels, std::move(title), showcase.panelNodeViewIcon, [this, panel] { RenderStateMachinePanel(*panel); }); // Both machines' views, and which one is open, kept with the layout. panels[id].saveState = [panel] { JsonValue state = JsonValue::MakeObject(); diff --git a/examples/showcase/panel_table.cpp b/examples/showcase/panel_table.cpp index 9fd4d0b6..f76c1c9e 100644 --- a/examples/showcase/panel_table.cpp +++ b/examples/showcase/panel_table.cpp @@ -1,5 +1,6 @@ #include "application.h" #include +#include #include #include @@ -63,7 +64,7 @@ namespace tachyon std::vector columns; }; - ID Application::CreateTablePanel(std::unordered_map& panels, std::string title) + ID Application::CreateTablePanel(std::unordered_map& panels, std::string title) { auto panel = std::make_shared(); const auto& rows = GetDemoRows(); @@ -112,7 +113,7 @@ namespace tachyon if (from < to) std::rotate(columns->begin() + from, columns->begin() + from + 1, columns->begin() + to + 1); else std::rotate(columns->begin() + to, columns->begin() + from, columns->begin() + from + 1); }; - return CreatePanel(panels, std::move(title), showcase.panelMiscIcon, [this, panel] { RenderTablePanel(*panel); }); + return docking::CreatePanel(*this, dockingContext, panels, std::move(title), showcase.panelMiscIcon, [this, panel] { RenderTablePanel(*panel); }); } void Application::RenderTablePanel(TablePanel& panel) diff --git a/examples/showcase/panel_tree_table.cpp b/examples/showcase/panel_tree_table.cpp index 418d2688..6dcb2bed 100644 --- a/examples/showcase/panel_tree_table.cpp +++ b/examples/showcase/panel_tree_table.cpp @@ -1,6 +1,7 @@ #include "application.h" #include #include +#include #include #include @@ -57,7 +58,7 @@ namespace tachyon } }; - ID Application::CreateTreeTablePanel(std::unordered_map& panels, std::string title) + ID Application::CreateTreeTablePanel(std::unordered_map& panels, std::string title) { auto panel = std::make_shared(); TreeTablePanel* const self = panel.get(); @@ -179,7 +180,7 @@ namespace tachyon } } }; - return CreatePanel(panels, std::move(title), showcase.panelMiscIcon, [this, panel] { RenderTreeTablePanel(*panel); }); + return docking::CreatePanel(*this, dockingContext, panels, std::move(title), showcase.panelMiscIcon, [this, panel] { RenderTreeTablePanel(*panel); }); } void Application::RenderTreeTablePanel(TreeTablePanel& panel) diff --git a/examples/showcase/panel_view.cpp b/examples/showcase/panel_view.cpp index 02450406..988dcf2d 100644 --- a/examples/showcase/panel_view.cpp +++ b/examples/showcase/panel_view.cpp @@ -16,6 +16,7 @@ #endif #if TACHYON_METAL #include +#include #endif // @@ -111,7 +112,7 @@ namespace tachyon } } - ID Application::CreateViewportPanel(std::unordered_map& panels, std::string title) + ID Application::CreateViewportPanel(std::unordered_map& panels, std::string title) { SeedScene(); auto panel = std::make_shared(); @@ -165,7 +166,7 @@ namespace tachyon std::erase_if(m_viewportPanels, [](const auto& p) { return p.expired(); }); // closed ones m_viewportPanels.push_back(panel); - const ID id = CreatePanel(panels, std::move(title), showcase.panelViewportIcon, [this, panel] { RenderViewportPanel(*panel); }); + const ID id = docking::CreatePanel(*this, dockingContext, panels, std::move(title), showcase.panelViewportIcon, [this, panel] { RenderViewportPanel(*panel); }); // Built again when the scene changes, in another view too: the gizmo follows the shape. panels[id].cacheSignature = [this]() -> std::optional { uint64_t signature = uint64_t(int64_t(sceneSelected)); diff --git a/examples/tutorial/CMakeLists.txt b/examples/tutorial/CMakeLists.txt index c0a25252..88f32ca7 100644 --- a/examples/tutorial/CMakeLists.txt +++ b/examples/tutorial/CMakeLists.txt @@ -1,3 +1,3 @@ # The tutorial's app (docs/tutorial.md). The tests build my_app.cpp too, to check the # tutorial's panels behave as it says. -tachyon_add_example(my_app main.cpp my_app.cpp my_app.h) +tachyon_add_example(my_app main.cpp my_app.cpp my_app.h LIBS gui_docking) diff --git a/examples/tutorial/my_app.cpp b/examples/tutorial/my_app.cpp index a9a54021..106005cc 100644 --- a/examples/tutorial/my_app.cpp +++ b/examples/tutorial/my_app.cpp @@ -1,7 +1,10 @@ #include "my_app.h" +#include namespace my_app { + namespace docking = tachyon::docking; + void CounterPanel::Draw(tachyon::GUIApplication& ui) { // [counter] @@ -43,6 +46,7 @@ namespace my_app { if (tachyon::Result result = GUIApplication::Initialize(options); !result) return result; + docking::Install(*this, m_docking); // docking works at points of the frame OnGUI doesn't reach // The window and the dock layout keep their state between frames, so they get // IDs that stay the same: static IDs, made once. @@ -50,24 +54,32 @@ namespace my_app m_dockID = idManager.CreateStaticID(); const tachyon::IconID noIcon = tachyon::IconID::Invalid; - const tachyon::ID left = CreatePanel(m_layout.panels, "Counter", noIcon, [this] { counter.Draw(*this); }); - const tachyon::ID right = CreatePanel(m_layout.panels, "Greeting", noIcon, [this] { greeting.Draw(*this); }); - m_layout.root = tachyon::MakeSplit(tachyon::DockSplitMode::LeftPinned, 240, - tachyon::MakeLeaf({ left }), - tachyon::MakeLeaf({ right })); + const tachyon::ID left = docking::CreatePanel(*this, m_docking, m_layout.panels, "Counter", noIcon, [this] { counter.Draw(*this); }); + const tachyon::ID right = docking::CreatePanel(*this, m_docking, m_layout.panels, "Greeting", noIcon, [this] { greeting.Draw(*this); }); + m_layout.root = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 240, + docking::MakeLeaf({ left }), + docking::MakeLeaf({ right })); return {}; } // [app-initialize] + // [app-cleanup] + void MyApp::Cleanup() + { + docking::Cleanup(*this, m_docking); // the floated panels' windows, before the library's own + GUIApplication::Cleanup(); + } + // [app-cleanup] + // [app-ongui] void MyApp::OnGUI() { if (BeginWindow(m_windowID, "My app", theme.mainWindowStyleRef, tachyon::LayoutOverride::FixedSize(640, 360).Centered())) { - BeginDockingContainer(m_dockID, &m_layout, tachyon::LayoutOverride::Auto()); - EndDockingContainer(); - EmitFloatingDockWindows(); + docking::BeginDockingContainer(*this, m_docking, m_dockID, &m_layout, tachyon::LayoutOverride::Auto()); + docking::EndDockingContainer(*this, m_docking); + docking::EmitFloatingDockWindows(*this, m_docking); } EndWindow(); } diff --git a/examples/tutorial/my_app.h b/examples/tutorial/my_app.h index 1211b82c..c8f45f19 100644 --- a/examples/tutorial/my_app.h +++ b/examples/tutorial/my_app.h @@ -4,7 +4,8 @@ #pragma once #include -#include +#include +#include #include @@ -38,6 +39,7 @@ namespace my_app public: tachyon::Result Initialize(const InitializeOptions& options = {}) override; void OnGUI() override; + void Cleanup() override; CounterPanel counter; GreetingPanel greeting; @@ -45,7 +47,8 @@ namespace my_app private: tachyon::ID m_windowID = tachyon::ID::Invalid(); tachyon::ID m_dockID = tachyon::ID::Invalid(); - tachyon::DockingLayout m_layout; + tachyon::docking::DockingLayout m_layout; + tachyon::docking::Context m_docking; // docking's state: the panels' windows, drags }; // [app] } diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 5fce3c03..f7073b93 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -476,7 +476,6 @@ list(APPEND GUI_CONTROLS_FILES gui_controls/gui_application.cpp gui_controls/gui_content.h gui_controls/gui_widget_state_types.h - gui_controls/gui_docking_types.h gui_controls/gui_menu_manager.h gui_controls/gui_menu_manager.cpp @@ -497,8 +496,6 @@ list(APPEND GUI_CONTROLS_FILES gui_controls/subsystems/gui_ui_cache_subsystem.h gui_controls/subsystems/gui_ui_cache_subsystem.cpp - gui_controls/gui_dock_node.h - gui_controls/gui_dock_node.cpp gui_controls/gui_theme.h @@ -529,12 +526,9 @@ list(APPEND GUI_CONTROLS_FILES gui_controls/controls_reorderable.cpp gui_controls/controls_scrollbar.cpp gui_controls/controls_tabs.cpp - gui_controls/controls_documents.cpp - gui_controls/controls_docking.cpp gui_controls/gui_ui_state.cpp - gui_controls/gui_layout_presets.h - gui_controls/gui_layout_presets.cpp gui_controls/controls_toolbar_dock.h + gui_controls/gui_tab_types.h gui_controls/controls_toolbar_dock.cpp ) @@ -626,6 +620,25 @@ add_library(TachyonUI::gui_nodes ALIAS gui_nodes) source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR}/.. FILES ${GUI_NODES_FILES}) target_link_libraries(gui_nodes PUBLIC gui_controls) +# Docking: docked and floating panels, documents and layout presets. An extension on +# gui_controls; it hooks into the frame (GUIApplication::OnFrameStage). +set(GUI_DOCKING_FILES + gui_docking/gui_docking.h + gui_docking/gui_docking.cpp + gui_docking/gui_docking_internal.h + gui_docking/gui_docking_types.h + gui_docking/gui_dock_node.h + gui_docking/gui_dock_node.cpp + gui_docking/gui_layout_presets.h + gui_docking/gui_layout_presets.cpp + gui_docking/gui_docking_state.cpp + gui_docking/controls_docking.cpp + gui_docking/controls_documents.cpp) +add_library(gui_docking STATIC ${GUI_DOCKING_FILES}) +add_library(TachyonUI::gui_docking ALIAS gui_docking) +source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR}/.. FILES ${GUI_DOCKING_FILES}) +target_link_libraries(gui_docking PUBLIC gui_controls) + # Where GUIApplication::SetResourceRoot finds the resources in this build; the # installed package defines it for its own folder. target_compile_definitions(gui_controls INTERFACE @@ -646,9 +659,10 @@ tachyon_apply_compile_options(gui_curves) tachyon_apply_compile_options(gui_color) tachyon_apply_compile_options(gui_views) tachyon_apply_compile_options(gui_nodes) +tachyon_apply_compile_options(gui_docking) tachyon_precompile_headers(gui_core ) tachyon_precompile_headers(gui_controls ) -set_target_properties(gui_core gui_controls gui_dialogs gui_curves gui_color gui_views gui_nodes PROPERTIES FOLDER "Core") +set_target_properties(gui_core gui_controls gui_dialogs gui_curves gui_color gui_views gui_nodes gui_docking PROPERTIES FOLDER "Core") # For the install rules and the package. set(TACHYON_BACKEND_TARGETS ${TACHYON_BACKEND_TARGETS} PARENT_SCOPE) diff --git a/src/gui_controls/controls.cpp b/src/gui_controls/controls.cpp index bfb591a8..6fc42aad 100644 --- a/src/gui_controls/controls.cpp +++ b/src/gui_controls/controls.cpp @@ -1358,13 +1358,6 @@ namespace tachyon } } - void GUIApplication::InvalidatePanel(ID panelId) - { - if (const ID* contentID = m_panelContentIDs.Find(panelId)) - Invalidate(*contentID); - } - - // --------------------------------------------------------------------------- // Horizontal / Vertical flex containers (BeginArea with a direction/wrap style) // --------------------------------------------------------------------------- diff --git a/src/gui_controls/controls_toolbar_dock.cpp b/src/gui_controls/controls_toolbar_dock.cpp index 0d4b8eb7..a3a2b206 100644 --- a/src/gui_controls/controls_toolbar_dock.cpp +++ b/src/gui_controls/controls_toolbar_dock.cpp @@ -318,7 +318,7 @@ namespace tachyon } } - // One OS window per floating toolbar (like EmitFloatingDockWindows). Closing it + // One OS window per floating toolbar (like docking's floating panel windows). Closing it // docks the item back on its home side through onDockBack (without one, the // entry is erased and its windowID released). void GUIApplication::EmitFloatingToolbarWindows( @@ -492,7 +492,7 @@ namespace tachyon } } - // Runs from EndDockingFrame, after layout: caches side rects for next frame's drag hit-tests. + // Runs after the frame's input, after layout: caches side rects for next frame's drag hit-tests. void GUIApplication::SyncToolbarDockRects() { for (ToolbarDockState* state : m_toolbarDocksThisFrame) diff --git a/src/gui_controls/gui_application.cpp b/src/gui_controls/gui_application.cpp index 862f3572..5dfd8283 100644 --- a/src/gui_controls/gui_application.cpp +++ b/src/gui_controls/gui_application.cpp @@ -245,7 +245,6 @@ namespace tachyon m_labelGroup = std::make_unique(m_frame, elementStorage, guiStateManager, theme); m_buttonGroup = std::make_unique(m_frame, elementStorage, styleManager); m_reorderable = std::make_unique(m_frame); - m_dockTabDragSub = std::make_unique(); m_uiCache = std::make_unique(m_frame, elementStorage, guiStateManager); RegisterFrameBalanceChecks(); @@ -301,7 +300,6 @@ namespace tachyon { m_menuRects->EndFrame(); m_sliderFieldTrack->EndFrame(); - m_panelContentIDs.EndFrame(); m_titleBars.EndFrame(); // A popup window of state that went is closed now and its ID given back later, once @@ -316,6 +314,13 @@ namespace tachyon m_autocomplete.EndFrame([&](ID, AutocompleteState& state) { RetireWindow(state.listWindowID); return true; }); } + void GUIApplication::RunStage(FrameStage stage, FrameContext& ctx) + { + m_frame.RunStage(stage, ctx); + for (const auto& hook : m_stageHooks[size_t(stage)]) + hook(); + } + void GUIApplication::ReportMisuse(const char* message) { Diagnostics::ReportMisuse(kLogApp, message); } // A container left open at the end of the frame is reported and closed, and the next @@ -358,11 +363,6 @@ namespace tachyon Diagnostics::ReportMisuse(kLogApp, "GUIApplication: unbalanced BeginTabBar/EndTabBar at end of frame (closed)"); m_tabBarState = {}; } - if (m_dockingState.containerID != ID::Invalid()) - { - Diagnostics::ReportMisuse(kLogApp, "GUIApplication: unbalanced BeginDockingContainer/EndDockingContainer at end of frame (closed)"); - m_dockingState = {}; - } if (!menuManager.IsBalanced()) { Diagnostics::ReportMisuse(kLogApp, "GUIApplication: unbalanced BeginMenu/EndMenu at end of frame (closed)"); @@ -380,11 +380,6 @@ namespace tachyon void GUIApplication::ReleaseOwnIDs() { - // Torn-off windows: their panels are hidden and destroyed with them, and their IDs and - // trees' go back. - while (!m_floatingDockWindows.empty()) - CloseFloatingDockWindow(m_floatingDockWindows.size() - 1); - auto release = [this](ID& id) { if (id != ID::Invalid() && id.GetMode() == IDMode::Static) idManager.ReleaseStaticID(id); @@ -399,7 +394,6 @@ namespace tachyon release(retired.id); m_retiredWindows.clear(); menuManager.ReleaseWindowIDs(idManager); - m_closedPanels.clear(); // what they hold goes before the graphics it may use } void GUIApplication::Cleanup() @@ -456,23 +450,6 @@ namespace tachyon return Error{ ErrorCode::ParseFailed, "could not load theme " + m_themePath }; } - void GUIApplication::CreatePanel(std::unordered_map& panels, ID id, std::string title, tachyon::IconID icon, - std::function onPanelGUI, - std::string panelType, - std::function onEnable, - std::function onDisable) - { - panels[id] = Panel{ - .id = id, - .title = std::move(title), - .icon = icon, - .panelType = std::move(panelType), - .onPanelGUI = std::move(onPanelGUI), - .onEnable = std::move(onEnable), - .onDisable = std::move(onDisable), - }; - } - void GUIApplication::InjectedFocus(ID windowID, bool press) { // Input to a window gives it the focus. A menu or picker opened from it keeps the @@ -694,10 +671,9 @@ namespace tachyon && !transitionManager.IsReducedMotion()) CaptureThemeCrossfade(); - // Tear down panel resources before their styles disappear; m_dockingLayoutsThisFrame - // still holds last frame's layouts here. EnableVisiblePanels rebuilds them next frame. - for (DockingLayout* layout : m_dockingLayoutsThisFrame) - if (layout) DisableAllPanels(*layout); + // What must go while the styles are still there (docked panels' onDisable, say). + for (const auto& hook : m_stylesClearedHooks) + hook(); styleManager.ClearAll(); m_swatchSlots.Forget(); // ClearAll freed their styles @@ -1746,7 +1722,7 @@ namespace tachyon .elapsedTimeSecs = elapsedTimeSecs, }; - m_frame.RunStage(FrameStage::PreFrame, ctx); + RunStage(FrameStage::PreFrame, ctx); ApplyPendingStyleReload(); @@ -1787,7 +1763,7 @@ namespace tachyon // Before construction: drives the active-flash window in GetCurrentState. guiStateManager.Interaction().SetFrameTime(elapsedTimeSecs); - BeginDockingFrame(); + m_toolbarDocksThisFrame.clear(); // the docks built this frame register again tabChainManager.BeginFrame(guiStateManager); menuManager.BeginFrame(guiStateManager, *windowManager); @@ -1822,7 +1798,7 @@ namespace tachyon windowRegistry.Clear(); guiStateManager.Cursor().Clear(); - m_frame.RunStage(FrameStage::PreConstruct, ctx); + RunStage(FrameStage::PreConstruct, ctx); } // *** @@ -1834,7 +1810,7 @@ namespace tachyon { TACHYON_PROFILE_SCOPE("EndFrame"); - m_frame.RunStage(FrameStage::PostConstruct, ctx); + RunStage(FrameStage::PostConstruct, ctx); ShowCutShortText(); tooltipManager.EndFrame(); @@ -1865,7 +1841,7 @@ namespace tachyon // Apply user-moved/resized OS window rects before layout. SyncWindowsBeforeLayout(*windowManager, windowRegistry, elementStorage); - m_frame.RunStage(FrameStage::PreLayout, ctx); + RunStage(FrameStage::PreLayout, ctx); layoutEngine->Layout(*windowManager, elementStorage); @@ -1879,14 +1855,14 @@ namespace tachyon entry.callback(plCtx); } - m_frame.RunStage(FrameStage::PostLayout, ctx); + RunStage(FrameStage::PostLayout, ctx); windowRegistry.BuildRenderSkipLinks(); // Create/update OS windows for layout-driven windows. SyncWindowsAfterLayout(*windowManager, windowRegistry, elementStorage, textSystem, onGui); - m_frame.RunStage(FrameStage::PreInput, ctx); + RunStage(FrameStage::PreInput, ctx); if (inputManager) inputManager->UpdatePreHover(guiStateManager); @@ -1942,26 +1918,26 @@ namespace tachyon if (const auto caret = textSystem->GetCaretScreenRect()) windowManager->SetTextInputArea(frameInput.activeWindowID, *caret); - m_frame.RunStage(FrameStage::PostInput, ctx); + RunStage(FrameStage::PostInput, ctx); - EndDockingFrame(); + SyncToolbarDockRects(); } - m_frame.RunStage(FrameStage::PreRender, ctx); + RunStage(FrameStage::PreRender, ctx); { TACHYON_PROFILE_SCOPE("OnRender"); OnRender(elapsedTimeSecs); } - m_frame.RunStage(FrameStage::PostRender, ctx); + RunStage(FrameStage::PostRender, ctx); transitionManager.Purge(elapsedTimeSecs); if (!m_crossfades.empty() && elapsedTimeSecs - m_crossfadeStart >= kThemeCrossfadeSecs) EndThemeCrossfade(); NoteFrameNeeds(elapsedTimeSecs); - m_frame.RunStage(FrameStage::EndFrame, ctx); + RunStage(FrameStage::EndFrame, ctx); idManager.EndFrame(); @@ -2153,4 +2129,101 @@ namespace tachyon m_drawnDropTargetID = target; } } -} \ No newline at end of file + + // --------------------------------------------------------------------------- + // Command modes and input dispatch + // --------------------------------------------------------------------------- + + void GUIApplication::ClaimCommandMode(ID owner, CommandMode mode) + { + if (owner == ID::Invalid() || mode == CommandMode::Default) + return; + m_commandModeClaims[owner] = { mode, m_commandModeFrame }; + } + + void GUIApplication::ApplyClaimedCommandMode() + { + // The claim the focus is in: the focused element's own, else one around it. + const InteractionState& interaction = guiStateManager.Interaction(); + const ID focused = interaction.GetFocusedID(); + std::optional mode; + for (auto it = m_commandModeClaims.begin(); it != m_commandModeClaims.end(); ) + { + const bool within = interaction.IsFocusWithin(it->first); + if (within && (!mode || it->first == focused)) + mode = it->second.mode; + // Not built this frame, and not where the focus is: gone (a closed panel's). + if (!within && it->second.frame != m_commandModeFrame) + it = m_commandModeClaims.erase(it); + else + ++it; + } + ++m_commandModeFrame; + + if (mode) + { + if (commandManager.GetMode() != *mode) + commandManager.SetMode(*mode); + m_claimedCommandMode = *mode; + } + else if (m_claimedCommandMode != CommandMode::Default) + { + // The focus left: Default again, unless the app set a mode of its own since. + if (commandManager.GetMode() == m_claimedCommandMode) + commandManager.SetMode(CommandMode::Default); + m_claimedCommandMode = CommandMode::Default; + } + } + + void GUIApplication::DispatchInput(ID overID) + { + ApplyClaimedCommandMode(); + // What the user acts on, taken before the handlers move the focus or the capture. + std::vector actedOn = ActedOnIDs(overID); + if (inputManager) + inputManager->Process(guiStateManager, elementStorage, tabChainManager, textSystem, overID); + for (const auto& hook : m_inputDispatchedHooks) + hook(actedOn); + } + + std::vector GUIApplication::ActedOnIDs(ID overID) const + { + std::vector ids; + if (!inputManager) + return ids; + bool pointer = false, keys = false; + for (const RecordedInputEvent& e : inputManager->GetRecordedEvents()) + switch (e.type) + { + case EventType::MouseDown: + case EventType::MouseUp: + case EventType::MouseScroll: + pointer = true; + break; + case EventType::MouseMove: + pointer |= e.state.buttons != MouseButtons::None; // a drag, not a pass over + break; + case EventType::KeyDown: + case EventType::KeyUp: + case EventType::TextInput: + keys = true; + break; + default: + break; + } + const InteractionState& interaction = guiStateManager.Interaction(); + auto add = [&ids](ID id) { + if (id != ID::Invalid() && std::find(ids.begin(), ids.end(), id) == ids.end()) + ids.push_back(id); + }; + if (pointer) + { + add(overID); + add(interaction.GetCaptureID()); + add(interaction.GetActiveID()); + } + if (keys) + add(interaction.GetFocusedID()); + return ids; + } +} diff --git a/src/gui_controls/gui_application.h b/src/gui_controls/gui_application.h index 237d3b34..e36278b2 100644 --- a/src/gui_controls/gui_application.h +++ b/src/gui_controls/gui_application.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include #include @@ -62,7 +63,7 @@ #include #include #include -#include +#include #include #include #include @@ -70,8 +71,6 @@ #include #include -#include -#include #include #include @@ -201,7 +200,6 @@ namespace tachyon std::unique_ptr m_labelGroup; std::unique_ptr m_buttonGroup; std::unique_ptr m_reorderable; - std::unique_ptr m_dockTabDragSub; ToolbarWindowDragSubsystem m_toolbarWindowDrag{}; std::unique_ptr m_uiCache; @@ -250,107 +248,6 @@ namespace tachyon ///@} - /// @name Panels and floating windows - ///@{ - - /// Adds a panel to `panels` (usually a DockingLayout's). onPanelGUI builds its content; - /// onEnable / onDisable run when it becomes visible / hidden. panelType names its kind, - /// which saved UI state matches panels by (else the title). - void CreatePanel(std::unordered_map& panels, ID id, std::string title, tachyon::IconID icon, - std::function onPanelGUI, - std::string panelType = {}, - std::function onEnable = {}, - std::function onDisable = {}); - - /// As above, with a new static ID, which it returns. The ID goes back when the panel is - /// closed (its tab, its window, its document, or a layout applied without it). - tachyon::ID CreatePanel(std::unordered_map& panels, std::string title, tachyon::IconID icon, - std::function onPanelGUI, - std::string panelType = {}, - std::function onEnable = {}, - std::function onDisable = {}) - { - ID id = idManager.CreateStaticID(); - CreatePanel(panels, id, std::move(title), icon, std::move(onPanelGUI), - std::move(panelType), std::move(onEnable), std::move(onDisable)); - panels[id].internal.ownsID = true; - return id; - } - - - /// Panel lifecycle. A panel is enabled iff it is the selectedTab of a leaf reachable - /// from layout.root; the docking enables the visible ones each frame. - /// DisableAllPanels brackets disruptive operations (theme reload, preset swap). - void DisableAllPanels(DockingLayout& layout); - - /// One OS window per floating toolbar. Closed windows are erased and their IDs released. - void EmitFloatingToolbarWindows(std::vector& floatingItems, - const struct FloatingToolbarOptions* options = nullptr); - - /// Dock leaf whose tab bar contains screenPos, plus its owning layout (needed by - /// TransferPanel for cross-layout drops). {nullptr, nullptr} on miss. - DockLeafResult FindDockLeafAtScreenPos(tachyon::int2 screenPos); - - /// The leaf whose content (as last laid out) holds screenPos, the part of it the point - /// is in (an edge, or Center), and its layout; none off every leaf's content. Tab bars - /// aren't content: FindDockLeafAtScreenPos finds those. - DockDropResult FindDockDropTargetAtScreenPos(tachyon::int2 screenPos); - - /// Call from OnGUI after the main docking container. Empty windows are closed. - void EmitFloatingDockWindows(); - /// With documents in several main windows: in each, after its Documents, the windows of - /// the panels torn from its documents. They belong to it, and to the window a document - /// is moved to. - void EmitFloatingDockWindows(const DocumentSet& documents); - /// Moves a docked panel into its own window at a screen position, as tearing its tab - /// off does; the window's Dock button returns it. False if the layout hasn't the panel. - bool FloatPanel(DockingLayout& layout, ID panelID, int2 screenPos); - /// Before an app destroys `layout`: closes the windows of the panels torn off it (they - /// would dock back into it) and stops saving it. - void ForgetDockingLayout(DockingLayout& layout); - /// Closes a layout for good, as ForgetDockingLayout does, and empties it: its panels are - /// hidden (onDisable) and destroyed, and the IDs CreatePanel made for them and its - /// tree's go back. Call it before the app destroys a layout it made, or at exit. - void ReleaseDockingLayout(DockingLayout& layout); - - /// Closes the window for good: its panels are disabled and destroyed. - void CloseFloatingDockWindow(size_t index); - - /// Closes the panel at `tabIndex` of a docked leaf, as the tab's Close action does. - void CloseDockedPanel(DockingLayout& layout, DockNode& leaf, int tabIndex); - /// For a control with shortcuts of its own (CommandManager::RegisterMode): while the - /// focus is within `owner`, the command mode is `mode`; once it's within none, Default - /// again. Call it as the control is built, every frame it is. The mode is set once a - /// frame, before input is handled, from where the focus is, so two controls of one mode - /// (two panels of a kind) don't undo each other. Default claims nothing. - void ClaimCommandMode(ID owner, CommandMode mode); - - /// Closes a panel of `layout` for good, wherever it is: out of its tree (its leaf - /// closing up when it empties), hidden first (onDisable) if it's shown, its ID back when - /// CreatePanel made it. Its callbacks, and what they hold, are destroyed when the next - /// frame starts, so it can be called from an input handler. - void ClosePanel(DockingLayout& layout, ID panelID); - - /// Adds a document at the end of `set`, with new static IDs and an empty layout, which - /// the caller fills (CreatePanel, MakeLeaf). The first one added becomes the active one. - Document& CreateDocument(DocumentSet& set, std::string name, std::string extension, std::string kind, - tachyon::IconID icon); - /// Closes `set`'s document at `index` for good: its panels are disabled and destroyed, - /// its torn-off panel windows closed, its IDs released and its layout no longer saved - /// (PersistDocking). The active document stays - /// active; when it's the one closed, the next one (else the one before) takes over. - /// Call from OnGUI, not from an input handler. - void CloseDocument(DocumentSet& set, int index); - /// Closes every document of `set`, as CloseDocument does each: at exit, say. - void CloseAllDocuments(DocumentSet& set); - - /// Moves a panel from sourceNode/sourceLayout to targetLayout, fixing up selectedTab. - static void TransferPanel(tachyon::ID panelID, tachyon::DockNode* sourceNode, - DockingLayout* sourceLayout, - DockingLayout* targetLayout); - - ///@} - /// @name Setup and resources ///@{ @@ -957,8 +854,6 @@ namespace tachyon /// Enables the retained-render cache (on by default). When off, every scope rebuilds. void SetDrawCacheEnabled(bool enabled) { if (m_uiCache) m_uiCache->SetDrawCacheEnabled(enabled); } - /// Invalidates a docked panel's cached content by panel id. Safe from event handlers. - void InvalidatePanel(ID panelId); /// Undecorated flex containers; the Wrap variants wrap onto further lines/columns. bool BeginHorizontal(ID id, StyleRef style, LayoutOverride&& constraints = {}); @@ -1009,6 +904,9 @@ namespace tachyon bool BeginToolbar(bool horizontal = true); /// Closes BeginToolbar. void EndToolbar(); + /// One OS window per floating toolbar. Closed windows are erased and their IDs released. + void EmitFloatingToolbarWindows(std::vector& floatingItems, + const struct FloatingToolbarOptions* options = nullptr); ///@} @@ -1271,46 +1169,6 @@ namespace tachyon ///@} - /// @name Docking - ///@{ - - // ---- DockingContainer ---- - /// Builds `layout`'s docked panels (each one's onPanelGUI) in a container, enabling the - /// visible panels first. Then call EmitFloatingDockWindows. - bool BeginDockingContainer(ID id, DockingLayout* layout, StyleRef style, LayoutOverride&& constraints = {}); - /// As above, in the theme's dock style. - inline bool BeginDockingContainer(ID id, DockingLayout* layout, LayoutOverride&& constraints = {}) - { return BeginDockingContainer(id, layout, theme.dockContainerStyleRef, std::move(constraints)); } - /// As above, with the call site as the ID. - inline bool BeginDockingContainer(DockingLayout* layout, StyleRef style, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) - { return BeginDockingContainer(idManager.AllocateDynamicID(site), layout, style, std::move(constraints)); } - /// As above, with the call site as the ID, in the theme's dock style. - inline bool BeginDockingContainer(DockingLayout* layout, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) - { return BeginDockingContainer(idManager.AllocateDynamicID(site), layout, theme.dockContainerStyleRef, std::move(constraints)); } - /// Closes BeginDockingContainer. - void EndDockingContainer(); - - /// The document bar of `set`, under the title bar, and below it the active document's - /// panels, filling the rest of the window's column. Each tab is in its document type's - /// colors; a click shows that document, its close button (or Ctrl+W) asks - /// DocumentSet::onClose and closes it on the next frame. Then call EmitFloatingDockWindows. - void Documents(ID id, DocumentSet& set, LayoutOverride&& constraints = {}); - /// The document bar of `set` alone: its tabs, "+", "N open" and the line in the active - /// document's color. With DocumentPanels, the two parts of Documents placed apart (the - /// bar in the title bar, say); call it first, once a frame. In - /// theme.titleBarDocumentsStyleRef, which fits it in a title bar, it leaves its line out: - /// DocumentLine draws it under the whole title bar. - void DocumentBar(ID id, DocumentSet& set, StyleRef style, LayoutOverride&& constraints = LayoutOverride::Auto()); - /// As above, in the theme's document bar style. - inline void DocumentBar(ID id, DocumentSet& set, LayoutOverride&& constraints = LayoutOverride::Auto()) { DocumentBar(id, set, theme.documentBarStyleRef, std::move(constraints)); } - /// The line under the document bar of `set`, in the active document's color, across - /// what it's in: after the title bar the bar is in. - void DocumentLine(const DocumentSet& set, LayoutOverride&& constraints = LayoutOverride::Auto()); - /// The active document's panels of `set`, after its DocumentBar. - void DocumentPanels(DocumentSet& set, LayoutOverride&& constraints = LayoutOverride::Auto()); - - ///@} - /// @name Fields ///@{ @@ -2161,8 +2019,6 @@ namespace tachyon template auto Invalid(A&&... a) { return Scope<&GUIApplication::EndInvalid>(*this, BeginInvalid(std::forward(a)...)); } template auto Selected(A&&... a) { return Scope<&GUIApplication::EndSelected>(*this, BeginSelected(std::forward(a)...)); } template auto Indeterminate(A&&... a) { return Scope<&GUIApplication::EndIndeterminate>(*this, BeginIndeterminate(std::forward(a)...)); } - template auto DockingContainer(A&&... a) { return Scope<&GUIApplication::EndDockingContainer>(*this, BeginDockingContainer(std::forward(a)...)); } - template auto DockingFrame(A&&... a) { return Scope<&GUIApplication::EndDockingFrame>(*this, BeginDockingFrame(std::forward(a)...)); } ///@} /// @name Boxes @@ -2273,12 +2129,9 @@ namespace tachyon /// must outlive the naming: /// /// PersistWindow("main", mainWindowID); // position, size, mode - /// PersistDocking("dock", dockingLayout); // panels by type, else title /// PersistToolbars("toolbars", toolbarSides); // items by debugName /// PersistValue("zoom", zoom); // an app setting, if it wants - /// PersistDocuments("documents", windows); // each main window's documents /// PersistShortcuts("shortcuts", commandManager); // the shortcuts the user changed - /// PersistLayoutPresets("layouts", presets); // saved layouts, file types' layouts /// /// RestoreUIState applies saved text: windows when they are next declared, the rest /// at once. What it doesn't know (keys, panels, columns) is skipped. @@ -2286,8 +2139,6 @@ namespace tachyon /// Keeps the window's position, size and mode. void PersistWindow(std::string key, ID windowID); - /// Keeps the layout's dock tree; panels are matched by type, else by title. - void PersistDocking(std::string key, DockingLayout& layout); /// Keeps each side's toolbar items, by debugName. void PersistToolbars(std::string key, std::span, kToolbarSideCount> sides); /// Keeps an app value. @@ -2298,55 +2149,31 @@ namespace tachyon void PersistValue(std::string key, float& value); /// As above, for a string. void PersistValue(std::string key, std::string& value); - /// Keeps the documents of each main window that `windows` lists when the state is - /// saved: their names, kinds and order, the active one, each one's dock tree, and the - /// window's position, size and mode. The app makes them again (TakeSavedDocuments). - void PersistDocuments(std::string key, std::function()> windows); /// Keeps the shortcuts that aren't the ones their commands were registered with, /// matching commands by mode name and description. Register the commands before /// RestoreUIState; ones it doesn't find keep their own. void PersistShortcuts(std::string key, CommandManager& commands); /// Keeps a library's own state (views::PersistTable, say): what `save` gives, under /// `section` and `key`. RestoreUIState gives what it finds there to `restore`. + /// A window's place: where it is, in which mode, and the monitor it was on (empty when + /// not known), as the saved UI state keeps it. + struct WindowPlace + { + IntRect rect {}; + WindowMode mode = WindowMode::Normal; + IntRect monitor {}; + }; + /// The window's place as saved UI state keeps it; nothing when it isn't open. + std::optional SaveWindowPlace(ID windowID) const; + /// SaveWindowPlace's text read back; nothing when it has no size. + static std::optional ReadWindowPlace(const JsonValue* saved); + /// Puts the window at `place` when it's next declared (OpenWindow), as RestoreUIState + /// does a persisted one. + void RestoreWindowPlace(ID windowID, const WindowPlace& place); void PersistJson(std::string section, std::string key, std::function save, std::function restore); - /// Keeps the layouts the user saved and the file types' layouts; the app adds its - /// built-in ones itself, before or after RestoreUIState. - void PersistLayoutPresets(std::string key, LayoutPresets& presets); /// Keeps each theme's variables, set with SetThemeVariable. void PersistThemeVariables(std::string key); - /// The main windows of documents RestoreUIState read for `key`, in the order they were - /// listed; empty when none were saved. Taking them clears them. Make each document with - /// its panels, then RestoreDocumentLayout, and place each window with RestoreWindowPlace. - std::vector TakeSavedDocuments(std::string_view key); - /// Lays a document's panels out as saved, and gives them their own states back: - /// - panels by type, else title; with several of one kind, the n-th in the saved tree - /// is the n-th the document has - /// - a panel the saved tree names that the document hasn't (a second of a kind, say) - /// is made by `makePanel`, as for ApplyDockLayout; without it, it's left out - /// - the document's panels the saved tree doesn't have go to its first leaf - /// - /// False (the layout stays) when it can't be read. - bool RestoreDocumentLayout(Document& document, const SavedDocument& saved, - const std::function(std::string_view key)>& makePanel = {}); - /// Puts a window where `saved` was when it's next declared, as PersistWindow does - /// (on its monitor, or the same place on another). Nothing when no place was saved. - void RestoreWindowPlace(ID windowID, const SavedDocumentWindow& saved); - /// A layout's dock tree as text, panels by type, else title, as a LayoutPreset keeps - /// it; empty when it has none. Floating panels aren't in it. - std::string SaveDockLayout(const DockingLayout& layout) const; - /// Lays a layout's panels out as `tree` (SaveDockLayout's text) says: - /// - a panel it names that the layout hasn't is made by `makePanel`, given the panel's - /// type, else title; it creates the panel in layout.panels and returns its ID, or - /// nullopt to leave it out - /// - with several of one kind in the tree, each is a panel of its own: the layout's - /// own first, then ones `makePanel` makes - /// - panels it doesn't name are closed, as closing their tabs does - /// - /// False when the tree can't be read or has no panel left: the layout stays as it was. - /// Call it outside the layout's Docking, e.g. before it in the frame. - bool ApplyDockLayout(DockingLayout& layout, std::string_view tree, - const std::function(std::string_view key)>& makePanel = {}); /// The named state as JSON text. std::string SaveUIState() const; /// Applies JSON text from SaveUIState. An error when it doesn't parse, isn't an object @@ -2421,6 +2248,34 @@ namespace tachyon /// Until set back to 0: the fields built fill the row they're in, at least `minWidth` /// pixels wide, and a switch sits at the row's end (a node's property row, say). void SetFieldRowFill(int32_t minWidth) { m_fieldRowFill = minWidth; } + /// For a control with shortcuts of its own (CommandManager::RegisterMode): while the + /// focus is within `owner`, the command mode is `mode`; once it's within none, Default + /// again. Call it as the control is built, every frame it is. The mode is set once a + /// frame, before input is handled, from where the focus is, so two controls of one mode + /// (two panels of a kind) don't undo each other. Default claims nothing. + void ClaimCommandMode(ID owner, CommandMode mode); + /// For a library that runs at points of the frame OnGUI can't reach (docking, say): `fn` + /// runs each frame at `stage`, after the app's own work there. Register once. + void OnFrameStage(FrameStage stage, std::function fn) { m_stageHooks[size_t(stage)].push_back(std::move(fn)); } + /// `fn` runs after each frame's input is handed to the elements, with the elements the + /// user acted on: under the pointer, captured or active for pointer input, focused for keys. + void OnInputDispatched(std::function actedOn)> fn) { m_inputDispatchedHooks.push_back(std::move(fn)); } + /// `fn` runs when the theme reloads, before every style is cleared: for what must go + /// while its styles are still there (a panel's onDisable, say). + void OnBeforeStylesCleared(std::function fn) { m_stylesClearedHooks.push_back(std::move(fn)); } + /// A control in the open title bar whose own background is caption: its empty space + /// drags the window (a tab strip, say). + void TitleBarCaption(ID id) { m_titleBarCaptions.push_back(id); } + /// The reorder drag in progress (a tab, or a reorderable group's item): for a library + /// that takes a dragged tab elsewhere (docking). + ReorderableDragState& ReorderDrag() { return m_reorderable->Drag(); } + /// The tab bar being built (between BeginTabBar and EndTabBar): which of its tabs it + /// shows, say. + const TabBarState& CurrentTabBar() const { return m_tabBarState; } + /// The tab being built (between BeginTab and EndTab): its body's ID, say. + const TabState& CurrentTab() const { return m_tabState; } + /// The window being built (between BeginWindow and EndWindow); Invalid outside one. + ID CurrentWindowID() const { return activeWindowID; } /// API misuse (e.g. an End without its Begin): logged once, and the caller carries on. static void ReportMisuse(const char* message); /// Closes a popup window whose state went, and gives its static ID back a few frames @@ -2458,8 +2313,6 @@ namespace tachyon void RefreshCachedInputFlags(); - /// Panel id -> its dock content (cached scope) id, for InvalidatePanel. - RecentIDMap m_panelContentIDs; /// Save-stack for nested BeginToolbar/EndToolbar. std::vector controlStylesStack; @@ -2478,18 +2331,8 @@ namespace tachyon TabBarState m_tabBarState; TabState m_tabState; - /// Enables the panels reachable from layout.root; called by BeginDockingContainer each frame. - void EnableVisiblePanels(DockingLayout& layout); - /// Transient, valid only between BeginDockingContainer / EndDockingContainer - /// (def in gui_docking_types.h); handlers must capture pointers, not read this. - DockingConstructionState m_dockingState; - /// Docking layouts emitted this frame (cleared at frame start); used by - /// SyncDockingScrollOffsets and cross-dock drop hit-testing. - std::vector m_dockingLayoutsThisFrame{}; - /// Panels closed this frame, kept until the next one starts (ClosePanel). - std::vector m_closedPanels; /// The controls with a command mode of their own (ClaimCommandMode), by their ID, and /// the frame each was last built in. struct CommandModeClaim { CommandMode mode; uint64_t frame; }; @@ -2501,36 +2344,15 @@ namespace tachyon /// Toolbar docks emitted this frame, walked by SyncToolbarDockRects (type in controls_toolbar_dock.h). std::vector m_toolbarDocksThisFrame{}; - /// After input dispatch: stores each selected panel's scroll offset so it survives a tab switch. - void SyncDockingScrollOffsets(); /// Snapshots each toolbar dock side's screen rect for next frame's drag hit-testing. void SyncToolbarDockRects(); - /// Uses last frame's tab-bar rects, so it works during construction. - tachyon::DockNode* FindDockLeafTabBarCachedAtScreenPos(tachyon::int2 screenPos); - std::vector> m_floatingDockWindows; - /// The floating windows of `documents` (all of them when null). - void EmitFloatingDockWindowsOf(const DocumentSet* documents); - /// Document sets built this frame (cleared at frame start): ActivateDocumentOf, and the - /// bars a dragged document drops on. - std::vector m_documentSetsThisFrame{}; - /// Shows the document of a set built this frame that owns `layout`; false when none does. - bool ActivateDocumentOf(const DockingLayout* layout); std::unordered_map m_statusBars; - DocumentDrag m_documentDrag; ///< the document tab being dragged, if any - std::vector m_documentBarRects; ///< last frame's document bars, screen pixels - std::optional m_documentMove; ///< a drop, done at the next frame's start - /// Moves or tears off the dropped document (m_documentMove); at frame start. - void ApplyDocumentMove(); - /// After layout: each set's bar and tab rects, for next frame's drops. - void SyncDocumentRects(); - /// The set whose bar is at `screenPos` (last frame's rects); null when none is. - DocumentSet* FindDocumentBarAt(tachyon::int2 screenPos); /// Debug asserts for Begin*/End* stacks left unbalanced at frame end. Also used by the headless tests. void RegisterFrameHooks(); // per-frame stage hooks; Initialize (and test harnesses) call it @@ -2634,12 +2456,9 @@ namespace tachyon /// Saved UI state: what the app named, and windows waiting for their saved rect. struct PersistedWindow { std::string key; ID target; }; - struct PersistedDock { std::string key; DockingLayout* target; }; struct PersistedToolbars { std::string key; std::span, kToolbarSideCount> target; }; struct PersistedValue { using Target = std::variant; std::string key; Target target; }; - struct PersistedDocuments { std::string key; std::function()> target; }; struct PersistedShortcuts { std::string key; CommandManager* target; }; - struct PersistedPresets { std::string key; LayoutPresets* target; }; struct PersistedJson { std::string section, key; std::function save; std::function restore; }; struct RestoredWindow { @@ -2651,16 +2470,11 @@ namespace tachyon bool rectDone = false; }; std::vector m_persistWindows; - std::vector m_persistDocks; std::vector m_persistJson ; std::vector m_persistToolbars; std::vector m_persistValues; - std::vector m_persistDocuments; std::vector m_persistShortcuts; - std::vector m_persistPresets; std::vector m_persistThemeVariables; ///< PersistThemeVariables' keys - /// Read by RestoreUIState, until the app takes them (TakeSavedDocuments). - std::unordered_map> m_savedDocuments; std::unordered_map m_restoredWindows; void ApplyRestoredWindow(ID windowID, LayoutOverride& constraints, ElementFlags& flags); /// Moves a restored rect onto the monitor it was saved on, or the same place on another. @@ -2763,30 +2577,28 @@ namespace tachyon /// it applies after the frame is drawn. std::vector m_cacheRebuildRequests; - /// Internal: called by the docking each frame. - void NotePanelContentID(ID panelId, ID contentID) { m_panelContentIDs[panelId] = contentID; } /// At Cleanup: gives back the static IDs the application made for itself (its popup, /// tooltip, menu and picker windows, toasts) and closes its torn-off panel windows. void ReleaseOwnIDs(); - /// Destroys every panel of `layout`, as ClosePanel does each, leaving its tree. - void ErasePanels(DockingLayout& layout); /// Sets the command mode from the claims (ClaimCommandMode) the focus is within, before /// the frame's input is handled; drops claims no longer built that the focus isn't in. void ApplyClaimedCommandMode(); - /// Hands the frame's input to the element handlers, then calls onChanged of the docked - /// panels the user acted in. + /// Hands the frame's input to the element handlers, then gives the OnInputDispatched + /// hooks the elements the user acted on. void DispatchInput(ID overID); /// The elements the user acts on with this frame's input: under the pointer and the /// one holding it for a press, a release, a drag or the wheel; the focused one for keys /// and text. None for the pointer only moving. std::vector ActedOnIDs(ID overID) const; - /// Calls onChanged of each docked panel holding one of `actedOn`, once each. - void ReportChangedPanels(std::vector actedOn); int32_t m_fieldRowFill = 0; ///< SetFieldRowFill + /// OnFrameStage, OnInputDispatched and OnBeforeStylesCleared's. + std::array>, size_t(FrameStage::EndFrame) + 1> m_stageHooks; + std::vector)>> m_inputDispatchedHooks; + std::vector> m_stylesClearedHooks; + /// Runs the stage's callbacks, then its OnFrameStage hooks. + void RunStage(FrameStage stage, FrameContext& ctx); - bool BeginDockingFrame(); - void EndDockingFrame(); ID activeWindowID { ID::Invalid() }; std::vector m_windowIdScopeStack; @@ -2841,9 +2653,6 @@ namespace tachyon /// Render: AddCustomDrawAfter owners waiting for the walk to pass their subtree. struct PendingAfterDraw { uint32_t endIdx; ElementRef owner; }; std::vector m_pendingAfterDraws; - /// A control in the open title bar whose own background is caption (e.g. a tab strip). - void TitleBarCaption(ID id) { m_titleBarCaptions.push_back(id); } - void DockFloatingWindow(FloatingDockWindow& fw); diff --git a/src/gui_controls/gui_application_internal.h b/src/gui_controls/gui_application_internal.h index 4646bfb2..f889370d 100644 --- a/src/gui_controls/gui_application_internal.h +++ b/src/gui_controls/gui_application_internal.h @@ -16,7 +16,6 @@ namespace tachyon using GUIApplication::m_labelGroup; using GUIApplication::m_buttonGroup; using GUIApplication::m_reorderable; - using GUIApplication::m_dockTabDragSub; using GUIApplication::m_toolbarWindowDrag; using GUIApplication::m_uiCache; using GUIApplication::FireStateTransitions; @@ -30,8 +29,6 @@ namespace tachyon using GUIApplication::contextMenuTargetID; using GUIApplication::tabDragGhostWindowID; - using GUIApplication::m_dockingState; - using GUIApplication::m_floatingDockWindows; using GUIApplication::activeWindowID; using GUIApplication::m_windowIdScopeStack; @@ -40,6 +37,9 @@ namespace tachyon using GUIApplication::m_inFrame; using GUIApplication::m_themePath; using GUIApplication::RegisterFrameHooks; + using GUIApplication::RunStage; + using GUIApplication::m_toolbarDocksThisFrame; + using GUIApplication::SyncToolbarDockRects; using GUIApplication::ApplyPendingStyleReload; using GUIApplication::InvalidateCachedScopesForInput; using GUIApplication::DispatchInput; @@ -52,8 +52,6 @@ namespace tachyon using GUIApplication::RunPressOutsideWatches; using GUIApplication::DispatchFileDrops; using GUIApplication::UpdateMouseCursor; - using GUIApplication::BeginDockingFrame; - using GUIApplication::EndDockingFrame; using GUIApplication::OnFrame; using GUIApplication::OnRender; using GUIApplication::RegisterElementInternal; @@ -61,12 +59,8 @@ namespace tachyon // For the library's free helpers, which get a plain GUIApplication. static ID& TabDragGhostWindowID(GUIApplication& app) { return app.tabDragGhostWindowID; } static ReorderableSubsystem& Reorderable(GUIApplication& app) { return *app.m_reorderable; } - static DockTabDragSubsystem& DockTabDrag(GUIApplication& app) { return *app.m_dockTabDragSub; } static MenuRectsSubsystem& MenuRects(GUIApplication& app) { return *app.m_menuRects; } - static auto& FloatingDockWindows(GUIApplication& app) { return app.m_floatingDockWindows; } static auto& ToolbarDocksThisFrame(GUIApplication& app) { return app.m_toolbarDocksThisFrame; } - static DockNode* FindDockLeafTabBarCachedAtScreenPos(GUIApplication& app, int2 screenPos) { return app.FindDockLeafTabBarCachedAtScreenPos(screenPos); } - static void NotePanelContentID(GUIApplication& app, ID panelId, ID contentID) { app.NotePanelContentID(panelId, contentID); } static void TitleBarCaption(GUIApplication& app, ID id) { app.TitleBarCaption(id); } static void ReloadThemeNextFrame(GUIApplication& app) { app.m_themeReloadPending = true; } /// Moves the frame clock to `nowNanos`, as a frame does: for a headless frame, run on its own clock. diff --git a/src/gui_controls/gui_tab_types.h b/src/gui_controls/gui_tab_types.h new file mode 100644 index 00000000..847ceb84 --- /dev/null +++ b/src/gui_controls/gui_tab_types.h @@ -0,0 +1,77 @@ +#pragma once + +// What a tab bar (BeginTabBar) keeps while it's built and from frame to frame. + +#include +#include +#include // IconID + +#include +#include +#include +#include +#include + +namespace tachyon +{ + /// @addtogroup controls_docking + /// @{ + + /// How a tab bar lays out tabs that don't fit on one row. + enum class TabBarLayout : uint8_t + { + OneRow, ///< one row; the tabs that don't fit are listed by a "+N" button after the others + Rows ///< every tab shown, on as many rows as they take + }; + + // ---- TabBar: reorderable tabs ---- + /// What a tab bar offers besides its tabs. + struct TabBarOptions { + std::string_view closeLabel = "Close Panel"; ///< the item of a tab's context menu that closes it + /// "+N" after the tabs that fit lists the rest. Without it the caller lists them another + /// way; what it adds after the tabs is left room for (TabBarMemory::trailingWidth). + bool listHidden = true; + bool layoutMenu = true; ///< the context menus offer Collapse Rows / Multiple Rows + /// An element around the bar (its row, say) that counts as the bar while a tab is + /// dragged: in it the tab reorders, and only off it is it dragged out. Invalid: the bar. + tachyon::ID dropArea = tachyon::ID::Invalid(); + }; + + /// Construction state of the current tab bar; internal. + struct TabBarState { + tachyon::ID barID = tachyon::ID::Invalid(); + int* selectedIndex = nullptr; + int nextTabIndex = 0; + std::function onClose; ///< tab index, when its close button is clicked + std::function onDragOut; ///< tab index and mouse release pos + TabBarLayout* layout = nullptr; ///< the bar's layout, which its context menu sets + TabBarOptions options; + std::vector shown; ///< by tab index; empty: every tab is shown + struct HiddenTab { int index = 0; tachyon::IconID icon = tachyon::IconID::Invalid; std::string text; }; + std::vector hidden; ///< the tabs left out, listed by the overflow button + }; + + /// Construction state of the current tab, between BeginTab and EndTab; internal. + struct TabState { + bool open = false; ///< BeginTab built it (it wasn't left out) + tachyon::ID id = tachyon::ID::Invalid(); + tachyon::ID bodyID = tachyon::ID::Invalid(); + int index = 0; + bool selected = false; + }; + + /// What a tab bar keeps across frames (element data store, by bar ID): its keyboard + /// navigation, and the sizes it measured, in pixels, that decide which tabs fit. + struct TabBarMemory { + int tabCount = 0; ///< last frame's + int focusIndex = -1; ///< the tab that takes focus as it's built, after an arrow key + TabBarLayout layout = TabBarLayout::OneRow; ///< for a bar whose caller doesn't keep one + + std::vector widths; ///< by tab index; a hidden tab keeps its last width + int32_t barWidth = 0; ///< the bar's inner width + int32_t overflowWidth = 0; ///< the overflow button's width + int32_t trailingWidth = 0; ///< what the caller adds after the tabs, always shown + }; + + /// @} +} diff --git a/src/gui_controls/gui_theme.cpp b/src/gui_controls/gui_theme.cpp index d2aa112f..1e92464a 100644 --- a/src/gui_controls/gui_theme.cpp +++ b/src/gui_controls/gui_theme.cpp @@ -151,7 +151,6 @@ namespace tachyon chevronRightIcon = registerIcon("chevron-right", R"()"); retryIcon = registerIcon("retry", R"()"); eyedropperIcon = registerIcon("eyedropper", R"()"); - dockIcon = registerIcon("dock", R"()"); dragHandleIcon = registerIcon("drag-handle", R"()" R"()"); @@ -705,30 +704,8 @@ namespace tachyon timelineRowButtonStyleRef = registerCSS("timeline-row-button"); - documentsStyleRef = registerCSS("documents"); - documentBarStyleRef = registerCSS("document-bar"); - documentRowStyleRef = registerCSS("document-row"); - documentTabBarStyleRef = registerCSS("document-tab-bar"); - documentTabStyleRef = registerCSS("document-tab"); - documentNameStyleRef = registerCSS("document-name"); - documentExtensionStyleRef = registerCSS("document-extension"); - documentMarkStyleRef = registerCSS("document-mark"); - documentCloseStyleRef = registerCSS("document-close"); - documentDirtyStyleRef = registerCSS("document-dirty"); - documentLineStyleRef = registerCSS("document-line"); - documentNewStyleRef = registerCSS("document-new"); - documentListStyleRef = registerCSS("document-list"); - titleBarDocumentsStyleRef = registerCSS("title-bar-documents"); // Docking container styles - dockContainerStyleRef = registerCSS("dock-container"); - dockContainerMainStyleRef = registerCSS("dock-container-main"); - dockSplitHorzStyleRef = registerCSS("dock-split-horz"); - dockSplitVertStyleRef = registerCSS("dock-split-vert"); - dockSizerHorzStyleRef = registerCSS("dock-sizer-horz"); - dockSizerVertStyleRef = registerCSS("dock-sizer-vert"); - dockLeafStyleRef = registerCSS("dock-leaf"); - dockContentStyleRef = registerCSS("dock-content"); firstIconStyleRef = registerCSS("first-icon"); iconLeftStyleRef = registerCSS("icon-left"); @@ -746,10 +723,6 @@ namespace tachyon // ------------------------------------------------------------------------- windowStyleRef = registerCSS("window"); mainWindowStyleRef = registerCSS("main-window"); - dockWindowStyleRef = registerCSS("dock-window"); - dockWindowLeafStyleRef = registerCSS("dock-window-leaf"); - dockWindowPanelStyleRef = registerCSS("dock-window-panel"); - dockWindowBodyStyleRef = registerCSS("dock-window-body"); titleBarTabBarStyleRef = registerCSS("title-bar-tab-bar"); titleBarTabStyleRef = registerCSS("title-bar-tab"); titleBarTabPanelFocusedStyleRef = registerCSS("title-bar-tab-panel-focused"); @@ -774,7 +747,6 @@ namespace tachyon { regularControls.menuTrigger, partsOf("menu-trigger") }, { toolbarControls.menuTrigger, partsOf("toolbar-menu-trigger") }, { menuBarDropdownStyleRef, partsOf("menu-bar-dropdown") }, - { documentListStyleRef, partsOf("document-list") }, { tabOverflowStyleRef, partsOf("tab-overflow") }, { iconMenuButtonStyleRef, DropdownParts{ registerCSS("icon-menu-button-text"), StyleRef::Invalid() } }, }; diff --git a/src/gui_controls/gui_theme.h b/src/gui_controls/gui_theme.h index 9b64c069..dc9c6aa1 100644 --- a/src/gui_controls/gui_theme.h +++ b/src/gui_controls/gui_theme.h @@ -220,10 +220,6 @@ namespace tachyon StyleRef itemStyleRef {}; ///< an item in it StyleRef mainWindowStyleRef{}; ///< a window without padding, its content in a column StyleRef windowStyleRef {}; ///< BeginWindow's default - StyleRef dockWindowStyleRef {}; ///< floating dock window - no internal padding - StyleRef dockWindowLeafStyleRef {}; ///< a torn-off window's root leaf: the title bar over the panel - StyleRef dockWindowPanelStyleRef {}; ///< the panel inset under a torn-off window's title bar - StyleRef dockWindowBodyStyleRef {}; ///< a torn-off window's split layout, inset the same StyleRef titleBarTabBarStyleRef {}; ///< the tab strip in a torn-off window's title bar StyleRef titleBarTabStyleRef {}; ///< a tab in it StyleRef titleBarTabPanelFocusedStyleRef {}; ///< a tab in it while the window holds the focus @@ -371,30 +367,8 @@ namespace tachyon /// their colors from its type's classes (.document-tab-level, ...); these are the plain /// ones, for a type the theme has none for. ///@{ - StyleRef documentsStyleRef {}; ///< the bar and the active document's panels, a column - StyleRef documentBarStyleRef {}; ///< the bar: its row over the line - StyleRef documentRowStyleRef {}; ///< the tabs, "+" and the list - StyleRef documentTabBarStyleRef {}; ///< the tabs and "+" - StyleRef documentTabStyleRef {}; - StyleRef documentNameStyleRef {}; ///< a tab's icon and name - StyleRef documentExtensionStyleRef {}; ///< ".level", after the name - StyleRef documentMarkStyleRef {}; ///< the slot for the close button or the unsaved dot - StyleRef documentCloseStyleRef {}; - StyleRef documentDirtyStyleRef {}; ///< the unsaved-changes dot - StyleRef documentLineStyleRef {}; ///< under the bar, in the active document's color - StyleRef documentNewStyleRef {}; ///< "+" - StyleRef documentListStyleRef {}; ///< "N open", listing every document - StyleRef titleBarDocumentsStyleRef {}; ///< a document bar in a title bar (DocumentBar) ///@} - StyleRef dockContainerStyleRef {}; ///< a docking container - StyleRef dockContainerMainStyleRef {}; ///< a main window's docking area, with a side gutter - StyleRef dockSplitHorzStyleRef {}; ///< horizontal flex row (split into left / right) - StyleRef dockSplitVertStyleRef {}; ///< vertical flex column (split into top / bottom) - StyleRef dockSizerHorzStyleRef {}; ///< vertical bar between left / right panes - StyleRef dockSizerVertStyleRef {}; ///< horizontal bar between top / bottom panes - StyleRef dockLeafStyleRef {}; ///< vertical flex: [tab bar][content] - StyleRef dockContentStyleRef {}; ///< content area holding the selected panel's draw() StyleRef shortcutButtonStyleRef {}; ///< ShortcutButton: a flat row of keycaps StyleRef keycapStyleRef {}; ///< a key in a ShortcutButton @@ -424,7 +398,6 @@ namespace tachyon IconID removeIcon = IconID::Invalid; ///< list / dictionary Field(): remove a row IconID dragHandleIcon = IconID::Invalid; ///< three-bar grip of a reorderable list / tree row - IconID dockIcon = IconID::Invalid; ///< returns a torn-off panel to its dock IconID eyedropperIcon = IconID::Invalid; ///< picks a color from the screen IconID alertIcon = IconID::Invalid; ///< message severity: warning IconID powerIcon = IconID::Invalid; ///< message severity: quitting diff --git a/src/gui_controls/gui_ui_state.cpp b/src/gui_controls/gui_ui_state.cpp index 00d6fa6a..a2f58f5a 100644 --- a/src/gui_controls/gui_ui_state.cpp +++ b/src/gui_controls/gui_ui_state.cpp @@ -44,37 +44,6 @@ namespace tachyon return monitor.rect.w > 0 && monitor.rect.h > 0 ? monitor.rect : monitor.workArea; } - // A panel's key: its type when it has one, else its title. - std::string PanelKey(const Panel& panel) { return panel.panelType.empty() ? panel.title : panel.panelType; } - - // The layout's panel for a saved tab of `key`: the first of that key not handed out - // yet, so a tree with two of a kind gets two panels; else the one `makePanel` makes - // (it adds it to the layout), recorded in `made`. Nullopt when there's neither. - std::optional PanelForKey(DockingLayout& layout, std::string_view key, std::vector& handed, - const std::function(std::string_view)>& makePanel, std::vector& made) - { - for (const auto& [id, panel] : layout.panels) - if (PanelKey(panel) == key && std::find(handed.begin(), handed.end(), id) == handed.end()) - { - handed.push_back(id); - return id; - } - if (!makePanel) - return std::nullopt; - const std::optional created = makePanel(key); - if (!created || layout.panels.find(*created) == layout.panels.end()) - return std::nullopt; // it made none - made.push_back(*created); - handed.push_back(*created); - return created; - } - - DockNode* FirstLeaf(DockNode* node) - { - while (node != nullptr && !node->isLeaf) - node = node->first ? node->first.get() : node->second.get(); - return node; - } template void Upsert(std::vector& entries, std::string key, Target target) @@ -84,6 +53,12 @@ namespace tachyon entries.push_back(Entry{ std::move(key), target }); } + std::string StringOf(const JsonValue& object, const char* name) + { + const JsonValue* v = object.Find(name); + return v && v->IsString() ? v->AsString() : std::string(); + } + // Each side's items by debugName: { "Top": ["File", "View"], "Right": [], ... }. JsonValue ToolbarSidesJson(std::span, kToolbarSideCount> sides) { @@ -123,144 +98,6 @@ namespace tachyon sides[size_t(s)] = std::move(rebuilt[s]); } - // A layout's dock tree as JSON, panels by key; null when it has none. - std::optional DockTreeJson(const DockingLayout& layout) - { - if (!layout.root) - return std::nullopt; - const std::string tree = SerializeDockTree(*layout.root, [&layout](ID id) { - const auto it = layout.panels.find(id); - return it != layout.panels.end() ? PanelKey(it->second) : std::string(); - }); - Result parsed = JsonValue::Parse(tree); - return parsed ? std::optional(std::move(*parsed)) : std::nullopt; - } - - // A saved dock tree applied to a layout: panels by key, a panel `makePanel` makes for - // each it lacks, the ones it hasn't to its first leaf. False when it can't be read; the - // layout stays. The old tree's node and tab-bar IDs go back to `idManager`. - bool ApplyDockTree(DockingLayout& layout, std::string_view tree, IDManager& idManager, - const std::function(std::string_view)>& makePanel = {}) - { - std::vector handed, made; - std::unique_ptr root = ParseDockTree(tree, [&](std::string_view panelKey) { - return PanelForKey(layout, panelKey, handed, makePanel, made); - }); - if (!root) - { - // Never shown: only their IDs, when CreatePanel made them, to give back. - for (const ID id : made) - if (const auto it = layout.panels.find(id); it != layout.panels.end()) - { - if (it->second.internal.ownsID) - idManager.ReleaseStaticID(id); - layout.panels.erase(it); - } - return false; - } - std::vector all; - for (const auto& [id, panel] : layout.panels) all.push_back(id); - if (DockNode* leaf = FirstLeaf(root.get())) - for (const ID id : UnplacedPanels(*root, all)) - leaf->panelIds.push_back(id); - ReleaseDockTreeIDs(layout.root.get(), &idManager); - layout.root = std::move(root); - return true; - } - - std::string StringOf(const JsonValue& object, const char* name) - { - const JsonValue* v = object.Find(name); - return v && v->IsString() ? v->AsString() : std::string(); - } - - // A layout's panels' own view states, by panel key: { "NodeView": "..." }. Several - // panels of one key go in an array, in the order they're in the tree, "" for one that - // keeps nothing: { "Timeline": ["...", "..."] }. Null when none keeps one. - std::optional PanelStatesJson(const DockingLayout& layout) - { - if (!layout.root) - return std::nullopt; - std::vector>> byKey; - bool any = false; - for (const ID id : PanelsInTree(*layout.root)) - { - const auto it = layout.panels.find(id); - if (it == layout.panels.end()) - continue; - const Panel& panel = it->second; - std::string state = panel.saveState ? panel.saveState() : std::string(); - any |= !state.empty(); - const std::string key = PanelKey(panel); - auto entry = std::find_if(byKey.begin(), byKey.end(), [&key](const auto& e) { return e.first == key; }); - if (entry == byKey.end()) - entry = byKey.insert(byKey.end(), { key, {} }); - entry->second.push_back(std::move(state)); - } - if (!any) - return std::nullopt; - JsonValue states = JsonValue::MakeObject(); - for (auto& [key, list] : byKey) - { - if (std::all_of(list.begin(), list.end(), [](const std::string& s) { return s.empty(); })) - continue; - if (list.size() == 1) - { - states.Set(key, std::move(list[0])); - continue; - } - JsonValue array = JsonValue::MakeArray(); - for (std::string& state : list) - array.Push(std::move(state)); - states.Set(key, std::move(array)); - } - return states; - } - - // Saved view states handed to the layout's panels of the same keys: the n-th saved - // for a key to the n-th panel of that key in the tree. - void ApplyPanelStates(DockingLayout& layout, std::span> states) - { - if (!layout.root) - return; - std::vector> taken; // per key, how many are handed out - for (const ID id : PanelsInTree(*layout.root)) - { - const auto it = layout.panels.find(id); - if (it == layout.panels.end()) - continue; - Panel& panel = it->second; - const std::string key = PanelKey(panel); - auto count = std::find_if(taken.begin(), taken.end(), [&key](const auto& e) { return e.first == key; }); - if (count == taken.end()) - count = taken.insert(taken.end(), { key, 0 }); - const size_t n = count->second++; - size_t seen = 0; - for (const auto& [savedKey, state] : states) - if (savedKey == key && seen++ == n) - { - if (panel.restoreState && !state.empty()) - panel.restoreState(state); - break; - } - } - } - - // The saved states as pairs, a key's array as one pair each, in order. - std::vector> PanelStatesOf(const JsonValue* states) - { - std::vector> out; - if (states && states->IsObject()) - for (const auto& [key, state] : states->Members()) - { - if (state.IsString()) - out.emplace_back(key, state.AsString()); - else if (state.IsArray()) - for (const JsonValue& one : state.Items()) - out.emplace_back(key, one.IsString() ? one.AsString() : std::string()); - } - return out; - } } std::string SaveToolbarLayout(std::span, kToolbarSideCount> sides) @@ -278,17 +115,12 @@ namespace tachyon } void GUIApplication::PersistWindow(std::string key, ID windowID) { Upsert(m_persistWindows, std::move(key), windowID); } - void GUIApplication::PersistDocking(std::string key, DockingLayout& layout) { Upsert(m_persistDocks, std::move(key), &layout); } void GUIApplication::PersistToolbars(std::string key, std::span, kToolbarSideCount> sides) { Upsert(m_persistToolbars, std::move(key), sides); } void GUIApplication::PersistValue(std::string key, bool& value) { Upsert(m_persistValues, std::move(key), PersistedValue::Target(&value)); } void GUIApplication::PersistValue(std::string key, int& value) { Upsert(m_persistValues, std::move(key), PersistedValue::Target(&value)); } void GUIApplication::PersistValue(std::string key, float& value) { Upsert(m_persistValues, std::move(key), PersistedValue::Target(&value)); } void GUIApplication::PersistValue(std::string key, std::string& value) { Upsert(m_persistValues, std::move(key), PersistedValue::Target(&value)); } - void GUIApplication::PersistDocuments(std::string key, std::function()> windows) - { - Upsert(m_persistDocuments, std::move(key), std::move(windows)); - } void GUIApplication::PersistShortcuts(std::string key, CommandManager& commands) { Upsert(m_persistShortcuts, std::move(key), &commands); } void GUIApplication::PersistJson(std::string section, std::string key, std::function save, std::function restore) @@ -302,72 +134,65 @@ namespace tachyon } m_persistJson.push_back({ std::move(section), std::move(key), std::move(save), std::move(restore) }); } - void GUIApplication::PersistLayoutPresets(std::string key, LayoutPresets& presets) { Upsert(m_persistPresets, std::move(key), &presets); } void GUIApplication::PersistThemeVariables(std::string key) { if (std::find(m_persistThemeVariables.begin(), m_persistThemeVariables.end(), key) == m_persistThemeVariables.end()) m_persistThemeVariables.push_back(std::move(key)); } - std::string GUIApplication::SaveDockLayout(const DockingLayout& layout) const - { - const std::optional tree = DockTreeJson(layout); - return tree ? tree->Write() : std::string(); - } - - bool GUIApplication::ApplyDockLayout(DockingLayout& layout, std::string_view tree, - const std::function(std::string_view key)>& makePanel) + std::optional GUIApplication::SaveWindowPlace(ID windowID) const { - // Each key to a panel: the layout's own, else a new one. - std::vector handed, made; - std::unique_ptr root = ParseDockTree(tree, [&](std::string_view panelKey) { - return PanelForKey(layout, panelKey, handed, makePanel, made); - }); - if (!root) + if (!windowManager || windowManager->GetWindowHandle(windowID) == nullptr) + return std::nullopt; + const IntRect rect = windowManager->GetWindowRect(windowID); + JsonValue w = JsonValue::MakeObject(); + w.Set("x", rect.x); w.Set("y", rect.y); w.Set("w", rect.w); w.Set("h", rect.h); + w.Set("mode", ModeName(windowManager->GetWindowMode(windowID))); + // The monitor it's on (its center's), so it can come back there, or to the same + // place on another monitor when that one is gone. + const int2 center{ rect.x + rect.w / 2, rect.y + rect.h / 2 }; + for (const MonitorInfo& monitor : windowManager->Monitors()) { - for (const ID id : made) - ClosePanel(layout, id); - return false; + const IntRect bounds = MonitorBounds(monitor); + if (bounds.Contains(center)) + { + JsonValue m = JsonValue::MakeObject(); + m.Set("x", bounds.x); m.Set("y", bounds.y); m.Set("w", bounds.w); m.Set("h", bounds.h); + w.Set("monitor", std::move(m)); + break; + } } - - DisableAllPanels(layout); - std::vector all; - for (const auto& [id, panel] : layout.panels) all.push_back(id); - for (const ID id : UnplacedPanels(*root, all)) - ClosePanel(layout, id); - ReleaseDockTreeIDs(layout.root.get(), &idManager); - layout.root = std::move(root); - return true; - } - - std::vector GUIApplication::TakeSavedDocuments(std::string_view key) - { - const auto it = m_savedDocuments.find(std::string(key)); - if (it == m_savedDocuments.end()) - return {}; - std::vector windows = std::move(it->second); - m_savedDocuments.erase(it); - return windows; + return w; } - bool GUIApplication::RestoreDocumentLayout(Document& document, const SavedDocument& saved, - const std::function(std::string_view key)>& makePanel) + std::optional GUIApplication::ReadWindowPlace(const JsonValue* saved) { - if (saved.layout.empty() || !ApplyDockTree(document.layout, saved.layout, idManager, makePanel)) - return false; - ApplyPanelStates(document.layout, saved.panelStates); - return true; + if (!saved || !saved->IsObject()) + return std::nullopt; + const JsonValue* w = saved; + WindowPlace place; + place.rect = IntRect{ int32_t(w->Find("x") ? w->Find("x")->AsNumber() : 0), int32_t(w->Find("y") ? w->Find("y")->AsNumber() : 0), + int32_t(w->Find("w") ? w->Find("w")->AsNumber() : 0), int32_t(w->Find("h") ? w->Find("h")->AsNumber() : 0) }; + if (place.rect.w <= 0 || place.rect.h <= 0) + return std::nullopt; + place.mode = ModeFromName(w->Find("mode") ? w->Find("mode")->AsString() : std::string_view{}); + if (const JsonValue* m = w->Find("monitor"); m && m->IsObject()) + { + auto number = [m](const char* name) { const JsonValue* v = m->Find(name); return v ? int32_t(v->AsNumber()) : 0; }; + place.monitor = IntRect{ number("x"), number("y"), number("w"), number("h") }; + } + return place; } - void GUIApplication::RestoreWindowPlace(ID windowID, const SavedDocumentWindow& saved) + void GUIApplication::RestoreWindowPlace(ID windowID, const WindowPlace& place) { - if (saved.rect.w <= 0 || saved.rect.h <= 0) + if (place.rect.w <= 0 || place.rect.h <= 0) return; RestoredWindow restored; - restored.rect = saved.rect; - restored.mode = saved.mode; - restored.monitor = saved.monitor; - restored.hasMonitor = saved.monitor.w > 0 && saved.monitor.h > 0; + restored.rect = place.rect; + restored.mode = place.mode; + restored.monitor = place.monitor; + restored.hasMonitor = place.monitor.w > 0 && place.monitor.h > 0; m_restoredWindows[windowID] = restored; } @@ -376,84 +201,12 @@ namespace tachyon JsonValue doc = JsonValue::MakeObject(); doc.Set("version", kStateVersion); - // A window's place; null when it isn't open (its last place isn't known here). - auto windowJson = [this](ID windowID) -> std::optional - { - if (!windowManager || windowManager->GetWindowHandle(windowID) == nullptr) - return std::nullopt; - const IntRect rect = windowManager->GetWindowRect(windowID); - JsonValue w = JsonValue::MakeObject(); - w.Set("x", rect.x); w.Set("y", rect.y); w.Set("w", rect.w); w.Set("h", rect.h); - w.Set("mode", ModeName(windowManager->GetWindowMode(windowID))); - // The monitor it's on (its center's), so it can come back there, or to the same - // place on another monitor when that one is gone. - const int2 center{ rect.x + rect.w / 2, rect.y + rect.h / 2 }; - for (const MonitorInfo& monitor : windowManager->Monitors()) - { - const IntRect bounds = MonitorBounds(monitor); - if (bounds.Contains(center)) - { - JsonValue m = JsonValue::MakeObject(); - m.Set("x", bounds.x); m.Set("y", bounds.y); m.Set("w", bounds.w); m.Set("h", bounds.h); - w.Set("monitor", std::move(m)); - break; - } - } - return w; - }; - JsonValue windows = JsonValue::MakeObject(); for (const auto& [key, windowID] : m_persistWindows) - if (std::optional w = windowJson(windowID)) + if (std::optional w = SaveWindowPlace(windowID)) windows.Set(key, std::move(*w)); doc.Set("windows", std::move(windows)); - JsonValue docking = JsonValue::MakeObject(); - JsonValue dockingStates = JsonValue::MakeObject(); - for (const auto& [key, layout] : m_persistDocks) - { - if (std::optional tree = DockTreeJson(*layout)) - docking.Set(key, std::move(*tree)); - if (std::optional states = PanelStatesJson(*layout)) - dockingStates.Set(key, std::move(*states)); - } - doc.Set("docking", std::move(docking)); - doc.Set("panelStates", std::move(dockingStates)); - - // Each main window's documents: which, in what order, the active one and their dock - // trees, with the window's place. - JsonValue documents = JsonValue::MakeObject(); - for (const auto& [key, listWindows] : m_persistDocuments) - { - JsonValue list = JsonValue::MakeArray(); - for (const DocumentWindowRef& window : listWindows ? listWindows() : std::vector{}) - { - if (!window.documents) - continue; - JsonValue w = JsonValue::MakeObject(); - if (std::optional place = windowJson(window.windowID)) - w.Set("window", std::move(*place)); - w.Set("active", window.documents->active); - JsonValue items = JsonValue::MakeArray(); - for (const auto& document : window.documents->documents) - { - JsonValue d = JsonValue::MakeObject(); - d.Set("name", document->name); - d.Set("extension", document->extension); - d.Set("kind", document->kind); - if (std::optional tree = DockTreeJson(document->layout)) - d.Set("layout", std::move(*tree)); - if (std::optional states = PanelStatesJson(document->layout)) - d.Set("panelStates", std::move(*states)); - items.Push(std::move(d)); - } - w.Set("documents", std::move(items)); - list.Push(std::move(w)); - } - documents.Set(key, std::move(list)); - } - doc.Set("documents", std::move(documents)); - JsonValue toolbars = JsonValue::MakeObject(); for (const auto& [key, sides] : m_persistToolbars) toolbars.Set(key, ToolbarSidesJson(sides)); @@ -491,12 +244,6 @@ namespace tachyon } doc.Set("shortcuts", std::move(shortcuts)); - JsonValue presets = JsonValue::MakeObject(); - for (const auto& [key, target] : m_persistPresets) - if (Result parsed = JsonValue::Parse(target->ToJson())) - presets.Set(key, std::move(*parsed)); - doc.Set("layoutPresets", std::move(presets)); - // Each theme's variables, by its path: { "themes/dark.css": { "--bg-panel": "#202020" } }. JsonValue themeVariables = JsonValue::MakeObject(); for (const std::string& key : m_persistThemeVariables) @@ -524,7 +271,8 @@ namespace tachyon JsonValue section = JsonValue::MakeObject(); for (const PersistedJson& entry : m_persistJson) if (entry.section == name && entry.save) - section.Set(entry.key, entry.save()); + if (JsonValue value = entry.save(); !value.IsNull()) // null: nothing to keep + section.Set(entry.key, std::move(value)); doc.Set(name, std::move(section)); } @@ -552,75 +300,10 @@ namespace tachyon return s ? s->Find(key) : nullptr; }; - // A saved window place; null when it has no size. - auto readWindow = [](const JsonValue* w) -> std::optional - { - if (!w || !w->IsObject()) - return std::nullopt; - RestoredWindow restored; - restored.rect = IntRect{ int32_t(w->Find("x") ? w->Find("x")->AsNumber() : 0), int32_t(w->Find("y") ? w->Find("y")->AsNumber() : 0), - int32_t(w->Find("w") ? w->Find("w")->AsNumber() : 0), int32_t(w->Find("h") ? w->Find("h")->AsNumber() : 0) }; - if (restored.rect.w <= 0 || restored.rect.h <= 0) - return std::nullopt; - restored.mode = ModeFromName(w->Find("mode") ? w->Find("mode")->AsString() : std::string_view{}); - if (const JsonValue* m = w->Find("monitor"); m && m->IsObject()) - { - auto number = [m](const char* name) { const JsonValue* v = m->Find(name); return v ? int32_t(v->AsNumber()) : 0; }; - restored.monitor = IntRect{ number("x"), number("y"), number("w"), number("h") }; - restored.hasMonitor = restored.monitor.w > 0 && restored.monitor.h > 0; - } - return restored; - }; - // Windows: applied when each is next declared (OpenWindow). for (const auto& [key, windowID] : m_persistWindows) - if (std::optional restored = readWindow(section("windows", key))) - m_restoredWindows[windowID] = *restored; - - // Dock trees: panels by key; panels the saved tree doesn't have go to its first leaf. - // Nothing usable: the app's own layout stays. - for (const auto& [key, layout] : m_persistDocks) - { - if (const JsonValue* tree = section("docking", key)) - (void)ApplyDockTree(*layout, tree->Write(), idManager); - ApplyPanelStates(*layout, PanelStatesOf(section("panelStates", key))); - } - - // Documents: kept for the app, which makes them again (TakeSavedDocuments). - for (const auto& [key, listWindows] : m_persistDocuments) - { - const JsonValue* saved = section("documents", key); - if (!saved || !saved->IsArray()) - continue; - std::vector windows; - for (const JsonValue& w : saved->Items()) - { - if (!w.IsObject()) - continue; - SavedDocumentWindow window; - if (const JsonValue* items = w.Find("documents"); items && items->IsArray()) - for (const JsonValue& d : items->Items()) - { - if (!d.IsObject() || StringOf(d, "name").empty()) - continue; - const JsonValue* tree = d.Find("layout"); - window.documents.push_back(SavedDocument{ StringOf(d, "name"), StringOf(d, "extension"), StringOf(d, "kind"), - tree ? tree->Write() : std::string(), PanelStatesOf(d.Find("panelStates")) }); - } - if (window.documents.empty()) - continue; - const JsonValue* active = w.Find("active"); - window.active = std::clamp(active && active->IsNumber() ? int(active->AsNumber()) : 0, 0, int(window.documents.size()) - 1); - if (std::optional place = readWindow(w.Find("window"))) - { - window.rect = place->rect; - window.mode = place->mode; - window.monitor = place->hasMonitor ? place->monitor : IntRect{}; - } - windows.push_back(std::move(window)); - } - m_savedDocuments[key] = std::move(windows); - } + if (std::optional place = ReadWindowPlace(section("windows", key))) + RestoreWindowPlace(windowID, *place); // Toolbars: each named item on its saved side and place; the rest stay where they are. for (const auto& [key, sides] : m_persistToolbars) @@ -670,11 +353,6 @@ namespace tachyon } } - // Layout presets: the saved ones and the file types'; the app's built-in ones stay. - for (const auto& [key, target] : m_persistPresets) - if (const JsonValue* saved = section("layoutPresets", key)) - (void)target->FromJson(saved->Write()); - // Theme variables, in place of the ones set before; the theme loads again with them, when // they differ from the ones it has (a start that changed nothing loads it once). for (const std::string& key : m_persistThemeVariables) diff --git a/src/gui_controls/controls_docking.cpp b/src/gui_docking/controls_docking.cpp similarity index 75% rename from src/gui_controls/controls_docking.cpp rename to src/gui_docking/controls_docking.cpp index af81d707..b4b1b485 100644 --- a/src/gui_controls/controls_docking.cpp +++ b/src/gui_docking/controls_docking.cpp @@ -1,6 +1,6 @@ -#include +#include -#include +#include #include @@ -9,7 +9,7 @@ #include #include -namespace tachyon +namespace tachyon::docking { // --------------------------------------------------------------------------- @@ -154,16 +154,16 @@ namespace tachyon return static_cast(mousePos.x - grabOffset - estimatedX); } - void EmitDockNode(GUIApplication& app, tachyon::DockingLayout* layout, DockNode* node); + void EmitDockNode(GUIApplication& app, Context& context, tachyon::docking::DockingLayout* layout, DockNode* node); // Ghost panel at the cursor previewing the floating window a drop would create: // a dock-leaf box with the dragged tab and an empty content area. - void EmitGhostTab(GUIApplication& app, const tachyon::Panel& panel, tachyon::int2 mousePos) + void EmitGhostTab(GUIApplication& app, Context& context, const tachyon::docking::Panel& panel, tachyon::int2 mousePos) { // Smaller than the real 400x300 spawn so it doesn't swamp the cursor. const tachyon::int2 kGhostSize { app.styleManager.Px(220), app.styleManager.Px(150) }; - if (app.BeginCursorGhostWindow(GUIApplicationInternals::TabDragGhostWindowID(app), mousePos, kGhostSize, - app.theme.dockLeafStyleRef)) + if (app.BeginCursorGhostWindow(app.DragGhostWindowID(), mousePos, kGhostSize, + GetStyles(app, context).dockLeafStyleRef)) { // Tab bar across the top, holding the single dragged tab. tachyon::ID barID = app.idManager.AllocateDynamicID("dock_ghost_bar"); @@ -207,7 +207,7 @@ namespace tachyon tachyon::ID contentID = app.idManager.AllocateDynamicID("dock_ghost_content"); tachyon::Element content{}; content.id = contentID; - content.styleRef = app.theme.dockContentStyleRef; + content.styleRef = GetStyles(app, context).dockContentStyleRef; content.state = app.guiStateManager.GetCurrentState(contentID); app.RegisterElement(std::move(content), tachyon::LayoutOverride{}.FlexGrow(1)); } @@ -218,7 +218,7 @@ namespace tachyon void EmitDropZoneOverlayRect(GUIApplication& app, IntRect overlay) { if (overlay.w <= 0 || overlay.h <= 0) return; - app.BeginGhostWindow(GUIApplicationInternals::TabDragGhostWindowID(app), + app.BeginGhostWindow(app.DragGhostWindowID(), { overlay.x, overlay.y }, { overlay.w, overlay.h }, app.theme.panelDropVisualizationStyleRef); // the window itself is the overlay app.EndGhostWindow(); @@ -248,25 +248,25 @@ namespace tachyon } // Its end: Dock, then the window buttons (EndTitleBar adds those). - void EndDockTitleBar(GUIApplication& app, const tachyon::DockingLayout* layout) + void EndDockTitleBar(GUIApplication& app, Context& context, const tachyon::docking::DockingLayout* layout) { if (layout->onDock) { - app.Button(app.idManager.AllocateDynamicID("dock_back"), { app.theme.dockIcon, "Dock" }, layout->onDock, + app.Button(app.idManager.AllocateDynamicID("dock_back"), { GetStyles(app, context).dockIcon, "Dock" }, layout->onDock, app.theme.titleBarTextButtonStyleRef); app.SetTooltip("Dock back into the main window"); } app.EndTitleBar(); } - void EmitDockLeaf(GUIApplication& app, tachyon::DockingLayout* layout, DockNode* node) + void EmitDockLeaf(GUIApplication& app, Context& context, tachyon::docking::DockingLayout* layout, DockNode* node) { // A torn-off window's only leaf: its tabs go in the title bar, the panel inset under it. const bool inTitleBar = layout->tabsInTitleBar && node == layout->root.get(); tachyon::Element leafElem{}; leafElem.id = node->nodeID; - leafElem.styleRef = inTitleBar ? app.theme.dockWindowLeafStyleRef : app.theme.dockLeafStyleRef; + leafElem.styleRef = inTitleBar ? GetStyles(app, context).dockWindowLeafStyleRef : GetStyles(app, context).dockLeafStyleRef; leafElem.state = app.guiStateManager.GetCurrentState(node->nodeID); const tachyon::ElementRef leafRef = app.RegisterElement(std::move(leafElem), {}); VERIFY(app.elementStorage.BeginChildren()); @@ -283,22 +283,22 @@ namespace tachyon (void)layout; ReorderLeafTabs(*node, from, to); }; - auto onClose = [&app, layout, node](int tabIndex) { - app.CloseDockedPanel(*layout, *node, tabIndex); + auto onClose = [&app, layout, node, &context](int tabIndex) { + CloseDockedPanel(app, context, *layout, *node, tabIndex); }; // Snapshot the selection to restore on drag-out (MouseDown selected the dragged tab). - if (!GUIApplicationInternals::Reorderable(app).Drag().IsPressed() || GUIApplicationInternals::Reorderable(app).Drag().groupID != node->tabBarID) + if (!app.ReorderDrag().IsPressed() || app.ReorderDrag().groupID != node->tabBarID) node->selectedTabBeforeDrag = node->selectedTab; // Publish cross-container drag info when this leaf is the drag source - // (reset in BeginDockingFrame when no drag is active). + // (reset in BeginFrame when no drag is active). { - auto& drag = GUIApplicationInternals::Reorderable(app).Drag(); + auto& drag = app.ReorderDrag(); if (drag.IsDragging() && drag.groupID == node->tabBarID && drag.draggedIndex >= 0 && drag.draggedIndex < (int)node->panelIds.size()) { - auto& info = GUIApplicationInternals::DockTabDrag(app).Info(); + auto& info = context.tabDrag.Info(); tachyon::ID pid = node->panelIds[drag.draggedIndex]; auto panelIt = layout->panels.find(pid); if (panelIt != layout->panels.end()) @@ -314,10 +314,10 @@ namespace tachyon // ----- onDragOut: full priority chain ----- // Fires end-of-frame when a tab is released outside the bar bounds. - auto onDragOut = [&app, layout, node](int tabIndex, tachyon::int2 mousePos) + auto onDragOut = [&app, layout, node, &context](int tabIndex, tachyon::int2 mousePos) { - GUIApplicationInternals::DockTabDrag(app).DropZoneAnim().hasTarget = false; - app.windowManager->RequestCloseAllowReopen(GUIApplicationInternals::TabDragGhostWindowID(app)); + context.tabDrag.DropZoneAnim().hasTarget = false; + app.windowManager->RequestCloseAllowReopen(app.DragGhostWindowID()); if (tabIndex < 0 || tabIndex >= (int)node->panelIds.size()) return; @@ -327,12 +327,12 @@ namespace tachyon // 1. Tab-bar drop - insert as tab at the hovered position. // TransferPanel moves the Panel object too when crossing layouts. - auto tabResult = app.FindDockLeafAtScreenPos(mousePos); + auto tabResult = FindDockLeafAtScreenPos(app, context, mousePos); if (tabResult.leaf && tabResult.leaf != node) { int insertIdx = TabInsertionIndex(*tabResult.leaf, mousePos); insertIdx = std::clamp(insertIdx, 0, (int)tabResult.leaf->panelIds.size()); - GUIApplication::TransferPanel(panelID, node, layout, tabResult.layout); + TransferPanel(panelID, node, layout, tabResult.layout); tabResult.leaf->panelIds.insert(tabResult.leaf->panelIds.begin() + insertIdx, panelID); tabResult.leaf->selectedTab = insertIdx; // Raise the destination, or the OS may focus an unrelated window @@ -344,7 +344,7 @@ namespace tachyon // 2. Content-area edge drop -> split the target leaf. // Center is not a target, so a floating window can always be made. - auto dropResult = app.FindDockDropTargetAtScreenPos(mousePos); + auto dropResult = FindDockDropTargetAtScreenPos(app, context, mousePos); if (dropResult.target.leaf && dropResult.target.zone != DockDropZone::None && dropResult.target.zone != DockDropZone::Center) @@ -352,7 +352,7 @@ namespace tachyon auto* ownerPtr = FindNodeOwner(dropResult.layout->root, dropResult.target.leaf); if (ownerPtr) { - GUIApplication::TransferPanel(panelID, node, layout, dropResult.layout); + TransferPanel(panelID, node, layout, dropResult.layout); SplitLeafAtZone(*ownerPtr, panelID, dropResult.target.zone); if (dropResult.layout->hostWindowID != tachyon::ID::Invalid()) app.windowManager->BringToFront(dropResult.layout->hostWindowID); @@ -361,13 +361,13 @@ namespace tachyon } // 3. No valid target -> tear off into a floating window - app.FloatPanel(*layout, panelID, mousePos); + FloatPanel(app, context, *layout, panelID, mousePos); }; // ----- dragVisualizer: drop-zone overlay OR ghost tab ----- // Animated overlay over an edge drop zone, otherwise a ghost panel at the // cursor. Both share the ghost window ID; only one renders per frame. - auto dragVisualizer = [&app, layout, node](int tabIndex, tachyon::int2 mousePos) + auto dragVisualizer = [&app, layout, node, &context](int tabIndex, tachyon::int2 mousePos) { if (tabIndex < 0 || tabIndex >= (int)node->panelIds.size()) return; tachyon::ID panelID = node->panelIds[tabIndex]; @@ -375,15 +375,15 @@ namespace tachyon if (panelIt == layout->panels.end()) return; // 1. Tab-bar hover -> the target bar's phantom tab is the visual. - DockNode* tabTarget = GUIApplicationInternals::FindDockLeafTabBarCachedAtScreenPos(app, mousePos); + DockNode* tabTarget = FindDockLeafTabBarCachedAtScreenPos(app, context, mousePos); if (tabTarget && tabTarget != node && !tabTarget->cachedTabRects.empty()) { - GUIApplicationInternals::DockTabDrag(app).DropZoneAnim().hasTarget = false; + context.tabDrag.DropZoneAnim().hasTarget = false; return; } // 2. Content-area edge drop zone -> animated overlay - auto dropResult = app.FindDockDropTargetAtScreenPos(mousePos); + auto dropResult = FindDockDropTargetAtScreenPos(app, context, mousePos); if (dropResult.target.leaf && dropResult.target.zone != DockDropZone::None && dropResult.target.zone != DockDropZone::Center) @@ -392,29 +392,29 @@ namespace tachyon if (targetRect.w <= 0 || targetRect.h <= 0) return; auto now = std::chrono::steady_clock::now(); - if (GUIApplicationInternals::DockTabDrag(app).DropZoneAnim().hasTarget) + if (context.tabDrag.DropZoneAnim().hasTarget) { // Animate from current position toward target - float dt = std::chrono::duration(now - GUIApplicationInternals::DockTabDrag(app).DropZoneAnim().lastTime).count(); + float dt = std::chrono::duration(now - context.tabDrag.DropZoneAnim().lastTime).count(); float t = 1.0f - std::exp(-dt / kRectAnimationTimeSecs); - GUIApplicationInternals::DockTabDrag(app).DropZoneAnim().currentRect = LerpRect(GUIApplicationInternals::DockTabDrag(app).DropZoneAnim().currentRect, targetRect, t); + context.tabDrag.DropZoneAnim().currentRect = LerpRect(context.tabDrag.DropZoneAnim().currentRect, targetRect, t); } else { // First frame with a drop zone - snap immediately - GUIApplicationInternals::DockTabDrag(app).DropZoneAnim().currentRect = targetRect; + context.tabDrag.DropZoneAnim().currentRect = targetRect; } - GUIApplicationInternals::DockTabDrag(app).DropZoneAnim().targetRect = targetRect; - GUIApplicationInternals::DockTabDrag(app).DropZoneAnim().hasTarget = true; - GUIApplicationInternals::DockTabDrag(app).DropZoneAnim().lastTime = now; + context.tabDrag.DropZoneAnim().targetRect = targetRect; + context.tabDrag.DropZoneAnim().hasTarget = true; + context.tabDrag.DropZoneAnim().lastTime = now; - EmitDropZoneOverlayRect(app, GUIApplicationInternals::DockTabDrag(app).DropZoneAnim().currentRect); + EmitDropZoneOverlayRect(app, context.tabDrag.DropZoneAnim().currentRect); } else { // Center zone or no target -> ghost panel (drop makes a floating window) - GUIApplicationInternals::DockTabDrag(app).DropZoneAnim().hasTarget = false; - EmitGhostTab(app, panelIt->second, mousePos); + context.tabDrag.DropZoneAnim().hasTarget = false; + EmitGhostTab(app, context, panelIt->second, mousePos); } }; @@ -425,7 +425,7 @@ namespace tachyon LayoutOverride{}, &node->tabLayout)) { // Between the tabs, the strip drags the window. - if (inTitleBar) GUIApplicationInternals::TitleBarCaption(app, node->tabBarID); + if (inTitleBar) app.TitleBarCaption(node->tabBarID); const int count = static_cast(node->panelIds.size()); if (count > 0 && (node->selectedTab < 0 || node->selectedTab >= count)) node->selectedTab = std::clamp(node->selectedTab, 0, count - 1); @@ -433,8 +433,8 @@ namespace tachyon // ----- Cross-container phantom tab detection ----- // A tab dragged from another bar over this one gets a phantom at the // insertion point so the real tabs shift apart, like within-bar reorder. - auto& drag = GUIApplicationInternals::Reorderable(app).Drag(); - const auto& dragInfo = GUIApplicationInternals::DockTabDrag(app).Info(); + auto& drag = app.ReorderDrag(); + const auto& dragInfo = context.tabDrag.Info(); tachyon::int2 mousePos = drag.cursorScreen; bool emitPhantom = false; int phantomIdx = 0; @@ -507,9 +507,9 @@ namespace tachyon if (inTitleBar) { (void)app.idManager.PushParent(node->nodeID); - EndDockTitleBar(app, layout); + EndDockTitleBar(app, context, layout); (void)app.idManager.PopParent(); - app.BeginArea(app.theme.dockWindowPanelStyleRef, tachyon::LayoutOverride{}.FlexGrow(1)); + app.BeginArea(GetStyles(app, context).dockWindowPanelStyleRef, tachyon::LayoutOverride{}.FlexGrow(1)); } // ----- Content area ----- @@ -524,8 +524,8 @@ namespace tachyon (void)app.idManager.PopParent(); node->lastContentID = contentID; node->lastContentPanelID = selectedPanelID; - // Record panel->content so InvalidatePanel(panelId) can resolve it. - GUIApplicationInternals::NotePanelContentID(app, selectedPanelID, contentID); + // Record panel->content so InvalidatePanel(app, context, panelId) can resolve it. + NotePanelContentID(app, context, selectedPanelID, contentID); auto panelIt = layout->panels.find(selectedPanelID); if (panelIt != layout->panels.end()) @@ -549,14 +549,14 @@ namespace tachyon { // BeginCached is the content container: it scopes the panel's // dynamic IDs under contentID and skips onPanelGUI on a cache hit. - if (app.BeginCached(contentID, app.theme.dockContentStyleRef, *cacheKey, {})) + if (app.BeginCached(contentID, GetStyles(app, context).dockContentStyleRef, *cacheKey, {})) { if (panelIt != layout->panels.end() && panelIt->second.onPanelGUI) panelIt->second.onPanelGUI(); } app.EndCached(); } - else if (app.BeginArea(contentID, app.theme.dockContentStyleRef, {})) + else if (app.BeginArea(contentID, GetStyles(app, context).dockContentStyleRef, {})) { // Opted out (or no panel): scope the panel's dynamic IDs under // its content area so they can't leak their counter into the @@ -574,19 +574,19 @@ namespace tachyon VERIFY(app.elementStorage.EndChildren()); } - void EmitDockSplit(GUIApplication& app, tachyon::DockingLayout* layout, DockNode* node) + void EmitDockSplit(GUIApplication& app, Context& context, tachyon::docking::DockingLayout* layout, DockNode* node) { const bool horizontal = IsHorizontalSplit(node->mode); const bool pinSecond = PinsSecondChild(node->mode); tachyon::Element container{}; container.id = node->nodeID; - container.styleRef = horizontal ? app.theme.dockSplitHorzStyleRef : app.theme.dockSplitVertStyleRef; + container.styleRef = horizontal ? GetStyles(app, context).dockSplitHorzStyleRef : GetStyles(app, context).dockSplitVertStyleRef; container.state = app.guiStateManager.GetCurrentState(node->nodeID); app.RegisterElement(std::move(container), {}); VERIFY(app.elementStorage.BeginChildren()); - EmitDockNode(app, layout, node->first.get()); + EmitDockNode(app, context, layout, node->first.get()); // Pin the sized child: first by default, second when pinSecond. if (!pinSecond) @@ -605,7 +605,7 @@ namespace tachyon tachyon::ID sizerID = app.idManager.AllocateDynamicID("dock_sizer"); tachyon::Element sizer{}; sizer.id = sizerID; - sizer.styleRef = horizontal ? app.theme.dockSizerHorzStyleRef : app.theme.dockSizerVertStyleRef; + sizer.styleRef = horizontal ? GetStyles(app, context).dockSizerHorzStyleRef : GetStyles(app, context).dockSizerVertStyleRef; sizer.state = app.guiStateManager.GetCurrentState(sizerID); // Last frame's laid-out extent bounds the split so a shrunken window or a long // drag can't squeeze the other child below its minimum. No extent yet: unbounded. @@ -634,7 +634,7 @@ namespace tachyon } } - EmitDockNode(app, layout, node->second.get()); + EmitDockNode(app, context, layout, node->second.get()); // When pinSecond, pin the second child after it's been emitted. if (pinSecond) @@ -652,11 +652,11 @@ namespace tachyon VERIFY(app.elementStorage.EndChildren()); } - void EmitDockNode(GUIApplication& app, tachyon::DockingLayout* layout, DockNode* node) + void EmitDockNode(GUIApplication& app, Context& context, tachyon::docking::DockingLayout* layout, DockNode* node) { if (!node) return; - if (node->isLeaf) EmitDockLeaf(app, layout, node); - else EmitDockSplit(app, layout, node); + if (node->isLeaf) EmitDockLeaf(app, context, layout, node); + else EmitDockSplit(app, context, layout, node); } } // namespace @@ -664,26 +664,23 @@ namespace tachyon // Per-frame docking bookkeeping // --------------------------------------------------------------------------- - bool GUIApplication::BeginDockingFrame() + void BeginFrame(GUIApplication& app, Context& context) { - m_closedPanels.clear(); // the last frame that could point into them is drawn - m_dockingLayoutsThisFrame.clear(); - m_toolbarDocksThisFrame.clear(); - if (!m_reorderable->Drag().IsPressed()) + context.closedPanels.clear(); // the last frame that could point into them is drawn + context.layoutsThisFrame.clear(); + if (!app.ReorderDrag().IsPressed()) { - m_dockTabDragSub->Info() = {}; - m_documentDrag = {}; + context.tabDrag.Info() = {}; + context.documentDrag = {}; } - ApplyDocumentMove(); // last frame's sets are still alive: nothing has been built yet - m_documentSetsThisFrame.clear(); - return true; + ApplyDocumentMove(app, context); // last frame's sets are still alive: nothing has been built yet + context.documentSetsThisFrame.clear(); } - void GUIApplication::EndDockingFrame() + void EndFrame(GUIApplication& app, Context& context) { - SyncDockingScrollOffsets(); - SyncDocumentRects(); - SyncToolbarDockRects(); + SyncDockingScrollOffsets(app, context); + SyncDocumentRects(app, context); } // --------------------------------------------------------------------------- @@ -711,7 +708,7 @@ namespace tachyon } } - void GUIApplication::DisableAllPanels(DockingLayout& layout) + void DisableAllPanels(GUIApplication&, Context&, DockingLayout& layout) { for (auto& [id, panel] : layout.panels) { @@ -721,7 +718,7 @@ namespace tachyon } } - void GUIApplication::EnableVisiblePanels(DockingLayout& layout) + void EnableVisiblePanels(GUIApplication&, Context&, DockingLayout& layout) { // Mark visible panels first so we can do the disable pass with a // single tree walk instead of one walk per panel. @@ -771,53 +768,53 @@ namespace tachyon CloseLeafTab(*node, i); } - bool GUIApplication::BeginDockingContainer(ID id, DockingLayout* layout, StyleRef style, LayoutOverride&& constraints) + bool BeginDockingContainer(GUIApplication& app, Context& context, ID id, DockingLayout* layout, StyleRef style, LayoutOverride&& constraints) { - m_dockingState = {}; - m_dockingState.containerID = id; - m_dockingState.layout = layout; + context.dockingState = {}; + context.dockingState.containerID = id; + context.dockingState.layout = layout; if (layout) { - m_dockingLayoutsThisFrame.push_back(layout); + context.layoutsThisFrame.push_back(layout); // Stamp the hosting OS window so cross-window drops can raise // the destination after the source window is destroyed. - layout->hostWindowID = activeWindowID; + layout->hostWindowID = app.CurrentWindowID(); } tachyon::Element container{}; container.id = id; container.styleRef = style; - container.state = guiStateManager.GetCurrentState(id); - RegisterElement(std::move(container), std::move(constraints)); - VERIFY(elementStorage.BeginChildren()); + container.state = app.guiStateManager.GetCurrentState(id); + app.RegisterElement(std::move(container), std::move(constraints)); + VERIFY(app.elementStorage.BeginChildren()); if (!layout) return true; DropMissingPanels(layout->root.get(), *layout); - CollapseEmptyLeaves(layout->root, &idManager); - AssignMissingNodeIDs(layout->root.get(), idManager); + CollapseEmptyLeaves(layout->root, &app.idManager); + AssignMissingNodeIDs(layout->root.get(), app.idManager); // Fire onEnable/onDisable transitions before any panel's onPanelGUI // runs, so a freshly-visible panel's resources are ready by emit time. - EnableVisiblePanels(*layout); + EnableVisiblePanels(app, context, *layout); if (layout->root && !(layout->root->isLeaf && layout->root->panelIds.empty())) - EmitDockNode(*this, layout, layout->root.get()); + EmitDockNode(app, context, layout, layout->root.get()); return true; } - void GUIApplication::EndDockingContainer() + void EndDockingContainer(GUIApplication& app, Context& context) { - VERIFY(elementStorage.EndChildren()); - m_dockingState = {}; + VERIFY(app.elementStorage.EndChildren()); + context.dockingState = {}; } // --------------------------------------------------------------------------- // Panel transfer helper // --------------------------------------------------------------------------- - void GUIApplication::TransferPanel(tachyon::ID panelID, DockNode* sourceNode, + void TransferPanel(tachyon::ID panelID, DockNode* sourceNode, DockingLayout* sourceLayout, DockingLayout* targetLayout) { @@ -855,16 +852,16 @@ namespace tachyon // Hit-testing // --------------------------------------------------------------------------- - tachyon::DockLeafResult GUIApplication::FindDockLeafAtScreenPos(int2 screenPos) + tachyon::docking::DockLeafResult FindDockLeafAtScreenPos(GUIApplication& app, Context& context, int2 screenPos) { DockLeafResult found {}; - auto walk = [this, screenPos, &found](auto& self, DockNode* node, DockingLayout* layout) -> void + auto walk = [&app, screenPos, &found](auto& self, DockNode* node, DockingLayout* layout) -> void { if (!node || found.leaf) return; if (node->isLeaf) { - auto ref = elementStorage.FindElementRefByID(node->tabBarID); - if (const auto* rectPtr = elementStorage.GetElementRectPtr(ref)) + auto ref = app.elementStorage.FindElementRefByID(node->tabBarID); + if (const auto* rectPtr = app.elementStorage.GetElementRectPtr(ref)) if (rectPtr->rect.Contains(screenPos)) found = { node, layout }; return; @@ -873,7 +870,7 @@ namespace tachyon if (!found.leaf) self(self, node->second.get(), layout); }; - for (DockingLayout* layout : m_dockingLayoutsThisFrame) + for (DockingLayout* layout : context.layoutsThisFrame) { if (!layout || found.leaf) break; walk(walk, layout->root.get(), layout); @@ -881,7 +878,7 @@ namespace tachyon return found; } - DockNode* GUIApplication::FindDockLeafTabBarCachedAtScreenPos(int2 screenPos) + DockNode* FindDockLeafTabBarCachedAtScreenPos(GUIApplication&, Context& context, int2 screenPos) { DockNode* found = nullptr; auto walk = [screenPos, &found](auto& self, DockNode* node) -> void @@ -898,7 +895,7 @@ namespace tachyon if (!found) self(self, node->second.get()); }; - for (DockingLayout* layout : m_dockingLayoutsThisFrame) + for (DockingLayout* layout : context.layoutsThisFrame) { if (!layout || found) break; walk(walk, layout->root.get()); @@ -906,7 +903,7 @@ namespace tachyon return found; } - tachyon::DockDropResult GUIApplication::FindDockDropTargetAtScreenPos(int2 screenPos) + tachyon::docking::DockDropResult FindDockDropTargetAtScreenPos(GUIApplication&, Context& context, int2 screenPos) { // Uses last frame's cachedContentRect; called during construction, before layout. DockDropResult result {}; @@ -930,7 +927,7 @@ namespace tachyon if (!result.target.leaf) self(self, node->second.get(), layout); }; - for (DockingLayout* layout : m_dockingLayoutsThisFrame) + for (DockingLayout* layout : context.layoutsThisFrame) { if (!layout || result.target.leaf) break; walk(walk, layout->root.get(), layout); @@ -942,7 +939,7 @@ namespace tachyon // Floating dock windows // --------------------------------------------------------------------------- - void GUIApplication::CloseDockedPanel(DockingLayout& layout, DockNode& leaf, int tabIndex) + void CloseDockedPanel(GUIApplication& app, Context& context, DockingLayout& layout, DockNode& leaf, int tabIndex) { if (!leaf.isLeaf || tabIndex < 0 || tabIndex >= int(leaf.panelIds.size())) return; const tachyon::ID panelID = leaf.panelIds[size_t(tabIndex)]; @@ -950,50 +947,50 @@ namespace tachyon // Closing is permanent: the panel and its state are destroyed (a new // panel can be created later), after its onDisable if it was shown. - ClosePanel(layout, panelID); + ClosePanel(app, context, layout, panelID); } - void GUIApplication::ClosePanel(DockingLayout& layout, ID panelID) + void ClosePanel(GUIApplication& app, Context& context, DockingLayout& layout, ID panelID) { if (layout.root) - (void)RemovePanel(layout.root, panelID, &idManager); + (void)RemovePanel(layout.root, panelID, &app.idManager); auto it = layout.panels.find(panelID); if (it == layout.panels.end()) return; if (it->second.internal.enabled && it->second.onDisable) it->second.onDisable(); - if (it->second.internal.ownsID) idManager.ReleaseStaticID(panelID); + if (it->second.internal.ownsID) app.idManager.ReleaseStaticID(panelID); // Out of the layout now; destroyed when the next frame starts. Closed while input is // handled, this frame's drawing, recorded after, may still point into what it holds // (a viewport's scene, a custom draw). - m_closedPanels.push_back(std::move(it->second)); + context.closedPanels.push_back(std::move(it->second)); layout.panels.erase(it); } - void GUIApplication::ErasePanels(DockingLayout& layout) + void ErasePanels(GUIApplication& app, Context& context, DockingLayout& layout) { - DisableAllPanels(layout); + DisableAllPanels(app, context, layout); for (auto& [id, panel] : layout.panels) { if (panel.internal.ownsID) - idManager.ReleaseStaticID(id); - m_closedPanels.push_back(std::move(panel)); // as ClosePanel: gone next frame + app.idManager.ReleaseStaticID(id); + context.closedPanels.push_back(std::move(panel)); // as ClosePanel: gone next frame } layout.panels.clear(); } - void GUIApplication::CloseFloatingDockWindow(size_t index) + void CloseFloatingDockWindow(GUIApplication& app, Context& context, size_t index) { - if (index >= m_floatingDockWindows.size()) return; - auto& fw = *m_floatingDockWindows[index]; + if (index >= context.floatingDockWindows.size()) return; + auto& fw = *context.floatingDockWindows[index]; // Closing the window closes its panels for good: they're disabled and // destroyed with the window's layout, and every ID it held is released. - ErasePanels(fw.layout); - ReleaseDockTreeIDs(fw.layout.root.get(), &idManager); + ErasePanels(app, context, fw.layout); + ReleaseDockTreeIDs(fw.layout.root.get(), &app.idManager); fw.layout.root.reset(); - idManager.ReleaseStaticID(fw.windowID); - m_floatingDockWindows.erase(m_floatingDockWindows.begin() + (ptrdiff_t)index); + app.idManager.ReleaseStaticID(fw.windowID); + context.floatingDockWindows.erase(context.floatingDockWindows.begin() + (ptrdiff_t)index); } - bool GUIApplication::FloatPanel(DockingLayout& layout, ID panelID, int2 screenPos) + bool FloatPanel(GUIApplication& app, Context& context, DockingLayout& layout, ID panelID, int2 screenPos) { DockNode* leaf = nullptr; auto find = [&](auto& self, DockNode* node) -> void @@ -1013,7 +1010,7 @@ namespace tachyon TransferPanel(panelID, leaf, &layout, nullptr); auto fw = std::make_unique(); - fw->windowID = idManager.CreateStaticID(); + fw->windowID = app.idManager.CreateStaticID(); fw->spawnPosition = screenPos; fw->layout.root = MakeLeaf({ panelID }); fw->layout.panels[panelID] = std::move(panelIt->second); @@ -1021,23 +1018,23 @@ namespace tachyon // Dock returns it here; floated from another torn-off window, to that one's home. fw->home = &layout; fw->homeLeafID = leaf->nodeID; - for (const auto& other : m_floatingDockWindows) + for (const auto& other : context.floatingDockWindows) if (&other->layout == &layout) { fw->home = other->home; fw->homeLeafID = other->homeLeafID; } - m_floatingDockWindows.push_back(std::move(fw)); + context.floatingDockWindows.push_back(std::move(fw)); return true; } - void GUIApplication::DockFloatingWindow(FloatingDockWindow& fw) + void DockFloatingWindow(GUIApplication& app, Context& context, FloatingDockWindow& fw) { fw.dockRequested = false; // Its home must still be docked this frame (not a closed window's layout). DockingLayout* home = fw.home; if (home == &fw.layout) return; - if (std::find(m_dockingLayoutsThisFrame.begin(), m_dockingLayoutsThisFrame.end(), home) == m_dockingLayoutsThisFrame.end()) + if (std::find(context.layoutsThisFrame.begin(), context.layoutsThisFrame.end(), home) == context.layoutsThisFrame.end()) { // A document that's open but not shown: show it, and dock once it's built. - if (ActivateDocumentOf(home)) + if (ActivateDocumentOf(app, context, home)) fw.dockRequested = true; return; } @@ -1077,23 +1074,24 @@ namespace tachyon } if (!moves.empty()) target->selectedTab = int(target->panelIds.size()) - 1; - CollapseEmptyLeaves(fw.layout.root, &idManager); + CollapseEmptyLeaves(fw.layout.root, &app.idManager); if (home->hostWindowID != ID::Invalid()) - windowManager->BringToFront(home->hostWindowID); + app.windowManager->BringToFront(home->hostWindowID); } - void GUIApplication::EmitFloatingDockWindows() + void EmitFloatingDockWindows(GUIApplication& app, Context& context) { - EmitFloatingDockWindowsOf(nullptr); + EmitFloatingDockWindowsOf(app, context, nullptr); } - void GUIApplication::EmitFloatingDockWindows(const DocumentSet& documents) + void EmitFloatingDockWindows(GUIApplication& app, Context& context, const DocumentSet& documents) { - EmitFloatingDockWindowsOf(&documents); + EmitFloatingDockWindowsOf(app, context, &documents); } - void GUIApplication::EmitFloatingDockWindowsOf(const DocumentSet* documents) + void EmitFloatingDockWindowsOf(GUIApplication& app, Context& context, const DocumentSet* documents) { + const Styles& styles = GetStyles(app, context); // A set's: those torn from its documents, wherever they were torn from since. auto ofSet = [documents](const FloatingDockWindow& fw) { @@ -1104,23 +1102,23 @@ namespace tachyon return true; return false; }; - for (size_t i = 0; i < m_floatingDockWindows.size(); ) + for (size_t i = 0; i < context.floatingDockWindows.size(); ) { - auto& fw = *m_floatingDockWindows[i]; + auto& fw = *context.floatingDockWindows[i]; if (!ofSet(fw)) { ++i; continue; } if (fw.dockRequested) - DockFloatingWindow(fw); + DockFloatingWindow(app, context, fw); // Check if layout is empty (all panels were dragged out) bool isEmpty = !fw.layout.root || (fw.layout.root->isLeaf && fw.layout.root->panelIds.empty()); if (isEmpty) { - CloseFloatingDockWindow(i); + CloseFloatingDockWindow(app, context, i); continue; } @@ -1147,7 +1145,7 @@ namespace tachyon static_cast(fw.spawnPosition.y)); fw.positioned = true; } - const bool open = BeginWindow(fw.windowID, title, theme.dockWindowStyleRef, std::move(constraints), + const bool open = app.BeginWindow(fw.windowID, title, styles.dockWindowStyleRef, std::move(constraints), ElementFlags::WindowUserControlled | ElementFlags::WindowCustomTitleBar | ElementFlags::WindowCloseWithParent); if (open) { @@ -1157,25 +1155,25 @@ namespace tachyon fw.layout.onDock = fw.home ? std::function([&fw] { fw.dockRequested = true; }) : std::function{}; if (fw.home) fw.layout.newTabMenu = fw.home->newTabMenu; - tachyon::ID containerID = idManager.AllocateDynamicID("floating_dock_container"); + tachyon::ID containerID = app.idManager.AllocateDynamicID("floating_dock_container"); if (fw.layout.tabsInTitleBar) - BeginDockingContainer(containerID, &fw.layout); + BeginDockingContainer(app, context, containerID, &fw.layout); else { - (void)idManager.PushParent(fw.windowID); - BeginDockTitleBar(*this, idManager.AllocateDynamicID("dock_title_bar")); - Text(idManager.AllocateDynamicID("dock_title"), title, theme.titleBarTitleStyleRef, LayoutOverride{}.FlexGrow(1)); - EndDockTitleBar(*this, &fw.layout); - (void)idManager.PopParent(); - BeginDockingContainer(containerID, &fw.layout, theme.dockWindowBodyStyleRef); + (void)app.idManager.PushParent(fw.windowID); + BeginDockTitleBar(app, app.idManager.AllocateDynamicID("dock_title_bar")); + app.Text(app.idManager.AllocateDynamicID("dock_title"), title, app.theme.titleBarTitleStyleRef, LayoutOverride{}.FlexGrow(1)); + EndDockTitleBar(app, context, &fw.layout); + (void)app.idManager.PopParent(); + BeginDockingContainer(app, context, containerID, &fw.layout, styles.dockWindowBodyStyleRef); } - EndDockingContainer(); + EndDockingContainer(app, context); } - EndWindow(); + app.EndWindow(); if (open) ++i; else - CloseFloatingDockWindow(i); // closed by the user + CloseFloatingDockWindow(app, context, i); // closed by the user } } @@ -1183,9 +1181,9 @@ namespace tachyon // Scroll offset sync // --------------------------------------------------------------------------- - void GUIApplication::SyncDockingScrollOffsets() + void SyncDockingScrollOffsets(GUIApplication& app, Context& context) { - auto walk = [this](auto& self, DockNode* node, DockingLayout* layout) -> void + auto walk = [&app](auto& self, DockNode* node, DockingLayout* layout) -> void { if (!node || !layout) return; if (node->isLeaf) @@ -1195,162 +1193,70 @@ namespace tachyon auto panelIt = layout->panels.find(node->lastContentPanelID); if (panelIt == layout->panels.end()) return; - auto& scrollManagement = guiStateManager.GetScrollManagement(); + auto& scrollManagement = app.guiStateManager.GetScrollManagement(); auto handle = scrollManagement.GetScrollOffsetHandle(node->lastContentID); if (handle != ScrollOffsetHandle::Invalid) panelIt->second.scrollOffset = scrollManagement.GetScrollOffset(handle); // Cache rects for next frame's construction-time hit-testing and overlays. - auto contentRef = elementStorage.FindElementRefByID(node->lastContentID); - if (const auto* rectPtr = elementStorage.GetElementRectPtr(contentRef)) + auto contentRef = app.elementStorage.FindElementRefByID(node->lastContentID); + if (const auto* rectPtr = app.elementStorage.GetElementRectPtr(contentRef)) node->cachedContentRect = rectPtr->rect; - auto leafRef = elementStorage.FindElementRefByID(node->nodeID); - if (const auto* leafRectPtr = elementStorage.GetElementRectPtr(leafRef)) + auto leafRef = app.elementStorage.FindElementRefByID(node->nodeID); + if (const auto* leafRectPtr = app.elementStorage.GetElementRectPtr(leafRef)) node->cachedLeafRect = leafRectPtr->rect; // Cache tab bar and tab rects for cross-container insertion. Tabs are looked // up by panel ID so the phantom is excluded (avoids feedback oscillation). node->cachedTabRects.clear(); - auto tabBarRef = elementStorage.FindElementRefByID(node->tabBarID); - if (const auto* tabBarRectPtr = elementStorage.GetElementRectPtr(tabBarRef)) + auto tabBarRef = app.elementStorage.FindElementRefByID(node->tabBarID); + if (const auto* tabBarRectPtr = app.elementStorage.GetElementRectPtr(tabBarRef)) node->cachedTabBarRect = tabBarRectPtr->rect; // One per panel, so the index is the panel's; an empty rect for a tab that's in // the overflow list rather than the bar. for (const auto& panelId : node->panelIds) { - auto tabRef = elementStorage.FindElementRefByID(panelId); - const auto* r = elementStorage.GetElementRectPtr(tabRef); + auto tabRef = app.elementStorage.FindElementRefByID(panelId); + const auto* r = app.elementStorage.GetElementRectPtr(tabRef); node->cachedTabRects.push_back(r ? r->rect : IntRect{}); } return; } - auto splitRef = elementStorage.FindElementRefByID(node->nodeID); - if (const auto* splitRectPtr = elementStorage.GetElementRectPtr(splitRef)) + auto splitRef = app.elementStorage.FindElementRefByID(node->nodeID); + if (const auto* splitRectPtr = app.elementStorage.GetElementRectPtr(splitRef)) node->cachedSplitRect = splitRectPtr->rect; self(self, node->first.get(), layout); self(self, node->second.get(), layout); }; - for (DockingLayout* layout : m_dockingLayoutsThisFrame) + for (DockingLayout* layout : context.layoutsThisFrame) { if (!layout) continue; walk(walk, layout->root.get(), layout); } - // m_dockingLayoutsThisFrame stays: onDragOut, run during input dispatch, reads it. - // BeginDockingFrame clears it. - } - void GUIApplication::ClaimCommandMode(ID owner, CommandMode mode) - { - if (owner == ID::Invalid() || mode == CommandMode::Default) - return; - m_commandModeClaims[owner] = { mode, m_commandModeFrame }; - } - - void GUIApplication::ApplyClaimedCommandMode() - { - // The claim the focus is in: the focused element's own, else one around it. - const InteractionState& interaction = guiStateManager.Interaction(); - const ID focused = interaction.GetFocusedID(); - std::optional mode; - for (auto it = m_commandModeClaims.begin(); it != m_commandModeClaims.end(); ) - { - const bool within = interaction.IsFocusWithin(it->first); - if (within && (!mode || it->first == focused)) - mode = it->second.mode; - // Not built this frame, and not where the focus is: gone (a closed panel's). - if (!within && it->second.frame != m_commandModeFrame) - it = m_commandModeClaims.erase(it); - else - ++it; - } - ++m_commandModeFrame; - - if (mode) - { - if (commandManager.GetMode() != *mode) - commandManager.SetMode(*mode); - m_claimedCommandMode = *mode; - } - else if (m_claimedCommandMode != CommandMode::Default) - { - // The focus left: Default again, unless the app set a mode of its own since. - if (commandManager.GetMode() == m_claimedCommandMode) - commandManager.SetMode(CommandMode::Default); - m_claimedCommandMode = CommandMode::Default; - } + // context.layoutsThisFrame stays: onDragOut, run during input dispatch, reads it. + // BeginFrame clears it. } - - void GUIApplication::DispatchInput(ID overID) - { - ApplyClaimedCommandMode(); - // What the user acts on, taken before the handlers move the focus or the capture. - std::vector actedOn = ActedOnIDs(overID); - if (inputManager) - inputManager->Process(guiStateManager, elementStorage, tabChainManager, textSystem, overID); - ReportChangedPanels(std::move(actedOn)); - } - - std::vector GUIApplication::ActedOnIDs(ID overID) const - { - std::vector ids; - if (!inputManager) - return ids; - bool pointer = false, keys = false; - for (const RecordedInputEvent& e : inputManager->GetRecordedEvents()) - switch (e.type) - { - case EventType::MouseDown: - case EventType::MouseUp: - case EventType::MouseScroll: - pointer = true; - break; - case EventType::MouseMove: - pointer |= e.state.buttons != MouseButtons::None; // a drag, not a pass over - break; - case EventType::KeyDown: - case EventType::KeyUp: - case EventType::TextInput: - keys = true; - break; - default: - break; - } - const InteractionState& interaction = guiStateManager.Interaction(); - auto add = [&ids](ID id) { - if (id != ID::Invalid() && std::find(ids.begin(), ids.end(), id) == ids.end()) - ids.push_back(id); - }; - if (pointer) - { - add(overID); - add(interaction.GetCaptureID()); - add(interaction.GetActiveID()); - } - if (keys) - add(interaction.GetFocusedID()); - return ids; - } - - void GUIApplication::ReportChangedPanels(std::vector actedOn) + void ReportChangedPanels(GUIApplication& app, Context& context, std::span actedOn) { - if (actedOn.empty() || m_dockingLayoutsThisFrame.empty()) + if (actedOn.empty() || context.layoutsThisFrame.empty()) return; // Each element's ancestors: a panel holds it when its content area is one of them. std::vector ancestors; for (const ID id : actedOn) - for (ElementRef r = elementStorage.FindElementRefByID(id); r != ElementRef::Invalid(); r = elementStorage.GetParentRef(r)) - if (const Element* e = elementStorage.GetElementPtr(r)) + for (ElementRef r = app.elementStorage.FindElementRefByID(id); r != ElementRef::Invalid(); r = app.elementStorage.GetParentRef(r)) + if (const Element* e = app.elementStorage.GetElementPtr(r)) ancestors.push_back(e->id); if (ancestors.empty()) return; // Gathered first: an onChanged may change the layouts. std::vector> calls; - for (DockingLayout* layout : m_dockingLayoutsThisFrame) + for (DockingLayout* layout : context.layoutsThisFrame) for (auto& [panelID, panel] : layout->panels) { if (!panel.onChanged) continue; - const ID* content = m_panelContentIDs.Find(panelID); + const ID* content = context.panelContentIDs.Find(panelID); if (content && std::find(ancestors.begin(), ancestors.end(), *content) != ancestors.end()) calls.push_back(panel.onChanged); } diff --git a/src/gui_controls/controls_documents.cpp b/src/gui_docking/controls_documents.cpp similarity index 58% rename from src/gui_controls/controls_documents.cpp rename to src/gui_docking/controls_documents.cpp index 6c84e0f3..2b6c283d 100644 --- a/src/gui_controls/controls_documents.cpp +++ b/src/gui_docking/controls_documents.cpp @@ -1,11 +1,11 @@ -#include +#include -#include +#include #include #include -namespace tachyon +namespace tachyon::docking { // --------------------------------------------------------------------------- @@ -23,7 +23,7 @@ namespace tachyon StyleRef line; }; - KindStyles StylesOf(const GUITheme& theme, std::string_view kind) + KindStyles StylesOf(GUIApplication& app, Context& context, std::string_view kind) { auto find = [&](std::string_view part, StyleRef plain) { @@ -31,12 +31,12 @@ namespace tachyon return plain; std::string cssClass = "document-"; cssClass.append(part).append("-").append(kind); - const Result found = theme.FindStyle(cssClass); + const Result found = app.theme.FindStyle(cssClass); return found ? *found : plain; }; - return { find("tab", theme.documentTabStyleRef), - find("name", theme.documentNameStyleRef), - find("line", theme.documentLineStyleRef) }; + return { find("tab", GetStyles(app, context).documentTabStyleRef), + find("name", GetStyles(app, context).documentNameStyleRef), + find("line", GetStyles(app, context).documentLineStyleRef) }; } // Moves a document within the set; the active one stays active. @@ -68,26 +68,26 @@ namespace tachyon } // A dragged document's tab, as it looks active: its kind's tab and name. - ElementRef DocumentTabPreview(GUIApplication& app, const Document& document, ID id, LayoutOverride&& constraints) + ElementRef DocumentTabPreview(GUIApplication& app, Context& context, const Document& document, ID id, LayoutOverride&& constraints) { - const KindStyles styles = StylesOf(app.theme, document.kind); - const ElementRef ref = app.RegisterElement(tachyon::Element{ .id = id, .styleRef = styles.tab, .flags = ElementFlags::NoInput, + const KindStyles kindStyles = StylesOf(app, context, document.kind); + const ElementRef ref = app.RegisterElement(tachyon::Element{ .id = id, .styleRef = kindStyles.tab, .flags = ElementFlags::NoInput, .state = ElementState::Selected }, std::move(constraints)); VERIFY(app.elementStorage.BeginChildren()); [[maybe_unused]] const bool pushed = app.idManager.PushParent(id); const ID nameID = app.idManager.AllocateDynamicID("name"); app.RegisterElement(tachyon::Element{ .id = nameID, - .textID = app.textSystem->RegisterText(nameID, document.icon, document.name, styles.name, ElementState::Selected), - .styleRef = styles.name, + .textID = app.textSystem->RegisterText(nameID, document.icon, document.name, kindStyles.name, ElementState::Selected), + .styleRef = kindStyles.name, .flags = ElementFlags::NoInput, .state = ElementState::Selected }, LayoutOverride::Auto()); const ID extensionID = app.idManager.AllocateDynamicID("extension"); app.RegisterElement(tachyon::Element{ .id = extensionID, .textID = app.textSystem->RegisterText(extensionID, IconID::Invalid, document.extension, - app.theme.documentExtensionStyleRef, ElementState::Selected), - .styleRef = app.theme.documentExtensionStyleRef, + GetStyles(app, context).documentExtensionStyleRef, ElementState::Selected), + .styleRef = GetStyles(app, context).documentExtensionStyleRef, .flags = ElementFlags::NoInput, .state = ElementState::Selected }, LayoutOverride::Auto()); if (pushed) @@ -98,79 +98,79 @@ namespace tachyon // At the cursor, the window a drop would make: its document bar with the tab, over an // empty workspace. - void DocumentGhost(GUIApplication& app, const Document& document, int2 cursor) + void DocumentGhost(GUIApplication& app, Context& context, const Document& document, int2 cursor) { const int2 size{ app.styleManager.Px(260), app.styleManager.Px(150) }; - if (app.BeginCursorGhostWindow(GUIApplicationInternals::TabDragGhostWindowID(app), cursor, size, + if (app.BeginCursorGhostWindow(app.DragGhostWindowID(), cursor, size, app.theme.mainWindowStyleRef)) { app.RegisterElement(tachyon::Element{ .id = app.idManager.AllocateDynamicID("document_ghost_bar"), - .styleRef = app.theme.documentBarStyleRef }, LayoutOverride::Auto()); + .styleRef = GetStyles(app, context).documentBarStyleRef }, LayoutOverride::Auto()); VERIFY(app.elementStorage.BeginChildren()); app.RegisterElement(tachyon::Element{ .id = app.idManager.AllocateDynamicID("document_ghost_row"), - .styleRef = app.theme.documentRowStyleRef }, LayoutOverride::Auto()); + .styleRef = GetStyles(app, context).documentRowStyleRef }, LayoutOverride::Auto()); VERIFY(app.elementStorage.BeginChildren()); - DocumentTabPreview(app, document, app.idManager.AllocateDynamicID("document_ghost_tab"), LayoutOverride::Auto()); + DocumentTabPreview(app, context, document, app.idManager.AllocateDynamicID("document_ghost_tab"), LayoutOverride::Auto()); VERIFY(app.elementStorage.EndChildren()); app.RegisterElement(tachyon::Element{ .id = app.idManager.AllocateDynamicID("document_ghost_line"), - .styleRef = StylesOf(app.theme, document.kind).line }, LayoutOverride::Auto()); + .styleRef = StylesOf(app, context, document.kind).line }, LayoutOverride::Auto()); VERIFY(app.elementStorage.EndChildren()); } app.EndGhostWindow(); } } - Document& GUIApplication::CreateDocument(DocumentSet& set, std::string name, std::string extension, + Document& CreateDocument(GUIApplication& app, Context&, DocumentSet& set, std::string name, std::string extension, std::string kind, IconID icon) { auto document = std::make_unique(); - document->id = idManager.CreateStaticID(); + document->id = app.idManager.CreateStaticID(); document->name = std::move(name); document->extension = std::move(extension); document->kind = std::move(kind); document->icon = icon; - document->internal.dockID = idManager.CreateStaticID(); + document->internal.dockID = app.idManager.CreateStaticID(); set.documents.push_back(std::move(document)); if (set.documents.size() == 1) set.active = 0; return *set.documents.back(); } - void GUIApplication::ForgetDockingLayout(DockingLayout& layout) + void ForgetDockingLayout(GUIApplication& app, Context& context, DockingLayout& layout) { - for (size_t i = m_floatingDockWindows.size(); i-- > 0; ) - if (m_floatingDockWindows[i]->home == &layout) - CloseFloatingDockWindow(i); - std::erase(m_dockingLayoutsThisFrame, &layout); - std::erase_if(m_persistDocks, [&](const PersistedDock& dock) { return dock.target == &layout; }); + for (size_t i = context.floatingDockWindows.size(); i-- > 0; ) + if (context.floatingDockWindows[i]->home == &layout) + CloseFloatingDockWindow(app, context, i); + std::erase(context.layoutsThisFrame, &layout); + std::erase_if(context.persistedLayouts, [&](const auto& kept) { return kept.second == &layout; }); } - void GUIApplication::ReleaseDockingLayout(DockingLayout& layout) + void ReleaseDockingLayout(GUIApplication& app, Context& context, DockingLayout& layout) { - ForgetDockingLayout(layout); - ErasePanels(layout); - ReleaseDockTreeIDs(layout.root.get(), &idManager); + ForgetDockingLayout(app, context, layout); + ErasePanels(app, context, layout); + ReleaseDockTreeIDs(layout.root.get(), &app.idManager); layout.root.reset(); } - void GUIApplication::CloseDocument(DocumentSet& set, int index) + void CloseDocument(GUIApplication& app, Context& context, DocumentSet& set, int index) { if (index < 0 || index >= int(set.documents.size())) return; Document& document = *set.documents[size_t(index)]; // A drag or drop of its tab ends with it: both point at the document. - if (m_documentDrag.document == &document) - m_documentDrag = {}; - if (m_documentMove && m_documentMove->document == &document) - m_documentMove.reset(); + if (context.documentDrag.document == &document) + context.documentDrag = {}; + if (context.documentMove && context.documentMove->document == &document) + context.documentMove.reset(); // Its panels, and its torn-off ones, go with it; they would dock back into a layout // that's gone. - ReleaseDockingLayout(document.layout); - idManager.ReleaseStaticID(document.internal.dockID); + ReleaseDockingLayout(app, context, document.layout); + app.idManager.ReleaseStaticID(document.internal.dockID); if (document.id.GetMode() == IDMode::Static) - idManager.ReleaseStaticID(document.id); + app.idManager.ReleaseStaticID(document.id); set.documents.erase(set.documents.begin() + index); // The active one stays; when it was this one, the one after it (else before it). @@ -179,27 +179,29 @@ namespace tachyon set.active = std::clamp(set.active, 0, std::max(0, int(set.documents.size()) - 1)); } - void GUIApplication::CloseAllDocuments(DocumentSet& set) + void CloseAllDocuments(GUIApplication& app, Context& context, DocumentSet& set) { while (!set.documents.empty()) - CloseDocument(set, int(set.documents.size()) - 1); + CloseDocument(app, context, set, int(set.documents.size()) - 1); } - void GUIApplication::Documents(ID id, DocumentSet& set, LayoutOverride&& constraints) + void Documents(GUIApplication& app, Context& context, ID id, DocumentSet& set, LayoutOverride&& constraints) { - RegisterElement(tachyon::Element{ .id = id, .styleRef = theme.documentsStyleRef, .state = guiStateManager.GetCurrentState(id) }, + const Styles& styles = GetStyles(app, context); + app.RegisterElement(tachyon::Element{ .id = id, .styleRef = styles.documentsStyleRef, .state = app.guiStateManager.GetCurrentState(id) }, std::move(constraints)); - VERIFY(elementStorage.BeginChildren()); - [[maybe_unused]] const bool pushed = idManager.PushParent(id); - DocumentBar(idManager.AllocateDynamicID("document_bar"), set); + VERIFY(app.elementStorage.BeginChildren()); + [[maybe_unused]] const bool pushed = app.idManager.PushParent(id); + DocumentBar(app, context, app.idManager.AllocateDynamicID("document_bar"), set); if (pushed) - (void)idManager.PopParent(); - DocumentPanels(set); - VERIFY(elementStorage.EndChildren()); + (void)app.idManager.PopParent(); + DocumentPanels(app, context, set); + VERIFY(app.elementStorage.EndChildren()); } - void GUIApplication::DocumentBar(ID id, DocumentSet& set, StyleRef style, LayoutOverride&& constraints) + void DocumentBar(GUIApplication& app, Context& context, ID id, DocumentSet& set, StyleRef style, LayoutOverride&& constraints) { + const Styles& styles = GetStyles(app, context); // The documents whose tabs asked to close, now that no handler holds on to them. for (size_t i = set.documents.size(); i-- > 0; ) { @@ -208,28 +210,28 @@ namespace tachyon continue; document.internal.closeAsked = false; if (!set.onClose || set.onClose(document)) - CloseDocument(set, int(i)); + CloseDocument(app, context, set, int(i)); } set.active = std::clamp(set.active, 0, std::max(0, int(set.documents.size()) - 1)); - m_documentSetsThisFrame.push_back(&set); - set.internal.hostWindowID = activeWindowID; + context.documentSetsThisFrame.push_back(&set); + set.internal.hostWindowID = app.CurrentWindowID(); // Only the active document's panels are shown. Document* const active = set.Active(); for (const auto& document : set.documents) if (document.get() != active) - DisableAllPanels(document->layout); + DisableAllPanels(app, context, document->layout); // ---- The bar: the tabs, "+", and the list of every document ---- set.internal.barID = id; - RegisterElement(tachyon::Element{ .id = id, .styleRef = style }, std::move(constraints)); - VERIFY(elementStorage.BeginChildren()); - [[maybe_unused]] const bool pushed = idManager.PushParent(id); - RegisterElement(tachyon::Element{ .id = idManager.AllocateDynamicID("document_row"), .styleRef = theme.documentRowStyleRef }, + app.RegisterElement(tachyon::Element{ .id = id, .styleRef = style }, std::move(constraints)); + VERIFY(app.elementStorage.BeginChildren()); + [[maybe_unused]] const bool pushed = app.idManager.PushParent(id); + app.RegisterElement(tachyon::Element{ .id = app.idManager.AllocateDynamicID("document_row"), .styleRef = styles.documentRowStyleRef }, LayoutOverride::Auto()); - VERIFY(elementStorage.BeginChildren()); + VERIFY(app.elementStorage.BeginChildren()); - const ID tabBarID = idManager.AllocateDynamicID("document_tabs"); + const ID tabBarID = app.idManager.AllocateDynamicID("document_tabs"); set.internal.tabBarID = tabBarID; TabBarLayout oneRow = TabBarLayout::OneRow; DocumentSet* const setPtr = &set; @@ -237,50 +239,50 @@ namespace tachyon // A tab dropped off the bar: onto another bar it moves there, elsewhere it's torn off // into a window of its own; either at the next frame's start. Only document bars take // documents: a drop on panels is a tear-off too. - auto onDragOut = [this, setPtr](int index, int2 screenPos) + auto onDragOut = [&app, setPtr, &context](int index, int2 screenPos) { - windowManager->RequestCloseAllowReopen(tabDragGhostWindowID); + app.windowManager->RequestCloseAllowReopen(app.DragGhostWindowID()); if (index < 0 || index >= int(setPtr->documents.size())) return; Document* const document = setPtr->documents[size_t(index)].get(); // Its own bar, off the tabs ("+", the empty bar, "N open"): it moves along it, last // when it's past them. - DocumentSet* const target = FindDocumentBarAt(screenPos); + DocumentSet* const target = FindDocumentBarAt(app, context, screenPos); if (target) - m_documentMove = DocumentMove{ document, setPtr, target, InsertionIndex(*target, screenPos.x), screenPos }; + context.documentMove = DocumentMove{ document, setPtr, target, InsertionIndex(*target, screenPos.x), screenPos }; else if (setPtr->onTearOff) - m_documentMove = DocumentMove{ document, setPtr, nullptr, 0, screenPos }; + context.documentMove = DocumentMove{ document, setPtr, nullptr, 0, screenPos }; }; // Off the bar: over another one its phantom tab shows where it goes, elsewhere the // window a drop would make follows the cursor. - auto dragVisualizer = [this, setPtr](int index, int2 cursor) + auto dragVisualizer = [&app, setPtr, &context](int index, int2 cursor) { if (index < 0 || index >= int(setPtr->documents.size()) || !setPtr->onTearOff) return; - for (const IntRect& bar : m_documentBarRects) + for (const IntRect& bar : context.documentBarRects) if (bar.Contains(cursor)) return; - DocumentGhost(*this, *setPtr->documents[size_t(index)], cursor); + DocumentGhost(app, context, *setPtr->documents[size_t(index)], cursor); }; - BeginTabBar(tabBarID, &set.active, + app.BeginTabBar(tabBarID, &set.active, [setPtr](int from, int to) { MoveDocument(*setPtr, from, to); }, [setPtr](int index) { if (index >= 0 && index < int(setPtr->documents.size())) setPtr->documents[size_t(index)]->internal.closeAsked = true; }, - std::move(onDragOut), std::move(dragVisualizer), theme.documentTabBarStyleRef, {}, &oneRow, + std::move(onDragOut), std::move(dragVisualizer), styles.documentTabBarStyleRef, {}, &oneRow, TabBarOptions{ .closeLabel = "Close Document", .listHidden = false, .layoutMenu = false, .dropArea = set.internal.barID }); // the whole bar, its line and "N open" too // This bar's tab being dragged: the other bars learn which document it is. - const ReorderableDragState& drag = m_reorderable->Drag(); + const ReorderableDragState& drag = app.ReorderDrag(); if (drag.IsDragging() && drag.groupID == tabBarID) { // The drag counts the tabs in the bar; the ones left out are skipped. int index = -1; for (int i = 0, slot = 0; i < int(set.documents.size()); ++i) { - const auto& shown = m_tabBarState.shown; + const auto& shown = app.CurrentTabBar().shown; if (!shown.empty() && (size_t(i) >= shown.size() || !shown[size_t(i)])) continue; if (slot++ == drag.draggedIndex) @@ -291,13 +293,13 @@ namespace tachyon } const bool measured = index >= 0 && drag.draggedIndex < int(drag.originalRects.size()); if (index >= 0) - m_documentDrag = { set.documents[size_t(index)].get(), &set, + context.documentDrag = { set.documents[size_t(index)].get(), &set, measured ? drag.originalRects[size_t(drag.draggedIndex)].w : 0, measured ? drag.press.drag.pressScreen.x - drag.originalRects[size_t(drag.draggedIndex)].x : 0 }; } // Another bar's tab over this one: a phantom where it would go, the tabs moving apart. int phantomAt = -1; - if (m_documentDrag.document && m_documentDrag.source != &set && drag.IsPressed() && drag.groupID != tabBarID + if (context.documentDrag.document && context.documentDrag.source != &set && drag.IsPressed() && drag.groupID != tabBarID && set.internal.barRect.Contains(drag.cursorScreen)) phantomAt = InsertionIndex(set, drag.cursorScreen.x); // It follows the cursor, held where it was grabbed, over the other tabs, as a tab @@ -305,13 +307,13 @@ namespace tachyon // tab before it, else where the tab after it starts). auto phantom = [&] { - const ElementRef ref = DocumentTabPreview(*this, *m_documentDrag.document, idManager.AllocateDynamicID("document_phantom"), - m_documentDrag.tabWidth > 0 ? LayoutOverride::Auto().Width(Pixels{ m_documentDrag.tabWidth }) + const ElementRef ref = DocumentTabPreview(app, context, *context.documentDrag.document, app.idManager.AllocateDynamicID("document_phantom"), + context.documentDrag.tabWidth > 0 ? LayoutOverride::Auto().Width(Pixels{ context.documentDrag.tabWidth }) : LayoutOverride::Auto()); - if (!elementStorage.IsValidRef(ref)) + if (!app.elementStorage.IsValidRef(ref)) return; const auto& rects = set.internal.tabRects; - const LayoutStyle* barLayout = styleManager.GetLayoutStyle(theme.documentTabBarStyleRef.layoutStyleIndex); + const LayoutStyle* barLayout = app.styleManager.GetLayoutStyle(styles.documentTabBarStyleRef.layoutStyleIndex); const int32_t gap = barLayout ? int32_t(barLayout->layoutData.flex.gap) : 0; int32_t placed = set.internal.barRect.x; bool found = false; @@ -327,12 +329,12 @@ namespace tachyon placed = rects[i].x; found = true; } - const int32_t offset = drag.cursorScreen.x - m_documentDrag.grabOffset - placed; - auto& rect = elementStorage.GetElementRectUnsafe(ref); + const int32_t offset = drag.cursorScreen.x - context.documentDrag.grabOffset - placed; + auto& rect = app.elementStorage.GetElementRectUnsafe(ref); const LayoutOverride relative = LayoutOverride{}.Relative(static_cast(offset), 0); rect.constraints.x = relative.x; rect.constraints.y = relative.y; - windowRegistry.MoveSubtreeToEnd(ref); + app.windowRegistry.MoveSubtreeToEnd(ref); }; for (size_t i = 0; i < set.documents.size(); ++i) @@ -340,119 +342,121 @@ namespace tachyon if (int(i) == phantomAt) phantom(); Document& document = *set.documents[i]; - const KindStyles styles = StylesOf(theme, document.kind); - if (BeginTab(document.id, { document.icon, document.name }, styles.tab, styles.name)) + const KindStyles kindStyles = StylesOf(app, context, document.kind); + if (app.BeginTab(document.id, { document.icon, document.name }, kindStyles.tab, kindStyles.name)) { - const ElementState state = guiStateManager.GetCurrentState(m_tabState.bodyID); - [[maybe_unused]] const bool inTab = idManager.PushParent(document.id); + const ElementState state = app.guiStateManager.GetCurrentState(app.CurrentTab().bodyID); + [[maybe_unused]] const bool inTab = app.idManager.PushParent(document.id); // Name + extension: the extension right after the name, muted. - const ID extensionID = idManager.AllocateDynamicID("extension"); - RegisterElement(tachyon::Element{ + const ID extensionID = app.idManager.AllocateDynamicID("extension"); + app.RegisterElement(tachyon::Element{ .id = extensionID, - .textID = textSystem->RegisterText(extensionID, IconID::Invalid, document.extension, theme.documentExtensionStyleRef, state), - .styleRef = theme.documentExtensionStyleRef, + .textID = app.textSystem->RegisterText(extensionID, IconID::Invalid, document.extension, styles.documentExtensionStyleRef, state), + .styleRef = styles.documentExtensionStyleRef, .flags = ElementFlags::NoInput, .state = state }, LayoutOverride::Auto()); - RegisterElement(tachyon::Element{ .id = idManager.AllocateDynamicID("gap"), .styleRef = theme.emptyHorzStyleRef, + app.RegisterElement(tachyon::Element{ .id = app.idManager.AllocateDynamicID("gap"), .styleRef = app.theme.emptyHorzStyleRef, .flags = ElementFlags::NoInput }, LayoutOverride{}.FlexGrow(1)); // Its close button on the active or hovered tab, else a dot for unsaved changes. // The slot keeps its size, so the tab doesn't change width on hover. - RegisterElement(tachyon::Element{ .id = idManager.AllocateDynamicID("mark"), .styleRef = theme.documentMarkStyleRef, + app.RegisterElement(tachyon::Element{ .id = app.idManager.AllocateDynamicID("mark"), .styleRef = styles.documentMarkStyleRef, .state = state }, LayoutOverride::Auto()); - VERIFY(elementStorage.BeginChildren()); + VERIFY(app.elementStorage.BeginChildren()); const bool showClose = (state & (ElementState::Selected | ElementState::Hover)) != ElementState::None; if (showClose) { Document* const target = &document; - Button(idManager.AllocateDynamicID("close"), theme.tabCloseIcon, - [target] { target->internal.closeAsked = true; }, theme.documentCloseStyleRef); + app.Button(app.idManager.AllocateDynamicID("close"), app.theme.tabCloseIcon, + [target] { target->internal.closeAsked = true; }, styles.documentCloseStyleRef); } else if (document.dirty) - RegisterElement(tachyon::Element{ .id = idManager.AllocateDynamicID("dirty"), .styleRef = theme.documentDirtyStyleRef, + app.RegisterElement(tachyon::Element{ .id = app.idManager.AllocateDynamicID("dirty"), .styleRef = styles.documentDirtyStyleRef, .flags = ElementFlags::NoInput, .state = state }, LayoutOverride::Auto()); - VERIFY(elementStorage.EndChildren()); + VERIFY(app.elementStorage.EndChildren()); if (inTab) - (void)idManager.PopParent(); + (void)app.idManager.PopParent(); } - EndTab(); + app.EndTab(); } if (phantomAt >= int(set.documents.size())) phantom(); // "+" after the last tab; the bar leaves room for it when tabs don't all fit. - auto& fit = guiStateManager.GetElementDataStore().GetOrCreate(tabBarID); + auto& fit = app.guiStateManager.GetElementDataStore().GetOrCreate(tabBarID); if (set.onNew) { - const ID newID = idManager.AllocateDynamicID("document_new"); - Button(newID, theme.addIcon, [setPtr] { if (setPtr->onNew) setPtr->onNew(); }, theme.documentNewStyleRef, + const ID newID = app.idManager.AllocateDynamicID("document_new"); + app.Button(newID, app.theme.addIcon, [setPtr] { if (setPtr->onNew) setPtr->onNew(); }, styles.documentNewStyleRef, LayoutOverride{}.NoGrow().NoShrink()); - if (const ElementRef ref = elementStorage.FindElementRefByID(newID); ref.IsValid()) - [[maybe_unused]] auto added = elementStorage.AddPostLayout(ref, [this, tabBarID](PostLayoutContext& ctx) - { guiStateManager.GetElementDataStore().GetOrCreate(tabBarID).trailingWidth = ctx.ElementRect().w; }); + if (const ElementRef ref = app.elementStorage.FindElementRefByID(newID); ref.IsValid()) + [[maybe_unused]] auto added = app.elementStorage.AddPostLayout(ref, [&app, tabBarID](PostLayoutContext& ctx) + { app.guiStateManager.GetElementDataStore().GetOrCreate(tabBarID).trailingWidth = ctx.ElementRect().w; }); } else fit.trailingWidth = 0; - EndTabBar(); + app.EndTabBar(); // "N open": every document, the hidden ones too; picking one shows it. if (!set.documents.empty()) { - const ID listID = idManager.AllocateDynamicID("document_list"); + const ID listID = app.idManager.AllocateDynamicID("document_list"); // A dropdown also when the bar is in a title bar, not one of its menus. - if (BeginDropdownMenu(listID, std::to_string(set.documents.size()) + " open", theme.documentListStyleRef, - theme.menuStyleRef, theme.menuItemRowStyleRef, LayoutOverride{}.NoGrow().NoShrink())) + if (app.BeginDropdownMenu(listID, std::to_string(set.documents.size()) + " open", styles.documentListStyleRef, + app.theme.menuStyleRef, app.theme.menuItemRowStyleRef, LayoutOverride{}.NoGrow().NoShrink())) { for (size_t i = 0; i < set.documents.size(); ++i) { const Document& document = *set.documents[i]; - MenuItem({ document.icon, document.name + document.extension }, + app.MenuItem({ document.icon, document.name + document.extension }, [setPtr, index = int(i)] { setPtr->active = index; }); } } - EndMenu(); + app.EndMenu(); } - VERIFY(elementStorage.EndChildren()); // row + VERIFY(app.elementStorage.EndChildren()); // row // The line under the bar, in the active document's color: the workspace below is its. // In a title bar it goes under the whole bar instead (DocumentLine). - if (style != theme.titleBarDocumentsStyleRef) - DocumentLine(set); + if (style != styles.titleBarDocumentsStyleRef) + DocumentLine(app, context, set); if (pushed) - (void)idManager.PopParent(); - VERIFY(elementStorage.EndChildren()); // bar + (void)app.idManager.PopParent(); + VERIFY(app.elementStorage.EndChildren()); // bar } - void GUIApplication::DocumentLine(const DocumentSet& set, LayoutOverride&& constraints) + void DocumentLine(GUIApplication& app, Context& context, const DocumentSet& set, LayoutOverride&& constraints) { + const Styles& styles = GetStyles(app, context); const Document* const active = set.Active(); - RegisterElement(tachyon::Element{ .id = idManager.AllocateDynamicID("document_line"), - .styleRef = active ? StylesOf(theme, active->kind).line : theme.documentLineStyleRef }, + app.RegisterElement(tachyon::Element{ .id = app.idManager.AllocateDynamicID("document_line"), + .styleRef = active ? StylesOf(app, context, active->kind).line : styles.documentLineStyleRef }, std::move(constraints)); } - void GUIApplication::DocumentPanels(DocumentSet& set, LayoutOverride&& constraints) + void DocumentPanels(GUIApplication& app, Context& context, DocumentSet& set, LayoutOverride&& constraints) { + const Styles& styles = GetStyles(app, context); if (Document* const active = set.Active()) { active->layout.newTabMenu = set.newTabMenu; - BeginDockingContainer(active->internal.dockID, &active->layout, theme.dockContainerMainStyleRef, std::move(constraints)); - EndDockingContainer(); + BeginDockingContainer(app, context, active->internal.dockID, &active->layout, styles.dockContainerMainStyleRef, std::move(constraints)); + EndDockingContainer(app, context); } } - void GUIApplication::ApplyDocumentMove() + void ApplyDocumentMove(GUIApplication& app, Context& context) { - if (!m_documentMove) + if (!context.documentMove) return; - const DocumentMove move = *m_documentMove; - m_documentMove.reset(); + const DocumentMove move = *context.documentMove; + context.documentMove.reset(); // Both sets were built last frame, so they're still there. - auto built = [this](const DocumentSet* set) - { return std::find(m_documentSetsThisFrame.begin(), m_documentSetsThisFrame.end(), set) != m_documentSetsThisFrame.end(); }; + auto built = [&app, &context](const DocumentSet* set) + { return std::find(context.documentSetsThisFrame.begin(), context.documentSetsThisFrame.end(), set) != context.documentSetsThisFrame.end(); }; if (!built(move.source) || (move.target && !built(move.target)) || (!move.target && !move.source->onTearOff)) return; auto& from = move.source->documents; @@ -478,38 +482,38 @@ namespace tachyon to.insert(to.begin() + at, std::move(taken)); move.target->active = at; if (move.target->internal.hostWindowID != ID::Invalid()) - windowManager->BringToFront(move.target->internal.hostWindowID); + app.windowManager->BringToFront(move.target->internal.hostWindowID); } - void GUIApplication::SyncDocumentRects() + void SyncDocumentRects(GUIApplication& app, Context& context) { - auto rectOf = [this](ID id) + auto rectOf = [&app](ID id) { - const auto* rect = elementStorage.GetElementRectPtr(elementStorage.FindElementRefByID(id)); + const auto* rect = app.elementStorage.GetElementRectPtr(app.elementStorage.FindElementRefByID(id)); return rect ? rect->rect : IntRect{}; }; - m_documentBarRects.clear(); - for (DocumentSet* set : m_documentSetsThisFrame) + context.documentBarRects.clear(); + for (DocumentSet* set : context.documentSetsThisFrame) { set->internal.barRect = rectOf(set->internal.barID); set->internal.tabRects.clear(); for (const auto& document : set->documents) set->internal.tabRects.push_back(rectOf(document->id)); - m_documentBarRects.push_back(set->internal.barRect); + context.documentBarRects.push_back(set->internal.barRect); } } - DocumentSet* GUIApplication::FindDocumentBarAt(int2 screenPos) + DocumentSet* FindDocumentBarAt(GUIApplication&, Context& context, int2 screenPos) { - for (DocumentSet* set : m_documentSetsThisFrame) + for (DocumentSet* set : context.documentSetsThisFrame) if (set->internal.barRect.Contains(screenPos)) return set; return nullptr; } - bool GUIApplication::ActivateDocumentOf(const DockingLayout* layout) + bool ActivateDocumentOf(GUIApplication&, Context& context, const DockingLayout* layout) { - for (DocumentSet* set : m_documentSetsThisFrame) + for (DocumentSet* set : context.documentSetsThisFrame) for (size_t i = 0; i < set->documents.size(); ++i) if (&set->documents[i]->layout == layout) { diff --git a/src/gui_controls/gui_dock_node.cpp b/src/gui_docking/gui_dock_node.cpp similarity index 99% rename from src/gui_controls/gui_dock_node.cpp rename to src/gui_docking/gui_dock_node.cpp index 65a3ab09..14dae1d5 100644 --- a/src/gui_controls/gui_dock_node.cpp +++ b/src/gui_docking/gui_dock_node.cpp @@ -1,4 +1,4 @@ -#include +#include #include @@ -7,7 +7,7 @@ #include #include -namespace tachyon +namespace tachyon::docking { // ---- Factory helpers ---------------------------------------------------- diff --git a/src/gui_controls/gui_dock_node.h b/src/gui_docking/gui_dock_node.h similarity index 97% rename from src/gui_controls/gui_dock_node.h rename to src/gui_docking/gui_dock_node.h index 13ae30c2..f53feaf8 100644 --- a/src/gui_controls/gui_dock_node.h +++ b/src/gui_docking/gui_dock_node.h @@ -1,6 +1,7 @@ #pragma once #include +#include // TabBarLayout #include #include @@ -13,11 +14,15 @@ #include namespace tachyon +{ + class IDManager; +} + +namespace tachyon::docking { /// @addtogroup controls_docking /// @{ - class IDManager; /// Split direction and which child is pinned to splitSize; the other child flexes. @@ -51,12 +56,6 @@ namespace tachyon Center ///< the interior, not near any edge }; - /// How a tab bar lays out tabs that don't fit on one row. - enum class TabBarLayout : uint8_t - { - OneRow, ///< one row; the tabs that don't fit are listed by a "+N" button after the others - Rows ///< every tab shown, on as many rows as they take - }; /// Docking tree node: a leaf with panel tabs, or a split with two children where /// splitSize applies to the pinned child. No application dependencies, so it's unit-testable. diff --git a/src/gui_docking/gui_docking.cpp b/src/gui_docking/gui_docking.cpp new file mode 100644 index 00000000..cb534fd4 --- /dev/null +++ b/src/gui_docking/gui_docking.cpp @@ -0,0 +1,129 @@ +#include +#include + +#include + +#include +#include + +namespace tachyon::docking +{ + namespace + { + // A Lucide shape (ISC), 24-unit strokes with round caps, in one neutral grey so it draws + // as a mask in the color of where it's shown; as the theme registers its own. + IconID RegisterIcon(ITextSystem* textSystem, const char* name, const char* shapes) + { + if (!textSystem) + return IconID::Invalid; + const std::string svg = std::string(R"()") + shapes + ""; + const std::string fullName = std::string("tachyon/") + name; + return textSystem->RegisterIconFromSVG(fullName.c_str(), svg.data(), svg.size()); + } + } + + void Styles::Load(GUIApplication& app) + { + GUITheme& theme = app.theme; + dockWindowStyleRef = theme.GetStyle("dock-window"); + dockWindowLeafStyleRef = theme.GetStyle("dock-window-leaf"); + dockWindowPanelStyleRef = theme.GetStyle("dock-window-panel"); + dockWindowBodyStyleRef = theme.GetStyle("dock-window-body"); + documentsStyleRef = theme.GetStyle("documents"); + documentBarStyleRef = theme.GetStyle("document-bar"); + documentRowStyleRef = theme.GetStyle("document-row"); + documentTabBarStyleRef = theme.GetStyle("document-tab-bar"); + documentTabStyleRef = theme.GetStyle("document-tab"); + documentNameStyleRef = theme.GetStyle("document-name"); + documentExtensionStyleRef = theme.GetStyle("document-extension"); + documentMarkStyleRef = theme.GetStyle("document-mark"); + documentCloseStyleRef = theme.GetStyle("document-close"); + documentDirtyStyleRef = theme.GetStyle("document-dirty"); + documentLineStyleRef = theme.GetStyle("document-line"); + documentNewStyleRef = theme.GetStyle("document-new"); + documentListStyleRef = theme.GetStyle("document-list"); + titleBarDocumentsStyleRef = theme.GetStyle("title-bar-documents"); + dockContainerStyleRef = theme.GetStyle("dock-container"); + dockContainerMainStyleRef = theme.GetStyle("dock-container-main"); + dockSplitHorzStyleRef = theme.GetStyle("dock-split-horz"); + dockSplitVertStyleRef = theme.GetStyle("dock-split-vert"); + dockSizerHorzStyleRef = theme.GetStyle("dock-sizer-horz"); + dockSizerVertStyleRef = theme.GetStyle("dock-sizer-vert"); + dockLeafStyleRef = theme.GetStyle("dock-leaf"); + dockContentStyleRef = theme.GetStyle("dock-content"); + dockIcon = RegisterIcon(app.textSystem, "dock", R"()"); + // The document list's trigger draws its text and arrow in parts of its own. + theme.RegisterDropdownParts(documentListStyleRef, "document-list"); + } + + Context& Prepare(GUIApplication& app, Context& context) + { + if (context.stylesGeneration != app.StylesGeneration()) + { + context.styles.Load(app); + context.stylesGeneration = app.StylesGeneration(); + } + return context; + } + + const Styles& GetStyles(GUIApplication& app, Context& context) { return Prepare(app, context).styles; } + + void Install(GUIApplication& app, Context& context) + { + app.OnFrameStage(FrameStage::PreConstruct, [&app, &context] { BeginFrame(app, context); }); + app.OnFrameStage(FrameStage::PostInput, [&app, &context] { EndFrame(app, context); }); + app.OnFrameStage(FrameStage::EndFrame, [&context] + { + context.panelContentIDs.EndFrame(); + // A container left open: reported and closed, and the next frame starts clean. + if (context.dockingState.containerID != ID::Invalid()) + { + GUIApplication::ReportMisuse("docking: unbalanced BeginDockingContainer/EndDockingContainer at end of frame (closed)"); + context.dockingState = {}; + } + }); + app.OnInputDispatched([&app, &context](std::span actedOn) { ReportChangedPanels(app, context, actedOn); }); + // The panels go before their styles do; layoutsThisFrame still holds last frame's + // layouts here, and the visible panels come back next frame. + app.OnBeforeStylesCleared([&app, &context] + { + for (DockingLayout* layout : context.layoutsThisFrame) + if (layout) DisableAllPanels(app, context, *layout); + }); + } + + void Cleanup(GUIApplication& app, Context& context) + { + // Torn-off windows: their panels are hidden and destroyed with them, and their IDs and + // trees' go back. + while (!context.floatingDockWindows.empty()) + CloseFloatingDockWindow(app, context, context.floatingDockWindows.size() - 1); + context.closedPanels.clear(); // what they hold goes before the graphics it may use + } + + void NotePanelContentID(GUIApplication&, Context& context, ID panelId, ID contentID) { context.panelContentIDs[panelId] = contentID; } + + void InvalidatePanel(GUIApplication& app, Context& context, ID panelId) + { + if (const ID* contentID = context.panelContentIDs.Find(panelId)) + app.Invalidate(*contentID); + } + + void CreatePanel(GUIApplication&, Context&, std::unordered_map& panels, ID id, std::string title, tachyon::IconID icon, + std::function onPanelGUI, + std::string panelType, + std::function onEnable, + std::function onDisable) + { + panels[id] = Panel{ + .id = id, + .title = std::move(title), + .icon = icon, + .panelType = std::move(panelType), + .onPanelGUI = std::move(onPanelGUI), + .onEnable = std::move(onEnable), + .onDisable = std::move(onDisable), + }; + } +} diff --git a/src/gui_docking/gui_docking.h b/src/gui_docking/gui_docking.h new file mode 100644 index 00000000..58855af7 --- /dev/null +++ b/src/gui_docking/gui_docking.h @@ -0,0 +1,329 @@ +#pragma once + +// Docking: docked and floating panels, documents and layout presets. A library of its own on +// gui_controls, in namespace tachyon::docking: each function takes the application and a +// docking::Context, which the app owns. It works at points of the frame OnGUI doesn't reach, +// so the app installs it once: +// +// docking::Context dockingContext; // a member of the app class +// +// docking::Install(*this, dockingContext); // after Initialize +// docking::BeginDockingContainer(*this, dockingContext, dockID, &layout); +// docking::EndDockingContainer(*this, dockingContext); +// docking::EmitFloatingDockWindows(*this, dockingContext); +// docking::Cleanup(*this, dockingContext); // before GUIApplication::Cleanup + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace tachyon::docking +{ + /// @addtogroup controls_docking + /// @{ + + /// Docking's styles, looked up in the theme after each load. + struct Styles + { + StyleRef dockWindowStyleRef {}; ///< floating dock window - no internal padding + StyleRef dockWindowLeafStyleRef {}; ///< a torn-off window's root leaf: the title bar over the panel + StyleRef dockWindowPanelStyleRef {}; ///< the panel inset under a torn-off window's title bar + StyleRef dockWindowBodyStyleRef {}; ///< a torn-off window's split layout, inset the same + StyleRef documentsStyleRef {}; ///< the bar and the active document's panels, a column + StyleRef documentBarStyleRef {}; ///< the bar: its row over the line + StyleRef documentRowStyleRef {}; ///< the tabs, "+" and the list + StyleRef documentTabBarStyleRef {}; ///< the tabs and "+" + StyleRef documentTabStyleRef {}; + StyleRef documentNameStyleRef {}; ///< a tab's icon and name + StyleRef documentExtensionStyleRef {}; ///< ".level", after the name + StyleRef documentMarkStyleRef {}; ///< the slot for the close button or the unsaved dot + StyleRef documentCloseStyleRef {}; + StyleRef documentDirtyStyleRef {}; ///< the unsaved-changes dot + StyleRef documentLineStyleRef {}; ///< under the bar, in the active document's color + StyleRef documentNewStyleRef {}; ///< "+" + StyleRef documentListStyleRef {}; ///< "N open", listing every document + StyleRef titleBarDocumentsStyleRef {}; ///< a document bar in a title bar (DocumentBar) + StyleRef dockContainerStyleRef {}; ///< a docking container + StyleRef dockContainerMainStyleRef {}; ///< a main window's docking area, with a side gutter + StyleRef dockSplitHorzStyleRef {}; ///< horizontal flex row (split into left / right) + StyleRef dockSplitVertStyleRef {}; ///< vertical flex column (split into top / bottom) + StyleRef dockSizerHorzStyleRef {}; ///< vertical bar between left / right panes + StyleRef dockSizerVertStyleRef {}; ///< horizontal bar between top / bottom panes + StyleRef dockLeafStyleRef {}; ///< vertical flex: [tab bar][content] + StyleRef dockContentStyleRef {}; ///< content area holding the selected panel's draw() + IconID dockIcon {}; ///< returns a torn-off panel to its dock + + /// Looks them all up in `app`'s theme, after it loads. + void Load(GUIApplication& app); + }; + + /// What docking keeps from frame to frame, the app's to own and pass to each of its + /// functions. The hooks Install registers hold it by reference, so it stays where it is + /// (it can't be copied). + struct Context + { + Context() = default; + Context(const Context&) = delete; + Context& operator=(const Context&) = delete; + + Styles styles; + uint32_t stylesGeneration = 0; ///< the app's StylesGeneration the styles were looked up at + + DockTabDragSubsystem tabDrag; ///< a dock tab being dragged, and the drop zone shown + /// Each panel's content (its cached scope) by panel ID, for InvalidatePanel and for + /// the panels an input acted in. + RecentIDMap panelContentIDs; + /// Between BeginDockingContainer and EndDockingContainer only; handlers hold pointers + /// and never read it. + DockingConstructionState dockingState; + std::vector layoutsThisFrame; ///< built this frame: scroll sync and drops between them + std::vector closedPanels; ///< closed this frame, kept until the next one starts + std::vector> floatingDockWindows; + std::vector documentSetsThisFrame; ///< the document sets built this frame + DocumentDrag documentDrag; ///< the document tab being dragged, if any + std::vector documentBarRects; ///< last frame's document bars, screen pixels + std::optional documentMove; ///< a drop, done at the next frame's start + /// The layouts kept in the saved UI state, by key (PersistDocking); ForgetDockingLayout + /// takes one out. + std::unordered_map persistedLayouts; + /// The documents RestoreUIState read, until the app takes them (TakeSavedDocuments). + std::unordered_map> savedDocuments; + }; + + /// Docking's styles in `app`'s theme, looked up again after each theme load. + const Styles& GetStyles(GUIApplication& app, Context& context); + + /// Hooks docking into `app`'s frame (GUIApplication::OnFrameStage and the like): before + /// each frame's construction, after its input, and before a theme reload clears the + /// styles. Call it once, after Initialize. + void Install(GUIApplication& app, Context& context); + + /// Closes the panels' floating windows (their panels hidden and destroyed) and lets go + /// of the panels closed this frame. Call it before GUIApplication::Cleanup. + void Cleanup(GUIApplication& app, Context& context); + + /// @name Panels and floating windows + ///@{ + + /// Adds a panel to `panels` (usually a DockingLayout's). onPanelGUI builds its content; + /// onEnable / onDisable run when it becomes visible / hidden. panelType names its kind, + /// which saved UI state matches panels by (else the title). + void CreatePanel(GUIApplication& app, Context& context, std::unordered_map& panels, ID id, std::string title, tachyon::IconID icon, + std::function onPanelGUI, + std::string panelType = {}, + std::function onEnable = {}, + std::function onDisable = {}); + + /// As above, with a new static ID, which it returns. The ID goes back when the panel is + /// closed (its tab, its window, its document, or a layout applied without it). + inline tachyon::ID CreatePanel(GUIApplication& app, Context& context, std::unordered_map& panels, std::string title, tachyon::IconID icon, + std::function onPanelGUI, + std::string panelType = {}, + std::function onEnable = {}, + std::function onDisable = {}) + { + ID id = app.idManager.CreateStaticID(); + CreatePanel(app, context, panels, id, std::move(title), icon, std::move(onPanelGUI), + std::move(panelType), std::move(onEnable), std::move(onDisable)); + panels[id].internal.ownsID = true; + return id; + } + + + /// Panel lifecycle. A panel is enabled iff it is the selectedTab of a leaf reachable + /// from layout.root; the docking enables the visible ones each frame. + /// DisableAllPanels brackets disruptive operations (theme reload, preset swap). + void DisableAllPanels(GUIApplication& app, Context& context, DockingLayout& layout); + + + /// Dock leaf whose tab bar contains screenPos, plus its owning layout (needed by + /// TransferPanel for cross-layout drops). {nullptr, nullptr} on miss. + DockLeafResult FindDockLeafAtScreenPos(GUIApplication& app, Context& context, tachyon::int2 screenPos); + + /// The leaf whose content (as last laid out) holds screenPos, the part of it the point + /// is in (an edge, or Center), and its layout; none off every leaf's content. Tab bars + /// aren't content: FindDockLeafAtScreenPos finds those. + DockDropResult FindDockDropTargetAtScreenPos(GUIApplication& app, Context& context, tachyon::int2 screenPos); + + /// Call from OnGUI after the main docking container. Empty windows are closed. + void EmitFloatingDockWindows(GUIApplication& app, Context& context); + /// With documents in several main windows: in each, after its Documents, the windows of + /// the panels torn from its documents. They belong to it, and to the window a document + /// is moved to. + void EmitFloatingDockWindows(GUIApplication& app, Context& context, const DocumentSet& documents); + /// Moves a docked panel into its own window at a screen position, as tearing its tab + /// off does; the window's Dock button returns it. False if the layout hasn't the panel. + bool FloatPanel(GUIApplication& app, Context& context, DockingLayout& layout, ID panelID, int2 screenPos); + /// Before an app destroys `layout`: closes the windows of the panels torn off it (they + /// would dock back into it) and stops saving it. + void ForgetDockingLayout(GUIApplication& app, Context& context, DockingLayout& layout); + /// Closes a layout for good, as ForgetDockingLayout does, and empties it: its panels are + /// hidden (onDisable) and destroyed, and the IDs CreatePanel made for them and its + /// tree's go back. Call it before the app destroys a layout it made, or at exit. + void ReleaseDockingLayout(GUIApplication& app, Context& context, DockingLayout& layout); + + /// Closes the window for good: its panels are disabled and destroyed. + void CloseFloatingDockWindow(GUIApplication& app, Context& context, size_t index); + + /// Closes the panel at `tabIndex` of a docked leaf, as the tab's Close action does. + void CloseDockedPanel(GUIApplication& app, Context& context, DockingLayout& layout, DockNode& leaf, int tabIndex); + + /// Closes a panel of `layout` for good, wherever it is: out of its tree (its leaf + /// closing up when it empties), hidden first (onDisable) if it's shown, its ID back when + /// CreatePanel made it. Its callbacks, and what they hold, are destroyed when the next + /// frame starts, so it can be called from an input handler. + void ClosePanel(GUIApplication& app, Context& context, DockingLayout& layout, ID panelID); + + /// Adds a document at the end of `set`, with new static IDs and an empty layout, which + /// the caller fills (CreatePanel, MakeLeaf). The first one added becomes the active one. + Document& CreateDocument(GUIApplication& app, Context& context, DocumentSet& set, std::string name, std::string extension, std::string kind, + tachyon::IconID icon); + /// Closes `set`'s document at `index` for good: its panels are disabled and destroyed, + /// its torn-off panel windows closed, its IDs released and its layout no longer saved + /// (PersistDocking). The active document stays + /// active; when it's the one closed, the next one (else the one before) takes over. + /// Call from OnGUI, not from an input handler. + void CloseDocument(GUIApplication& app, Context& context, DocumentSet& set, int index); + /// Closes every document of `set`, as CloseDocument does each: at exit, say. + void CloseAllDocuments(GUIApplication& app, Context& context, DocumentSet& set); + + /// Moves a panel from sourceNode/sourceLayout to targetLayout, fixing up selectedTab. + void TransferPanel(tachyon::ID panelID, tachyon::docking::DockNode* sourceNode, + DockingLayout* sourceLayout, + DockingLayout* targetLayout); + + ///@} + + + /// @name Docking + ///@{ + + // ---- DockingContainer ---- + /// Builds `layout`'s docked panels (each one's onPanelGUI) in a container, enabling the + /// visible panels first. Then call EmitFloatingDockWindows. + bool BeginDockingContainer(GUIApplication& app, Context& context, ID id, DockingLayout* layout, StyleRef style, LayoutOverride&& constraints = {}); + /// As above, in the theme's dock style. + inline bool BeginDockingContainer(GUIApplication& app, Context& context, ID id, DockingLayout* layout, LayoutOverride&& constraints = {}) + { return BeginDockingContainer(app, context, id, layout, GetStyles(app, context).dockContainerStyleRef, std::move(constraints)); } + /// As above, with the call site as the ID. + inline bool BeginDockingContainer(GUIApplication& app, Context& context, DockingLayout* layout, StyleRef style, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) + { return BeginDockingContainer(app, context, app.idManager.AllocateDynamicID(site), layout, style, std::move(constraints)); } + /// As above, with the call site as the ID, in the theme's dock style. + inline bool BeginDockingContainer(GUIApplication& app, Context& context, DockingLayout* layout, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) + { return BeginDockingContainer(app, context, app.idManager.AllocateDynamicID(site), layout, GetStyles(app, context).dockContainerStyleRef, std::move(constraints)); } + /// Closes BeginDockingContainer. + void EndDockingContainer(GUIApplication& app, Context& context); + + /// The document bar of `set`, under the title bar, and below it the active document's + /// panels, filling the rest of the window's column. Each tab is in its document type's + /// colors; a click shows that document, its close button (or Ctrl+W) asks + /// DocumentSet::onClose and closes it on the next frame. Then call EmitFloatingDockWindows. + void Documents(GUIApplication& app, Context& context, ID id, DocumentSet& set, LayoutOverride&& constraints = {}); + /// The document bar of `set` alone: its tabs, "+", "N open" and the line in the active + /// document's color. With DocumentPanels, the two parts of Documents placed apart (the + /// bar in the title bar, say); call it first, once a frame. In + /// GetStyles(app, context).titleBarDocumentsStyleRef, which fits it in a title bar, it leaves its line out: + /// DocumentLine draws it under the whole title bar. + void DocumentBar(GUIApplication& app, Context& context, ID id, DocumentSet& set, StyleRef style, LayoutOverride&& constraints = LayoutOverride::Auto()); + /// As above, in the theme's document bar style. + inline void DocumentBar(GUIApplication& app, Context& context, ID id, DocumentSet& set, LayoutOverride&& constraints = LayoutOverride::Auto()) { DocumentBar(app, context, id, set, GetStyles(app, context).documentBarStyleRef, std::move(constraints)); } + /// The line under the document bar of `set`, in the active document's color, across + /// what it's in: after the title bar the bar is in. + void DocumentLine(GUIApplication& app, Context& context, const DocumentSet& set, LayoutOverride&& constraints = LayoutOverride::Auto()); + /// The active document's panels of `set`, after its DocumentBar. + void DocumentPanels(GUIApplication& app, Context& context, DocumentSet& set, LayoutOverride&& constraints = LayoutOverride::Auto()); + + ///@} + + + /// Invalidates a docked panel's cached content by panel id. Safe from event handlers. + void InvalidatePanel(GUIApplication& app, Context& context, ID panelId); + + /// @name Saved UI state + ///@{ + /// Keeps the layout's dock tree in the app's saved UI state (GUIApplication::PersistJson); + /// panels are matched by type, else by title, and get their own states back. + void PersistDocking(GUIApplication& app, Context& context, std::string key, DockingLayout& layout); + /// Keeps the documents of each main window that `windows` lists when the state is saved: + /// their names, kinds and order, the active one, each one's dock tree, and the window's + /// position, size and mode. The app makes them again (TakeSavedDocuments). + void PersistDocuments(GUIApplication& app, Context& context, std::string key, std::function()> windows); + /// Keeps the saved layouts and the file types' layouts. + void PersistLayoutPresets(GUIApplication& app, std::string key, LayoutPresets& presets); + /// The main windows of documents RestoreUIState read for `key`, in the order they were + /// listed; empty when none were saved. Taking them clears them. Make each document with + /// its panels, then RestoreDocumentLayout, and place each window with RestoreWindowPlace. + std::vector TakeSavedDocuments(Context& context, std::string_view key); + /// Lays a document's panels out as saved, and gives them their own states back: + /// - panels by type, else title; with several of one kind, the n-th in the saved tree + /// is the n-th the document has + /// - a panel the saved tree names that the document hasn't (a second of a kind, say) + /// is made by `makePanel`, as for ApplyDockLayout; without it, it's left out + /// - the document's panels the saved tree doesn't have go to its first leaf + /// False when nothing was saved for it or it can't be read: the document keeps its layout. + bool RestoreDocumentLayout(GUIApplication& app, Context& context, Document& document, const SavedDocument& saved, + const std::function(std::string_view key)>& makePanel = {}); + /// Puts the window where the saved one was, when it's next declared. + void RestoreWindowPlace(GUIApplication& app, ID windowID, const SavedDocumentWindow& saved); + /// A layout's dock tree as text, panels by type, else title, as a LayoutPreset keeps + /// it; empty when it has none. Floating panels aren't in it. + std::string SaveDockLayout(const DockingLayout& layout); + /// Lays a layout's panels out as `tree` (SaveDockLayout's text) says: + /// - a panel it names that the layout hasn't is made by `makePanel`, given the panel's + /// type, else title; it creates the panel in layout.panels and returns its ID, or + /// nothing to leave that tab out + /// - with several of one kind in the tree, each is a panel of its own: the layout's + /// own first, then ones `makePanel` makes + /// - panels it doesn't name are closed, as closing their tabs does + /// - the old tree's node and tab-bar IDs go back + /// False when the tree can't be read or has no panel left: the layout stays as it was. + /// Call it outside the layout's Docking, e.g. before it in the frame. + bool ApplyDockLayout(GUIApplication& app, Context& context, DockingLayout& layout, std::string_view tree, + const std::function(std::string_view key)>& makePanel = {}); + ///@} + + /// A docking container's scope: EndDockingContainer runs when it leaves. + /// + /// if (auto dock = docking::DockingContainer(*this, dockingContext, dockID, &layout)) { } + class [[nodiscard]] ContainerScope + { + public: + ContainerScope(GUIApplication& app, Context& context, bool open) : m_app(&app), m_context(&context), m_open(open) {} + ContainerScope(ContainerScope&& other) noexcept : m_app(std::exchange(other.m_app, nullptr)), m_context(other.m_context), m_open(other.m_open) {} + ContainerScope(const ContainerScope&) = delete; + ContainerScope& operator=(const ContainerScope&) = delete; + ContainerScope& operator=(ContainerScope&&) = delete; + ~ContainerScope() { End(); } + + /// Ends the container now instead of when the scope leaves. + void End() + { + if (GUIApplication* app = std::exchange(m_app, nullptr)) + EndDockingContainer(*app, *m_context); + } + explicit operator bool() const { return m_open; } + + private: + GUIApplication* m_app; + Context* m_context; + bool m_open; + }; + /// The scope for BeginDockingContainer, taking its arguments. + template auto DockingContainer(GUIApplication& app, Context& context, A&&... a) + { return ContainerScope(app, context, BeginDockingContainer(app, context, std::forward(a)...)); } + + /// @} +} diff --git a/src/gui_docking/gui_docking_internal.h b/src/gui_docking/gui_docking_internal.h new file mode 100644 index 00000000..50954986 --- /dev/null +++ b/src/gui_docking/gui_docking_internal.h @@ -0,0 +1,41 @@ +#pragma once + +// Not installed: docking's helpers shared between its files. + +#include + +#include + +namespace tachyon::docking +{ + /// `context`, with its styles looked up again when the app's styles loaded since. + Context& Prepare(GUIApplication& app, Context& context); + /// Notes the content element (cached scope) of a docked panel, for InvalidatePanel. + void NotePanelContentID(GUIApplication& app, Context& context, ID panelId, ID contentID); + /// Calls onChanged of each docked panel holding one of `actedOn`, once each. + void ReportChangedPanels(GUIApplication& app, Context& context, std::span actedOn); + /// Before the frame is built: what last frame left (closed panels, a dropped document). + void BeginFrame(GUIApplication& app, Context& context); + /// After the frame's input: scroll offsets and the document bars' rects, for next frame. + void EndFrame(GUIApplication& app, Context& context); + + /// Enables the panels reachable from layout.root; called by BeginDockingContainer each frame. + void EnableVisiblePanels(GUIApplication& app, Context& context, DockingLayout& layout); + /// After input dispatch: stores each selected panel's scroll offset so it survives a tab switch. + void SyncDockingScrollOffsets(GUIApplication& app, Context& context); + /// Uses last frame's tab-bar rects, so it works during construction. + DockNode* FindDockLeafTabBarCachedAtScreenPos(GUIApplication& app, Context& context, tachyon::int2 screenPos); + /// The floating windows of `documents` (all of them when null). + void EmitFloatingDockWindowsOf(GUIApplication& app, Context& context, const DocumentSet* documents); + /// Shows the document of a set built this frame that owns `layout`; false when none does. + bool ActivateDocumentOf(GUIApplication& app, Context& context, const DockingLayout* layout); + /// Moves or tears off the dropped document (Context::documentMove); at frame start. + void ApplyDocumentMove(GUIApplication& app, Context& context); + /// After layout: each set's bar and tab rects, for next frame's drops. + void SyncDocumentRects(GUIApplication& app, Context& context); + /// The set whose bar is at `screenPos` (last frame's rects); null when none is. + DocumentSet* FindDocumentBarAt(GUIApplication& app, Context& context, tachyon::int2 screenPos); + /// Destroys every panel of `layout`, as ClosePanel does each, leaving its tree. + void ErasePanels(GUIApplication& app, Context& context, DockingLayout& layout); + void DockFloatingWindow(GUIApplication& app, Context& context, FloatingDockWindow& fw); +} diff --git a/src/gui_docking/gui_docking_state.cpp b/src/gui_docking/gui_docking_state.cpp new file mode 100644 index 00000000..ddb126e0 --- /dev/null +++ b/src/gui_docking/gui_docking_state.cpp @@ -0,0 +1,341 @@ +#include +#include + +#include + +#include +#include +#include +#include +#include + +namespace tachyon::docking +{ + namespace + { + // A panel's key: its type when it has one, else its title. + std::string PanelKey(const Panel& panel) { return panel.panelType.empty() ? panel.title : panel.panelType; } + + // The layout's panel for a saved tab of `key`: the first of that key not handed out + // yet, so a tree with two of a kind gets two panels; else the one `makePanel` makes + // (it adds it to the layout), recorded in `made`. Nullopt when there's neither. + std::optional PanelForKey(DockingLayout& layout, std::string_view key, std::vector& handed, + const std::function(std::string_view)>& makePanel, std::vector& made) + { + for (const auto& [id, panel] : layout.panels) + if (PanelKey(panel) == key && std::find(handed.begin(), handed.end(), id) == handed.end()) + { + handed.push_back(id); + return id; + } + if (!makePanel) + return std::nullopt; + const std::optional created = makePanel(key); + if (!created || layout.panels.find(*created) == layout.panels.end()) + return std::nullopt; // it made none + made.push_back(*created); + handed.push_back(*created); + return created; + } + + DockNode* FirstLeaf(DockNode* node) + { + while (node != nullptr && !node->isLeaf) + node = node->first ? node->first.get() : node->second.get(); + return node; + } + + // A layout's dock tree as JSON, panels by key; null when it has none. + std::optional DockTreeJson(const DockingLayout& layout) + { + if (!layout.root) + return std::nullopt; + const std::string tree = SerializeDockTree(*layout.root, [&layout](ID id) { + const auto it = layout.panels.find(id); + return it != layout.panels.end() ? PanelKey(it->second) : std::string(); + }); + Result parsed = JsonValue::Parse(tree); + return parsed ? std::optional(std::move(*parsed)) : std::nullopt; + } + + // A saved dock tree applied to a layout: panels by key, a panel `makePanel` makes for + // each it lacks, the ones it hasn't to its first leaf. False when it can't be read; the + // layout stays. The old tree's node and tab-bar IDs go back to `idManager`. + bool ApplyDockTree(DockingLayout& layout, std::string_view tree, IDManager& idManager, + const std::function(std::string_view)>& makePanel = {}) + { + std::vector handed, made; + std::unique_ptr root = ParseDockTree(tree, [&](std::string_view panelKey) { + return PanelForKey(layout, panelKey, handed, makePanel, made); + }); + if (!root) + { + // Never shown: only their IDs, when CreatePanel made them, to give back. + for (const ID id : made) + if (const auto it = layout.panels.find(id); it != layout.panels.end()) + { + if (it->second.internal.ownsID) + idManager.ReleaseStaticID(id); + layout.panels.erase(it); + } + return false; + } + std::vector all; + for (const auto& [id, panel] : layout.panels) all.push_back(id); + if (DockNode* leaf = FirstLeaf(root.get())) + for (const ID id : UnplacedPanels(*root, all)) + leaf->panelIds.push_back(id); + ReleaseDockTreeIDs(layout.root.get(), &idManager); + layout.root = std::move(root); + return true; + } + + std::string StringOf(const JsonValue& object, const char* name) + { + const JsonValue* v = object.Find(name); + return v && v->IsString() ? v->AsString() : std::string(); + } + + // A layout's panels' own view states, by panel key: { "NodeView": "..." }. Several + // panels of one key go in an array, in the order they're in the tree, "" for one that + // keeps nothing: { "Timeline": ["...", "..."] }. Null when none keeps one. + std::optional PanelStatesJson(const DockingLayout& layout) + { + if (!layout.root) + return std::nullopt; + std::vector>> byKey; + bool any = false; + for (const ID id : PanelsInTree(*layout.root)) + { + const auto it = layout.panels.find(id); + if (it == layout.panels.end()) + continue; + const Panel& panel = it->second; + std::string state = panel.saveState ? panel.saveState() : std::string(); + any |= !state.empty(); + const std::string key = PanelKey(panel); + auto entry = std::find_if(byKey.begin(), byKey.end(), [&key](const auto& e) { return e.first == key; }); + if (entry == byKey.end()) + entry = byKey.insert(byKey.end(), { key, {} }); + entry->second.push_back(std::move(state)); + } + if (!any) + return std::nullopt; + JsonValue states = JsonValue::MakeObject(); + for (auto& [key, list] : byKey) + { + if (std::all_of(list.begin(), list.end(), [](const std::string& s) { return s.empty(); })) + continue; + if (list.size() == 1) + { + states.Set(key, std::move(list[0])); + continue; + } + JsonValue array = JsonValue::MakeArray(); + for (std::string& state : list) + array.Push(std::move(state)); + states.Set(key, std::move(array)); + } + return states; + } + + // Saved view states handed to the layout's panels of the same keys: the n-th saved + // for a key to the n-th panel of that key in the tree. + void ApplyPanelStates(DockingLayout& layout, std::span> states) + { + if (!layout.root) + return; + std::vector> taken; // per key, how many are handed out + for (const ID id : PanelsInTree(*layout.root)) + { + const auto it = layout.panels.find(id); + if (it == layout.panels.end()) + continue; + Panel& panel = it->second; + const std::string key = PanelKey(panel); + auto count = std::find_if(taken.begin(), taken.end(), [&key](const auto& e) { return e.first == key; }); + if (count == taken.end()) + count = taken.insert(taken.end(), { key, 0 }); + const size_t n = count->second++; + size_t seen = 0; + for (const auto& [savedKey, state] : states) + if (savedKey == key && seen++ == n) + { + if (panel.restoreState && !state.empty()) + panel.restoreState(state); + break; + } + } + } + + // The saved states as pairs, a key's array as one pair each, in order. + std::vector> PanelStatesOf(const JsonValue* states) + { + std::vector> out; + if (states && states->IsObject()) + for (const auto& [key, state] : states->Members()) + { + if (state.IsString()) + out.emplace_back(key, state.AsString()); + else if (state.IsArray()) + for (const JsonValue& one : state.Items()) + out.emplace_back(key, one.IsString() ? one.AsString() : std::string()); + } + return out; + } + } + + void PersistDocking(GUIApplication& app, Context& context, std::string key, DockingLayout& layout) + { + // The dock tree first: the panels' own states go to the panels it put in place. + // Nothing usable: the app's own layout stays. A layout forgotten since keeps nothing. + const bool known = context.persistedLayouts.contains(key); + context.persistedLayouts[key] = &layout; + if (known) + return; + auto layoutOf = [&context, key]() -> DockingLayout* { + const auto it = context.persistedLayouts.find(key); + return it != context.persistedLayouts.end() ? it->second : nullptr; + }; + app.PersistJson("docking", key, + [layoutOf] { DockingLayout* l = layoutOf(); return l ? DockTreeJson(*l).value_or(JsonValue()) : JsonValue(); }, + [&app, layoutOf](const JsonValue& tree) { if (DockingLayout* l = layoutOf()) (void)ApplyDockTree(*l, tree.Write(), app.idManager); }); + app.PersistJson("panelStates", key, + [layoutOf] { DockingLayout* l = layoutOf(); return l ? PanelStatesJson(*l).value_or(JsonValue()) : JsonValue(); }, + [layoutOf](const JsonValue& states) { if (DockingLayout* l = layoutOf()) ApplyPanelStates(*l, PanelStatesOf(&states)); }); + } + + void PersistDocuments(GUIApplication& app, Context& context, std::string key, std::function()> windows) + { + // Each main window's documents: which, in what order, the active one and their dock + // trees, with the window's place. + auto save = [&app, listWindows = std::move(windows)] + { + JsonValue list = JsonValue::MakeArray(); + for (const DocumentWindowRef& window : listWindows ? listWindows() : std::vector{}) + { + if (!window.documents) + continue; + JsonValue w = JsonValue::MakeObject(); + if (std::optional place = app.SaveWindowPlace(window.windowID)) + w.Set("window", std::move(*place)); + w.Set("active", window.documents->active); + JsonValue items = JsonValue::MakeArray(); + for (const auto& document : window.documents->documents) + { + JsonValue d = JsonValue::MakeObject(); + d.Set("name", document->name); + d.Set("extension", document->extension); + d.Set("kind", document->kind); + if (std::optional tree = DockTreeJson(document->layout)) + d.Set("layout", std::move(*tree)); + if (std::optional states = PanelStatesJson(document->layout)) + d.Set("panelStates", std::move(*states)); + items.Push(std::move(d)); + } + w.Set("documents", std::move(items)); + list.Push(std::move(w)); + } + return list; + }; + // Kept for the app, which makes them again (TakeSavedDocuments). + auto restore = [&context, key](const JsonValue& saved) + { + if (!saved.IsArray()) + return; + std::vector windows; + for (const JsonValue& w : saved.Items()) + { + if (!w.IsObject()) + continue; + SavedDocumentWindow window; + if (const JsonValue* items = w.Find("documents"); items && items->IsArray()) + for (const JsonValue& d : items->Items()) + { + if (!d.IsObject() || StringOf(d, "name").empty()) + continue; + const JsonValue* tree = d.Find("layout"); + window.documents.push_back(SavedDocument{ StringOf(d, "name"), StringOf(d, "extension"), StringOf(d, "kind"), + tree ? tree->Write() : std::string(), PanelStatesOf(d.Find("panelStates")) }); + } + if (window.documents.empty()) + continue; + const JsonValue* active = w.Find("active"); + window.active = std::clamp(active && active->IsNumber() ? int(active->AsNumber()) : 0, 0, int(window.documents.size()) - 1); + if (std::optional place = GUIApplication::ReadWindowPlace(w.Find("window"))) + { + window.rect = place->rect; + window.mode = place->mode; + window.monitor = place->monitor; + } + windows.push_back(std::move(window)); + } + context.savedDocuments[key] = std::move(windows); + }; + app.PersistJson("documents", std::move(key), std::move(save), std::move(restore)); + } + + void PersistLayoutPresets(GUIApplication& app, std::string key, LayoutPresets& presets) + { + // The saved ones and the file types'; the app's built-in ones stay. + LayoutPresets* target = &presets; + app.PersistJson("layoutPresets", std::move(key), + [target] { Result parsed = JsonValue::Parse(target->ToJson()); return parsed ? std::move(*parsed) : JsonValue(); }, + [target](const JsonValue& saved) { (void)target->FromJson(saved.Write()); }); + } + + std::string SaveDockLayout(const DockingLayout& layout) + { + const std::optional tree = DockTreeJson(layout); + return tree ? tree->Write() : std::string(); + } + + bool ApplyDockLayout(GUIApplication& app, Context& context, DockingLayout& layout, std::string_view tree, + const std::function(std::string_view key)>& makePanel) + { + // Each key to a panel: the layout's own, else a new one. + std::vector handed, made; + std::unique_ptr root = ParseDockTree(tree, [&](std::string_view panelKey) { + return PanelForKey(layout, panelKey, handed, makePanel, made); + }); + if (!root) + { + for (const ID id : made) + ClosePanel(app, context, layout, id); + return false; + } + + DisableAllPanels(app, context, layout); + std::vector all; + for (const auto& [id, panel] : layout.panels) all.push_back(id); + for (const ID id : UnplacedPanels(*root, all)) + ClosePanel(app, context, layout, id); + ReleaseDockTreeIDs(layout.root.get(), &app.idManager); + layout.root = std::move(root); + return true; + } + + std::vector TakeSavedDocuments(Context& context, std::string_view key) + { + const auto it = context.savedDocuments.find(std::string(key)); + if (it == context.savedDocuments.end()) + return {}; + std::vector windows = std::move(it->second); + context.savedDocuments.erase(it); + return windows; + } + + bool RestoreDocumentLayout(GUIApplication& app, Context&, Document& document, const SavedDocument& saved, + const std::function(std::string_view key)>& makePanel) + { + if (saved.layout.empty() || !ApplyDockTree(document.layout, saved.layout, app.idManager, makePanel)) + return false; + ApplyPanelStates(document.layout, saved.panelStates); + return true; + } + + void RestoreWindowPlace(GUIApplication& app, ID windowID, const SavedDocumentWindow& saved) + { + app.RestoreWindowPlace(windowID, GUIApplication::WindowPlace{ .rect = saved.rect, .mode = saved.mode, .monitor = saved.monitor }); + } +} diff --git a/src/gui_controls/gui_docking_types.h b/src/gui_docking/gui_docking_types.h similarity index 81% rename from src/gui_controls/gui_docking_types.h rename to src/gui_docking/gui_docking_types.h index 3f9ea9bd..e42e3d97 100644 --- a/src/gui_controls/gui_docking_types.h +++ b/src/gui_docking/gui_docking_types.h @@ -4,7 +4,7 @@ #include #include // IconID -#include // DockNode, DockDropTarget +#include // DockNode, DockDropTarget #include // WindowMode #include @@ -18,61 +18,12 @@ // Docking + panel data model: Panel, DockingLayout (tree + panel registry), // per-frame construction state, hit-test results and floating windows. -namespace tachyon +namespace tachyon::docking { /// @addtogroup controls_docking /// @{ - // ---- TabBar: reorderable tabs ---- - /// What a tab bar offers besides its tabs. - struct TabBarOptions { - std::string_view closeLabel = "Close Panel"; ///< the item of a tab's context menu that closes it - /// "+N" after the tabs that fit lists the rest. Without it the caller lists them another - /// way; what it adds after the tabs is left room for (TabBarMemory::trailingWidth). - bool listHidden = true; - bool layoutMenu = true; ///< the context menus offer Collapse Rows / Multiple Rows - /// An element around the bar (its row, say) that counts as the bar while a tab is - /// dragged: in it the tab reorders, and only off it is it dragged out. Invalid: the bar. - tachyon::ID dropArea = tachyon::ID::Invalid(); - }; - - /// Construction state of the current tab bar; internal. - struct TabBarState { - tachyon::ID barID = tachyon::ID::Invalid(); - int* selectedIndex = nullptr; - int nextTabIndex = 0; - std::function onClose; ///< tab index, when its close button is clicked - std::function onDragOut; ///< tab index and mouse release pos - TabBarLayout* layout = nullptr; ///< the bar's layout, which its context menu sets - TabBarOptions options; - std::vector shown; ///< by tab index; empty: every tab is shown - struct HiddenTab { int index = 0; tachyon::IconID icon = tachyon::IconID::Invalid; std::string text; }; - std::vector hidden; ///< the tabs left out, listed by the overflow button - }; - - /// Construction state of the current tab, between BeginTab and EndTab; internal. - struct TabState { - bool open = false; ///< BeginTab built it (it wasn't left out) - tachyon::ID id = tachyon::ID::Invalid(); - tachyon::ID bodyID = tachyon::ID::Invalid(); - int index = 0; - bool selected = false; - }; - - /// What a tab bar keeps across frames (element data store, by bar ID): its keyboard - /// navigation, and the sizes it measured, in pixels, that decide which tabs fit. - struct TabBarMemory { - int tabCount = 0; ///< last frame's - int focusIndex = -1; ///< the tab that takes focus as it's built, after an arrow key - TabBarLayout layout = TabBarLayout::OneRow; ///< for a bar whose caller doesn't keep one - - std::vector widths; ///< by tab index; a hidden tab keeps its last width - int32_t barWidth = 0; ///< the bar's inner width - int32_t overflowWidth = 0; ///< the overflow button's width - int32_t trailingWidth = 0; ///< what the caller adds after the tabs, always shown - }; - // ---- Panel + DockingContainer ---- // Panel: a unit of UI content, built by onPanelGUI during OnGUI. DockNodes store only // panel IDs; the Panels live in the DockingLayout. @@ -156,7 +107,7 @@ namespace tachyon /// Panels torn off it float in windows that dock back into it: before destroying a layout /// while the app runs on, call ForgetDockingLayout (CloseDocument does for a document's). struct DockingLayout { - std::unique_ptr root; ///< the dock tree; leaves hold panel tabs + std::unique_ptr root; ///< the dock tree; leaves hold panel tabs std::unordered_map panels; ///< every panel of this layout, by ID /// OS window hosting this layout, refreshed each frame. A cross-window tab drop @@ -182,13 +133,13 @@ namespace tachyon /// Result of FindDockLeafAtScreenPos: the leaf and its layout, both null on a miss. struct DockLeafResult { - tachyon::DockNode* leaf = nullptr; + tachyon::docking::DockNode* leaf = nullptr; DockingLayout* layout = nullptr; }; /// Result of FindDockDropTargetAtScreenPos: the drop target and its layout. struct DockDropResult { - tachyon::DockDropTarget target; + tachyon::docking::DockDropTarget target; DockingLayout* layout = nullptr; }; diff --git a/src/gui_controls/gui_layout_presets.cpp b/src/gui_docking/gui_layout_presets.cpp similarity index 98% rename from src/gui_controls/gui_layout_presets.cpp rename to src/gui_docking/gui_layout_presets.cpp index ef57448c..1abd5d84 100644 --- a/src/gui_controls/gui_layout_presets.cpp +++ b/src/gui_docking/gui_layout_presets.cpp @@ -1,9 +1,9 @@ -#include +#include #include #include -namespace tachyon +namespace tachyon::docking { namespace { diff --git a/src/gui_controls/gui_layout_presets.h b/src/gui_docking/gui_layout_presets.h similarity index 99% rename from src/gui_controls/gui_layout_presets.h rename to src/gui_docking/gui_layout_presets.h index 0d84c3aa..7098b218 100644 --- a/src/gui_controls/gui_layout_presets.h +++ b/src/gui_docking/gui_layout_presets.h @@ -5,7 +5,7 @@ #include #include -namespace tachyon +namespace tachyon::docking { /// @addtogroup controls_docking /// @{ diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 63ae878a..dfbfa621 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -200,7 +200,7 @@ target_compile_definitions(gui_core_tests PRIVATE TACHYON_FRAME_ALLOC_BENCH=$>) tachyon_apply_compile_options(${target}) diff --git a/tests/controls_docking_test.cpp b/tests/controls_docking_test.cpp index 74c88fa4..f6e96667 100644 --- a/tests/controls_docking_test.cpp +++ b/tests/controls_docking_test.cpp @@ -7,8 +7,9 @@ #include "headless_gui_app.h" -#include +#include #include +#include namespace tachyon { @@ -20,7 +21,8 @@ namespace tachyon { protected: HeadlessGUIApp app; - tachyon::DockingLayout layout; + docking::Context dockingContext; + tachyon::docking::DockingLayout layout; tachyon::ID containerID{}; tachyon::ID panelA{}, panelB{}, panelC{}; int drawsA = 0, drawsB = 0, drawsC = 0; @@ -29,21 +31,22 @@ namespace tachyon void SetUp() override { ASSERT_TRUE(app.Initialize()); + docking::Install(app, dockingContext); containerID = app.idManager.CreateStaticID(); - panelA = app.CreatePanel(layout.panels, "A", IconID::Invalid, + panelA = docking::CreatePanel(app, dockingContext, layout.panels, "A", IconID::Invalid, [this] { drawsA++; }, {}, [this] { enables[0]++; }, [this] { disables[0]++; }); - panelB = app.CreatePanel(layout.panels, "B", IconID::Invalid, + panelB = docking::CreatePanel(app, dockingContext, layout.panels, "B", IconID::Invalid, [this] { drawsB++; }, {}, [this] { enables[1]++; }, [this] { disables[1]++; }); - panelC = app.CreatePanel(layout.panels, "C", IconID::Invalid, + panelC = docking::CreatePanel(app, dockingContext, layout.panels, "C", IconID::Invalid, [this] { drawsC++; }, {}, [this] { enables[2]++; }, [this] { disables[2]++; }); // [A] | [B, C] - left pane pinned at 250px. - layout.root = MakeSplit(DockSplitMode::LeftPinned, 250, - MakeLeaf({ panelA }), - MakeLeaf({ panelB, panelC })); + layout.root = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 250, + docking::MakeLeaf({ panelA }), + docking::MakeLeaf({ panelB, panelC })); } void TearDown() override { app.Cleanup(); } @@ -51,16 +54,16 @@ namespace tachyon void EmitDock() { app.BeginRootWindow(); - app.BeginDockingContainer(containerID, &layout, + docking::BeginDockingContainer(app, dockingContext, containerID, &layout, tachyon::LayoutOverride{}.Size(800, 600)); - app.EndDockingContainer(); + docking::EndDockingContainer(app, dockingContext); app.EndRootWindow(); } void Frame() { app.Frame([&] { EmitDock(); }); } // The content element of a leaf, as registered during construction. - tachyon::IntRect ContentRect(const DockNode* leaf) const + tachyon::IntRect ContentRect(const docking::DockNode* leaf) const { return app.GetElementRect(leaf->lastContentID); } @@ -89,7 +92,7 @@ namespace tachyon TEST_F(DockingTest, ATabWhosePanelIsGoneIsDropped) { const ID gone = app.idManager.CreateStaticID(); - DockNode& right = *layout.root->second; + docking::DockNode& right = *layout.root->second; right.panelIds = { gone, panelB, panelC }; right.selectedTab = 2; // C Frame(); @@ -159,19 +162,19 @@ namespace tachyon { Frame(); Frame(); - DockNode* right = layout.root->second.get(); + docking::DockNode* right = layout.root->second.get(); const IntRect bar = app.GetElementRect(right->tabBarID); ASSERT_GT(bar.w, 0); - const DockLeafResult onBar = app.FindDockLeafAtScreenPos({ bar.x + bar.w / 2, bar.y + bar.h / 2 }); + const docking::DockLeafResult onBar = docking::FindDockLeafAtScreenPos(app, dockingContext, { bar.x + bar.w / 2, bar.y + bar.h / 2 }); EXPECT_EQ(onBar.leaf, right); EXPECT_EQ(onBar.layout, &layout); const IntRect content = ContentRect(right); - const DockLeafResult inContent = app.FindDockLeafAtScreenPos({ content.x + content.w / 2, content.y + content.h / 2 }); + const docking::DockLeafResult inContent = docking::FindDockLeafAtScreenPos(app, dockingContext, { content.x + content.w / 2, content.y + content.h / 2 }); EXPECT_EQ(inContent.leaf, nullptr) << "a leaf's content isn't its tab bar"; EXPECT_EQ(inContent.layout, nullptr); - EXPECT_EQ(app.FindDockLeafAtScreenPos({ 5000, 5000 }).leaf, nullptr); + EXPECT_EQ(docking::FindDockLeafAtScreenPos(app, dockingContext, { 5000, 5000 }).leaf, nullptr); } // A point in a leaf's content finds that leaf and the part of it: an edge to split it @@ -180,29 +183,29 @@ namespace tachyon { Frame(); Frame(); - DockNode* left = layout.root->first.get(); - DockNode* right = layout.root->second.get(); + docking::DockNode* left = layout.root->first.get(); + docking::DockNode* right = layout.root->second.get(); const IntRect c = right->cachedContentRect; ASSERT_GT(c.w, 0); ASSERT_GT(c.h, 0); - const DockDropResult middle = app.FindDockDropTargetAtScreenPos({ c.x + c.w / 2, c.y + c.h / 2 }); + const docking::DockDropResult middle = docking::FindDockDropTargetAtScreenPos(app, dockingContext, { c.x + c.w / 2, c.y + c.h / 2 }); EXPECT_EQ(middle.target.leaf, right); - EXPECT_EQ(middle.target.zone, DockDropZone::Center); + EXPECT_EQ(middle.target.zone, docking::DockDropZone::Center); EXPECT_EQ(middle.layout, &layout); - EXPECT_EQ(app.FindDockDropTargetAtScreenPos({ c.x + 2, c.y + c.h / 2 }).target.zone, DockDropZone::Left); - EXPECT_EQ(app.FindDockDropTargetAtScreenPos({ c.x + c.w - 3, c.y + c.h / 2 }).target.zone, DockDropZone::Right); - EXPECT_EQ(app.FindDockDropTargetAtScreenPos({ c.x + c.w / 2, c.y + 2 }).target.zone, DockDropZone::Top); - EXPECT_EQ(app.FindDockDropTargetAtScreenPos({ c.x + c.w / 2, c.y + c.h - 3 }).target.zone, DockDropZone::Bottom); + EXPECT_EQ(docking::FindDockDropTargetAtScreenPos(app, dockingContext, { c.x + 2, c.y + c.h / 2 }).target.zone, docking::DockDropZone::Left); + EXPECT_EQ(docking::FindDockDropTargetAtScreenPos(app, dockingContext, { c.x + c.w - 3, c.y + c.h / 2 }).target.zone, docking::DockDropZone::Right); + EXPECT_EQ(docking::FindDockDropTargetAtScreenPos(app, dockingContext, { c.x + c.w / 2, c.y + 2 }).target.zone, docking::DockDropZone::Top); + EXPECT_EQ(docking::FindDockDropTargetAtScreenPos(app, dockingContext, { c.x + c.w / 2, c.y + c.h - 3 }).target.zone, docking::DockDropZone::Bottom); const IntRect l = left->cachedContentRect; - EXPECT_EQ(app.FindDockDropTargetAtScreenPos({ l.x + l.w / 2, l.y + l.h / 2 }).target.leaf, left); + EXPECT_EQ(docking::FindDockDropTargetAtScreenPos(app, dockingContext, { l.x + l.w / 2, l.y + l.h / 2 }).target.leaf, left); const IntRect bar = app.GetElementRect(right->tabBarID); - EXPECT_EQ(app.FindDockDropTargetAtScreenPos({ bar.x + bar.w / 2, bar.y + bar.h / 2 }).target.leaf, nullptr) + EXPECT_EQ(docking::FindDockDropTargetAtScreenPos(app, dockingContext, { bar.x + bar.w / 2, bar.y + bar.h / 2 }).target.leaf, nullptr) << "tab bars are FindDockLeafAtScreenPos's"; - const DockDropResult outside = app.FindDockDropTargetAtScreenPos({ 5000, 5000 }); + const docking::DockDropResult outside = docking::FindDockDropTargetAtScreenPos(app, dockingContext, { 5000, 5000 }); EXPECT_EQ(outside.target.leaf, nullptr); EXPECT_EQ(outside.layout, nullptr); } @@ -211,10 +214,10 @@ namespace tachyon // next to it), and between layouts the panel goes with it. TEST_F(DockingTest, TransferPanelKeepsTheSelectedTabAndMovesThePanel) { - DockNode& right = *layout.root->second; + docking::DockNode& right = *layout.root->second; right.selectedTab = 1; // C - DockingLayout other; - GUIApplication::TransferPanel(panelB, &right, &layout, &other); + docking::DockingLayout other; + docking::TransferPanel(panelB, &right, &layout, &other); EXPECT_EQ(right.panelIds, (std::vector{ panelC })); EXPECT_EQ(right.selectedTab, 0) << "C still, now first"; EXPECT_EQ(layout.panels.count(panelB), 0u); @@ -224,20 +227,20 @@ namespace tachyon // The selected, last tab moved within the layout: the one before it shows. right.panelIds = { panelC, panelA }; right.selectedTab = 1; - GUIApplication::TransferPanel(panelA, &right, &layout, &layout); + docking::TransferPanel(panelA, &right, &layout, &layout); EXPECT_EQ(right.panelIds, (std::vector{ panelC })); EXPECT_EQ(right.selectedTab, 0); EXPECT_EQ(layout.panels.count(panelA), 1u) << "the same layout keeps it"; // The leaf's last panel: an empty leaf. - GUIApplication::TransferPanel(panelC, &right, &layout, nullptr); + docking::TransferPanel(panelC, &right, &layout, nullptr); EXPECT_TRUE(right.panelIds.empty()); EXPECT_EQ(right.selectedTab, 0); EXPECT_EQ(layout.panels.count(panelC), 1u) << "no target layout: the panel stays"; // A panel the leaf doesn't hold leaves it as it is. right.panelIds = { panelC }; - GUIApplication::TransferPanel(panelA, &right, &layout, &layout); + docking::TransferPanel(panelA, &right, &layout, &layout); EXPECT_EQ(right.panelIds, (std::vector{ panelC })); layout.panels[panelB] = std::move(other.panels[panelB]); // back, for the fixture to close } @@ -249,7 +252,7 @@ namespace tachyon app.SetUIScale(2.0f); Frame(); Frame(); - const DockNode* pinned = layout.root->first.get(); + const docking::DockNode* pinned = layout.root->first.get(); EXPECT_EQ(app.GetElementRect(pinned->nodeID).w, 500); const auto a0 = ContentRect(layout.root->first.get()); @@ -271,7 +274,7 @@ namespace tachyon TEST_F(DockingTest, SingleLeafFillsContainer) { - layout.root = MakeLeaf({ panelA }); + layout.root = docking::MakeLeaf({ panelA }); Frame(); const auto a = ContentRect(layout.root.get()); ASSERT_GT(a.w, 0); @@ -283,7 +286,7 @@ namespace tachyon // ---- Floating dock windows ---- // Static IDs a dock tree holds (node + tab-bar IDs, assigned on emit). - static size_t CountTreeStaticIDs(const DockNode* n) + static size_t CountTreeStaticIDs(const docking::DockNode* n) { if (!n) return 0; size_t c = 0; @@ -297,14 +300,14 @@ namespace tachyon // releases every static ID it held, its dock tree's included. TEST_F(DockingTest, EmptiedFloatingWindowReleasesItsTreeIDs) { - auto fw = std::make_unique(); + auto fw = std::make_unique(); fw->windowID = app.idManager.CreateStaticID(); - const ID floating = app.CreatePanel(fw->layout.panels, "F", IconID::Invalid, [] {}, {}, {}, {}); - fw->layout.root = MakeLeaf({ floating }); - FloatingDockWindow* window = fw.get(); - app.m_floatingDockWindows.push_back(std::move(fw)); + const ID floating = docking::CreatePanel(app, dockingContext, fw->layout.panels, "F", IconID::Invalid, [] {}, {}, {}, {}); + fw->layout.root = docking::MakeLeaf({ floating }); + docking::FloatingDockWindow* window = fw.get(); + dockingContext.floatingDockWindows.push_back(std::move(fw)); - auto frame = [&] { app.Frame([&] { EmitDock(); app.EmitFloatingDockWindows(); }); }; + auto frame = [&] { app.Frame([&] { EmitDock(); docking::EmitFloatingDockWindows(app, dockingContext); }); }; frame(); frame(); const size_t treeIDs = CountTreeStaticIDs(window->layout.root.get()); @@ -312,13 +315,13 @@ namespace tachyon const size_t before = app.idManager.GetStaticIDCount(); // Its last tab dragged out: the panel goes to another layout, as TransferPanel moves it. - DockingLayout elsewhere; + docking::DockingLayout elsewhere; elsewhere.panels[floating] = std::move(window->layout.panels.at(floating)); window->layout.panels.erase(floating); window->layout.root->panelIds.clear(); frame(); - ASSERT_TRUE(app.m_floatingDockWindows.empty()); + ASSERT_TRUE(dockingContext.floatingDockWindows.empty()); EXPECT_EQ(app.idManager.GetStaticIDCount(), before - 1 - treeIDs) << "the window's and its tree's (its panel moved out)"; EXPECT_TRUE(app.idManager.IsStaticIDValid(floating)) << "the panel keeps its own where it went"; } @@ -328,15 +331,15 @@ namespace tachyon TEST_F(DockingTest, ClosingAFloatingWindowClosesItsPanels) { int enabled = 0, disabled = 0; - auto fw = std::make_unique(); + auto fw = std::make_unique(); fw->windowID = app.idManager.CreateStaticID(); - const ID floating = app.CreatePanel(fw->layout.panels, "F", IconID::Invalid, [] {}, {}, + const ID floating = docking::CreatePanel(app, dockingContext, fw->layout.panels, "F", IconID::Invalid, [] {}, {}, [&] { enabled++; }, [&] { disabled++; }); - fw->layout.root = MakeLeaf({ floating }); - FloatingDockWindow* window = fw.get(); - app.m_floatingDockWindows.push_back(std::move(fw)); + fw->layout.root = docking::MakeLeaf({ floating }); + docking::FloatingDockWindow* window = fw.get(); + dockingContext.floatingDockWindows.push_back(std::move(fw)); - auto frame = [&] { app.Frame([&] { EmitDock(); app.EmitFloatingDockWindows(); }); }; + auto frame = [&] { app.Frame([&] { EmitDock(); docking::EmitFloatingDockWindows(app, dockingContext); }); }; frame(); frame(); ASSERT_EQ(enabled, 1) << "test setup: the floating panel is shown"; @@ -345,10 +348,10 @@ namespace tachyon // A user close (the OS reports the window gone) ends here; the // headless harness has no OS windows, so call it directly. - app.CloseFloatingDockWindow(0); + docking::CloseFloatingDockWindow(app, dockingContext, 0); frame(); - EXPECT_TRUE(app.m_floatingDockWindows.empty()); + EXPECT_TRUE(dockingContext.floatingDockWindows.empty()); EXPECT_EQ(disabled, 1) << "the panel is closed (onDisable), like closing its tab"; EXPECT_EQ(app.idManager.GetStaticIDCount(), before - 2 - treeIDs) << "the window's, its panel's and its tree's"; } @@ -358,24 +361,24 @@ namespace tachyon TEST_F(DockingTest, DockReturnsTheTornOffPanelsToTheirLeaf) { Frame(); - DockNode* home = layout.root->second.get(); - auto fw = std::make_unique(); + docking::DockNode* home = layout.root->second.get(); + auto fw = std::make_unique(); fw->windowID = app.idManager.CreateStaticID(); fw->home = &layout; fw->homeLeafID = home->nodeID; - const ID floating = app.CreatePanel(fw->layout.panels, "F", IconID::Invalid, [] {}, {}, {}, {}); - fw->layout.root = MakeLeaf({ floating }); - FloatingDockWindow* window = fw.get(); - app.m_floatingDockWindows.push_back(std::move(fw)); + const ID floating = docking::CreatePanel(app, dockingContext, fw->layout.panels, "F", IconID::Invalid, [] {}, {}, {}, {}); + fw->layout.root = docking::MakeLeaf({ floating }); + docking::FloatingDockWindow* window = fw.get(); + dockingContext.floatingDockWindows.push_back(std::move(fw)); - auto frame = [&] { app.Frame([&] { EmitDock(); app.EmitFloatingDockWindows(); }); }; + auto frame = [&] { app.Frame([&] { EmitDock(); docking::EmitFloatingDockWindows(app, dockingContext); }); }; frame(); ASSERT_TRUE(window->layout.onDock) << "a window with a home gets a Dock button"; window->layout.onDock(); frame(); frame(); - EXPECT_TRUE(app.m_floatingDockWindows.empty()); + EXPECT_TRUE(dockingContext.floatingDockWindows.empty()); ASSERT_EQ(home->panelIds.size(), 3u); EXPECT_EQ(home->panelIds.back(), floating); EXPECT_EQ(home->selectedTab, 2) << "the returned panel is the one shown"; @@ -386,19 +389,19 @@ namespace tachyon // its panels with it) though the app declares it again the next frame. TEST_F(DockingTest, ClosingATornOffWindowFromItsTitleBarKeepsItClosed) { - auto fw = std::make_unique(); + auto fw = std::make_unique(); fw->windowID = app.idManager.CreateStaticID(); - const ID floating = app.CreatePanel(fw->layout.panels, "F", IconID::Invalid, [] {}, {}, {}, {}); - fw->layout.root = MakeLeaf({ floating }); + const ID floating = docking::CreatePanel(app, dockingContext, fw->layout.panels, "F", IconID::Invalid, [] {}, {}, {}, {}); + fw->layout.root = docking::MakeLeaf({ floating }); const ID windowID = fw->windowID; - app.m_floatingDockWindows.push_back(std::move(fw)); + dockingContext.floatingDockWindows.push_back(std::move(fw)); - auto frame = [&] { app.Frame([&] { EmitDock(); app.EmitFloatingDockWindows(); }); }; + auto frame = [&] { app.Frame([&] { EmitDock(); docking::EmitFloatingDockWindows(app, dockingContext); }); }; frame(); - app.Frame([&] { (void)app.windowManager->RequestUserClose(windowID); EmitDock(); app.EmitFloatingDockWindows(); }); + app.Frame([&] { (void)app.windowManager->RequestUserClose(windowID); EmitDock(); docking::EmitFloatingDockWindows(app, dockingContext); }); frame(); - EXPECT_TRUE(app.m_floatingDockWindows.empty()); + EXPECT_TRUE(dockingContext.floatingDockWindows.empty()); } // A torn-off window's tab takes the title bar's tab style (in the light theme it joins @@ -439,13 +442,13 @@ namespace tachyon TEST_F(DockingTest, TornOffTabsUseTheTitleBarTabStyle) { - auto fw = std::make_unique(); + auto fw = std::make_unique(); fw->windowID = app.idManager.CreateStaticID(); - const ID floating = app.CreatePanel(fw->layout.panels, "F", IconID::Invalid, [] {}, {}, {}, {}); - fw->layout.root = MakeLeaf({ floating }); - app.m_floatingDockWindows.push_back(std::move(fw)); + const ID floating = docking::CreatePanel(app, dockingContext, fw->layout.panels, "F", IconID::Invalid, [] {}, {}, {}, {}); + fw->layout.root = docking::MakeLeaf({ floating }); + dockingContext.floatingDockWindows.push_back(std::move(fw)); - auto frame = [&] { app.Frame([&] { EmitDock(); app.EmitFloatingDockWindows(); }); }; + auto frame = [&] { app.Frame([&] { EmitDock(); docking::EmitFloatingDockWindows(app, dockingContext); }); }; frame(); frame(); @@ -467,14 +470,14 @@ namespace tachyon // drags the window, the tabs themselves stay the GUI's. TEST_F(DockingTest, TornOffTabsSitInTheTitleBar) { - auto fw = std::make_unique(); + auto fw = std::make_unique(); fw->windowID = app.idManager.CreateStaticID(); - const ID floating = app.CreatePanel(fw->layout.panels, "F", IconID::Invalid, [] {}, {}, {}, {}); - fw->layout.root = MakeLeaf({ floating }); - FloatingDockWindow* window = fw.get(); - app.m_floatingDockWindows.push_back(std::move(fw)); + const ID floating = docking::CreatePanel(app, dockingContext, fw->layout.panels, "F", IconID::Invalid, [] {}, {}, {}, {}); + fw->layout.root = docking::MakeLeaf({ floating }); + docking::FloatingDockWindow* window = fw.get(); + dockingContext.floatingDockWindows.push_back(std::move(fw)); - auto frame = [&] { app.Frame([&] { EmitDock(); app.EmitFloatingDockWindows(); }); }; + auto frame = [&] { app.Frame([&] { EmitDock(); docking::EmitFloatingDockWindows(app, dockingContext); }); }; frame(); frame(); const IntRect strip = app.GetElementRect(window->layout.root->tabBarID); @@ -486,14 +489,14 @@ namespace tachyon } // Closing a docked tab closes its panel for good: onDisable fires and the - // Panel (and its state) is gone; a new panel can be created later. + // docking::Panel (and its state) is gone; a new panel can be created later. TEST_F(DockingTest, ClosingADockedTabDestroysItsPanel) { Frame(); ASSERT_EQ(enables[1], 1) << "test setup: B is the visible tab"; - DockNode* right = layout.root->second.get(); + docking::DockNode* right = layout.root->second.get(); - app.CloseDockedPanel(layout, *right, 0); // close B + docking::CloseDockedPanel(app, dockingContext, layout, *right, 0); // close B Frame(); EXPECT_EQ(disables[1], 1); @@ -532,7 +535,7 @@ namespace tachyon TEST_F(DockingTest, ATabGroupsPlusAddsATab) { // The "+" buttons in a leaf's tab bar: what draws there in the icon-menu-button style. - auto PlusButtons = [this](const DockNode* leaf) { + auto PlusButtons = [this](const docking::DockNode* leaf) { std::vector found; const IntRect bar = app.GetElementRect(leaf->tabBarID); const auto& storage = app.elementStorage; @@ -550,14 +553,14 @@ namespace tachyon }; Frame(); Frame(); - DockNode* right = layout.root->second.get(); + docking::DockNode* right = layout.root->second.get(); EXPECT_TRUE(PlusButtons(right).empty()) << "no new-tab menu, no +"; ID added = ID::Invalid(); - layout.newTabMenu = [this, &added](DockingLayout& in, ID leafNodeID) { + layout.newTabMenu = [this, &added](docking::DockingLayout& in, ID leafNodeID) { app.MenuItem("Notes", [this, &in, leafNodeID, &added] { - added = app.CreatePanel(in.panels, "Notes", IconID::Invalid, [] {}); - EXPECT_TRUE(AddPanelToLeaf(in.root.get(), leafNodeID, added)); + added = docking::CreatePanel(app, dockingContext, in.panels, "Notes", IconID::Invalid, [] {}); + EXPECT_TRUE(docking::AddPanelToLeaf(in.root.get(), leafNodeID, added)); }); }; Frame(); @@ -594,24 +597,26 @@ namespace tachyon TEST(PanelCloseTest, AClosedPanelLivesUntilTheNextFrame) { HeadlessGUIApp app; + docking::Context dockingContext; ASSERT_TRUE(app.Initialize()); - DockingLayout layout; + docking::Install(app, dockingContext); + docking::DockingLayout layout; const ID container = app.idManager.CreateStaticID(), closeButton = app.idManager.CreateStaticID(); auto held = std::make_shared(0); const std::weak_ptr watch = held; ID closing = ID::Invalid(); - closing = app.CreatePanel(layout.panels, "Closing", IconID::Invalid, [&app, &layout, &closing, closeButton, held] { - app.Button(closeButton, "Close", [&app, &layout, &closing] { app.ClosePanel(layout, closing); }); + closing = docking::CreatePanel(app, dockingContext, layout.panels, "Closing", IconID::Invalid, [&app, &layout, &closing, closeButton, held, &dockingContext] { + app.Button(closeButton, "Close", [&app, &layout, &closing, &dockingContext] { docking::ClosePanel(app, dockingContext, layout, closing); }); }); layout.panels[closing].cacheSignature = [] { return std::optional{}; }; // built each frame - const ID other = app.CreatePanel(layout.panels, "Other", IconID::Invalid, [] {}); - layout.root = MakeSplit(DockSplitMode::LeftPinned, 400, MakeLeaf({ closing }), MakeLeaf({ other })); + const ID other = docking::CreatePanel(app, dockingContext, layout.panels, "Other", IconID::Invalid, [] {}); + layout.root = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 400, docking::MakeLeaf({ closing }), docking::MakeLeaf({ other })); held.reset(); auto frame = [&] { app.Frame([&] { app.BeginRootWindow(); - app.BeginDockingContainer(container, &layout, LayoutOverride{}.Size(800, 600)); - app.EndDockingContainer(); + docking::BeginDockingContainer(app, dockingContext, container, &layout, LayoutOverride{}.Size(800, 600)); + docking::EndDockingContainer(app, dockingContext); app.EndRootWindow(); }); }; @@ -627,6 +632,7 @@ namespace tachyon EXPECT_FALSE(watch.expired()) << "what it holds lives through the frame it was closed in"; frame(); EXPECT_TRUE(watch.expired()) << "and goes when the next one starts"; + docking::Cleanup(app, dockingContext); app.Cleanup(); } } // namespace diff --git a/tests/controls_documents_test.cpp b/tests/controls_documents_test.cpp index 17974db2..556ff330 100644 --- a/tests/controls_documents_test.cpp +++ b/tests/controls_documents_test.cpp @@ -7,8 +7,9 @@ #include "headless_gui_app.h" #include -#include +#include #include +#include #include @@ -22,11 +23,12 @@ namespace tachyon { protected: HeadlessGUIApp app; - DocumentSet set; + docking::Context dockingContext; + docking::DocumentSet set; ID documentsID{}; int2 windowSize{ 1200, 700 }; // A second bar under the first, as another main window's would be. - DocumentSet other; + docking::DocumentSet other; ID otherID{}; bool twoBars = false; @@ -36,6 +38,7 @@ namespace tachyon void SetUp() override { ASSERT_TRUE(app.Initialize()); + docking::Install(app, dockingContext); app.runPostLayoutCallbacks = true; // the tab bar measures what fits documentsID = app.idManager.CreateStaticID(); otherID = app.idManager.CreateStaticID(); @@ -44,15 +47,15 @@ namespace tachyon void TearDown() override { app.Cleanup(); } // A document with one panel, whose draws and visibility are logged. - Document& Add(std::string name, std::string extension, std::string kind) { return AddTo(set, std::move(name), std::move(extension), std::move(kind)); } - Document& AddTo(DocumentSet& to, std::string name, std::string extension, std::string kind) + docking::Document& Add(std::string name, std::string extension, std::string kind) { return AddTo(set, std::move(name), std::move(extension), std::move(kind)); } + docking::Document& AddTo(docking::DocumentSet& to, std::string name, std::string extension, std::string kind) { - Document& document = app.CreateDocument(to, name, std::move(extension), std::move(kind), IconID::Invalid); + docking::Document& document = docking::CreateDocument(app, dockingContext, to, name, std::move(extension), std::move(kind), IconID::Invalid); PanelLog* log = logs.emplace_back(std::make_unique()).get(); - const ID panel = app.CreatePanel(document.layout.panels, name + " panel", IconID::Invalid, + const ID panel = docking::CreatePanel(app, dockingContext, document.layout.panels, name + " panel", IconID::Invalid, [log] { log->draws++; }, {}, [log] { log->enables++; }, [log] { log->disables++; }); - document.layout.root = MakeLeaf({ panel }); + document.layout.root = docking::MakeLeaf({ panel }); return document; } @@ -62,16 +65,16 @@ namespace tachyon app.BeginRootWindow(windowSize, ElementFlags::None, app.theme.mainWindowStyleRef); if (!twoBars) { - app.Documents(documentsID, set); + docking::Documents(app, dockingContext, documentsID, set); app.EndRootWindow(); - app.EmitFloatingDockWindows(); + docking::EmitFloatingDockWindows(app, dockingContext); return; } - app.Documents(documentsID, set, LayoutOverride{}.Height(windowSize.y / 2)); - app.Documents(otherID, other, LayoutOverride{}.Height(windowSize.y / 2)); + docking::Documents(app, dockingContext, documentsID, set, LayoutOverride{}.Height(windowSize.y / 2)); + docking::Documents(app, dockingContext, otherID, other, LayoutOverride{}.Height(windowSize.y / 2)); app.EndRootWindow(); - app.EmitFloatingDockWindows(set); - app.EmitFloatingDockWindows(other); + docking::EmitFloatingDockWindows(app, dockingContext, set); + docking::EmitFloatingDockWindows(app, dockingContext, other); }); } @@ -97,7 +100,7 @@ namespace tachyon StyleRef Class(std::string_view cssClass) const { return *app.theme.FindStyle(cssClass); } // The tab of `document`, by its name. - int2 TabCenter(const Document& document) const { return app.CenterOf(app.FindByText(document.name)); } + int2 TabCenter(const docking::Document& document) const { return app.CenterOf(app.FindByText(document.name)); } // Presses a tab, drags it to `to` (stopping there for `during`) and drops it. void DragTab(int2 from, int2 to, const std::function& during = {}) @@ -116,8 +119,8 @@ namespace tachyon Frame(); Frame(); } - IntRect BarOf(const DocumentSet& documents) const { return app.GetElementRect(documents.internal.barID); } - static std::vector Names(const DocumentSet& documents) + IntRect BarOf(const docking::DocumentSet& documents) const { return app.GetElementRect(documents.internal.barID); } + static std::vector Names(const docking::DocumentSet& documents) { std::vector names; for (const auto& document : documents.documents) @@ -159,16 +162,16 @@ namespace tachyon app.Frame([&] { app.BeginRootWindow(windowSize, ElementFlags::WindowCustomTitleBar, app.theme.mainWindowStyleRef); app.BeginTitleBar(titleBarID); - app.DocumentBar(documentsID, set, app.theme.titleBarDocumentsStyleRef); + docking::DocumentBar(app, dockingContext, documentsID, set, docking::GetStyles(app, dockingContext).titleBarDocumentsStyleRef); app.EndTitleBar(); - app.DocumentLine(set); + docking::DocumentLine(app, dockingContext, set); EXPECT_TRUE(app.menuManager.menuBarTriggers.empty()) << "\"N open\" isn't one of the title bar's menus"; app.BeginMenuBar(menuBarID); if (app.BeginMenu(fileID, "File", app.theme.menuBarTriggerStyleRef, app.theme.menuStyleRef, app.theme.menuItemRowStyleRef)) app.MenuItem("New", nullptr); app.EndMenu(); app.EndMenuBar(); - app.DocumentPanels(set); + docking::DocumentPanels(app, dockingContext, set); app.EndRootWindow(); }); }; @@ -222,7 +225,7 @@ namespace tachyon TEST_F(DocumentsTest, ClickingATabShowsItsDocument) { Add("Forest", ".level", "level"); - Document& desert = Add("Desert", ".level", "level"); + docking::Document& desert = Add("Desert", ".level", "level"); Settle(); app.ClickAt(TabCenter(desert)); Frame(); @@ -240,7 +243,7 @@ namespace tachyon EXPECT_EQ(FindAllByStyle(Class("document-tab-level")).size(), 1u); EXPECT_EQ(FindAllByStyle(Class("document-tab-material")).size(), 1u); - EXPECT_EQ(FindAllByStyle(app.theme.documentTabStyleRef).size(), 1u) << "an unknown type gets the plain tab"; + EXPECT_EQ(FindAllByStyle(docking::GetStyles(app, dockingContext).documentTabStyleRef).size(), 1u) << "an unknown type gets the plain tab"; EXPECT_EQ(FindAllByStyle(Class("document-name-material")).size(), 1u) << "the icon in the type's color"; EXPECT_NE(FindByStyle(Class("document-line-level")), ID::Invalid()) << "the line is the active document's"; EXPECT_EQ(FindByStyle(Class("document-line-material")), ID::Invalid()); @@ -251,12 +254,12 @@ namespace tachyon EXPECT_EQ(FindByStyle(Class("document-line-level")), ID::Invalid()); set.active = 2; Frame(); - EXPECT_NE(FindByStyle(app.theme.documentLineStyleRef), ID::Invalid()); + EXPECT_NE(FindByStyle(docking::GetStyles(app, dockingContext).documentLineStyleRef), ID::Invalid()); } TEST_F(DocumentsTest, TheNameIsFollowedByItsExtension) { - Document& forest = Add("Forest", ".level", "level"); + docking::Document& forest = Add("Forest", ".level", "level"); Settle(); const ID name = app.FindByText("Forest"); const ID extension = app.FindByText(".level"); @@ -271,8 +274,8 @@ namespace tachyon TEST_F(DocumentsTest, ATypeWithoutClassesLooksLikeTheOthers) { - Document& forest = Add("Forest", ".level", "level"); - Document& notes = Add("Notes", ".txt", "text"); + docking::Document& forest = Add("Forest", ".level", "level"); + docking::Document& notes = Add("Notes", ".txt", "text"); Settle(); const IntRect n = app.GetElementRect(app.FindByText("Notes")); const IntRect e = app.GetElementRect(app.FindByText(".txt")); @@ -286,7 +289,7 @@ namespace tachyon { Add("Forest", ".level", "level"); Settle(); - const IntRect bar = app.GetElementRect(FindByStyle(app.theme.documentBarStyleRef)); + const IntRect bar = app.GetElementRect(FindByStyle(docking::GetStyles(app, dockingContext).documentBarStyleRef)); const IntRect line = app.GetElementRect(FindByStyle(Class("document-line-level"))); EXPECT_EQ(bar.h, app.styleManager.Px(36)); EXPECT_EQ(line.h, app.styleManager.Px(2)); @@ -303,10 +306,10 @@ namespace tachyon Add("Desert", ".level", "level"); int asked = 0; bool allow = false; - set.onClose = [&](Document& document) { ++asked; EXPECT_EQ(document.name, "Forest"); return allow; }; + set.onClose = [&](docking::Document& document) { ++asked; EXPECT_EQ(document.name, "Forest"); return allow; }; Settle(); - const std::vector closes = FindAllByStyle(app.theme.documentCloseStyleRef); + const std::vector closes = FindAllByStyle(docking::GetStyles(app, dockingContext).documentCloseStyleRef); ASSERT_EQ(closes.size(), 1u) << "only the active tab shows its close button"; app.ClickAt(app.CenterOf(closes[0])); Frame(); @@ -317,7 +320,7 @@ namespace tachyon EXPECT_EQ(set.active, 0) << "a click on the close button doesn't select"; allow = true; - app.ClickAt(app.CenterOf(FindByStyle(app.theme.documentCloseStyleRef))); + app.ClickAt(app.CenterOf(FindByStyle(docking::GetStyles(app, dockingContext).documentCloseStyleRef))); Frame(); Frame(); EXPECT_EQ(asked, 2); @@ -331,7 +334,7 @@ namespace tachyon TEST_F(DocumentsTest, CtrlWClosesTheFocusedDocument) { Add("Forest", ".level", "level"); - Document& desert = Add("Desert", ".level", "level"); + docking::Document& desert = Add("Desert", ".level", "level"); Settle(); app.ClickAt(TabCenter(desert)); Frame(); @@ -351,19 +354,19 @@ namespace tachyon Add("D", ".level", "level"); set.active = 2; Settle(); - app.CloseDocument(set, 0); + docking::CloseDocument(app, dockingContext, set, 0); EXPECT_EQ(set.active, 1); EXPECT_EQ(set.Active()->name, "C"); - app.CloseDocument(set, 2); + docking::CloseDocument(app, dockingContext, set, 2); EXPECT_EQ(set.Active()->name, "C") << "one after it closed"; - app.CloseDocument(set, 1); + docking::CloseDocument(app, dockingContext, set, 1); EXPECT_EQ(set.Active()->name, "B") << "the active one closed, the last: the one before"; - app.CloseDocument(set, 5); // no such document + docking::CloseDocument(app, dockingContext, set, 5); // no such document EXPECT_EQ(set.documents.size(), 1u); - app.CloseDocument(set, 0); + docking::CloseDocument(app, dockingContext, set, 0); EXPECT_EQ(set.Active(), nullptr); Frame(); // a set without documents still builds its bar - EXPECT_NE(FindByStyle(app.theme.documentLineStyleRef), ID::Invalid()); + EXPECT_NE(FindByStyle(docking::GetStyles(app, dockingContext).documentLineStyleRef), ID::Invalid()); } TEST_F(DocumentsTest, ClosingReleasesTheDocumentsIDs) @@ -372,44 +375,44 @@ namespace tachyon Add("Desert", ".level", "level"); Settle(); const size_t before = app.idManager.GetStaticIDCount(); - const DockNode* root = set.documents[0]->layout.root.get(); + const docking::DockNode* root = set.documents[0]->layout.root.get(); ASSERT_NE(root->nodeID, ID::Invalid()) << "test setup: the tree was built"; const size_t treeIDs = (root->nodeID.GetMode() == IDMode::Static) + (root->tabBarID.GetMode() == IDMode::Static); - app.CloseDocument(set, 0); + docking::CloseDocument(app, dockingContext, set, 0); EXPECT_EQ(app.idManager.GetStaticIDCount(), before - 3 - treeIDs) << "its own two, its panel's and its tree's"; } TEST_F(DocumentsTest, AClosedDocumentsLayoutIsNoLongerSaved) { - Document& forest = Add("Forest", ".level", "level"); + docking::Document& forest = Add("Forest", ".level", "level"); Add("Desert", ".level", "level"); - app.PersistDocking("forest", forest.layout); + docking::PersistDocking(app, dockingContext, "forest", forest.layout); Settle(); ASSERT_NE(app.SaveUIState().find("\"forest\""), std::string::npos) << "test setup: it's saved"; - app.CloseDocument(set, 0); + docking::CloseDocument(app, dockingContext, set, 0); EXPECT_EQ(app.SaveUIState().find("\"forest\""), std::string::npos); } TEST_F(DocumentsTest, AnUnsavedDocumentShowsADotUntilHovered) { Add("Forest", ".level", "level"); - Document& desert = Add("Desert", ".level", "level"); + docking::Document& desert = Add("Desert", ".level", "level"); desert.dirty = true; Settle(); - EXPECT_EQ(FindAllByStyle(app.theme.documentDirtyStyleRef).size(), 1u); - EXPECT_EQ(FindAllByStyle(app.theme.documentCloseStyleRef).size(), 1u) << "the active tab's only"; + EXPECT_EQ(FindAllByStyle(docking::GetStyles(app, dockingContext).documentDirtyStyleRef).size(), 1u); + EXPECT_EQ(FindAllByStyle(docking::GetStyles(app, dockingContext).documentCloseStyleRef).size(), 1u) << "the active tab's only"; app.InjectMouseMove(TabCenter(desert)); Frame(); Frame(); - EXPECT_EQ(FindAllByStyle(app.theme.documentDirtyStyleRef).size(), 0u) << "hovered: its close button instead"; - EXPECT_EQ(FindAllByStyle(app.theme.documentCloseStyleRef).size(), 2u); + EXPECT_EQ(FindAllByStyle(docking::GetStyles(app, dockingContext).documentDirtyStyleRef).size(), 0u) << "hovered: its close button instead"; + EXPECT_EQ(FindAllByStyle(docking::GetStyles(app, dockingContext).documentCloseStyleRef).size(), 2u); const IntRect tabBefore = app.GetElementRect(desert.id); app.InjectMouseMove({ 5, windowSize.y - 5 }); Frame(); Frame(); - EXPECT_EQ(FindAllByStyle(app.theme.documentDirtyStyleRef).size(), 1u); + EXPECT_EQ(FindAllByStyle(docking::GetStyles(app, dockingContext).documentDirtyStyleRef).size(), 1u); EXPECT_EQ(app.GetElementRect(desert.id).w, tabBefore.w) << "the mark's slot keeps the tab's width"; } @@ -417,12 +420,12 @@ namespace tachyon { Add("Forest", ".level", "level"); Settle(); - EXPECT_EQ(FindByStyle(app.theme.documentNewStyleRef), ID::Invalid()) << "none without onNew"; + EXPECT_EQ(FindByStyle(docking::GetStyles(app, dockingContext).documentNewStyleRef), ID::Invalid()) << "none without onNew"; int created = 0; - set.onNew = [&] { ++created; app.CreateDocument(set, "Untitled", ".level", "level", IconID::Invalid); }; + set.onNew = [&] { ++created; docking::CreateDocument(app, dockingContext, set, "Untitled", ".level", "level", IconID::Invalid); }; Settle(); - const ID plus = FindByStyle(app.theme.documentNewStyleRef); + const ID plus = FindByStyle(docking::GetStyles(app, dockingContext).documentNewStyleRef); ASSERT_NE(plus, ID::Invalid()); const IntRect last = app.GetElementRect(set.documents[0]->id); EXPECT_GT(app.GetElementRect(plus).x, last.x + last.w) << "after the last tab"; @@ -442,7 +445,7 @@ namespace tachyon Settle(); const ID list = app.FindByText("3 open"); ASSERT_NE(list, ID::Invalid()); - const IntRect bar = app.GetElementRect(FindByStyle(app.theme.documentBarStyleRef)); + const IntRect bar = app.GetElementRect(FindByStyle(docking::GetStyles(app, dockingContext).documentBarStyleRef)); const IntRect at = app.GetElementRect(list); EXPECT_GT(at.x, bar.x + bar.w / 2) << "on the right"; @@ -478,7 +481,7 @@ namespace tachyon EXPECT_EQ(FindByStyle(app.theme.tabOverflowStyleRef), ID::Invalid()) << "no \"+N\": the list has them"; auto noOverlap = [&](const char* when) { - const IntRect plus = app.GetElementRect(FindByStyle(app.theme.documentNewStyleRef)); + const IntRect plus = app.GetElementRect(FindByStyle(docking::GetStyles(app, dockingContext).documentNewStyleRef)); const IntRect list = app.GetElementRect(app.FindByText(std::to_string(set.documents.size()) + " open")); EXPECT_LE(plus.x + plus.w, list.x) << "\"+\" still fits before the list " << when; for (const auto& document : set.documents) @@ -502,8 +505,8 @@ namespace tachyon TEST_F(DocumentsTest, DraggingATabReordersTheDocuments) { - Document& a = Add("A", ".level", "level"); - Document& b = Add("B", ".level", "level"); + docking::Document& a = Add("A", ".level", "level"); + docking::Document& b = Add("B", ".level", "level"); Add("C", ".level", "level"); Settle(); ASSERT_EQ(set.active, 0); @@ -565,7 +568,7 @@ namespace tachyon TEST_F(DocumentsTest, ATabsMenuClosesItAndHasNoLayouts) { - Document& forest = Add("Forest", ".level", "level"); + docking::Document& forest = Add("Forest", ".level", "level"); Settle(); const int2 at = TabCenter(forest); app.InjectMouseMove(at); @@ -578,7 +581,7 @@ namespace tachyon app.menuManager.CloseAll(app.guiStateManager); // The empty part of the bar, after the tabs, has no layouts either. - const IntRect bar = app.GetElementRect(FindByStyle(app.theme.documentTabBarStyleRef)); + const IntRect bar = app.GetElementRect(FindByStyle(docking::GetStyles(app, dockingContext).documentTabBarStyleRef)); const int2 strip{ bar.x + bar.w - 10, bar.y + bar.h / 2 }; app.InjectMouseMove(strip); Frame(); @@ -593,12 +596,12 @@ namespace tachyon TEST_F(DocumentsTest, ATabDroppedOnAnotherBarMovesItsDocumentThere) { twoBars = true; - Document& forest = Add("Forest", ".level", "level"); + docking::Document& forest = Add("Forest", ".level", "level"); Add("Desert", ".level", "level"); Add("Dunes", ".level", "level"); AddTo(other, "Terrain", ".mat", "material"); AddTo(other, "Hud", ".layout", "layout"); - set.onTearOff = [](std::unique_ptr, int2) {}; // a drop off the bars would make a window + set.onTearOff = [](std::unique_ptr, int2) {}; // a drop off the bars would make a window Settle(); const IntRect terrain = app.GetElementRect(other.documents[0]->id); @@ -623,7 +626,7 @@ namespace tachyon TEST_F(DocumentsTest, ClosingTheDraggedDocumentEndsItsDrag) { twoBars = true; - Document& forest = Add("Forest", ".level", "level"); + docking::Document& forest = Add("Forest", ".level", "level"); Add("Desert", ".level", "level"); AddTo(other, "Terrain", ".mat", "material"); Settle(); @@ -631,7 +634,7 @@ namespace tachyon const IntRect terrain = app.GetElementRect(other.documents[0]->id); int forestsAfterClose = -1; DragTab(TabCenter(forest), { terrain.x + terrain.w * 3 / 4, terrain.y + terrain.h / 2 }, [&] { - app.CloseDocument(set, 0); + docking::CloseDocument(app, dockingContext, set, 0); Frame(); forestsAfterClose = app.CountByText("Forest"); }); @@ -645,7 +648,7 @@ namespace tachyon TEST_F(DocumentsTest, ThePhantomFollowsTheCursor) { twoBars = true; - Document& forest = Add("Forest", ".level", "level"); + docking::Document& forest = Add("Forest", ".level", "level"); AddTo(other, "Terrain", ".mat", "material"); AddTo(other, "Hud", ".layout", "layout"); Settle(); @@ -706,7 +709,7 @@ namespace tachyon for (const int x : { 0, 1, 2, 3, 4, 5 }) { const IntRect last = app.GetElementRect(set.documents.back()->id); - const IntRect plus = app.GetElementRect(FindByStyle(app.theme.documentNewStyleRef)); + const IntRect plus = app.GetElementRect(FindByStyle(docking::GetStyles(app, dockingContext).documentNewStyleRef)); const IntRect list = app.GetElementRect(app.FindByText(std::to_string(set.documents.size()) + " open")); const int32_t xs[] = { last.x + last.w + 2, plus.x + plus.w + 4, (plus.x + plus.w + list.x) / 2, list.x - 4, list.x + list.w / 2, bar.x + bar.w - 2 }; @@ -757,11 +760,11 @@ namespace tachyon TEST_F(DocumentsTest, ATabDroppedOffEveryBarIsTornOff) { twoBars = true; - Document& forest = Add("Forest", ".level", "level"); + docking::Document& forest = Add("Forest", ".level", "level"); Add("Desert", ".level", "level"); AddTo(other, "Terrain", ".mat", "material"); std::vector> tornOff; - set.onTearOff = [&](std::unique_ptr document, int2 at) { tornOff.push_back({ document->name, at }); }; + set.onTearOff = [&](std::unique_ptr document, int2 at) { tornOff.push_back({ document->name, at }); }; Settle(); // Over the other bar's panels: documents don't drop on panels. @@ -780,7 +783,7 @@ namespace tachyon TEST_F(DocumentsTest, WithoutOnTearOffATabDroppedOffTheBarsGoesBack) { - Document& forest = Add("Forest", ".level", "level"); + docking::Document& forest = Add("Forest", ".level", "level"); Add("Desert", ".level", "level"); Settle(); bool ghostDuring = true; @@ -795,7 +798,7 @@ namespace tachyon Add("Desert", ".level", "level"); Add("Dunes", ".level", "level"); int tornOff = 0; - set.onTearOff = [&](std::unique_ptr, int2) { ++tornOff; }; + set.onTearOff = [&](std::unique_ptr, int2) { ++tornOff; }; Settle(); // The bar past "N open", outside the tabs but still the bar: last. const IntRect bar = BarOf(set); @@ -816,7 +819,7 @@ namespace tachyon // A document dragged before: what's left of that drag shows nothing now. DragTab(TabCenter(*set.documents[1]), { bar.x + bar.w / 3, bar.y + bar.h / 2 }); ASSERT_EQ(Names(other), (std::vector{ "Terrain", "Desert" })); - app.CloseDocument(other, 1); + docking::CloseDocument(app, dockingContext, other, 1); Frame(); const ID panel = set.documents[0]->layout.root->panelIds[0]; @@ -826,66 +829,66 @@ namespace tachyon EXPECT_EQ(forestDuring, 1) << "no document phantom for a panel"; EXPECT_EQ(Names(other), (std::vector{ "Terrain" })); EXPECT_EQ(other.documents[0]->layout.panels.size(), 1u); - ASSERT_EQ(app.m_floatingDockWindows.size(), 1u) << "it floats, as off every dock"; - EXPECT_EQ(app.m_floatingDockWindows[0]->home, &set.documents[0]->layout); + ASSERT_EQ(dockingContext.floatingDockWindows.size(), 1u) << "it floats, as off every dock"; + EXPECT_EQ(dockingContext.floatingDockWindows[0]->home, &set.documents[0]->layout); } // An app's own layout, destroyed while a panel torn off it floats: forgotten first, // its windows go, and nothing refers to it after. TEST_F(DocumentsTest, AForgottenLayoutTakesItsFloatingWindows) { - auto layout = std::make_unique(); - const ID kept = app.CreatePanel(layout->panels, "Kept", IconID::Invalid, [] {}, {}); - const ID floated = app.CreatePanel(layout->panels, "Floated", IconID::Invalid, [] {}, {}); - layout->root = MakeLeaf({ kept, floated }); + auto layout = std::make_unique(); + const ID kept = docking::CreatePanel(app, dockingContext, layout->panels, "Kept", IconID::Invalid, [] {}, {}); + const ID floated = docking::CreatePanel(app, dockingContext, layout->panels, "Floated", IconID::Invalid, [] {}, {}); + layout->root = docking::MakeLeaf({ kept, floated }); const ID dockID = app.idManager.CreateStaticID(); auto draw = [&] { app.Frame([&] { app.BeginRootWindow(windowSize, ElementFlags::None, app.theme.mainWindowStyleRef); if (layout) { - app.BeginDockingContainer(dockID, layout.get(), LayoutOverride{}.Size(600, 400)); - app.EndDockingContainer(); + docking::BeginDockingContainer(app, dockingContext, dockID, layout.get(), LayoutOverride{}.Size(600, 400)); + docking::EndDockingContainer(app, dockingContext); } app.EndRootWindow(); - app.EmitFloatingDockWindows(); + docking::EmitFloatingDockWindows(app, dockingContext); }); }; draw(); - ASSERT_TRUE(app.FloatPanel(*layout, floated, { 100, 100 })); + ASSERT_TRUE(docking::FloatPanel(app, dockingContext, *layout, floated, { 100, 100 })); draw(); - ASSERT_EQ(app.m_floatingDockWindows.size(), 1u); + ASSERT_EQ(dockingContext.floatingDockWindows.size(), 1u); - app.ForgetDockingLayout(*layout); + docking::ForgetDockingLayout(app, dockingContext, *layout); layout.reset(); draw(); draw(); - EXPECT_TRUE(app.m_floatingDockWindows.empty()); + EXPECT_TRUE(dockingContext.floatingDockWindows.empty()); } TEST_F(DocumentsTest, TornOffPanelsBelongToTheirDocumentsWindow) { twoBars = true; - Document& forest = Add("Forest", ".level", "level"); + docking::Document& forest = Add("Forest", ".level", "level"); AddTo(other, "Terrain", ".mat", "material"); - const ID floated = app.CreatePanel(forest.layout.panels, "Floated", IconID::Invalid, [] {}, {}); - forest.layout.root = MakeSplit(DockSplitMode::LeftPinned, 200, std::move(forest.layout.root), MakeLeaf({ floated })); + const ID floated = docking::CreatePanel(app, dockingContext, forest.layout.panels, "Floated", IconID::Invalid, [] {}, {}); + forest.layout.root = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 200, std::move(forest.layout.root), docking::MakeLeaf({ floated })); Settle(); - ASSERT_TRUE(app.FloatPanel(forest.layout, floated, { 100, 100 })); + ASSERT_TRUE(docking::FloatPanel(app, dockingContext, forest.layout, floated, { 100, 100 })); Frame(); - ASSERT_EQ(app.m_floatingDockWindows.size(), 1u); - const ID window = app.m_floatingDockWindows[0]->windowID; + ASSERT_EQ(dockingContext.floatingDockWindows.size(), 1u); + const ID window = dockingContext.floatingDockWindows[0]->windowID; // Only the set holding its document builds it. int built = 0; - auto emitOnly = [&](DocumentSet& documents) + auto emitOnly = [&](docking::DocumentSet& documents) { app.Frame([&] { app.BeginRootWindow(windowSize, ElementFlags::None, app.theme.mainWindowStyleRef); - app.Documents(documentsID, set, LayoutOverride{}.Height(windowSize.y / 2)); - app.Documents(otherID, other, LayoutOverride{}.Height(windowSize.y / 2)); + docking::Documents(app, dockingContext, documentsID, set, LayoutOverride{}.Height(windowSize.y / 2)); + docking::Documents(app, dockingContext, otherID, other, LayoutOverride{}.Height(windowSize.y / 2)); app.EndRootWindow(); - app.EmitFloatingDockWindows(documents); + docking::EmitFloatingDockWindows(app, dockingContext, documents); }); built = app.HasElement(window) ? 1 : 0; }; @@ -902,13 +905,13 @@ namespace tachyon EXPECT_EQ(built, 0); emitOnly(other); EXPECT_EQ(built, 1); - EXPECT_EQ(app.m_floatingDockWindows.size(), 1u); + EXPECT_EQ(dockingContext.floatingDockWindows.size(), 1u); } TEST_F(DocumentsTest, ADocumentClosedBeforeItsDropIsDoneStaysClosed) { twoBars = true; - Document& forest = Add("Forest", ".level", "level"); + docking::Document& forest = Add("Forest", ".level", "level"); Add("Desert", ".level", "level"); AddTo(other, "Terrain", ".mat", "material"); Settle(); @@ -924,7 +927,7 @@ namespace tachyon Frame(); app.InjectMouseUp(to); Frame(); // dropped: the move waits for the next frame - app.CloseDocument(set, 0); + docking::CloseDocument(app, dockingContext, set, 0); Frame(); EXPECT_EQ(Names(set), (std::vector{ "Desert" })); EXPECT_EQ(Names(other), (std::vector{ "Terrain" })); @@ -932,41 +935,41 @@ namespace tachyon TEST_F(DocumentsTest, ClosingADocumentClosesItsTornOffPanels) { - Document& forest = Add("Forest", ".level", "level"); + docking::Document& forest = Add("Forest", ".level", "level"); Add("Desert", ".level", "level"); - const ID floated = app.CreatePanel(forest.layout.panels, "Floated", IconID::Invalid, [] {}, {}); - forest.layout.root = MakeSplit(DockSplitMode::LeftPinned, 200, std::move(forest.layout.root), MakeLeaf({ floated })); + const ID floated = docking::CreatePanel(app, dockingContext, forest.layout.panels, "Floated", IconID::Invalid, [] {}, {}); + forest.layout.root = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 200, std::move(forest.layout.root), docking::MakeLeaf({ floated })); Settle(); - ASSERT_TRUE(app.FloatPanel(forest.layout, floated, { 100, 100 })); + ASSERT_TRUE(docking::FloatPanel(app, dockingContext, forest.layout, floated, { 100, 100 })); Frame(); - ASSERT_EQ(app.m_floatingDockWindows.size(), 1u); + ASSERT_EQ(dockingContext.floatingDockWindows.size(), 1u); - app.CloseDocument(set, 0); - EXPECT_TRUE(app.m_floatingDockWindows.empty()) << "they would dock back into a layout that's gone"; + docking::CloseDocument(app, dockingContext, set, 0); + EXPECT_TRUE(dockingContext.floatingDockWindows.empty()) << "they would dock back into a layout that's gone"; Frame(); } TEST_F(DocumentsTest, DockingIntoAHiddenDocumentShowsItFirst) { - Document& forest = Add("Forest", ".level", "level"); + docking::Document& forest = Add("Forest", ".level", "level"); Add("Desert", ".level", "level"); - const ID floated = app.CreatePanel(forest.layout.panels, "Floated", IconID::Invalid, [] {}, {}); - forest.layout.root = MakeSplit(DockSplitMode::LeftPinned, 200, std::move(forest.layout.root), MakeLeaf({ floated })); + const ID floated = docking::CreatePanel(app, dockingContext, forest.layout.panels, "Floated", IconID::Invalid, [] {}, {}); + forest.layout.root = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 200, std::move(forest.layout.root), docking::MakeLeaf({ floated })); Settle(); - ASSERT_TRUE(app.FloatPanel(forest.layout, floated, { 100, 100 })); + ASSERT_TRUE(docking::FloatPanel(app, dockingContext, forest.layout, floated, { 100, 100 })); Frame(); set.active = 1; Frame(); - ASSERT_EQ(app.m_floatingDockWindows.size(), 1u); + ASSERT_EQ(dockingContext.floatingDockWindows.size(), 1u); - FloatingDockWindow& window = *app.m_floatingDockWindows[0]; + docking::FloatingDockWindow& window = *dockingContext.floatingDockWindows[0]; ASSERT_TRUE(window.layout.onDock); window.layout.onDock(); Frame(); EXPECT_EQ(set.active, 0) << "its document is shown"; Frame(); Frame(); - EXPECT_TRUE(app.m_floatingDockWindows.empty()) << "and the panel docked back into it"; + EXPECT_TRUE(dockingContext.floatingDockWindows.empty()) << "and the panel docked back into it"; EXPECT_TRUE(forest.layout.panels.contains(floated)); } } diff --git a/tests/controls_tabs_test.cpp b/tests/controls_tabs_test.cpp index db177d12..be13cef9 100644 --- a/tests/controls_tabs_test.cpp +++ b/tests/controls_tabs_test.cpp @@ -8,6 +8,7 @@ #include #include #include +#include namespace tachyon { diff --git a/tests/dictionary_field_test.cpp b/tests/dictionary_field_test.cpp index 9befae86..973c3097 100644 --- a/tests/dictionary_field_test.cpp +++ b/tests/dictionary_field_test.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include @@ -27,6 +28,7 @@ namespace tachyon { protected: HeadlessGUIApp app; + docking::Context dockingContext; void SetUp() override { ASSERT_TRUE(app.Initialize()); } void TearDown() override { app.Cleanup(); } @@ -188,7 +190,7 @@ namespace tachyon std::unordered_map map = { { "ab", 7 } }; auto draw = [&] { app.BeginRootWindow({ 800, 600 }); - if (app.BeginArea(app.theme.dockContentStyleRef, LayoutOverride{}.FlexGrow(1))) + if (app.BeginArea(docking::GetStyles(app, dockingContext).dockContentStyleRef, LayoutOverride{}.FlexGrow(1))) { app.Field(map); app.EndArea(); @@ -229,7 +231,7 @@ namespace tachyon app.Frame([&] { app.BeginRootWindow({ 800, 600 }); - if (app.BeginArea(app.theme.dockContentStyleRef, LayoutOverride{}.FlexGrow(1))) + if (app.BeginArea(docking::GetStyles(app, dockingContext).dockContentStyleRef, LayoutOverride{}.FlexGrow(1))) { app.BeginLabelGroup(120, 40, 300); app.Label("Dictionary"); @@ -256,7 +258,7 @@ namespace tachyon auto frame = [&] { app.BeginRootWindow({ 800, 600 }); - if (app.BeginArea(app.theme.dockContentStyleRef, LayoutOverride{}.FlexGrow(1))) + if (app.BeginArea(docking::GetStyles(app, dockingContext).dockContentStyleRef, LayoutOverride{}.FlexGrow(1))) { app.BeginLabelGroup(120, 40, 300); app.Label("Dictionary"); @@ -296,7 +298,7 @@ namespace tachyon app.Frame([&] { app.BeginRootWindow({ 800, 600 }); - if (app.BeginArea(app.theme.dockContentStyleRef, LayoutOverride{}.FlexGrow(1))) + if (app.BeginArea(docking::GetStyles(app, dockingContext).dockContentStyleRef, LayoutOverride{}.FlexGrow(1))) { app.BeginLabelGroup(120, 40, 300); @@ -411,7 +413,7 @@ namespace tachyon app.Frame([&] { app.BeginRootWindow({ 800, 600 }); - if (app.BeginArea(outerID, app.theme.dockContentStyleRef, + if (app.BeginArea(outerID, docking::GetStyles(app, dockingContext).dockContentStyleRef, LayoutOverride::FixedWidth(CssPx(outerWidth)).NoGrow())) { app.Field(dict, tachyon::LayoutOverride{}.FlexGrow(1)); @@ -439,7 +441,7 @@ namespace tachyon app.Frame([&] { app.BeginRootWindow({ 260, 600 }); - if (app.BeginArea(app.theme.dockContentStyleRef, LayoutOverride{}.FlexGrow(1))) + if (app.BeginArea(docking::GetStyles(app, dockingContext).dockContentStyleRef, LayoutOverride{}.FlexGrow(1))) { app.BeginLabelGroup(200, 40, 300); app.Label("Dictionary"); @@ -481,7 +483,7 @@ namespace tachyon app.Frame([&] { app.BeginRootWindow({ 800, 600 }); - if (app.BeginArea(outerID, app.theme.dockContentStyleRef, + if (app.BeginArea(outerID, docking::GetStyles(app, dockingContext).dockContentStyleRef, LayoutOverride::FixedWidth(CssPx(outerWidth)).NoGrow())) { if (app.BeginArea(app.theme.listAreaStyleRef, LayoutOverride{}.FlexGrow(1))) diff --git a/tests/dock_node_test.cpp b/tests/dock_node_test.cpp index 18972864..9bc1d785 100644 --- a/tests/dock_node_test.cpp +++ b/tests/dock_node_test.cpp @@ -1,8 +1,9 @@ #include -#include +#include #include #include +#include #include #include @@ -14,7 +15,7 @@ namespace tachyon namespace { - // Distinct panel IDs without an IDManager (DockNode only compares IDs). + // Distinct panel IDs without an IDManager (docking::DockNode only compares IDs). ID MakePanelID(uint64_t seed) { ID id{}; @@ -32,7 +33,7 @@ namespace tachyon ID a = MakePanelID(1); ID b = MakePanelID(2); ID c = MakePanelID(3); - auto leaf = MakeLeaf({a, b, c}); + auto leaf = docking::MakeLeaf({a, b, c}); ASSERT_NE(leaf, nullptr); EXPECT_TRUE(leaf->isLeaf); @@ -48,7 +49,7 @@ namespace tachyon TEST(DockNodeTest, MakeLeafEmptyByDefault) { - auto leaf = MakeLeaf(); + auto leaf = docking::MakeLeaf(); ASSERT_NE(leaf, nullptr); EXPECT_TRUE(leaf->isLeaf); EXPECT_TRUE(leaf->panelIds.empty()); @@ -58,13 +59,13 @@ namespace tachyon { ID a = MakePanelID(1); ID b = MakePanelID(2); - auto split = MakeSplit(DockSplitMode::LeftPinned, 250, - MakeLeaf({a}), MakeLeaf({b}), + auto split = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 250, + docking::MakeLeaf({a}), docking::MakeLeaf({b}), 100, 60); ASSERT_NE(split, nullptr); EXPECT_FALSE(split->isLeaf); - EXPECT_EQ(split->mode, DockSplitMode::LeftPinned); + EXPECT_EQ(split->mode, docking::DockSplitMode::LeftPinned); EXPECT_EQ(split->splitSize, 250); EXPECT_EQ(split->minFirstSize, 100); EXPECT_EQ(split->minSecondSize, 60); @@ -80,25 +81,25 @@ namespace tachyon TEST(DockNodeTest, MakeSplitRespectsRightPinnedMode) { - auto split = MakeSplit(DockSplitMode::RightPinned, 200, - MakeLeaf({MakePanelID(1)}), - MakeLeaf({MakePanelID(2)})); - EXPECT_EQ(split->mode, DockSplitMode::RightPinned); + auto split = docking::MakeSplit(docking::DockSplitMode::RightPinned, 200, + docking::MakeLeaf({MakePanelID(1)}), + docking::MakeLeaf({MakePanelID(2)})); + EXPECT_EQ(split->mode, docking::DockSplitMode::RightPinned); EXPECT_TRUE(IsHorizontalSplit(split->mode)); EXPECT_TRUE(PinsSecondChild(split->mode)); } TEST(DockNodeTest, ModeHelpersClassifyAllValues) { - EXPECT_TRUE(IsHorizontalSplit(DockSplitMode::LeftPinned)); - EXPECT_TRUE(IsHorizontalSplit(DockSplitMode::RightPinned)); - EXPECT_FALSE(IsHorizontalSplit(DockSplitMode::TopPinned)); - EXPECT_FALSE(IsHorizontalSplit(DockSplitMode::BottomPinned)); + EXPECT_TRUE(IsHorizontalSplit(docking::DockSplitMode::LeftPinned)); + EXPECT_TRUE(IsHorizontalSplit(docking::DockSplitMode::RightPinned)); + EXPECT_FALSE(IsHorizontalSplit(docking::DockSplitMode::TopPinned)); + EXPECT_FALSE(IsHorizontalSplit(docking::DockSplitMode::BottomPinned)); - EXPECT_FALSE(PinsSecondChild(DockSplitMode::LeftPinned)); - EXPECT_TRUE (PinsSecondChild(DockSplitMode::RightPinned)); - EXPECT_FALSE(PinsSecondChild(DockSplitMode::TopPinned)); - EXPECT_TRUE (PinsSecondChild(DockSplitMode::BottomPinned)); + EXPECT_FALSE(PinsSecondChild(docking::DockSplitMode::LeftPinned)); + EXPECT_TRUE (PinsSecondChild(docking::DockSplitMode::RightPinned)); + EXPECT_FALSE(PinsSecondChild(docking::DockSplitMode::TopPinned)); + EXPECT_TRUE (PinsSecondChild(docking::DockSplitMode::BottomPinned)); } // ---------- ReorderLeafTabs ------------------------------------------------- @@ -106,13 +107,13 @@ namespace tachyon TEST(DockNodeTest, ReorderLeafTabs_MovesTabForward) { ID a = MakePanelID(1), b = MakePanelID(2), c = MakePanelID(3), d = MakePanelID(4); - DockNode leaf; + docking::DockNode leaf; leaf.isLeaf = true; leaf.panelIds = {a, b, c, d}; leaf.selectedTab = 0; // Move 'a' from index 0 to index 2 -> [b, c, a, d] - ReorderLeafTabs(leaf, 0, 2); + docking::ReorderLeafTabs(leaf, 0, 2); ASSERT_EQ(leaf.panelIds.size(), 4u); EXPECT_EQ(leaf.panelIds[0], b); @@ -126,13 +127,13 @@ namespace tachyon TEST(DockNodeTest, ReorderLeafTabs_MovesTabBackward) { ID a = MakePanelID(1), b = MakePanelID(2), c = MakePanelID(3), d = MakePanelID(4); - DockNode leaf; + docking::DockNode leaf; leaf.isLeaf = true; leaf.panelIds = {a, b, c, d}; leaf.selectedTab = 3; // 'd' selected // Move 'd' from index 3 to index 1 -> [a, d, b, c] - ReorderLeafTabs(leaf, 3, 1); + docking::ReorderLeafTabs(leaf, 3, 1); EXPECT_EQ(leaf.panelIds[0], a); EXPECT_EQ(leaf.panelIds[1], d); @@ -144,14 +145,14 @@ namespace tachyon TEST(DockNodeTest, ReorderLeafTabs_SelectionShiftsWhenPassedOver_Forward) { ID a = MakePanelID(1), b = MakePanelID(2), c = MakePanelID(3), d = MakePanelID(4); - DockNode leaf; + docking::DockNode leaf; leaf.isLeaf = true; leaf.panelIds = {a, b, c, d}; leaf.selectedTab = 1; // 'b' selected // Move 'a' (index 0) to index 2 -> [b, c, a, d] // 'b' is now at index 0. from from (0) and sel (1) <= to (2). - ReorderLeafTabs(leaf, 0, 2); + docking::ReorderLeafTabs(leaf, 0, 2); EXPECT_EQ(leaf.panelIds[0], b); EXPECT_EQ(leaf.selectedTab, 0); @@ -160,14 +161,14 @@ namespace tachyon TEST(DockNodeTest, ReorderLeafTabs_SelectionShiftsWhenPassedOver_Backward) { ID a = MakePanelID(1), b = MakePanelID(2), c = MakePanelID(3), d = MakePanelID(4); - DockNode leaf; + docking::DockNode leaf; leaf.isLeaf = true; leaf.panelIds = {a, b, c, d}; leaf.selectedTab = 1; // 'b' selected // Move 'd' (index 3) to index 0 -> [d, a, b, c] // 'b' moves from index 1 to index 2. - ReorderLeafTabs(leaf, 3, 0); + docking::ReorderLeafTabs(leaf, 3, 0); EXPECT_EQ(leaf.panelIds[0], d); EXPECT_EQ(leaf.panelIds[2], b); @@ -177,12 +178,12 @@ namespace tachyon TEST(DockNodeTest, ReorderLeafTabs_NoOpWhenFromEqualsTo) { ID a = MakePanelID(1), b = MakePanelID(2), c = MakePanelID(3); - DockNode leaf; + docking::DockNode leaf; leaf.isLeaf = true; leaf.panelIds = {a, b, c}; leaf.selectedTab = 2; - ReorderLeafTabs(leaf, 1, 1); + docking::ReorderLeafTabs(leaf, 1, 1); EXPECT_EQ(leaf.panelIds[0], a); EXPECT_EQ(leaf.panelIds[1], b); @@ -193,14 +194,14 @@ namespace tachyon TEST(DockNodeTest, ReorderLeafTabs_OutOfRangeIsNoOp) { ID a = MakePanelID(1), b = MakePanelID(2); - DockNode leaf; + docking::DockNode leaf; leaf.isLeaf = true; leaf.panelIds = {a, b}; leaf.selectedTab = 0; - ReorderLeafTabs(leaf, -1, 0); - ReorderLeafTabs(leaf, 0, 5); - ReorderLeafTabs(leaf, 5, 0); + docking::ReorderLeafTabs(leaf, -1, 0); + docking::ReorderLeafTabs(leaf, 0, 5); + docking::ReorderLeafTabs(leaf, 5, 0); EXPECT_EQ(leaf.panelIds[0], a); EXPECT_EQ(leaf.panelIds[1], b); @@ -212,12 +213,12 @@ namespace tachyon TEST(DockNodeTest, CloseLeafTab_RemovesIndexAndShifts) { ID a = MakePanelID(1), b = MakePanelID(2), c = MakePanelID(3); - DockNode leaf; + docking::DockNode leaf; leaf.isLeaf = true; leaf.panelIds = {a, b, c}; leaf.selectedTab = 2; // 'c' selected - bool empty = CloseLeafTab(leaf, 1); + bool empty = docking::CloseLeafTab(leaf, 1); EXPECT_FALSE(empty); ASSERT_EQ(leaf.panelIds.size(), 2u); @@ -230,12 +231,12 @@ namespace tachyon TEST(DockNodeTest, CloseLeafTab_ClampsSelectionWhenLastRemoved) { ID a = MakePanelID(1), b = MakePanelID(2); - DockNode leaf; + docking::DockNode leaf; leaf.isLeaf = true; leaf.panelIds = {a, b}; leaf.selectedTab = 1; - bool empty = CloseLeafTab(leaf, 1); + bool empty = docking::CloseLeafTab(leaf, 1); EXPECT_FALSE(empty); ASSERT_EQ(leaf.panelIds.size(), 1u); @@ -246,12 +247,12 @@ namespace tachyon TEST(DockNodeTest, CloseLeafTab_ReturnsTrueWhenEmpty) { ID a = MakePanelID(1); - DockNode leaf; + docking::DockNode leaf; leaf.isLeaf = true; leaf.panelIds = {a}; leaf.selectedTab = 0; - bool empty = CloseLeafTab(leaf, 0); + bool empty = docking::CloseLeafTab(leaf, 0); EXPECT_TRUE(empty); EXPECT_TRUE(leaf.panelIds.empty()); @@ -261,13 +262,13 @@ namespace tachyon TEST(DockNodeTest, CloseLeafTab_OutOfRangeIsNoOp) { ID a = MakePanelID(1), b = MakePanelID(2); - DockNode leaf; + docking::DockNode leaf; leaf.isLeaf = true; leaf.panelIds = {a, b}; leaf.selectedTab = 0; - CloseLeafTab(leaf, -1); - CloseLeafTab(leaf, 5); + docking::CloseLeafTab(leaf, -1); + docking::CloseLeafTab(leaf, 5); EXPECT_EQ(leaf.panelIds.size(), 2u); EXPECT_EQ(leaf.selectedTab, 0); @@ -278,10 +279,10 @@ namespace tachyon TEST(DockNodeTest, CollapseEmptyLeaves_LeafWithPanelsUntouched) { ID a = MakePanelID(1); - auto root = MakeLeaf({a}); - DockNode* ptrBefore = root.get(); + auto root = docking::MakeLeaf({a}); + docking::DockNode* ptrBefore = root.get(); - CollapseEmptyLeaves(root); + docking::CollapseEmptyLeaves(root); ASSERT_NE(root, nullptr); EXPECT_EQ(root.get(), ptrBefore); // same pointer, in place @@ -293,11 +294,11 @@ namespace tachyon TEST(DockNodeTest, CollapseEmptyLeaves_SplitWithEmptyFirstPromotesSecond) { ID a = MakePanelID(1); - auto root = MakeSplit(DockSplitMode::LeftPinned, 200, - MakeLeaf(), // empty leaf - MakeLeaf({a})); + auto root = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 200, + docking::MakeLeaf(), // empty leaf + docking::MakeLeaf({a})); - CollapseEmptyLeaves(root); + docking::CollapseEmptyLeaves(root); ASSERT_NE(root, nullptr); EXPECT_TRUE(root->isLeaf); @@ -308,11 +309,11 @@ namespace tachyon TEST(DockNodeTest, CollapseEmptyLeaves_SplitWithEmptySecondPromotesFirst) { ID a = MakePanelID(1); - auto root = MakeSplit(DockSplitMode::TopPinned, 150, - MakeLeaf({a}), - MakeLeaf()); // empty leaf + auto root = docking::MakeSplit(docking::DockSplitMode::TopPinned, 150, + docking::MakeLeaf({a}), + docking::MakeLeaf()); // empty leaf - CollapseEmptyLeaves(root); + docking::CollapseEmptyLeaves(root); ASSERT_NE(root, nullptr); EXPECT_TRUE(root->isLeaf); @@ -324,14 +325,14 @@ namespace tachyon { ID a = MakePanelID(1); // split(empty, split(empty, leaf{a})) should collapse to leaf{a} - auto inner = MakeSplit(DockSplitMode::LeftPinned, 100, - MakeLeaf(), - MakeLeaf({a})); - auto root = MakeSplit(DockSplitMode::TopPinned, 100, - MakeLeaf(), + auto inner = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 100, + docking::MakeLeaf(), + docking::MakeLeaf({a})); + auto root = docking::MakeSplit(docking::DockSplitMode::TopPinned, 100, + docking::MakeLeaf(), std::move(inner)); - CollapseEmptyLeaves(root); + docking::CollapseEmptyLeaves(root); ASSERT_NE(root, nullptr); EXPECT_TRUE(root->isLeaf); @@ -341,11 +342,11 @@ namespace tachyon TEST(DockNodeTest, CollapseEmptyLeaves_BothChildrenEmptyBecomesEmptyLeaf) { - auto root = MakeSplit(DockSplitMode::LeftPinned, 100, - MakeLeaf(), - MakeLeaf()); + auto root = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 100, + docking::MakeLeaf(), + docking::MakeLeaf()); - CollapseEmptyLeaves(root); + docking::CollapseEmptyLeaves(root); ASSERT_NE(root, nullptr); // never null EXPECT_TRUE(root->isLeaf); @@ -354,9 +355,9 @@ namespace tachyon TEST(DockNodeTest, CollapseEmptyLeaves_NullRootBecomesEmptyLeaf) { - std::unique_ptr root; // null + std::unique_ptr root; // null - CollapseEmptyLeaves(root); + docking::CollapseEmptyLeaves(root); ASSERT_NE(root, nullptr); EXPECT_TRUE(root->isLeaf); @@ -369,15 +370,15 @@ namespace tachyon { ID a = MakePanelID(1), b = MakePanelID(2); // split(leaf{a}, split(leaf{}, leaf{b})) - auto root = MakeSplit(DockSplitMode::LeftPinned, 200, - MakeLeaf({a}), - MakeSplit(DockSplitMode::TopPinned, 100, - MakeLeaf({b}), - MakeLeaf({MakePanelID(99)}))); + auto root = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 200, + docking::MakeLeaf({a}), + docking::MakeSplit(docking::DockSplitMode::TopPinned, 100, + docking::MakeLeaf({b}), + docking::MakeLeaf({MakePanelID(99)}))); // Now structure is: split(leaf{a}, split(leaf{b}, leaf{x})) where x is panel 99 // Remove panel b -> split(leaf{a}, leaf{x}) - bool removed = RemovePanel(root, b); + bool removed = docking::RemovePanel(root, b); EXPECT_TRUE(removed); ASSERT_NE(root, nullptr); EXPECT_FALSE(root->isLeaf); @@ -393,9 +394,9 @@ namespace tachyon { ID a = MakePanelID(1); ID missing = MakePanelID(999); - auto root = MakeLeaf({a}); + auto root = docking::MakeLeaf({a}); - bool removed = RemovePanel(root, missing); + bool removed = docking::RemovePanel(root, missing); EXPECT_FALSE(removed); ASSERT_NE(root, nullptr); @@ -406,9 +407,9 @@ namespace tachyon TEST(DockNodeTest, RemovePanel_InvalidIDReturnsFalse) { ID a = MakePanelID(1); - auto root = MakeLeaf({a}); + auto root = docking::MakeLeaf({a}); - bool removed = RemovePanel(root, ID::Invalid()); + bool removed = docking::RemovePanel(root, ID::Invalid()); EXPECT_FALSE(removed); } @@ -416,9 +417,9 @@ namespace tachyon TEST(DockNodeTest, RemovePanel_LastPanelInTreeLeavesEmptyLeaf) { ID a = MakePanelID(1); - auto root = MakeLeaf({a}); + auto root = docking::MakeLeaf({a}); - bool removed = RemovePanel(root, a); + bool removed = docking::RemovePanel(root, a); EXPECT_TRUE(removed); ASSERT_NE(root, nullptr); @@ -430,56 +431,56 @@ namespace tachyon TEST(DockNodeTest, FindNode_ReturnsMatchingRoot) { - auto root = MakeLeaf(); + auto root = docking::MakeLeaf(); root->nodeID = MakePanelID(42); - DockNode* hit = FindNode(root.get(), root->nodeID); + docking::DockNode* hit = docking::FindNode(root.get(), root->nodeID); EXPECT_EQ(hit, root.get()); } TEST(DockNodeTest, FindNode_ReturnsNestedNode) { - auto leafA = MakeLeaf(); leafA->nodeID = MakePanelID(1); - auto leafB = MakeLeaf(); leafB->nodeID = MakePanelID(2); + auto leafA = docking::MakeLeaf(); leafA->nodeID = MakePanelID(1); + auto leafB = docking::MakeLeaf(); leafB->nodeID = MakePanelID(2); ID leafBID = leafB->nodeID; - auto root = MakeSplit(DockSplitMode::LeftPinned, 100, + auto root = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 100, std::move(leafA), std::move(leafB)); root->nodeID = MakePanelID(10); - DockNode* hit = FindNode(root.get(), leafBID); + docking::DockNode* hit = docking::FindNode(root.get(), leafBID); ASSERT_NE(hit, nullptr); EXPECT_EQ(hit->nodeID, leafBID); } TEST(DockNodeTest, FindNode_InvalidIDReturnsNull) { - auto root = MakeLeaf(); + auto root = docking::MakeLeaf(); root->nodeID = MakePanelID(1); - EXPECT_EQ(FindNode(root.get(), ID::Invalid()), nullptr); + EXPECT_EQ(docking::FindNode(root.get(), ID::Invalid()), nullptr); } TEST(DockNodeTest, FindNode_MissingIDReturnsNull) { - auto root = MakeLeaf(); + auto root = docking::MakeLeaf(); root->nodeID = MakePanelID(1); - EXPECT_EQ(FindNode(root.get(), MakePanelID(999)), nullptr); + EXPECT_EQ(docking::FindNode(root.get(), MakePanelID(999)), nullptr); } TEST(DockNodeTest, FindNode_NullRootReturnsNull) { - EXPECT_EQ(FindNode(static_cast(nullptr), MakePanelID(1)), nullptr); + EXPECT_EQ(docking::FindNode(static_cast(nullptr), MakePanelID(1)), nullptr); } // ---------- ComputeSplitSizeRange / ClampSplitSize -------------------------- TEST(DockNodeTest, ComputeSplitSizeRange_NormalCase) { - DockNode split; + docking::DockNode split; split.isLeaf = false; split.minFirstSize = 50; split.minSecondSize = 80; - auto range = ComputeSplitSizeRange(split, /*container*/ 400, /*sizer*/ 4); + auto range = docking::ComputeSplitSizeRange(split, /*container*/ 400, /*sizer*/ 4); // min = 50, max = 400 - 4 - 80 = 316 EXPECT_EQ(range.min, 50); @@ -488,12 +489,12 @@ namespace tachyon TEST(DockNodeTest, ComputeSplitSizeRange_DegenerateTooSmall) { - DockNode split; + docking::DockNode split; split.isLeaf = false; split.minFirstSize = 200; split.minSecondSize = 200; - auto range = ComputeSplitSizeRange(split, /*container*/ 100, /*sizer*/ 4); + auto range = docking::ComputeSplitSizeRange(split, /*container*/ 100, /*sizer*/ 4); // container can't fit both mins; range collapses to {minFirst, minFirst} EXPECT_EQ(range.min, 200); @@ -502,47 +503,47 @@ namespace tachyon TEST(DockNodeTest, ClampSplitSize_WithinRange) { - DockNode split; + docking::DockNode split; split.isLeaf = false; split.minFirstSize = 50; split.minSecondSize = 80; split.splitSize = 150; - EXPECT_EQ(ClampSplitSize(split, 400, 4), 150); + EXPECT_EQ(docking::ClampSplitSize(split, 400, 4), 150); } TEST(DockNodeTest, ClampSplitSize_BelowMinClampsUp) { - DockNode split; + docking::DockNode split; split.isLeaf = false; split.minFirstSize = 50; split.minSecondSize = 80; split.splitSize = 10; - EXPECT_EQ(ClampSplitSize(split, 400, 4), 50); + EXPECT_EQ(docking::ClampSplitSize(split, 400, 4), 50); } TEST(DockNodeTest, ClampSplitSize_AboveMaxClampsDown) { - DockNode split; + docking::DockNode split; split.isLeaf = false; split.minFirstSize = 50; split.minSecondSize = 80; split.splitSize = 10000; // max = 400 - 4 - 80 = 316 - EXPECT_EQ(ClampSplitSize(split, 400, 4), 316); + EXPECT_EQ(docking::ClampSplitSize(split, 400, 4), 316); } TEST(DockNodeTest, ComputeSplitSizeRange_SecondPinnedUsesSecondMinAsFloor) { - DockNode split; + docking::DockNode split; split.isLeaf = false; - split.mode = DockSplitMode::RightPinned; + split.mode = docking::DockSplitMode::RightPinned; split.minFirstSize = 50; split.minSecondSize = 80; - auto range = ComputeSplitSizeRange(split, /*container*/ 400, /*sizer*/ 4); + auto range = docking::ComputeSplitSizeRange(split, /*container*/ 400, /*sizer*/ 4); // splitSize is the SECOND child's size: floor = minSecond, ceiling leaves minFirst for the other side. EXPECT_EQ(range.min, 80); @@ -551,14 +552,14 @@ namespace tachyon TEST(DockNodeTest, ClampSplitSize_SecondPinnedAboveMaxClampsDown) { - DockNode split; + docking::DockNode split; split.isLeaf = false; - split.mode = DockSplitMode::BottomPinned; + split.mode = docking::DockSplitMode::BottomPinned; split.minFirstSize = 50; split.minSecondSize = 80; split.splitSize = 10000; - EXPECT_EQ(ClampSplitSize(split, 400, 4), 346); + EXPECT_EQ(docking::ClampSplitSize(split, 400, 4), 346); } // ---------- AssignMissingNodeIDs -------------------------------------------- @@ -579,12 +580,12 @@ namespace tachyon TEST_F(DockNodeIDTest, AssignMissingNodeIDs_FillsInvalidIDs) { - auto root = MakeSplit(DockSplitMode::LeftPinned, 200, - MakeLeaf(), - MakeSplit(DockSplitMode::TopPinned, 100, - MakeLeaf(), MakeLeaf())); + auto root = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 200, + docking::MakeLeaf(), + docking::MakeSplit(docking::DockSplitMode::TopPinned, 100, + docking::MakeLeaf(), docking::MakeLeaf())); - AssignMissingNodeIDs(root.get(), idManager); + docking::AssignMissingNodeIDs(root.get(), idManager); // All nodes should now have valid IDs EXPECT_NE(root->nodeID, ID::Invalid()); @@ -613,28 +614,28 @@ namespace tachyon TEST_F(DockNodeIDTest, AssignMissingNodeIDs_PreservesExistingIDs) { - auto root = MakeLeaf(); + auto root = docking::MakeLeaf(); root->nodeID = MakePanelID(12345); const ID before = root->nodeID; - AssignMissingNodeIDs(root.get(), idManager); + docking::AssignMissingNodeIDs(root.get(), idManager); EXPECT_EQ(root->nodeID, before); } TEST_F(DockNodeIDTest, AssignMissingNodeIDs_IdempotentOnSecondCall) { - auto root = MakeSplit(DockSplitMode::LeftPinned, 100, - MakeLeaf(), MakeLeaf()); + auto root = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 100, + docking::MakeLeaf(), docking::MakeLeaf()); - AssignMissingNodeIDs(root.get(), idManager); + docking::AssignMissingNodeIDs(root.get(), idManager); const ID rootID = root->nodeID; const ID firstID = root->first->nodeID; const ID secondID = root->second->nodeID; const ID firstTabID = root->first->tabBarID; const ID secondTabID = root->second->tabBarID; - AssignMissingNodeIDs(root.get(), idManager); + docking::AssignMissingNodeIDs(root.get(), idManager); EXPECT_EQ(root->nodeID, rootID); EXPECT_EQ(root->first->nodeID, firstID); @@ -646,7 +647,7 @@ namespace tachyon TEST_F(DockNodeIDTest, AssignMissingNodeIDs_NullRootIsNoOp) { // Should not crash. - AssignMissingNodeIDs(nullptr, idManager); + docking::AssignMissingNodeIDs(nullptr, idManager); SUCCEED(); } @@ -657,40 +658,40 @@ namespace tachyon TEST(DockDropZone, OutsideReturnsNone) { IntRect rect { 100, 100, 200, 200 }; - EXPECT_EQ(ComputeDropZone(rect, { 50, 150 }), DockDropZone::None); - EXPECT_EQ(ComputeDropZone(rect, { 350, 150 }), DockDropZone::None); - EXPECT_EQ(ComputeDropZone(rect, { 150, 50 }), DockDropZone::None); - EXPECT_EQ(ComputeDropZone(rect, { 150, 350 }), DockDropZone::None); + EXPECT_EQ(docking::ComputeDropZone(rect, { 50, 150 }), docking::DockDropZone::None); + EXPECT_EQ(docking::ComputeDropZone(rect, { 350, 150 }), docking::DockDropZone::None); + EXPECT_EQ(docking::ComputeDropZone(rect, { 150, 50 }), docking::DockDropZone::None); + EXPECT_EQ(docking::ComputeDropZone(rect, { 150, 350 }), docking::DockDropZone::None); } TEST(DockDropZone, CenterZone) { IntRect rect { 0, 0, 200, 200 }; - EXPECT_EQ(ComputeDropZone(rect, { 100, 100 }), DockDropZone::Center); + EXPECT_EQ(docking::ComputeDropZone(rect, { 100, 100 }), docking::DockDropZone::Center); } TEST(DockDropZone, LeftStrip) { IntRect rect { 0, 0, 200, 200 }; - EXPECT_EQ(ComputeDropZone(rect, { 10, 100 }), DockDropZone::Left); + EXPECT_EQ(docking::ComputeDropZone(rect, { 10, 100 }), docking::DockDropZone::Left); } TEST(DockDropZone, RightStrip) { IntRect rect { 0, 0, 200, 200 }; - EXPECT_EQ(ComputeDropZone(rect, { 190, 100 }), DockDropZone::Right); + EXPECT_EQ(docking::ComputeDropZone(rect, { 190, 100 }), docking::DockDropZone::Right); } TEST(DockDropZone, TopStrip) { IntRect rect { 0, 0, 200, 200 }; - EXPECT_EQ(ComputeDropZone(rect, { 100, 10 }), DockDropZone::Top); + EXPECT_EQ(docking::ComputeDropZone(rect, { 100, 10 }), docking::DockDropZone::Top); } TEST(DockDropZone, BottomStrip) { IntRect rect { 0, 0, 200, 200 }; - EXPECT_EQ(ComputeDropZone(rect, { 100, 190 }), DockDropZone::Bottom); + EXPECT_EQ(docking::ComputeDropZone(rect, { 100, 190 }), docking::DockDropZone::Bottom); } // ============================================================================ @@ -699,26 +700,26 @@ namespace tachyon TEST(DockFindNodeOwner, ReturnsRoot) { - auto root = MakeLeaf({ ID::Invalid() }); - auto* owner = FindNodeOwner(root, root.get()); + auto root = docking::MakeLeaf({ ID::Invalid() }); + auto* owner = docking::FindNodeOwner(root, root.get()); ASSERT_NE(owner, nullptr); EXPECT_EQ(owner->get(), root.get()); } TEST(DockFindNodeOwner, ReturnsChild) { - auto root = MakeSplit(DockSplitMode::LeftPinned, 100, MakeLeaf(), MakeLeaf()); - DockNode* secondChild = root->second.get(); - auto* owner = FindNodeOwner(root, secondChild); + auto root = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 100, docking::MakeLeaf(), docking::MakeLeaf()); + docking::DockNode* secondChild = root->second.get(); + auto* owner = docking::FindNodeOwner(root, secondChild); ASSERT_NE(owner, nullptr); EXPECT_EQ(owner->get(), secondChild); } TEST(DockFindNodeOwner, ReturnsNullForUnknown) { - auto root = MakeLeaf(); - DockNode detached; - EXPECT_EQ(FindNodeOwner(root, &detached), nullptr); + auto root = docking::MakeLeaf(); + docking::DockNode detached; + EXPECT_EQ(docking::FindNodeOwner(root, &detached), nullptr); } // ============================================================================ @@ -727,14 +728,14 @@ namespace tachyon TEST(DockSplitAtZone, LeftCreatesHorizontalSplit) { - auto root = MakeLeaf({ ID::Invalid() }); + auto root = docking::MakeLeaf({ ID::Invalid() }); ID panelID; panelID.value.integer = 42; - DockNode* newLeaf = SplitLeafAtZone(root, panelID, DockDropZone::Left); + docking::DockNode* newLeaf = docking::SplitLeafAtZone(root, panelID, docking::DockDropZone::Left); ASSERT_NE(newLeaf, nullptr); EXPECT_FALSE(root->isLeaf); - EXPECT_EQ(root->mode, DockSplitMode::LeftPinned); + EXPECT_EQ(root->mode, docking::DockSplitMode::LeftPinned); EXPECT_EQ(root->first.get(), newLeaf); EXPECT_EQ(newLeaf->panelIds.size(), 1u); EXPECT_EQ(newLeaf->panelIds[0], panelID); @@ -743,35 +744,35 @@ namespace tachyon TEST(DockSplitAtZone, RightCreatesHorizontalSplit) { - auto root = MakeLeaf({ ID::Invalid() }); + auto root = docking::MakeLeaf({ ID::Invalid() }); ID panelID; panelID.value.integer = 42; - DockNode* newLeaf = SplitLeafAtZone(root, panelID, DockDropZone::Right); + docking::DockNode* newLeaf = docking::SplitLeafAtZone(root, panelID, docking::DockDropZone::Right); - EXPECT_EQ(root->mode, DockSplitMode::RightPinned); + EXPECT_EQ(root->mode, docking::DockSplitMode::RightPinned); EXPECT_EQ(root->second.get(), newLeaf); EXPECT_TRUE(root->first->isLeaf); } TEST(DockSplitAtZone, TopCreatesVerticalSplit) { - auto root = MakeLeaf({ ID::Invalid() }); + auto root = docking::MakeLeaf({ ID::Invalid() }); ID panelID; panelID.value.integer = 42; - DockNode* newLeaf = SplitLeafAtZone(root, panelID, DockDropZone::Top); + docking::DockNode* newLeaf = docking::SplitLeafAtZone(root, panelID, docking::DockDropZone::Top); - EXPECT_EQ(root->mode, DockSplitMode::TopPinned); + EXPECT_EQ(root->mode, docking::DockSplitMode::TopPinned); EXPECT_EQ(root->first.get(), newLeaf); } TEST(DockSplitAtZone, BottomCreatesVerticalSplit) { - auto root = MakeLeaf({ ID::Invalid() }); + auto root = docking::MakeLeaf({ ID::Invalid() }); ID panelID; panelID.value.integer = 42; - DockNode* newLeaf = SplitLeafAtZone(root, panelID, DockDropZone::Bottom); + docking::DockNode* newLeaf = docking::SplitLeafAtZone(root, panelID, docking::DockDropZone::Bottom); - EXPECT_EQ(root->mode, DockSplitMode::BottomPinned); + EXPECT_EQ(root->mode, docking::DockSplitMode::BottomPinned); EXPECT_EQ(root->second.get(), newLeaf); } @@ -783,9 +784,9 @@ namespace tachyon namespace { - // Simulate what Application::TransferPanel does to a DockNode: + // Simulate what Application::TransferPanel does to a docking::DockNode: // remove panelID from the source node's panelIds, fix selectedTab. - void SimulateTransferPanel(ID panelID, DockNode* sourceNode) + void SimulateTransferPanel(ID panelID, docking::DockNode* sourceNode) { auto it = std::find(sourceNode->panelIds.begin(), sourceNode->panelIds.end(), panelID); if (it == sourceNode->panelIds.end()) return; @@ -801,7 +802,7 @@ namespace tachyon } // Count total leaves in a tree. - int CountLeaves(const DockNode* n) + int CountLeaves(const docking::DockNode* n) { if (!n) return 0; if (n->isLeaf) return 1; @@ -809,7 +810,7 @@ namespace tachyon } // Count total panels across all leaves. - int CountTotalPanels(const DockNode* n) + int CountTotalPanels(const docking::DockNode* n) { if (!n) return 0; if (n->isLeaf) return (int)n->panelIds.size(); @@ -817,7 +818,7 @@ namespace tachyon } // Verify no panel ID appears more than once across all leaves. - void CollectPanelIDs(const DockNode* n, std::vector& out) + void CollectPanelIDs(const docking::DockNode* n, std::vector& out) { if (!n) return; if (n->isLeaf) { @@ -828,7 +829,7 @@ namespace tachyon CollectPanelIDs(n->second.get(), out); } - void ExpectNoDuplicatePanels(const DockNode* root) + void ExpectNoDuplicatePanels(const docking::DockNode* root) { std::vector ids; CollectPanelIDs(root, ids); @@ -848,12 +849,12 @@ namespace tachyon ID p3 = MakePanelID(3), p4 = MakePanelID(4), p5 = MakePanelID(5); ID p6 = MakePanelID(6), p7 = MakePanelID(7), p8 = MakePanelID(8); - auto root = MakeSplit(DockSplitMode::LeftPinned, 220, - MakeLeaf({p1, p2}), - MakeLeaf({p3, p4, p5, p6, p7, p8})); + auto root = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 220, + docking::MakeLeaf({p1, p2}), + docking::MakeLeaf({p3, p4, p5, p6, p7, p8})); - DockNode* leftLeaf = root->first.get(); - DockNode* rightLeaf = root->second.get(); + docking::DockNode* leftLeaf = root->first.get(); + docking::DockNode* rightLeaf = root->second.get(); // Drag p3 from rightLeaf, drop on LEFT edge of rightLeaf ID draggedPanel = p3; @@ -865,16 +866,16 @@ namespace tachyon rightLeaf->panelIds.end()) << "p3 should be removed from right leaf"; // Split right leaf at Left zone - auto* ownerPtr = FindNodeOwner(root, rightLeaf); + auto* ownerPtr = docking::FindNodeOwner(root, rightLeaf); ASSERT_NE(ownerPtr, nullptr); EXPECT_EQ(ownerPtr, &root->second) << "Owner should be root->second"; - DockNode* newLeaf = SplitLeafAtZone(*ownerPtr, draggedPanel, DockDropZone::Left); + docking::DockNode* newLeaf = docking::SplitLeafAtZone(*ownerPtr, draggedPanel, docking::DockDropZone::Left); ASSERT_NE(newLeaf, nullptr); // root->second is now a split, NOT the old rightLeaf EXPECT_FALSE(root->second->isLeaf); - EXPECT_EQ(root->second->mode, DockSplitMode::LeftPinned); + EXPECT_EQ(root->second->mode, docking::DockSplitMode::LeftPinned); // The inner split's first child is the new leaf (zone=Left -> newIsFirst) EXPECT_EQ(root->second->first.get(), newLeaf); @@ -896,7 +897,7 @@ namespace tachyon ExpectNoDuplicatePanels(root.get()); // CollapseEmptyLeaves should be a no-op (no empty leaves) - CollapseEmptyLeaves(root); + docking::CollapseEmptyLeaves(root); EXPECT_EQ(CountLeaves(root.get()), 3); EXPECT_EQ(CountTotalPanels(root.get()), 8); } @@ -907,27 +908,27 @@ namespace tachyon ID p1 = MakePanelID(1), p2 = MakePanelID(2); ID p3 = MakePanelID(3), p4 = MakePanelID(4), p5 = MakePanelID(5); - auto root = MakeSplit(DockSplitMode::LeftPinned, 220, - MakeLeaf({p1, p2}), - MakeLeaf({p3, p4, p5})); + auto root = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 220, + docking::MakeLeaf({p1, p2}), + docking::MakeLeaf({p3, p4, p5})); - DockNode* leftLeaf = root->first.get(); - DockNode* rightLeaf = root->second.get(); + docking::DockNode* leftLeaf = root->first.get(); + docking::DockNode* rightLeaf = root->second.get(); // Drag p3 from rightLeaf, drop on RIGHT edge of leftLeaf SimulateTransferPanel(p3, rightLeaf); EXPECT_EQ(rightLeaf->panelIds.size(), 2u); - auto* ownerPtr = FindNodeOwner(root, leftLeaf); + auto* ownerPtr = docking::FindNodeOwner(root, leftLeaf); ASSERT_NE(ownerPtr, nullptr); EXPECT_EQ(ownerPtr, &root->first); - DockNode* newLeaf = SplitLeafAtZone(*ownerPtr, p3, DockDropZone::Right); + docking::DockNode* newLeaf = docking::SplitLeafAtZone(*ownerPtr, p3, docking::DockDropZone::Right); ASSERT_NE(newLeaf, nullptr); // root->first is now a split EXPECT_FALSE(root->first->isLeaf); - EXPECT_EQ(root->first->mode, DockSplitMode::RightPinned); + EXPECT_EQ(root->first->mode, docking::DockSplitMode::RightPinned); // Right zone -> existing is first, new is second EXPECT_EQ(root->first->first.get(), leftLeaf); @@ -950,12 +951,12 @@ namespace tachyon { ID p1 = MakePanelID(1), p2 = MakePanelID(2), p3 = MakePanelID(3); - auto root = MakeSplit(DockSplitMode::LeftPinned, 220, - MakeLeaf({p1}), - MakeLeaf({p2, p3})); + auto root = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 220, + docking::MakeLeaf({p1}), + docking::MakeLeaf({p2, p3})); - DockNode* leftLeaf = root->first.get(); - DockNode* rightLeaf = root->second.get(); + docking::DockNode* leftLeaf = root->first.get(); + docking::DockNode* rightLeaf = root->second.get(); // Drag p1 (the only panel in leftLeaf) to right leaf's tab bar SimulateTransferPanel(p1, leftLeaf); @@ -963,7 +964,7 @@ namespace tachyon rightLeaf->panelIds.push_back(p1); // Collapse should promote rightLeaf as root - CollapseEmptyLeaves(root); + docking::CollapseEmptyLeaves(root); EXPECT_TRUE(root->isLeaf); EXPECT_EQ(root->panelIds.size(), 3u); EXPECT_EQ(CountTotalPanels(root.get()), 3); @@ -974,15 +975,15 @@ namespace tachyon { ID p1 = MakePanelID(1); - auto root = MakeLeaf({p1}); - DockNode* leaf = root.get(); + auto root = docking::MakeLeaf({p1}); + docking::DockNode* leaf = root.get(); SimulateTransferPanel(p1, leaf); EXPECT_TRUE(leaf->panelIds.empty()); - auto* ownerPtr = FindNodeOwner(root, leaf); + auto* ownerPtr = docking::FindNodeOwner(root, leaf); ASSERT_NE(ownerPtr, nullptr); - SplitLeafAtZone(*ownerPtr, p1, DockDropZone::Bottom); + docking::SplitLeafAtZone(*ownerPtr, p1, docking::DockDropZone::Bottom); // Bottom zone: existing is first, new is second -> // first=empty_leaf, second=new_leaf(p1) @@ -991,7 +992,7 @@ namespace tachyon EXPECT_TRUE(root->first->panelIds.empty()); // Collapse: empty first child -> promote second - CollapseEmptyLeaves(root); + docking::CollapseEmptyLeaves(root); EXPECT_TRUE(root->isLeaf); EXPECT_EQ(root->panelIds.size(), 1u); EXPECT_EQ(root->panelIds[0], p1); @@ -1002,24 +1003,24 @@ namespace tachyon { ID p1 = MakePanelID(1), p2 = MakePanelID(2), p3 = MakePanelID(3); - auto root = MakeLeaf({p1, p2, p3}); + auto root = docking::MakeLeaf({p1, p2, p3}); // First split: drop p1 on Left SimulateTransferPanel(p1, root.get()); - SplitLeafAtZone(root, p1, DockDropZone::Left); + docking::SplitLeafAtZone(root, p1, docking::DockDropZone::Left); EXPECT_EQ(CountLeaves(root.get()), 2); EXPECT_EQ(CountTotalPanels(root.get()), 3); // Now root is HSplit(leaf[p1], leaf[p2,p3]) // Second split: drop p2 on Top of the right leaf - DockNode* rightLeaf = root->second.get(); + docking::DockNode* rightLeaf = root->second.get(); ASSERT_TRUE(rightLeaf->isLeaf); ASSERT_EQ(rightLeaf->panelIds.size(), 2u); SimulateTransferPanel(p2, rightLeaf); - auto* ownerPtr = FindNodeOwner(root, rightLeaf); + auto* ownerPtr = docking::FindNodeOwner(root, rightLeaf); ASSERT_NE(ownerPtr, nullptr); - SplitLeafAtZone(*ownerPtr, p2, DockDropZone::Top); + docking::SplitLeafAtZone(*ownerPtr, p2, docking::DockDropZone::Top); // Now: HSplit(leaf[p1], VSplit(leaf[p2], leaf[p3])) EXPECT_EQ(CountLeaves(root.get()), 3); @@ -1027,7 +1028,7 @@ namespace tachyon ExpectNoDuplicatePanels(root.get()); EXPECT_FALSE(root->second->isLeaf); - EXPECT_EQ(root->second->mode, DockSplitMode::TopPinned); + EXPECT_EQ(root->second->mode, docking::DockSplitMode::TopPinned); EXPECT_EQ(root->second->first->panelIds.size(), 1u); EXPECT_EQ(root->second->first->panelIds[0], p2); EXPECT_EQ(root->second->second->panelIds.size(), 1u); @@ -1039,14 +1040,14 @@ namespace tachyon { ID p1 = MakePanelID(1), p2 = MakePanelID(2), p3 = MakePanelID(3); - auto root = MakeSplit(DockSplitMode::LeftPinned, 200, - MakeLeaf({p1}), - MakeSplit(DockSplitMode::TopPinned, 150, - MakeLeaf({p2}), - MakeLeaf({p3}))); + auto root = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 200, + docking::MakeLeaf({p1}), + docking::MakeSplit(docking::DockSplitMode::TopPinned, 150, + docking::MakeLeaf({p2}), + docking::MakeLeaf({p3}))); - DockNode* deepLeaf = root->second->second.get(); - auto* owner = FindNodeOwner(root, deepLeaf); + docking::DockNode* deepLeaf = root->second->second.get(); + auto* owner = docking::FindNodeOwner(root, deepLeaf); ASSERT_NE(owner, nullptr); EXPECT_EQ(owner->get(), deepLeaf); EXPECT_EQ(owner, &root->second->second); @@ -1056,14 +1057,14 @@ namespace tachyon TEST(DockSplitAtZone, PreservesSplitSize) { ID p1 = MakePanelID(1), p2 = MakePanelID(2); - auto root = MakeLeaf({p1}); + auto root = docking::MakeLeaf({p1}); - SplitLeafAtZone(root, p2, DockDropZone::Left, 150); + docking::SplitLeafAtZone(root, p2, docking::DockDropZone::Left, 150); EXPECT_EQ(root->splitSize, 150); // Default splitSize - auto root2 = MakeLeaf({p1}); - SplitLeafAtZone(root2, p2, DockDropZone::Right); + auto root2 = docking::MakeLeaf({p1}); + docking::SplitLeafAtZone(root2, p2, docking::DockDropZone::Right); EXPECT_EQ(root2->splitSize, 200); // default } @@ -1098,16 +1099,16 @@ namespace tachyon return names; } - std::unique_ptr SampleTree(const PanelNames& n) + std::unique_ptr SampleTree(const PanelNames& n) { - return MakeSplit(DockSplitMode::BottomPinned, 260, - MakeSplit(DockSplitMode::LeftPinned, 300, MakeLeaf({n.ids.at("Hierarchy")}), - MakeSplit(DockSplitMode::RightPinned, 360, MakeLeaf({n.ids.at("Viewport")}), MakeLeaf({n.ids.at("Inspector")}))), - MakeSplit(DockSplitMode::LeftPinned, 520, MakeLeaf({n.ids.at("Project")}), - MakeLeaf({n.ids.at("Diagnostics"), n.ids.at("Tasks")})), 240, 140); + return docking::MakeSplit(docking::DockSplitMode::BottomPinned, 260, + docking::MakeSplit(docking::DockSplitMode::LeftPinned, 300, docking::MakeLeaf({n.ids.at("Hierarchy")}), + docking::MakeSplit(docking::DockSplitMode::RightPinned, 360, docking::MakeLeaf({n.ids.at("Viewport")}), docking::MakeLeaf({n.ids.at("Inspector")}))), + docking::MakeSplit(docking::DockSplitMode::LeftPinned, 520, docking::MakeLeaf({n.ids.at("Project")}), + docking::MakeLeaf({n.ids.at("Diagnostics"), n.ids.at("Tasks")})), 240, 140); } - bool SameTree(const DockNode* a, const DockNode* b) + bool SameTree(const docking::DockNode* a, const docking::DockNode* b) { if (a == nullptr || b == nullptr) return a == b; if (a->isLeaf != b->isLeaf) return false; @@ -1123,8 +1124,8 @@ namespace tachyon auto names = Names(); auto tree = SampleTree(names); tree->second->second->selectedTab = 1; - const std::string text = SerializeDockTree(*tree, names.keyOf()); - const auto restored = ParseDockTree(text, names.idOf()); + const std::string text = docking::SerializeDockTree(*tree, names.keyOf()); + const auto restored = docking::ParseDockTree(text, names.idOf()); ASSERT_NE(restored, nullptr); EXPECT_TRUE(SameTree(tree.get(), restored.get())); } @@ -1135,53 +1136,53 @@ namespace tachyon { auto names = Names(); auto tree = SampleTree(names); - const std::string oneRow = SerializeDockTree(*tree, names.keyOf()); + const std::string oneRow = docking::SerializeDockTree(*tree, names.keyOf()); EXPECT_EQ(oneRow.find("rows"), std::string::npos); - const auto fromOneRow = ParseDockTree(oneRow, names.idOf()); + const auto fromOneRow = docking::ParseDockTree(oneRow, names.idOf()); ASSERT_NE(fromOneRow, nullptr); EXPECT_EQ(fromOneRow->second->second->tabLayout, TabBarLayout::OneRow); tree->second->second->tabLayout = TabBarLayout::Rows; - const std::string text = SerializeDockTree(*tree, names.keyOf()); - const auto restored = ParseDockTree(text, names.idOf()); + const std::string text = docking::SerializeDockTree(*tree, names.keyOf()); + const auto restored = docking::ParseDockTree(text, names.idOf()); ASSERT_NE(restored, nullptr); EXPECT_TRUE(SameTree(tree.get(), restored.get())); EXPECT_EQ(restored->second->second->tabLayout, TabBarLayout::Rows); EXPECT_EQ(restored->first->first->tabLayout, TabBarLayout::OneRow); - EXPECT_EQ(ParseDockTree(R"({"tabs":["Hierarchy"],"selected":0,"columns":1})", names.idOf()), nullptr) + EXPECT_EQ(docking::ParseDockTree(R"({"tabs":["Hierarchy"],"selected":0,"columns":1})", names.idOf()), nullptr) << "an unknown key after the selection"; } TEST(DockLayoutIO, DropsPanelsThatNoLongerExistAndCollapses) { auto names = Names(); - const std::string text = SerializeDockTree(*SampleTree(names), names.keyOf()); + const std::string text = docking::SerializeDockTree(*SampleTree(names), names.keyOf()); names.ids.erase("Viewport"); - const auto restored = ParseDockTree(text, names.idOf()); + const auto restored = docking::ParseDockTree(text, names.idOf()); ASSERT_NE(restored, nullptr); std::vector all; for (const auto& [name, id] : names.ids) all.push_back(id); - EXPECT_TRUE(UnplacedPanels(*restored, all).empty()); // every surviving panel is still placed + EXPECT_TRUE(docking::UnplacedPanels(*restored, all).empty()); // every surviving panel is still placed EXPECT_FALSE(restored->first->first->isLeaf == false && restored->first->first->first == nullptr); } TEST(DockLayoutIO, ReportsPanelsAddedSinceTheLayoutWasSaved) { auto names = Names(); - auto small = MakeSplit(DockSplitMode::LeftPinned, 200, MakeLeaf({names.ids.at("Hierarchy")}), MakeLeaf({names.ids.at("Viewport")})); - const std::string text = SerializeDockTree(*small, names.keyOf()); - const auto restored = ParseDockTree(text, names.idOf()); + auto small = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 200, docking::MakeLeaf({names.ids.at("Hierarchy")}), docking::MakeLeaf({names.ids.at("Viewport")})); + const std::string text = docking::SerializeDockTree(*small, names.keyOf()); + const auto restored = docking::ParseDockTree(text, names.idOf()); ASSERT_NE(restored, nullptr); std::vector all; for (const auto& [name, id] : names.ids) all.push_back(id); - EXPECT_EQ(UnplacedPanels(*restored, all).size(), 4u); + EXPECT_EQ(docking::UnplacedPanels(*restored, all).size(), 4u); } TEST(DockLayoutIO, RepeatedKeyIsPlacedOnce) { auto names = Names(); - const auto restored = ParseDockTree(R"({"tabs":["Viewport","Viewport","Tasks"],"selected":2})", names.idOf()); + const auto restored = docking::ParseDockTree(R"({"tabs":["Viewport","Viewport","Tasks"],"selected":2})", names.idOf()); ASSERT_NE(restored, nullptr); ASSERT_TRUE(restored->isLeaf); EXPECT_EQ(restored->panelIds.size(), 2u); @@ -1193,7 +1194,7 @@ namespace tachyon TEST(DockLayoutIO, SelectionFollowsThePanelWhenAnEarlierTabIsMissing) { auto names = Names(); - const auto restored = ParseDockTree(R"({"tabs":["Gone","Viewport","Tasks"],"selected":1})", names.idOf()); + const auto restored = docking::ParseDockTree(R"({"tabs":["Gone","Viewport","Tasks"],"selected":1})", names.idOf()); ASSERT_NE(restored, nullptr); ASSERT_EQ(restored->panelIds.size(), 2u); EXPECT_EQ(restored->panelIds[size_t(restored->selectedTab)], names.ids.at("Viewport")); @@ -1204,11 +1205,11 @@ namespace tachyon TEST(DockLayoutIO, MissingSelectedPanelSelectsItsNeighbour) { auto names = Names(); - auto next = ParseDockTree(R"({"tabs":["Viewport","Gone","Tasks"],"selected":1})", names.idOf()); + auto next = docking::ParseDockTree(R"({"tabs":["Viewport","Gone","Tasks"],"selected":1})", names.idOf()); ASSERT_NE(next, nullptr); EXPECT_EQ(next->panelIds[size_t(next->selectedTab)], names.ids.at("Tasks")); - auto prev = ParseDockTree(R"({"tabs":["Viewport","Tasks","Gone"],"selected":2})", names.idOf()); + auto prev = docking::ParseDockTree(R"({"tabs":["Viewport","Tasks","Gone"],"selected":2})", names.idOf()); ASSERT_NE(prev, nullptr); EXPECT_EQ(prev->panelIds[size_t(prev->selectedTab)], names.ids.at("Tasks")); } @@ -1219,16 +1220,16 @@ namespace tachyon for (const char* bad : {"", "{", "[]", R"({"tabs":["Viewport"]})", R"({"tabs":["Nope"],"selected":0})", R"({"split":"Sideways","size":1,"minFirst":1,"minSecond":1,"first":{"tabs":["Viewport"],"selected":0},"second":{"tabs":["Tasks"],"selected":0}})", R"({"tabs":["Viewport"],"selected":0} trailing)"}) - EXPECT_EQ(ParseDockTree(bad, names.idOf()), nullptr) << bad; + EXPECT_EQ(docking::ParseDockTree(bad, names.idOf()), nullptr) << bad; std::string deep; for (int i = 0; i < 40; ++i) deep += R"({"split":"LeftPinned","size":1,"minFirst":1,"minSecond":1,"first":)"; - EXPECT_EQ(ParseDockTree(deep, names.idOf()), nullptr); + EXPECT_EQ(docking::ParseDockTree(deep, names.idOf()), nullptr); } TEST(DockLayoutIO, MutatedTextNeverCrashes) { auto names = Names(); - const std::string text = SerializeDockTree(*SampleTree(names), names.keyOf()); + const std::string text = docking::SerializeDockTree(*SampleTree(names), names.keyOf()); std::mt19937 rng(5); int accepted = 0; for (int round = 0; round < 3000; ++round) @@ -1241,7 +1242,7 @@ namespace tachyon else if (rng() % 2 == 0) copy.erase(at, 1 + rng() % 6); else copy.insert(at, 1, "{}[]\":,0-"[rng() % 9]); } - if (ParseDockTree(copy, names.idOf())) ++accepted; + if (docking::ParseDockTree(copy, names.idOf())) ++accepted; } EXPECT_LT(accepted, 3000); } @@ -1253,8 +1254,8 @@ namespace tachyon for (const char* bad : { R"({"tabs":["Viewport"],"selected":-})", R"({"split":"LeftPinned","size":-,"minFirst":1,"minSecond":1,"first":{"tabs":["Viewport"],"selected":0},"second":{"tabs":["Tasks"],"selected":0}})" }) { - std::unique_ptr restored; - EXPECT_NO_THROW(restored = ParseDockTree(bad, names.idOf())) << bad; + std::unique_ptr restored; + EXPECT_NO_THROW(restored = docking::ParseDockTree(bad, names.idOf())) << bad; EXPECT_EQ(restored, nullptr) << bad; } } @@ -1263,9 +1264,9 @@ namespace tachyon // ---- Tab drop position ---- // Two wrapped rows of tabs, 24 high with a 4 px gap: [0 1 2] at y 0, [3 4] at y 28. - static tachyon::DockNode WrappedTabs() + static tachyon::docking::DockNode WrappedTabs() { - tachyon::DockNode leaf; + tachyon::docking::DockNode leaf; leaf.cachedTabRects = { { 0, 0, 80, 24 }, { 82, 0, 80, 24 }, { 164, 0, 80, 24 }, { 0, 28, 80, 24 }, { 82, 28, 80, 24 } }; return leaf; @@ -1274,10 +1275,10 @@ namespace tachyon TEST(TabInsertion, OnARowItGoesBetweenTheTabsAroundTheCursor) { const auto leaf = WrappedTabs(); - EXPECT_EQ(tachyon::TabInsertionIndex(leaf, { 10, 10 }), 0); - EXPECT_EQ(tachyon::TabInsertionIndex(leaf, { 100, 10 }), 1); - EXPECT_EQ(tachyon::TabInsertionIndex(leaf, { 230, 10 }), 3); - EXPECT_EQ(tachyon::TabInsertionIndex(leaf, { 100, 40 }), 4); + EXPECT_EQ(tachyon::docking::TabInsertionIndex(leaf, { 10, 10 }), 0); + EXPECT_EQ(tachyon::docking::TabInsertionIndex(leaf, { 100, 10 }), 1); + EXPECT_EQ(tachyon::docking::TabInsertionIndex(leaf, { 230, 10 }), 3); + EXPECT_EQ(tachyon::docking::TabInsertionIndex(leaf, { 100, 40 }), 4); } // The gap between wrapped rows belongs to the nearest row, not to "after the row @@ -1285,8 +1286,8 @@ namespace tachyon TEST(TabInsertion, TheGapBetweenRowsCountsAsTheNearestRow) { const auto leaf = WrappedTabs(); - EXPECT_EQ(tachyon::TabInsertionIndex(leaf, { 10, 25 }), 0) << "just under row 1"; - EXPECT_EQ(tachyon::TabInsertionIndex(leaf, { 10, 27 }), 3) << "just over row 2"; + EXPECT_EQ(tachyon::docking::TabInsertionIndex(leaf, { 10, 25 }), 0) << "just under row 1"; + EXPECT_EQ(tachyon::docking::TabInsertionIndex(leaf, { 10, 27 }), 3) << "just over row 2"; } // Above the first row (the tab bar's top padding) is the first row: dropping over @@ -1294,8 +1295,8 @@ namespace tachyon TEST(TabInsertion, AboveTheFirstRowCountsAsTheFirstRow) { const auto leaf = WrappedTabs(); - EXPECT_EQ(tachyon::TabInsertionIndex(leaf, { 100, -3 }), 1); - EXPECT_EQ(tachyon::TabInsertionIndex(leaf, { 150, -3 }), 2); + EXPECT_EQ(tachyon::docking::TabInsertionIndex(leaf, { 100, -3 }), 1); + EXPECT_EQ(tachyon::docking::TabInsertionIndex(leaf, { 150, -3 }), 2); } // Below the last row is the last row: under a tab it goes next to that tab (not to @@ -1303,20 +1304,20 @@ namespace tachyon TEST(TabInsertion, BelowTheLastRowCountsAsTheLastRow) { const auto leaf = WrappedTabs(); - EXPECT_EQ(tachyon::TabInsertionIndex(leaf, { 10, 60 }), 3); - EXPECT_EQ(tachyon::TabInsertionIndex(leaf, { 100, 60 }), 4); - EXPECT_EQ(tachyon::TabInsertionIndex(leaf, { 300, 60 }), 5); + EXPECT_EQ(tachyon::docking::TabInsertionIndex(leaf, { 10, 60 }), 3); + EXPECT_EQ(tachyon::docking::TabInsertionIndex(leaf, { 100, 60 }), 4); + EXPECT_EQ(tachyon::docking::TabInsertionIndex(leaf, { 300, 60 }), 5); } // Tabs in the overflow list have an empty rect: the drop goes between the tabs in the bar, // and an empty rect at the bar's corner doesn't count as a row above the cursor. TEST(TabInsertion, TabsInTheOverflowListAreSkipped) { - tachyon::DockNode leaf; + tachyon::docking::DockNode leaf; leaf.cachedTabRects = { { 0, 10, 80, 24 }, { 82, 10, 80, 24 }, {}, {}, { 164, 10, 80, 24 } }; - EXPECT_EQ(tachyon::TabInsertionIndex(leaf, { 10, 20 }), 0); - EXPECT_EQ(tachyon::TabInsertionIndex(leaf, { 150, 20 }), 2) << "after tab 1, before the hidden ones"; - EXPECT_EQ(tachyon::TabInsertionIndex(leaf, { 230, 20 }), 5) << "after the last tab in the bar"; - EXPECT_EQ(tachyon::TabInsertionIndex(leaf, { 10, 40 }), 0) << "below the bar is its row, not past an empty rect"; + EXPECT_EQ(tachyon::docking::TabInsertionIndex(leaf, { 10, 20 }), 0); + EXPECT_EQ(tachyon::docking::TabInsertionIndex(leaf, { 150, 20 }), 2) << "after tab 1, before the hidden ones"; + EXPECT_EQ(tachyon::docking::TabInsertionIndex(leaf, { 230, 20 }), 5) << "after the last tab in the bar"; + EXPECT_EQ(tachyon::docking::TabInsertionIndex(leaf, { 10, 40 }), 0) << "below the bar is its row, not past an empty rect"; } } diff --git a/tests/fuzz_test.cpp b/tests/fuzz_test.cpp index d1b83503..9e41b5f4 100644 --- a/tests/fuzz_test.cpp +++ b/tests/fuzz_test.cpp @@ -9,10 +9,11 @@ #include "misuse_reports.h" #include "skribidi_test_fixture.h" -#include +#include #include #include #include +#include #include #include @@ -144,7 +145,7 @@ namespace }; // A tree that parsed must be one the dock code can use. - void ExpectASaneTree(const DockNode* node, int depth = 0) + void ExpectASaneTree(const docking::DockNode* node, int depth = 0) { ASSERT_NE(node, nullptr); ASSERT_LE(depth, 64); @@ -171,13 +172,13 @@ namespace TEST(FuzzTest, DockLayoutParserTakesAnything) { Panels panels; - const auto whole = ParseDockTree(kLayout, panels.idOf()); + const auto whole = docking::ParseDockTree(kLayout, panels.idOf()); ASSERT_NE(whole, nullptr) << "test setup: the sample parses"; ExpectASaneTree(whole.get()); // Every truncation. for (size_t n = 0; n < kLayout.size(); n++) - if (const auto tree = ParseDockTree(std::string_view(kLayout).substr(0, n), panels.idOf())) + if (const auto tree = docking::ParseDockTree(std::string_view(kLayout).substr(0, n), panels.idOf())) ExpectASaneTree(tree.get()); // Every byte replaced by something that matters to JSON. @@ -187,7 +188,7 @@ namespace { std::string text = kLayout; text[at] = c; - if (const auto tree = ParseDockTree(text, panels.idOf())) + if (const auto tree = docking::ParseDockTree(text, panels.idOf())) ExpectASaneTree(tree.get()); } } @@ -212,7 +213,7 @@ namespace "", }; for (const std::string& text : cases) - if (const auto tree = ParseDockTree(text, panels.idOf())) + if (const auto tree = docking::ParseDockTree(text, panels.idOf())) ExpectASaneTree(tree.get()); } diff --git a/tests/headless_gui_app.cpp b/tests/headless_gui_app.cpp index 98cc8925..bd99625a 100644 --- a/tests/headless_gui_app.cpp +++ b/tests/headless_gui_app.cpp @@ -84,7 +84,6 @@ tachyon::Result HeadlessGUIApp::Initialize(const InitializeOptions& option m_labelGroup = std::make_unique(m_frame, elementStorage, guiStateManager, theme); m_buttonGroup = std::make_unique(m_frame, elementStorage, styleManager); m_reorderable = std::make_unique(m_frame); - m_dockTabDragSub = std::make_unique(); m_uiCache = std::make_unique(m_frame, elementStorage, guiStateManager); RegisterFrameBalanceChecks(); @@ -148,7 +147,7 @@ void HeadlessGUIApp::Frame(std::function onGuiFn) .elapsedTimeSecs = static_cast(m_timeMs) / 1000.0f, }; - m_frame.RunStage(tachyon::FrameStage::PreFrame, ctx); + RunStage(tachyon::FrameStage::PreFrame, ctx); TickFrameClock(*this, int64_t(m_timeMs) * 1000000); // AdvanceTime moves it ApplyPendingStyleReload(); @@ -159,7 +158,7 @@ void HeadlessGUIApp::Frame(std::function onGuiFn) [[maybe_unused]] bool wm = windowManager->BeginFrame(); guiStateManager.BeginFrame(); guiStateManager.Interaction().SetFrameTime(static_cast(m_timeMs) / 1000.0f); - BeginDockingFrame(); + m_toolbarDocksThisFrame.clear(); // the docks built this frame register again tabChainManager.BeginFrame(guiStateManager); menuManager.BeginFrame(guiStateManager, *windowManager); // Hover delays only fire when a test injects a MouseMove + AdvanceTime. @@ -187,12 +186,12 @@ void HeadlessGUIApp::Frame(std::function onGuiFn) windowRegistry.Clear(); guiStateManager.Cursor().Clear(); - m_frame.RunStage(tachyon::FrameStage::PreConstruct, ctx); + RunStage(tachyon::FrameStage::PreConstruct, ctx); // -- User construction. if (onGuiFn) onGuiFn(); - m_frame.RunStage(tachyon::FrameStage::PostConstruct, ctx); + RunStage(tachyon::FrameStage::PostConstruct, ctx); ShowCutShortText(); // as OnFrame: after OnGUI, while the tree is open // As OnFrame: a drag's visual (a ghost window following the cursor) is declared now. @@ -214,7 +213,7 @@ void HeadlessGUIApp::Frame(std::function onGuiFn) textSystem->Update(); - m_frame.RunStage(tachyon::FrameStage::PreLayout, ctx); + RunStage(tachyon::FrameStage::PreLayout, ctx); // -- Layout. SyncWindowsBeforeLayout is skipped (no live OS windows). layoutEngine->Layout(*windowManager, elementStorage); @@ -230,11 +229,11 @@ void HeadlessGUIApp::Frame(std::function onGuiFn) er->rect, er->innerRect, er->contentTransform }; entry.callback(plCtx); } - m_frame.RunStage(tachyon::FrameStage::PostLayout, ctx); + RunStage(tachyon::FrameStage::PostLayout, ctx); windowRegistry.BuildRenderSkipLinks(); - m_frame.RunStage(tachyon::FrameStage::PreInput, ctx); + RunStage(tachyon::FrameStage::PreInput, ctx); // -- EndFrame hit-tests the one root window and commits the hover/active // targets for Process(), which runs after it. @@ -264,17 +263,17 @@ void HeadlessGUIApp::Frame(std::function onGuiFn) RunPressOutsideWatches(); InvalidateCachedScopesForInput(overID); - // -- Dispatch the queued input events to element handlers, and report the panels acted in. + // -- Dispatch the queued input events to element handlers (and the OnInputDispatched hooks). DispatchInput(overID); DispatchFileDrops(frameInput); - m_frame.RunStage(tachyon::FrameStage::PostInput, ctx); + RunStage(tachyon::FrameStage::PostInput, ctx); - EndDockingFrame(); + SyncToolbarDockRects(); // No render pass, but fire PreRender/PostRender for subsystems that hook them. - m_frame.RunStage(tachyon::FrameStage::PreRender, ctx); - m_frame.RunStage(tachyon::FrameStage::PostRender, ctx); + RunStage(tachyon::FrameStage::PreRender, ctx); + RunStage(tachyon::FrameStage::PostRender, ctx); transitionManager.Purge(static_cast(m_timeMs) / 1000.0f); guiStateManager.GetScrollManagement().EndFrame(idManager); @@ -283,7 +282,7 @@ void HeadlessGUIApp::Frame(std::function onGuiFn) menuManager.EndFrame(elementStorage, guiStateManager); [[maybe_unused]] bool wmEnd = windowManager->EndFrame(); - m_frame.RunStage(tachyon::FrameStage::EndFrame, ctx); + RunStage(tachyon::FrameStage::EndFrame, ctx); idManager.EndFrame(); } diff --git a/tests/label_group_alignment_test.cpp b/tests/label_group_alignment_test.cpp index 853412ce..99a56c5e 100644 --- a/tests/label_group_alignment_test.cpp +++ b/tests/label_group_alignment_test.cpp @@ -3,6 +3,7 @@ // start at the same x. #include +#include #include "headless_gui_app.h" @@ -16,7 +17,9 @@ namespace TEST(LabelGroupAlignment, LabelAndDragLabelRowsLineUp) { HeadlessGUIApp app; + docking::Context dockingContext; ASSERT_TRUE(app.Initialize()); + docking::Install(app, dockingContext); const ID labelID = app.idManager.CreateStaticID(), textID = app.idManager.CreateStaticID(); const ID dragID = app.idManager.CreateStaticID(), floatID = app.idManager.CreateStaticID(); std::string text = "Editable"; @@ -24,7 +27,7 @@ namespace app.Frame([&] { app.BeginRootWindow({ 800, 600 }); - if (app.BeginArea(app.theme.dockContentStyleRef, LayoutOverride{}.FlexGrow(1))) + if (app.BeginArea(docking::GetStyles(app, dockingContext).dockContentStyleRef, LayoutOverride{}.FlexGrow(1))) { app.BeginLabelGroup(120, 40, 300); app.Label(labelID, "Text Box", app.theme.labelStyleRef); diff --git a/tests/layout_presets_test.cpp b/tests/layout_presets_test.cpp index 338dd871..157b188d 100644 --- a/tests/layout_presets_test.cpp +++ b/tests/layout_presets_test.cpp @@ -5,8 +5,9 @@ #include "headless_gui_app.h" -#include -#include +#include +#include +#include #include #include @@ -16,10 +17,10 @@ namespace using namespace tachyon; using GUITest::HeadlessGUIApp; - std::vector NamesOf(const LayoutPresets& presets) + std::vector NamesOf(const docking::LayoutPresets& presets) { std::vector names; - for (const LayoutPreset& preset : presets.All()) + for (const docking::LayoutPreset& preset : presets.All()) names.push_back(preset.name); return names; } @@ -28,7 +29,7 @@ namespace TEST(LayoutPresetsTest, BuiltInOnesComeFirstAndStay) { - LayoutPresets presets; + docking::LayoutPresets presets; presets.AddBuiltIn("Scene", "a"); EXPECT_TRUE(presets.Save("Mine", "m")); presets.AddBuiltIn("Graph", "b"); @@ -48,7 +49,7 @@ namespace TEST(LayoutPresetsTest, SavingANameAgainReplacesIt) { - LayoutPresets presets; + docking::LayoutPresets presets; EXPECT_FALSE(presets.Save("", "t")) << "it needs a name"; EXPECT_TRUE(presets.All().empty()); EXPECT_TRUE(presets.Save("Mine", "one")); @@ -69,7 +70,7 @@ namespace TEST(LayoutPresetsTest, AFileTypeOpensWithItsLayout) { - LayoutPresets presets; + docking::LayoutPresets presets; presets.AddBuiltIn("Graph", "g"); EXPECT_TRUE(presets.Save("Mine", "m")); presets.SetForFileType(".MAT", "Graph"); @@ -96,14 +97,14 @@ namespace TEST(LayoutPresetsTest, JsonKeepsTheSavedOnesAndTheFileTypes) { - LayoutPresets presets; + docking::LayoutPresets presets; presets.AddBuiltIn("Graph", "g"); EXPECT_TRUE(presets.Save("Mine", "{\"tabs\":[\"A\"],\"selected\":0}")); presets.SetForFileType(".mat", "Mine"); const std::string json = presets.ToJson(); EXPECT_EQ(json.find("Graph"), std::string::npos) << "built-in ones aren't in it"; - LayoutPresets again; + docking::LayoutPresets again; again.AddBuiltIn("Graph", "g2"); EXPECT_TRUE(again.Save("Stale", "s")); again.SetForFileType(".level", "Stale"); @@ -131,21 +132,22 @@ namespace { protected: HeadlessGUIApp app; + docking::Context dockingContext; void SetUp() override { ASSERT_TRUE(app.Initialize()); } void TearDown() override { app.Cleanup(); } - ID AddPanel(DockingLayout& layout, const char* title) + ID AddPanel(docking::DockingLayout& layout, const char* title) { - return app.CreatePanel(layout.panels, title, IconID::Invalid, [] {}); + return docking::CreatePanel(app, dockingContext, layout.panels, title, IconID::Invalid, [] {}); } // A panel of that title in the layout; Invalid when there's none. - static ID PanelNamed(const DockingLayout& layout, std::string_view title) + static ID PanelNamed(const docking::DockingLayout& layout, std::string_view title) { for (const auto& [id, panel] : layout.panels) if (panel.title == title) return id; return ID::Invalid(); } - static std::vector Titles(const DockingLayout& layout, const DockNode* leaf) + static std::vector Titles(const docking::DockingLayout& layout, const docking::DockNode* leaf) { std::vector titles; for (const ID id : leaf->panelIds) @@ -158,18 +160,18 @@ namespace // their place in it, the ones it hasn't are made, and the rest are closed. TEST_F(ApplyDockLayoutTest, ThePanelsAreLaidOutAsTheTreeSays) { - DockingLayout saved; + docking::DockingLayout saved; const ID scene = AddPanel(saved, "Scene"), details = AddPanel(saved, "Details"), log = AddPanel(saved, "Log"); - saved.root = MakeSplit(DockSplitMode::LeftPinned, 250, MakeLeaf({ scene }), MakeLeaf({ details, log })); + saved.root = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 250, docking::MakeLeaf({ scene }), docking::MakeLeaf({ details, log })); saved.root->second->selectedTab = 1; - const std::string tree = app.SaveDockLayout(saved); + const std::string tree = docking::SaveDockLayout(saved); ASSERT_FALSE(tree.empty()); - DockingLayout layout; + docking::DockingLayout layout; const ID ownLog = AddPanel(layout, "Log"), help = AddPanel(layout, "Help"); - layout.root = MakeLeaf({ ownLog, help }); + layout.root = docking::MakeLeaf({ ownLog, help }); std::vector made; - ASSERT_TRUE(app.ApplyDockLayout(layout, tree, [&](std::string_view key) -> std::optional { + ASSERT_TRUE(docking::ApplyDockLayout(app, dockingContext, layout, tree, [&](std::string_view key) -> std::optional { made.emplace_back(key); return AddPanel(layout, std::string(key).c_str()); })); @@ -184,23 +186,23 @@ namespace EXPECT_EQ(PanelNamed(layout, "Help"), ID::Invalid()) << "closed"; EXPECT_FALSE(app.idManager.IsStaticIDValid(help)) << "and its ID given back"; EXPECT_EQ(layout.panels.size(), 3u); - EXPECT_EQ(app.SaveDockLayout(layout), tree) << "laid out as saved"; + EXPECT_EQ(docking::SaveDockLayout(layout), tree) << "laid out as saved"; } // A tree with two panels of one kind: the layout's own goes in the first place, and a // second is made for the other. TEST_F(ApplyDockLayoutTest, TwoPanelsOfOneKindBothComeBack) { - DockingLayout saved; + docking::DockingLayout saved; const ID left = AddPanel(saved, "Timeline"), right = AddPanel(saved, "Timeline"); - saved.root = MakeSplit(DockSplitMode::LeftPinned, 400, MakeLeaf({ left }), MakeLeaf({ right })); - const std::string tree = app.SaveDockLayout(saved); + saved.root = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 400, docking::MakeLeaf({ left }), docking::MakeLeaf({ right })); + const std::string tree = docking::SaveDockLayout(saved); - DockingLayout layout; + docking::DockingLayout layout; const ID own = AddPanel(layout, "Timeline"); - layout.root = MakeLeaf({ own }); + layout.root = docking::MakeLeaf({ own }); int made = 0; - ASSERT_TRUE(app.ApplyDockLayout(layout, tree, [&](std::string_view key) -> std::optional { + ASSERT_TRUE(docking::ApplyDockLayout(app, dockingContext, layout, tree, [&](std::string_view key) -> std::optional { ++made; return AddPanel(layout, std::string(key).c_str()); })); @@ -211,25 +213,25 @@ namespace EXPECT_EQ(layout.root->first->panelIds[0], own); EXPECT_NE(layout.root->second->panelIds[0], own) << "a panel of its own"; EXPECT_EQ(layout.panels.size(), 2u); - EXPECT_EQ(app.SaveDockLayout(layout), tree) << "laid out as saved"; + EXPECT_EQ(docking::SaveDockLayout(layout), tree) << "laid out as saved"; } // Without a way to make them, the panels it lacks are left out, and the tree closes up. TEST_F(ApplyDockLayoutTest, PanelsItCantMakeAreLeftOut) { - DockingLayout layout; + docking::DockingLayout layout; const ID details = AddPanel(layout, "Details"); - layout.root = MakeLeaf({ details }); + layout.root = docking::MakeLeaf({ details }); const std::string tree = R"({"split":"LeftPinned","size":250,"minFirst":80,"minSecond":80,)" R"("first":{"tabs":["Scene"],"selected":0},"second":{"tabs":["Details"],"selected":0}})"; - ASSERT_TRUE(app.ApplyDockLayout(layout, tree)); + ASSERT_TRUE(docking::ApplyDockLayout(app, dockingContext, layout, tree)); ASSERT_TRUE(layout.root->isLeaf); EXPECT_EQ(layout.root->panelIds, (std::vector{ details })); // nullopt from makePanel, or an ID it made no panel for: left out too. - ASSERT_TRUE(app.ApplyDockLayout(layout, tree, [](std::string_view) -> std::optional { return std::nullopt; })); + ASSERT_TRUE(docking::ApplyDockLayout(app, dockingContext, layout, tree, [](std::string_view) -> std::optional { return std::nullopt; })); EXPECT_EQ(layout.root->panelIds, (std::vector{ details })); - ASSERT_TRUE(app.ApplyDockLayout(layout, tree, [this](std::string_view) -> std::optional { return app.idManager.CreateStaticID(); })); + ASSERT_TRUE(docking::ApplyDockLayout(app, dockingContext, layout, tree, [this](std::string_view) -> std::optional { return app.idManager.CreateStaticID(); })); ASSERT_TRUE(layout.root->isLeaf); EXPECT_EQ(layout.root->panelIds, (std::vector{ details })); EXPECT_EQ(layout.panels.size(), 1u); @@ -238,19 +240,19 @@ namespace // A tree that can't be read, or leaves no panel, changes nothing; panels made for it go. TEST_F(ApplyDockLayoutTest, ATreeThatCantBeUsedLeavesTheLayout) { - DockingLayout layout; + docking::DockingLayout layout; const ID details = AddPanel(layout, "Details"); - layout.root = MakeLeaf({ details }); - const DockNode* before = layout.root.get(); + layout.root = docking::MakeLeaf({ details }); + const docking::DockNode* before = layout.root.get(); int made = 0; auto makePanel = [&](std::string_view key) -> std::optional { ++made; return AddPanel(layout, std::string(key).c_str()); }; - EXPECT_FALSE(app.ApplyDockLayout(layout, "not a tree", makePanel)); - EXPECT_FALSE(app.ApplyDockLayout(layout, "", makePanel)); + EXPECT_FALSE(docking::ApplyDockLayout(app, dockingContext, layout, "not a tree", makePanel)); + EXPECT_FALSE(docking::ApplyDockLayout(app, dockingContext, layout, "", makePanel)); // Read as far as its first tab group, which made a panel, then cut off. - EXPECT_FALSE(app.ApplyDockLayout(layout, R"({"split":"LeftPinned","size":100,"minFirst":80,"minSecond":80,"first":{"tabs":["New"],"selected":0},"second":)", makePanel)); + EXPECT_FALSE(docking::ApplyDockLayout(app, dockingContext, layout, R"({"split":"LeftPinned","size":100,"minFirst":80,"minSecond":80,"first":{"tabs":["New"],"selected":0},"second":)", makePanel)); EXPECT_EQ(made, 1) << "test setup: a panel was made before it failed"; - EXPECT_FALSE(app.ApplyDockLayout(layout, R"({"tabs":["Gone"],"selected":0})", [](std::string_view) -> std::optional { return std::nullopt; })) + EXPECT_FALSE(docking::ApplyDockLayout(app, dockingContext, layout, R"({"tabs":["Gone"],"selected":0})", [](std::string_view) -> std::optional { return std::nullopt; })) << "no panel left"; EXPECT_EQ(layout.root.get(), before); @@ -261,16 +263,16 @@ namespace // Saved UI state: the saved layouts and the file types' layouts. TEST_F(ApplyDockLayoutTest, SavedPresetsAndFileTypesComeBack) { - LayoutPresets presets; + docking::LayoutPresets presets; presets.AddBuiltIn("Graph", "g"); ASSERT_TRUE(presets.Save("Mine", R"({"tabs":["Scene"],"selected":0})")); presets.SetForFileType(".level", "Mine"); - app.PersistLayoutPresets("layouts", presets); + docking::PersistLayoutPresets(app, "layouts", presets); const std::string saved = app.SaveUIState(); - LayoutPresets fresh; // a new run: the app's own again + docking::LayoutPresets fresh; // a new run: the app's own again fresh.AddBuiltIn("Graph", "g"); - app.PersistLayoutPresets("layouts", fresh); + docking::PersistLayoutPresets(app, "layouts", fresh); ASSERT_TRUE(app.RestoreUIState(saved)); EXPECT_EQ(NamesOf(fresh), (std::vector{ "Graph", "Mine" })); EXPECT_EQ(fresh.Find("Mine")->tree, presets.Find("Mine")->tree); diff --git a/tests/misuse_test.cpp b/tests/misuse_test.cpp index 0e2d18e4..a3a1c3cd 100644 --- a/tests/misuse_test.cpp +++ b/tests/misuse_test.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include @@ -26,10 +27,17 @@ namespace using GUITest::HeadlessGUIApp; using GUITest::MisuseReports; + // The libraries' contexts a case may use, the app's to own. + struct Contexts + { + views::Context views; + docking::Context docking; + }; + struct MisuseCase { const char* name; - std::function misuse; // runs inside a frame's root window + std::function misuse; // runs inside a frame's root window }; std::string CaseName(const ::testing::TestParamInfo& info) { return info.param.name; } @@ -52,17 +60,19 @@ namespace void RunMisuse(const MisuseCase& c) { HeadlessGUIApp app; - views::Context viewsContext; + Contexts contexts; ASSERT_TRUE(app.Initialize()); + docking::Install(app, contexts.docking); MisuseReports reports; app.Frame([&] { app.BeginRootWindow(); - c.misuse(app, viewsContext); + c.misuse(app, contexts); app.EndRootWindow(); - views::EndGUI(app, viewsContext); + views::EndGUI(app, contexts.views); }); EXPECT_GE(reports.Count(), 1u) << c.name << " wasn't reported"; ExpectTheNextFrameWorks(app); + docking::Cleanup(app, contexts.docking); app.Cleanup(); } @@ -73,37 +83,37 @@ namespace TEST_P(EndWithoutBeginTest, IsReportedAndIgnored) { RunMisuse(GetParam()); } INSTANTIATE_TEST_SUITE_P(Misuse, EndWithoutBeginTest, ::testing::Values( - MisuseCase{ "EndArea", [](HeadlessGUIApp& a, views::Context&) { a.EndArea(); } }, - MisuseCase{ "EndHorizontal", [](HeadlessGUIApp& a, views::Context&) { a.EndHorizontal(); } }, - MisuseCase{ "EndHorizontalWrap", [](HeadlessGUIApp& a, views::Context&) { a.EndHorizontalWrap(); } }, - MisuseCase{ "EndVertical", [](HeadlessGUIApp& a, views::Context&) { a.EndVertical(); } }, - MisuseCase{ "EndVerticalWrap", [](HeadlessGUIApp& a, views::Context&) { a.EndVerticalWrap(); } }, - MisuseCase{ "EndCached", [](HeadlessGUIApp& a, views::Context&) { a.EndCached(); } }, - MisuseCase{ "EndMenu", [](HeadlessGUIApp& a, views::Context&) { a.EndMenu(); } }, - MisuseCase{ "EndMenuBar", [](HeadlessGUIApp& a, views::Context&) { a.EndMenuBar(); } }, - MisuseCase{ "EndTitleBar", [](HeadlessGUIApp& a, views::Context&) { a.EndTitleBar(); } }, - MisuseCase{ "EndTooltip", [](HeadlessGUIApp& a, views::Context&) { a.EndTooltip(); } }, - MisuseCase{ "EndContextMenu", [](HeadlessGUIApp& a, views::Context&) { a.EndContextMenu(); } }, - MisuseCase{ "EndLabelGroup", [](HeadlessGUIApp& a, views::Context&) { a.EndLabelGroup(); } }, - MisuseCase{ "EndButtonGroup", [](HeadlessGUIApp& a, views::Context&) { a.EndButtonGroup(); } }, - MisuseCase{ "EndToggleGroup", [](HeadlessGUIApp& a, views::Context&) { a.EndToggleGroup(); } }, - MisuseCase{ "EndToolbar", [](HeadlessGUIApp& a, views::Context&) { a.EndToolbar(); } }, - MisuseCase{ "EndReorderableGroup", [](HeadlessGUIApp& a, views::Context&) { a.EndReorderableGroup(); } }, - MisuseCase{ "EndReorderableItem", [](HeadlessGUIApp& a, views::Context&) { a.EndReorderableItem(); } }, - MisuseCase{ "EndListView", [](HeadlessGUIApp& a, views::Context& viewsContext) { views::EndListView(a, viewsContext); } }, - MisuseCase{ "EndGridView", [](HeadlessGUIApp& a, views::Context& viewsContext) { views::EndGridView(a, viewsContext); } }, - MisuseCase{ "EndTable", [](HeadlessGUIApp& a, views::Context& viewsContext) { views::EndTable(a, viewsContext); } }, - MisuseCase{ "EndRow", [](HeadlessGUIApp& a, views::Context& viewsContext) { views::EndRow(a, viewsContext); } }, - MisuseCase{ "EndTabBar", [](HeadlessGUIApp& a, views::Context&) { a.EndTabBar(); } }, - MisuseCase{ "EndStatusBar", [](HeadlessGUIApp& a, views::Context&) { a.EndStatusBar(); } }, - MisuseCase{ "EndDockingContainer", [](HeadlessGUIApp& a, views::Context&) { a.EndDockingContainer(); } }, - MisuseCase{ "EndWindow", [](HeadlessGUIApp& a, views::Context&) { a.EndWindow(); } }, - MisuseCase{ "EndGhostWindow", [](HeadlessGUIApp& a, views::Context&) { a.EndGhostWindow(); } }, - MisuseCase{ "EndDisabled", [](HeadlessGUIApp& a, views::Context&) { a.EndDisabled(); } }, - MisuseCase{ "EndInvalid", [](HeadlessGUIApp& a, views::Context&) { a.EndInvalid(); } }, - MisuseCase{ "EndSelected", [](HeadlessGUIApp& a, views::Context&) { a.EndSelected(); } }, - MisuseCase{ "EndIndeterminate", [](HeadlessGUIApp& a, views::Context&) { a.EndIndeterminate(); } }, - MisuseCase{ "PopParent", [](HeadlessGUIApp& a, views::Context&) { (void)a.idManager.PopParent(); } } + MisuseCase{ "EndArea", [](HeadlessGUIApp& a, Contexts&) { a.EndArea(); } }, + MisuseCase{ "EndHorizontal", [](HeadlessGUIApp& a, Contexts&) { a.EndHorizontal(); } }, + MisuseCase{ "EndHorizontalWrap", [](HeadlessGUIApp& a, Contexts&) { a.EndHorizontalWrap(); } }, + MisuseCase{ "EndVertical", [](HeadlessGUIApp& a, Contexts&) { a.EndVertical(); } }, + MisuseCase{ "EndVerticalWrap", [](HeadlessGUIApp& a, Contexts&) { a.EndVerticalWrap(); } }, + MisuseCase{ "EndCached", [](HeadlessGUIApp& a, Contexts&) { a.EndCached(); } }, + MisuseCase{ "EndMenu", [](HeadlessGUIApp& a, Contexts&) { a.EndMenu(); } }, + MisuseCase{ "EndMenuBar", [](HeadlessGUIApp& a, Contexts&) { a.EndMenuBar(); } }, + MisuseCase{ "EndTitleBar", [](HeadlessGUIApp& a, Contexts&) { a.EndTitleBar(); } }, + MisuseCase{ "EndTooltip", [](HeadlessGUIApp& a, Contexts&) { a.EndTooltip(); } }, + MisuseCase{ "EndContextMenu", [](HeadlessGUIApp& a, Contexts&) { a.EndContextMenu(); } }, + MisuseCase{ "EndLabelGroup", [](HeadlessGUIApp& a, Contexts&) { a.EndLabelGroup(); } }, + MisuseCase{ "EndButtonGroup", [](HeadlessGUIApp& a, Contexts&) { a.EndButtonGroup(); } }, + MisuseCase{ "EndToggleGroup", [](HeadlessGUIApp& a, Contexts&) { a.EndToggleGroup(); } }, + MisuseCase{ "EndToolbar", [](HeadlessGUIApp& a, Contexts&) { a.EndToolbar(); } }, + MisuseCase{ "EndReorderableGroup", [](HeadlessGUIApp& a, Contexts&) { a.EndReorderableGroup(); } }, + MisuseCase{ "EndReorderableItem", [](HeadlessGUIApp& a, Contexts&) { a.EndReorderableItem(); } }, + MisuseCase{ "EndListView", [](HeadlessGUIApp& a, Contexts& contexts) { views::EndListView(a, contexts.views); } }, + MisuseCase{ "EndGridView", [](HeadlessGUIApp& a, Contexts& contexts) { views::EndGridView(a, contexts.views); } }, + MisuseCase{ "EndTable", [](HeadlessGUIApp& a, Contexts& contexts) { views::EndTable(a, contexts.views); } }, + MisuseCase{ "EndRow", [](HeadlessGUIApp& a, Contexts& contexts) { views::EndRow(a, contexts.views); } }, + MisuseCase{ "EndTabBar", [](HeadlessGUIApp& a, Contexts&) { a.EndTabBar(); } }, + MisuseCase{ "EndStatusBar", [](HeadlessGUIApp& a, Contexts&) { a.EndStatusBar(); } }, + MisuseCase{ "EndDockingContainer", [](HeadlessGUIApp& a, Contexts& contexts) { docking::EndDockingContainer(a, contexts.docking); } }, + MisuseCase{ "EndWindow", [](HeadlessGUIApp& a, Contexts&) { a.EndWindow(); } }, + MisuseCase{ "EndGhostWindow", [](HeadlessGUIApp& a, Contexts&) { a.EndGhostWindow(); } }, + MisuseCase{ "EndDisabled", [](HeadlessGUIApp& a, Contexts&) { a.EndDisabled(); } }, + MisuseCase{ "EndInvalid", [](HeadlessGUIApp& a, Contexts&) { a.EndInvalid(); } }, + MisuseCase{ "EndSelected", [](HeadlessGUIApp& a, Contexts&) { a.EndSelected(); } }, + MisuseCase{ "EndIndeterminate", [](HeadlessGUIApp& a, Contexts&) { a.EndIndeterminate(); } }, + MisuseCase{ "PopParent", [](HeadlessGUIApp& a, Contexts&) { (void)a.idManager.PopParent(); } } ), CaseName); // ---- A Begin left open at the end of the frame ---- @@ -115,33 +125,33 @@ namespace int g_selected = 0; views::TableState g_tableState; views::VirtualTableColumn g_columns[1]; - DockingLayout g_dockingLayout; + docking::DockingLayout g_dockingLayout; INSTANTIATE_TEST_SUITE_P(Misuse, BeginLeftOpenTest, ::testing::Values( - MisuseCase{ "BeginArea", [](HeadlessGUIApp& a, views::Context&) { a.BeginArea(a.idManager.CreateStaticID()); } }, - MisuseCase{ "BeginHorizontal", [](HeadlessGUIApp& a, views::Context&) { a.BeginHorizontal(a.idManager.CreateStaticID()); } }, - MisuseCase{ "BeginHorizontalWrap", [](HeadlessGUIApp& a, views::Context&) { a.BeginHorizontalWrap(a.idManager.CreateStaticID()); } }, - MisuseCase{ "BeginVertical", [](HeadlessGUIApp& a, views::Context&) { a.BeginVertical(a.idManager.CreateStaticID()); } }, - MisuseCase{ "BeginVerticalWrap", [](HeadlessGUIApp& a, views::Context&) { a.BeginVerticalWrap(a.idManager.CreateStaticID()); } }, - MisuseCase{ "BeginCached", [](HeadlessGUIApp& a, views::Context&) { a.BeginCached(a.idManager.CreateStaticID()); } }, - MisuseCase{ "BeginMenuBar", [](HeadlessGUIApp& a, views::Context&) { a.BeginMenuBar(a.idManager.CreateStaticID()); } }, - MisuseCase{ "BeginTitleBar", [](HeadlessGUIApp& a, views::Context&) { a.BeginTitleBar(a.idManager.CreateStaticID()); } }, - MisuseCase{ "BeginStatusBar", [](HeadlessGUIApp& a, views::Context&) { a.BeginStatusBar(a.idManager.CreateStaticID()); } }, - MisuseCase{ "BeginLabelGroup", [](HeadlessGUIApp& a, views::Context&) { a.BeginLabelGroup(a.idManager.CreateStaticID()); } }, - MisuseCase{ "BeginButtonGroup", [](HeadlessGUIApp& a, views::Context&) { a.BeginButtonGroup(); } }, - MisuseCase{ "BeginToggleGroup", [](HeadlessGUIApp& a, views::Context&) { a.BeginToggleGroup(); } }, - MisuseCase{ "BeginToolbar", [](HeadlessGUIApp& a, views::Context&) { a.BeginToolbar(); } }, - MisuseCase{ "BeginReorderableGroup", [](HeadlessGUIApp& a, views::Context&) { a.BeginReorderableGroup(a.idManager.CreateStaticID(), ReorderDirection::Vertical, [](int, int) {}); } }, - MisuseCase{ "BeginListView", [](HeadlessGUIApp& a, views::Context& viewsContext) { views::BeginListView(a, viewsContext, a.idManager.CreateStaticID(), &g_selected, 0); } }, - MisuseCase{ "BeginGridView", [](HeadlessGUIApp& a, views::Context& viewsContext) { views::BeginGridView(a, viewsContext, a.idManager.CreateStaticID(), &g_selected); } }, - MisuseCase{ "BeginTable", [](HeadlessGUIApp& a, views::Context& viewsContext) { views::BeginTable(a, viewsContext, a.idManager.CreateStaticID(), g_columns, g_tableState); } }, - MisuseCase{ "BeginTabBar", [](HeadlessGUIApp& a, views::Context&) { a.BeginTabBar(a.idManager.CreateStaticID(), &g_selected, [](int, int) {}); } }, - MisuseCase{ "BeginDockingContainer", [](HeadlessGUIApp& a, views::Context&) { a.BeginDockingContainer(a.idManager.CreateStaticID(), &g_dockingLayout); } }, - MisuseCase{ "BeginDisabled", [](HeadlessGUIApp& a, views::Context&) { a.BeginDisabled(); } }, - MisuseCase{ "BeginInvalid", [](HeadlessGUIApp& a, views::Context&) { a.BeginInvalid(); } }, - MisuseCase{ "BeginSelected", [](HeadlessGUIApp& a, views::Context&) { a.BeginSelected(); } }, - MisuseCase{ "BeginIndeterminate", [](HeadlessGUIApp& a, views::Context&) { a.BeginIndeterminate(); } }, - MisuseCase{ "PushParent", [](HeadlessGUIApp& a, views::Context&) { (void)a.idManager.PushParent(a.idManager.CreateStaticID()); } } + MisuseCase{ "BeginArea", [](HeadlessGUIApp& a, Contexts&) { a.BeginArea(a.idManager.CreateStaticID()); } }, + MisuseCase{ "BeginHorizontal", [](HeadlessGUIApp& a, Contexts&) { a.BeginHorizontal(a.idManager.CreateStaticID()); } }, + MisuseCase{ "BeginHorizontalWrap", [](HeadlessGUIApp& a, Contexts&) { a.BeginHorizontalWrap(a.idManager.CreateStaticID()); } }, + MisuseCase{ "BeginVertical", [](HeadlessGUIApp& a, Contexts&) { a.BeginVertical(a.idManager.CreateStaticID()); } }, + MisuseCase{ "BeginVerticalWrap", [](HeadlessGUIApp& a, Contexts&) { a.BeginVerticalWrap(a.idManager.CreateStaticID()); } }, + MisuseCase{ "BeginCached", [](HeadlessGUIApp& a, Contexts&) { a.BeginCached(a.idManager.CreateStaticID()); } }, + MisuseCase{ "BeginMenuBar", [](HeadlessGUIApp& a, Contexts&) { a.BeginMenuBar(a.idManager.CreateStaticID()); } }, + MisuseCase{ "BeginTitleBar", [](HeadlessGUIApp& a, Contexts&) { a.BeginTitleBar(a.idManager.CreateStaticID()); } }, + MisuseCase{ "BeginStatusBar", [](HeadlessGUIApp& a, Contexts&) { a.BeginStatusBar(a.idManager.CreateStaticID()); } }, + MisuseCase{ "BeginLabelGroup", [](HeadlessGUIApp& a, Contexts&) { a.BeginLabelGroup(a.idManager.CreateStaticID()); } }, + MisuseCase{ "BeginButtonGroup", [](HeadlessGUIApp& a, Contexts&) { a.BeginButtonGroup(); } }, + MisuseCase{ "BeginToggleGroup", [](HeadlessGUIApp& a, Contexts&) { a.BeginToggleGroup(); } }, + MisuseCase{ "BeginToolbar", [](HeadlessGUIApp& a, Contexts&) { a.BeginToolbar(); } }, + MisuseCase{ "BeginReorderableGroup", [](HeadlessGUIApp& a, Contexts&) { a.BeginReorderableGroup(a.idManager.CreateStaticID(), ReorderDirection::Vertical, [](int, int) {}); } }, + MisuseCase{ "BeginListView", [](HeadlessGUIApp& a, Contexts& contexts) { views::BeginListView(a, contexts.views, a.idManager.CreateStaticID(), &g_selected, 0); } }, + MisuseCase{ "BeginGridView", [](HeadlessGUIApp& a, Contexts& contexts) { views::BeginGridView(a, contexts.views, a.idManager.CreateStaticID(), &g_selected); } }, + MisuseCase{ "BeginTable", [](HeadlessGUIApp& a, Contexts& contexts) { views::BeginTable(a, contexts.views, a.idManager.CreateStaticID(), g_columns, g_tableState); } }, + MisuseCase{ "BeginTabBar", [](HeadlessGUIApp& a, Contexts&) { a.BeginTabBar(a.idManager.CreateStaticID(), &g_selected, [](int, int) {}); } }, + MisuseCase{ "BeginDockingContainer", [](HeadlessGUIApp& a, Contexts& contexts) { docking::BeginDockingContainer(a, contexts.docking, a.idManager.CreateStaticID(), &g_dockingLayout); } }, + MisuseCase{ "BeginDisabled", [](HeadlessGUIApp& a, Contexts&) { a.BeginDisabled(); } }, + MisuseCase{ "BeginInvalid", [](HeadlessGUIApp& a, Contexts&) { a.BeginInvalid(); } }, + MisuseCase{ "BeginSelected", [](HeadlessGUIApp& a, Contexts&) { a.BeginSelected(); } }, + MisuseCase{ "BeginIndeterminate", [](HeadlessGUIApp& a, Contexts&) { a.BeginIndeterminate(); } }, + MisuseCase{ "PushParent", [](HeadlessGUIApp& a, Contexts&) { (void)a.idManager.PushParent(a.idManager.CreateStaticID()); } } ), CaseName); // A menu that is open, left without its EndMenu. @@ -218,12 +228,12 @@ namespace } INSTANTIATE_TEST_SUITE_P(MisuseIDs, BeginLeftOpenTest, ::testing::Values( - MisuseCase{ "TheSameIDTwice", [](HeadlessGUIApp& a, views::Context&) { + MisuseCase{ "TheSameIDTwice", [](HeadlessGUIApp& a, Contexts&) { const ID id = a.idManager.CreateStaticID(); a.Button(id, "One", [] {}); a.Button(id, "Two", [] {}); } }, - MisuseCase{ "AnInvalidID", [](HeadlessGUIApp& a, views::Context&) { a.Button(ID::Invalid(), "Invalid", [] {}); } }, - MisuseCase{ "AnInvalidStyle", [](HeadlessGUIApp& a, views::Context&) { a.Label(a.idManager.CreateStaticID(), "Unstyled", StyleRef::Invalid()); } } + MisuseCase{ "AnInvalidID", [](HeadlessGUIApp& a, Contexts&) { a.Button(ID::Invalid(), "Invalid", [] {}); } }, + MisuseCase{ "AnInvalidStyle", [](HeadlessGUIApp& a, Contexts&) { a.Label(a.idManager.CreateStaticID(), "Unstyled", StyleRef::Invalid()); } } ), CaseName); // A released static ID used again: it's just an unknown ID now, not a crash. @@ -324,16 +334,18 @@ namespace TEST_P(OddValueTest, LaysOut) { HeadlessGUIApp app; - views::Context viewsContext; + Contexts contexts; ASSERT_TRUE(app.Initialize()); + docking::Install(app, contexts.docking); for (int i = 0; i < 2; i++) app.Frame([&] { app.BeginRootWindow(); - GetParam().misuse(app, viewsContext); + GetParam().misuse(app, contexts); app.EndRootWindow(); - views::EndGUI(app, viewsContext); + views::EndGUI(app, contexts.views); }); ExpectTheNextFrameWorks(app); + docking::Cleanup(app, contexts.docking); app.Cleanup(); } @@ -342,26 +354,26 @@ namespace std::string g_string; INSTANTIATE_TEST_SUITE_P(Misuse, OddValueTest, ::testing::Values( - MisuseCase{ "NaNField", [](HeadlessGUIApp& a, views::Context&) { g_float = std::numeric_limits::quiet_NaN(); a.Field(g_float); } }, - MisuseCase{ "InfinityField", [](HeadlessGUIApp& a, views::Context&) { g_float = std::numeric_limits::infinity(); a.Field(g_float); } }, - MisuseCase{ "NaNSlider", [](HeadlessGUIApp& a, views::Context&) { g_float = std::numeric_limits::quiet_NaN(); a.SliderField(a.idManager.CreateStaticID(), g_float, 0.0f, 1.0f, "NaN"); } }, - MisuseCase{ "SliderMinAboveMax", [](HeadlessGUIApp& a, views::Context&) { g_float = 0.5f; a.SliderField(a.idManager.CreateStaticID(), g_float, 1.0f, 0.0f, "Backwards"); } }, - MisuseCase{ "SliderEmptyRange", [](HeadlessGUIApp& a, views::Context&) { g_int = 3; a.Slider(a.idManager.CreateStaticID(), g_int, 5, 5); } }, - MisuseCase{ "IntSliderOutOfRange",[](HeadlessGUIApp& a, views::Context&) { g_int = 1000; a.Slider(a.idManager.CreateStaticID(), g_int, 0, 10); } }, - MisuseCase{ "EmptyLabel", [](HeadlessGUIApp& a, views::Context&) { a.Label(a.idManager.CreateStaticID(), ""); } }, - MisuseCase{ "HugeLabel", [](HeadlessGUIApp& a, views::Context&) { a.Label(a.idManager.CreateStaticID(), std::string(200000, 'x')); } }, - MisuseCase{ "InvalidUtf8Label", [](HeadlessGUIApp& a, views::Context&) { a.Label(a.idManager.CreateStaticID(), "\xff\xfe\xc3 \xe2\x82 \xf0\x9f"); } }, - MisuseCase{ "InvalidUtf8Field", [](HeadlessGUIApp& a, views::Context&) { g_string = "\xc3\x28\xa0\xa1"; a.Field(a.idManager.CreateStaticID(), g_string); } }, - MisuseCase{ "NegativeSize", [](HeadlessGUIApp& a, views::Context&) { a.Button(a.idManager.CreateStaticID(), "Negative", [] {}, LayoutOverride{}.Size(-50, -20)); } }, - MisuseCase{ "ZeroSize", [](HeadlessGUIApp& a, views::Context&) { a.Button(a.idManager.CreateStaticID(), "Zero", [] {}, LayoutOverride{}.Size(0, 0)); } }, - MisuseCase{ "HugeSize", [](HeadlessGUIApp& a, views::Context&) { a.Button(a.idManager.CreateStaticID(), "Huge", [] {}, LayoutOverride{}.Size(1000000, 1000000)); } }, - MisuseCase{ "ListPastSixteenBits",[](HeadlessGUIApp& a, views::Context& viewsContext) { + MisuseCase{ "NaNField", [](HeadlessGUIApp& a, Contexts&) { g_float = std::numeric_limits::quiet_NaN(); a.Field(g_float); } }, + MisuseCase{ "InfinityField", [](HeadlessGUIApp& a, Contexts&) { g_float = std::numeric_limits::infinity(); a.Field(g_float); } }, + MisuseCase{ "NaNSlider", [](HeadlessGUIApp& a, Contexts&) { g_float = std::numeric_limits::quiet_NaN(); a.SliderField(a.idManager.CreateStaticID(), g_float, 0.0f, 1.0f, "NaN"); } }, + MisuseCase{ "SliderMinAboveMax", [](HeadlessGUIApp& a, Contexts&) { g_float = 0.5f; a.SliderField(a.idManager.CreateStaticID(), g_float, 1.0f, 0.0f, "Backwards"); } }, + MisuseCase{ "SliderEmptyRange", [](HeadlessGUIApp& a, Contexts&) { g_int = 3; a.Slider(a.idManager.CreateStaticID(), g_int, 5, 5); } }, + MisuseCase{ "IntSliderOutOfRange",[](HeadlessGUIApp& a, Contexts&) { g_int = 1000; a.Slider(a.idManager.CreateStaticID(), g_int, 0, 10); } }, + MisuseCase{ "EmptyLabel", [](HeadlessGUIApp& a, Contexts&) { a.Label(a.idManager.CreateStaticID(), ""); } }, + MisuseCase{ "HugeLabel", [](HeadlessGUIApp& a, Contexts&) { a.Label(a.idManager.CreateStaticID(), std::string(200000, 'x')); } }, + MisuseCase{ "InvalidUtf8Label", [](HeadlessGUIApp& a, Contexts&) { a.Label(a.idManager.CreateStaticID(), "\xff\xfe\xc3 \xe2\x82 \xf0\x9f"); } }, + MisuseCase{ "InvalidUtf8Field", [](HeadlessGUIApp& a, Contexts&) { g_string = "\xc3\x28\xa0\xa1"; a.Field(a.idManager.CreateStaticID(), g_string); } }, + MisuseCase{ "NegativeSize", [](HeadlessGUIApp& a, Contexts&) { a.Button(a.idManager.CreateStaticID(), "Negative", [] {}, LayoutOverride{}.Size(-50, -20)); } }, + MisuseCase{ "ZeroSize", [](HeadlessGUIApp& a, Contexts&) { a.Button(a.idManager.CreateStaticID(), "Zero", [] {}, LayoutOverride{}.Size(0, 0)); } }, + MisuseCase{ "HugeSize", [](HeadlessGUIApp& a, Contexts&) { a.Button(a.idManager.CreateStaticID(), "Huge", [] {}, LayoutOverride{}.Size(1000000, 1000000)); } }, + MisuseCase{ "ListPastSixteenBits",[](HeadlessGUIApp& a, Contexts& contexts) { static int selected = 0; - if (views::BeginListView(a, viewsContext, a.idManager.CreateStaticID(), &selected, 70000)) + if (views::BeginListView(a, contexts.views, a.idManager.CreateStaticID(), &selected, 70000)) { for (int i = 0; i < 70000; i++) - views::ListItem(a, viewsContext, std::string_view("row")); - views::EndListView(a, viewsContext); + views::ListItem(a, contexts.views, std::string_view("row")); + views::EndListView(a, contexts.views); } } } ), CaseName); @@ -494,12 +506,12 @@ namespace // ---- Parts of a container used outside it ---- INSTANTIATE_TEST_SUITE_P(MisuseParts, EndWithoutBeginTest, ::testing::Values( - MisuseCase{ "MenuItemOutsideAMenu", [](HeadlessGUIApp& a, views::Context&) { a.MenuItem(a.idManager.CreateStaticID(), "Stray"); } }, - MisuseCase{ "ListItemOutsideAList", [](HeadlessGUIApp& a, views::Context& viewsContext) { views::ListItem(a, viewsContext, a.idManager.CreateStaticID(), std::string_view("Stray"), LayoutOverride{}); } }, - MisuseCase{ "TabOutsideATabBar", [](HeadlessGUIApp& a, views::Context&) { a.Tab(a.idManager.CreateStaticID(), "Stray"); } }, - MisuseCase{ "TreeCellOutsideATable", [](HeadlessGUIApp& a, views::Context& viewsContext) { bool open = true; views::TreeCell(a, viewsContext, "Stray", 0, &open); } }, - MisuseCase{ "CellOutsideATable", [](HeadlessGUIApp& a, views::Context& viewsContext) { views::Cell(a, viewsContext, "Stray"); } }, - MisuseCase{ "ReorderableItemOutsideAGroup",[](HeadlessGUIApp& a, views::Context&) { a.BeginReorderableItem(a.idManager.CreateStaticID()); a.EndReorderableItem(); } } + MisuseCase{ "MenuItemOutsideAMenu", [](HeadlessGUIApp& a, Contexts&) { a.MenuItem(a.idManager.CreateStaticID(), "Stray"); } }, + MisuseCase{ "ListItemOutsideAList", [](HeadlessGUIApp& a, Contexts& contexts) { views::ListItem(a, contexts.views, a.idManager.CreateStaticID(), std::string_view("Stray"), LayoutOverride{}); } }, + MisuseCase{ "TabOutsideATabBar", [](HeadlessGUIApp& a, Contexts&) { a.Tab(a.idManager.CreateStaticID(), "Stray"); } }, + MisuseCase{ "TreeCellOutsideATable", [](HeadlessGUIApp& a, Contexts& contexts) { bool open = true; views::TreeCell(a, contexts.views, "Stray", 0, &open); } }, + MisuseCase{ "CellOutsideATable", [](HeadlessGUIApp& a, Contexts& contexts) { views::Cell(a, contexts.views, "Stray"); } }, + MisuseCase{ "ReorderableItemOutsideAGroup",[](HeadlessGUIApp& a, Contexts&) { a.BeginReorderableItem(a.idManager.CreateStaticID()); a.EndReorderableItem(); } } ), CaseName); // ---- Scale and odd data ---- @@ -509,29 +521,29 @@ namespace nodes::NodeView g_badNodeView; INSTANTIATE_TEST_SUITE_P(MisuseScale, OddValueTest, ::testing::Values( - MisuseCase{ "DeepNesting", [](HeadlessGUIApp& a, views::Context&) { + MisuseCase{ "DeepNesting", [](HeadlessGUIApp& a, Contexts&) { for (int i = 0; i < 3000; i++) a.BeginVertical(); a.Label(a.idManager.CreateStaticID(), "deep"); for (int i = 0; i < 3000; i++) a.EndVertical(); } }, - MisuseCase{ "FortyThousandLabels", [](HeadlessGUIApp& a, views::Context&) { + MisuseCase{ "FortyThousandLabels", [](HeadlessGUIApp& a, Contexts&) { for (int i = 0; i < 40000; i++) a.Label(std::string_view("row")); } }, - MisuseCase{ "ATableOfAHundredThousandRows", [](HeadlessGUIApp& a, views::Context& viewsContext) { + MisuseCase{ "ATableOfAHundredThousandRows", [](HeadlessGUIApp& a, Contexts& contexts) { if (g_bigTableColumns.empty()) { g_bigTableColumns.resize(2); g_bigTableColumns[0].column.header = "A"; g_bigTableColumns[1].column.header = "B"; - for (auto& c : g_bigTableColumns) c.generateCell = [&a, &viewsContext](int row) { views::Cell(a, viewsContext, std::to_string(row)); }; + for (auto& c : g_bigTableColumns) c.generateCell = [&a, &contexts](int row) { views::Cell(a, contexts.views, std::to_string(row)); }; } - views::VirtualTable(a, viewsContext, a.idManager.CreateStaticID(), g_bigTableState, g_bigTableColumns, 100000, 0, {}, LayoutOverride{}.Size(400, 300)); } }, - MisuseCase{ "ATableWithNoColumns", [](HeadlessGUIApp& a, views::Context& viewsContext) { + views::VirtualTable(a, contexts.views, a.idManager.CreateStaticID(), g_bigTableState, g_bigTableColumns, 100000, 0, {}, LayoutOverride{}.Size(400, 300)); } }, + MisuseCase{ "ATableWithNoColumns", [](HeadlessGUIApp& a, Contexts& contexts) { static views::TableState state; - views::VirtualTable(a, viewsContext, a.idManager.CreateStaticID(), state, std::span{}, 10, 0, {}, LayoutOverride{}.Size(400, 300)); } }, - MisuseCase{ "ATableWithNegativeRows", [](HeadlessGUIApp& a, views::Context& viewsContext) { + views::VirtualTable(a, contexts.views, a.idManager.CreateStaticID(), state, std::span{}, 10, 0, {}, LayoutOverride{}.Size(400, 300)); } }, + MisuseCase{ "ATableWithNegativeRows", [](HeadlessGUIApp& a, Contexts& contexts) { static views::TableState state; static views::VirtualTableColumn column[1]; - views::VirtualTable(a, viewsContext, a.idManager.CreateStaticID(), state, column, -5, -10, {}, LayoutOverride{}.Size(400, 300)); } }, - MisuseCase{ "NodeWiresToNodesThatDontExist", [](HeadlessGUIApp& a, views::Context&) { nodes::Context nodesContext; + views::VirtualTable(a, contexts.views, a.idManager.CreateStaticID(), state, column, -5, -10, {}, LayoutOverride{}.Size(400, 300)); } }, + MisuseCase{ "NodeWiresToNodesThatDontExist", [](HeadlessGUIApp& a, Contexts&) { nodes::Context nodesContext; if (g_badNodeView.nodes.empty()) { g_badNodeView.nodes.resize(2); @@ -546,8 +558,8 @@ namespace g_badNodeView.ordering = { 5, -1, 0 }; // bad z-order } nodes::RenderNodeView(a, nodesContext, g_badNodeView); } }, - MisuseCase{ "AnEmptyNodeView", [](HeadlessGUIApp& a, views::Context&) { static nodes::NodeView view; nodes::Context nodesContext; nodes::RenderNodeView(a, nodesContext, view); } }, - MisuseCase{ "ATooltipForNoElement", [](HeadlessGUIApp& a, views::Context&) { a.SetTooltip(ID::Invalid(), "for nothing"); } } + MisuseCase{ "AnEmptyNodeView", [](HeadlessGUIApp& a, Contexts&) { static nodes::NodeView view; nodes::Context nodesContext; nodes::RenderNodeView(a, nodesContext, view); } }, + MisuseCase{ "ATooltipForNoElement", [](HeadlessGUIApp& a, Contexts&) { a.SetTooltip(ID::Invalid(), "for nothing"); } } ), CaseName); // The same window declared twice in one frame. diff --git a/tests/sizer_render_test.cpp b/tests/sizer_render_test.cpp index 4123db58..098fdfaa 100644 --- a/tests/sizer_render_test.cpp +++ b/tests/sizer_render_test.cpp @@ -2,6 +2,7 @@ #include #include "headless_gui_app.h" #include +#include namespace tachyon { @@ -11,6 +12,7 @@ namespace tachyon { protected: HeadlessGUIApp app; + docking::Context dockingContext; void SetUp() override { ASSERT_TRUE(app.Initialize()); } void TearDown() override { app.Cleanup(); } }; @@ -22,7 +24,7 @@ namespace tachyon app.Frame([&] { app.BeginRootWindow({ 800, 600 }); - if (app.BeginArea(app.theme.dockContentStyleRef, LayoutOverride{}.FlexGrow(1))) + if (app.BeginArea(docking::GetStyles(app, dockingContext).dockContentStyleRef, LayoutOverride{}.FlexGrow(1))) { app.BeginLabelGroup(120, 40, 300); app.DragLabel("Test Label"); diff --git a/tests/static_id_release_test.cpp b/tests/static_id_release_test.cpp index f26f5192..328f8a19 100644 --- a/tests/static_id_release_test.cpp +++ b/tests/static_id_release_test.cpp @@ -6,9 +6,10 @@ #include "headless_gui_app.h" #include -#include +#include #include #include +#include namespace tachyon { @@ -20,6 +21,7 @@ namespace tachyon { protected: HeadlessGUIApp app; + docking::Context dockingContext; color::Context colorContext; dialogs::Context dialogContext; void SetUp() override { ASSERT_TRUE(app.Initialize()); } @@ -30,15 +32,15 @@ namespace tachyon // an ID of the app's keeps it, for the app to release. TEST_F(StaticIDReleaseTest, AClosedPanelsIDGoesBackUnlessItWasTheApps) { - DockingLayout layout; - const ID made = app.CreatePanel(layout.panels, "Made", IconID::Invalid, [] {}); + docking::DockingLayout layout; + const ID made = docking::CreatePanel(app, dockingContext, layout.panels, "Made", IconID::Invalid, [] {}); const ID given = app.idManager.CreateStaticID(); - app.CreatePanel(layout.panels, given, "Given", IconID::Invalid, [] {}); - layout.root = MakeLeaf({ made, given }); + docking::CreatePanel(app, dockingContext, layout.panels, given, "Given", IconID::Invalid, [] {}); + layout.root = docking::MakeLeaf({ made, given }); - app.CloseDockedPanel(layout, *layout.root, 0); + docking::CloseDockedPanel(app, dockingContext, layout, *layout.root, 0); EXPECT_FALSE(app.idManager.IsStaticIDValid(made)); - app.CloseDockedPanel(layout, *layout.root, 0); + docking::CloseDockedPanel(app, dockingContext, layout, *layout.root, 0); EXPECT_TRUE(app.idManager.IsStaticIDValid(given)) << "the app's own"; EXPECT_TRUE(layout.panels.empty()); EXPECT_TRUE(app.idManager.ReleaseStaticID(given)); @@ -49,21 +51,21 @@ namespace tachyon { const size_t before = app.idManager.GetStaticIDCount(); const ID containerID = app.idManager.CreateStaticID(); - DockingLayout layout; + docking::DockingLayout layout; int disables = 0; - const ID a = app.CreatePanel(layout.panels, "A", IconID::Invalid, [] {}, {}, {}, [&] { disables++; }); - const ID b = app.CreatePanel(layout.panels, "B", IconID::Invalid, [] {}); - layout.root = MakeSplit(DockSplitMode::LeftPinned, 200, MakeLeaf({ a }), MakeLeaf({ b })); + const ID a = docking::CreatePanel(app, dockingContext, layout.panels, "A", IconID::Invalid, [] {}, {}, {}, [&] { disables++; }); + const ID b = docking::CreatePanel(app, dockingContext, layout.panels, "B", IconID::Invalid, [] {}); + layout.root = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 200, docking::MakeLeaf({ a }), docking::MakeLeaf({ b })); app.Frame([&] { app.BeginRootWindow(); - app.BeginDockingContainer(containerID, &layout, LayoutOverride{}.Size(800, 600)); - app.EndDockingContainer(); + docking::BeginDockingContainer(app, dockingContext, containerID, &layout, LayoutOverride{}.Size(800, 600)); + docking::EndDockingContainer(app, dockingContext); app.EndRootWindow(); dialogs::EndGUI(app, dialogContext); }); ASSERT_GT(app.idManager.GetStaticIDCount(), before + 3) << "test setup: the tree has IDs"; - app.ReleaseDockingLayout(layout); + docking::ReleaseDockingLayout(app, dockingContext, layout); EXPECT_EQ(disables, 1) << "a shown panel is hidden first"; EXPECT_TRUE(layout.panels.empty()); EXPECT_EQ(layout.root, nullptr); @@ -75,13 +77,13 @@ namespace tachyon TEST_F(StaticIDReleaseTest, ClosingAllDocumentsGivesBackTheirIDs) { const size_t before = app.idManager.GetStaticIDCount(); - DocumentSet set; + docking::DocumentSet set; for (const char* name : { "Forest", "Desert" }) { - Document& document = app.CreateDocument(set, name, ".level", "level", IconID::Invalid); - document.layout.root = MakeLeaf({ app.CreatePanel(document.layout.panels, "Scene", IconID::Invalid, [] {}) }); + docking::Document& document = docking::CreateDocument(app, dockingContext, set, name, ".level", "level", IconID::Invalid); + document.layout.root = docking::MakeLeaf({ docking::CreatePanel(app, dockingContext, document.layout.panels, "Scene", IconID::Invalid, [] {}) }); } - app.CloseAllDocuments(set); + docking::CloseAllDocuments(app, dockingContext, set); EXPECT_TRUE(set.documents.empty()); EXPECT_EQ(app.idManager.GetStaticIDCount(), before); } @@ -104,17 +106,17 @@ namespace tachyon colorContext.picker.windowID = app.idManager.CreateStaticID(); colorContext.gradientEditor.windowID = app.idManager.CreateStaticID(); - DockingLayout home; - auto fw = std::make_unique(); + docking::DockingLayout home; + auto fw = std::make_unique(); fw->windowID = app.idManager.CreateStaticID(); - fw->layout.root = MakeLeaf({ app.CreatePanel(fw->layout.panels, "Torn off", IconID::Invalid, [] {}) }); + fw->layout.root = docking::MakeLeaf({ docking::CreatePanel(app, dockingContext, fw->layout.panels, "Torn off", IconID::Invalid, [] {}) }); fw->home = &home; - app.m_floatingDockWindows.push_back(std::move(fw)); + dockingContext.floatingDockWindows.push_back(std::move(fw)); ASSERT_GT(app.idManager.GetStaticIDCount(), 0u); dialogs::Cleanup(app, dialogContext); color::Cleanup(app, colorContext); app.Cleanup(); EXPECT_EQ(app.idManager.GetStaticIDCount(), 0u); - EXPECT_TRUE(app.m_floatingDockWindows.empty()); + EXPECT_TRUE(dockingContext.floatingDockWindows.empty()); } } } diff --git a/tests/table_scrollbar_test.cpp b/tests/table_scrollbar_test.cpp index 65a6f796..b526898f 100644 --- a/tests/table_scrollbar_test.cpp +++ b/tests/table_scrollbar_test.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include @@ -35,12 +36,14 @@ namespace tachyon protected: SettingsHostApp app; views::Context viewsContext; + docking::Context dockingContext; tachyon::views::TableState state; std::vector cols; void SetUp() override { ASSERT_TRUE(app.Initialize()); + docking::Install(app, dockingContext); cols.resize(2); cols[0].column = { .header = "Name", .initialWidth = 120, .minWidth = 40, .maxWidth = 400 }; cols[0].generateCell = [this](int r) { (void)r; views::Cell(app, viewsContext, "name"); }; @@ -212,7 +215,7 @@ namespace tachyon tachyon::Element sizer{}; sizer.id = app.idManager.AllocateDynamicID("catSizer"); - sizer.styleRef = app.theme.dockSizerHorzStyleRef; + sizer.styleRef = docking::GetStyles(app, dockingContext).dockSizerHorzStyleRef; sizer.state = app.guiStateManager.GetCurrentState(sizer.id); sizer.eventHandler = tachyon::MakeHorizontalSizerHandler( app.guiStateManager, app.elementStorage, catWidth, 100, 400); @@ -244,7 +247,7 @@ namespace tachyon app.theme.flexFillRowStyleRef, tachyon::LayoutOverride{}.Size(900, 400).NoGrow().NoShrink()); app.BeginArea(app.idManager.AllocateDynamicID("dockContent"), - app.theme.dockContentStyleRef, + docking::GetStyles(app, dockingContext).dockContentStyleRef, tachyon::LayoutOverride{}.FlexGrow(1)); views::RenderSettingsPanel(app, viewsContext, sp); app.EndArea(); // dockContent diff --git a/tests/theme_metrics_test.cpp b/tests/theme_metrics_test.cpp index e53f5850..2bc12853 100644 --- a/tests/theme_metrics_test.cpp +++ b/tests/theme_metrics_test.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include "headless_gui_app.h" @@ -49,14 +50,16 @@ namespace TEST(ThemeMetrics, DividersShareOneHoverColor) { HeadlessGUIApp app; + docking::Context dockingContext; views::Context viewsContext; ASSERT_TRUE(app.Initialize()); + docking::Install(app, dockingContext); auto hoverBackground = [&](StyleRef style) { const VisualBoxStyle* box = app.styleManager.GetVisualBoxStyle(style.visualBoxStyleIndex, ElementState::Hover); return box ? box->backgroundColorIndex : VisualColorStyleIndex{}; }; - const auto dock = hoverBackground(app.theme.dockSizerHorzStyleRef); - EXPECT_EQ(hoverBackground(app.theme.dockSizerVertStyleRef), dock); + const auto dock = hoverBackground(docking::GetStyles(app, dockingContext).dockSizerHorzStyleRef); + EXPECT_EQ(hoverBackground(docking::GetStyles(app, dockingContext).dockSizerVertStyleRef), dock); EXPECT_EQ(hoverBackground(views::GetStyles(app, viewsContext).tableSizerStyleRef), dock); const color4f divider = app.theme.GetColor("--divider-hover"); EXPECT_GT(divider.a, 0.0f) << "the palette defines --divider-hover"; diff --git a/tests/theme_variables_test.cpp b/tests/theme_variables_test.cpp index a71075b2..9ac1dcb7 100644 --- a/tests/theme_variables_test.cpp +++ b/tests/theme_variables_test.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include diff --git a/tests/ui_cache_test.cpp b/tests/ui_cache_test.cpp index 860228fe..977faca5 100644 --- a/tests/ui_cache_test.cpp +++ b/tests/ui_cache_test.cpp @@ -14,8 +14,9 @@ #include #include #include -#include +#include #include +#include #include @@ -29,6 +30,7 @@ namespace tachyon { protected: HeadlessGUIApp app; + docking::Context dockingContext; nodes::Context nodesContext; ID scopeID, btnA, btnB, outsideID; int bodyRuns = 0; @@ -36,6 +38,7 @@ namespace tachyon void SetUp() override { ASSERT_TRUE(app.Initialize()); + docking::Install(app, dockingContext); scopeID = app.idManager.CreateStaticID(); btnA = app.idManager.CreateStaticID(); btnB = app.idManager.CreateStaticID(); @@ -237,7 +240,7 @@ namespace tachyon // Laid out as a docked panel: the canvas fills what the header leaves. app.Frame([&] { app.BeginRootWindow({ 1920, 1080 }, ElementFlags::None, app.theme.mainWindowStyleRef); - if (app.BeginCached(scopeID, app.theme.dockContentStyleRef, signature, + if (app.BeginCached(scopeID, docking::GetStyles(app, dockingContext).dockContentStyleRef, signature, tachyon::LayoutOverride{}.Width(600).Height(400))) { bodyRuns++; @@ -675,25 +678,27 @@ namespace tachyon TEST(UICacheDockingTest, PanelCacheVersioningInDockingContext) { HeadlessGUIApp app; + docking::Context dockingContext; ASSERT_TRUE(app.Initialize()); + docking::Install(app, dockingContext); app.InjectMouseMove({ 1900, 1000 }); - tachyon::DockingLayout layout; + tachyon::docking::DockingLayout layout; const tachyon::ID containerID = app.idManager.CreateStaticID(); int draws = 0; uint64_t sig = 1; - const tachyon::ID panel = app.CreatePanel(layout.panels, "P", IconID::Invalid, [&] { + const tachyon::ID panel = docking::CreatePanel(app, dockingContext, layout.panels, "P", IconID::Invalid, [&] { draws++; app.Button(app.idManager.AllocateDynamicID("cell"), "x", [] {}); }); layout.panels[panel].cacheSignature = [&] { return sig; }; - layout.root = MakeLeaf({ panel }); + layout.root = docking::MakeLeaf({ panel }); auto frame = [&] { app.Frame([&] { app.BeginRootWindow(); - app.BeginDockingContainer(containerID, &layout, tachyon::LayoutOverride{}.Size(800, 600)); - app.EndDockingContainer(); + docking::BeginDockingContainer(app, dockingContext, containerID, &layout, tachyon::LayoutOverride{}.Size(800, 600)); + docking::EndDockingContainer(app, dockingContext); app.EndRootWindow(); }); }; @@ -705,6 +710,7 @@ namespace tachyon sig = 2; // panel data changed frame(); EXPECT_EQ(draws, 2); // rebuilt frame(); EXPECT_EQ(draws, 2); // cached again + docking::Cleanup(app, dockingContext); app.Cleanup(); } @@ -713,26 +719,29 @@ namespace tachyon TEST(UICacheDockingTest, DefaultCachesWithoutSignature) { HeadlessGUIApp app; + docking::Context dockingContext; ASSERT_TRUE(app.Initialize()); + docking::Install(app, dockingContext); app.InjectMouseMove({ 1900, 1000 }); - tachyon::DockingLayout layout; + tachyon::docking::DockingLayout layout; const tachyon::ID containerID = app.idManager.CreateStaticID(); int draws = 0; - const tachyon::ID panel = app.CreatePanel(layout.panels, "P", IconID::Invalid, [&] { draws++; }); - layout.root = MakeLeaf({ panel }); + const tachyon::ID panel = docking::CreatePanel(app, dockingContext, layout.panels, "P", IconID::Invalid, [&] { draws++; }); + layout.root = docking::MakeLeaf({ panel }); auto frame = [&] { app.Frame([&] { app.BeginRootWindow(); - app.BeginDockingContainer(containerID, &layout, tachyon::LayoutOverride{}.Size(800, 600)); - app.EndDockingContainer(); + docking::BeginDockingContainer(app, dockingContext, containerID, &layout, tachyon::LayoutOverride{}.Size(800, 600)); + docking::EndDockingContainer(app, dockingContext); app.EndRootWindow(); }); }; frame(); frame(); frame(); EXPECT_EQ(draws, 1); // cached by default after the first build + docking::Cleanup(app, dockingContext); app.Cleanup(); } @@ -741,27 +750,30 @@ namespace tachyon TEST(UICacheDockingTest, OptedOutPanelRebuildsEachFrame) { HeadlessGUIApp app; + docking::Context dockingContext; ASSERT_TRUE(app.Initialize()); + docking::Install(app, dockingContext); app.InjectMouseMove({ 1900, 1000 }); - tachyon::DockingLayout layout; + tachyon::docking::DockingLayout layout; const tachyon::ID containerID = app.idManager.CreateStaticID(); int draws = 0; - const tachyon::ID panel = app.CreatePanel(layout.panels, "P", IconID::Invalid, [&] { draws++; }); + const tachyon::ID panel = docking::CreatePanel(app, dockingContext, layout.panels, "P", IconID::Invalid, [&] { draws++; }); layout.panels[panel].cacheSignature = [] { return std::optional{}; }; // opt out - layout.root = MakeLeaf({ panel }); + layout.root = docking::MakeLeaf({ panel }); auto frame = [&] { app.Frame([&] { app.BeginRootWindow(); - app.BeginDockingContainer(containerID, &layout, tachyon::LayoutOverride{}.Size(800, 600)); - app.EndDockingContainer(); + docking::BeginDockingContainer(app, dockingContext, containerID, &layout, tachyon::LayoutOverride{}.Size(800, 600)); + docking::EndDockingContainer(app, dockingContext); app.EndRootWindow(); }); }; frame(); frame(); frame(); EXPECT_EQ(draws, 3); // opted out -> rebuilds every frame + docking::Cleanup(app, dockingContext); app.Cleanup(); } @@ -769,31 +781,34 @@ namespace tachyon TEST(UICacheDockingTest, InvalidatePanelByIdRebuilds) { HeadlessGUIApp app; + docking::Context dockingContext; ASSERT_TRUE(app.Initialize()); + docking::Install(app, dockingContext); app.InjectMouseMove({ 1900, 1000 }); - tachyon::DockingLayout layout; + tachyon::docking::DockingLayout layout; const tachyon::ID containerID = app.idManager.CreateStaticID(); int draws = 0; - const tachyon::ID panel = app.CreatePanel(layout.panels, "P", IconID::Invalid, [&] { draws++; }); - layout.root = MakeLeaf({ panel }); + const tachyon::ID panel = docking::CreatePanel(app, dockingContext, layout.panels, "P", IconID::Invalid, [&] { draws++; }); + layout.root = docking::MakeLeaf({ panel }); auto frame = [&] { app.Frame([&] { app.BeginRootWindow(); - app.BeginDockingContainer(containerID, &layout, tachyon::LayoutOverride{}.Size(800, 600)); - app.EndDockingContainer(); + docking::BeginDockingContainer(app, dockingContext, containerID, &layout, tachyon::LayoutOverride{}.Size(800, 600)); + docking::EndDockingContainer(app, dockingContext); app.EndRootWindow(); }); }; frame(); frame(); EXPECT_EQ(draws, 1); // cached by default - app.InvalidatePanel(panel); // data changed -> force a rebuild + docking::InvalidatePanel(app, dockingContext, panel); // data changed -> force a rebuild frame(); EXPECT_EQ(draws, 2); // rebuilt frame(); EXPECT_EQ(draws, 2); // cached again + docking::Cleanup(app, dockingContext); app.Cleanup(); } @@ -802,8 +817,9 @@ namespace tachyon { protected: HeadlessGUIApp app; + docking::Context dockingContext; nodes::Context nodesContext; - tachyon::DockingLayout layout; + tachyon::docking::DockingLayout layout; tachyon::ID containerID{}, left{}, right{}, leftButton{}, rightButton{}, field{}; int leftChanged = 0, rightChanged = 0, rightDraws = 0; int shared = 0; // what both panels show @@ -815,23 +831,24 @@ namespace tachyon void SetUp() override { ASSERT_TRUE(app.Initialize()); + docking::Install(app, dockingContext); app.SetDrawCacheEnabled(true); // as an app runs: cached panels drawn from their copies app.InjectMouseMove({ 1900, 1000 }); containerID = app.idManager.CreateStaticID(); leftButton = app.idManager.CreateStaticID(); rightButton = app.idManager.CreateStaticID(); field = app.idManager.CreateStaticID(); - left = app.CreatePanel(layout.panels, "Left", IconID::Invalid, [this] { + left = docking::CreatePanel(app, dockingContext, layout.panels, "Left", IconID::Invalid, [this] { app.Button(leftButton, std::to_string(shared), [this] { ++shared; }); app.Field(field, text); }); - right = app.CreatePanel(layout.panels, "Right", IconID::Invalid, [this] { + right = docking::CreatePanel(app, dockingContext, layout.panels, "Right", IconID::Invalid, [this] { ++rightDraws; app.Button(rightButton, std::to_string(shared), [] {}); }); layout.panels[left].onChanged = [this] { ++leftChanged; }; layout.panels[right].onChanged = [this] { ++rightChanged; }; - layout.root = MakeSplit(tachyon::DockSplitMode::LeftPinned, 400, MakeLeaf({ left }), MakeLeaf({ right })); + layout.root = docking::MakeSplit(tachyon::docking::DockSplitMode::LeftPinned, 400, docking::MakeLeaf({ left }), docking::MakeLeaf({ right })); } void TearDown() override { app.Cleanup(); } @@ -839,8 +856,8 @@ namespace tachyon { app.Frame([&] { app.BeginRootWindow(); - app.BeginDockingContainer(containerID, &layout, tachyon::LayoutOverride{}.Size(800, 600)); - app.EndDockingContainer(); + docking::BeginDockingContainer(app, dockingContext, containerID, &layout, tachyon::LayoutOverride{}.Size(800, 600)); + docking::EndDockingContainer(app, dockingContext); app.EndRootWindow(); }); } @@ -897,7 +914,7 @@ namespace tachyon // what the first one changed. TEST_F(PanelChangedTest, AnotherPanelCatchesUpThroughOnChanged) { - layout.panels[left].onChanged = [this] { ++leftChanged; app.InvalidatePanel(right); }; + layout.panels[left].onChanged = [this] { ++leftChanged; docking::InvalidatePanel(app, dockingContext, right); }; Start(); const int drawn = rightDraws; Frames(); diff --git a/tests/ui_scale_test.cpp b/tests/ui_scale_test.cpp index 80f8a615..3e799c30 100644 --- a/tests/ui_scale_test.cpp +++ b/tests/ui_scale_test.cpp @@ -3,6 +3,7 @@ #include #include +#include #include "headless_gui_app.h" #include "scoped_temp_dir.h" @@ -69,12 +70,14 @@ namespace tachyon TEST(UIScaleTest, LabelGroupWidthIsInCssPixels) { HeadlessGUIApp app; + docking::Context dockingContext; ASSERT_TRUE(app.Initialize()); + docking::Install(app, dockingContext); const ID labelID = app.idManager.CreateStaticID(); auto frame = [&] { app.Frame([&] { app.BeginRootWindow({ 800, 600 }); - if (app.BeginArea(app.theme.dockContentStyleRef, LayoutOverride{}.FlexGrow(1))) + if (app.BeginArea(docking::GetStyles(app, dockingContext).dockContentStyleRef, LayoutOverride{}.FlexGrow(1))) { app.BeginLabelGroup(120, 40, 300); app.DragLabel(labelID, "X"); diff --git a/tests/ui_state_test.cpp b/tests/ui_state_test.cpp index 31a683b3..98ae6465 100644 --- a/tests/ui_state_test.cpp +++ b/tests/ui_state_test.cpp @@ -5,9 +5,10 @@ #include "headless_gui_app.h" #include "mock_window_backend.h" -#include +#include #include #include +#include #include #include @@ -70,6 +71,7 @@ namespace { protected: HeadlessGUIApp app; + docking::Context dockingContext; views::Context viewsContext; void SetUp() override { ASSERT_TRUE(app.Initialize()); } void TearDown() override { app.Cleanup(); } @@ -217,28 +219,28 @@ namespace TEST_F(UIStateTest, ADockTreeComesBackByPanelKey) { - auto addPanels = [](DockingLayout& layout, std::initializer_list titles) { + auto addPanels = [](docking::DockingLayout& layout, std::initializer_list titles) { std::vector ids; uint32_t n = 1; for (const char* title : titles) { ID id = ID::Invalid(); id.value.integer = 1000 + n++; // stable test IDs - layout.panels[id] = Panel{ .id = id, .title = title }; + layout.panels[id] = docking::Panel{ .id = id, .title = title }; ids.push_back(id); } return ids; }; - DockingLayout layout; + docking::DockingLayout layout; const std::vector a = addPanels(layout, { "Scene", "Details", "Log" }); - layout.root = MakeSplit(DockSplitMode::LeftPinned, 250, MakeLeaf({ a[0] }), MakeLeaf({ a[1], a[2] })); - app.PersistDocking("dock", layout); + layout.root = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 250, docking::MakeLeaf({ a[0] }), docking::MakeLeaf({ a[1], a[2] })); + docking::PersistDocking(app, dockingContext, "dock", layout); const std::string saved = app.SaveUIState(); - DockingLayout fresh; // a new run: new IDs, the panels in one leaf, and a new one + docking::DockingLayout fresh; // a new run: new IDs, the panels in one leaf, and a new one const std::vector b = addPanels(fresh, { "Log", "Details", "Scene", "Help" }); - fresh.root = MakeLeaf({ b[0], b[1], b[2], b[3] }); - app.PersistDocking("dock", fresh); + fresh.root = docking::MakeLeaf({ b[0], b[1], b[2], b[3] }); + docking::PersistDocking(app, dockingContext, "dock", fresh); ASSERT_TRUE(app.RestoreUIState(saved)); ASSERT_TRUE(fresh.root); @@ -253,17 +255,17 @@ namespace TEST_F(UIStateTest, APanelsOwnStateComesBackWithItsDock) { auto layoutOf = [](std::initializer_list titles) { - auto layout = std::make_unique(); + auto layout = std::make_unique(); std::vector ids; uint32_t n = 1; for (const char* title : titles) { ID id = ID::Invalid(); id.value.integer = 2000 + n++; - layout->panels[id] = Panel{ .id = id, .title = title }; + layout->panels[id] = docking::Panel{ .id = id, .title = title }; ids.push_back(id); } - layout->root = MakeLeaf({}); + layout->root = docking::MakeLeaf({}); layout->root->panelIds = std::move(ids); return layout; }; @@ -271,7 +273,7 @@ namespace for (auto& [id, panel] : first->panels) if (panel.title == "Graph") panel.saveState = [] { return std::string("pan 10 20 zoom 2"); }; - app.PersistDocking("dock", *first); + docking::PersistDocking(app, dockingContext, "dock", *first); const std::string saved = app.SaveUIState(); auto fresh = layoutOf({ "Log", "Graph" }); @@ -281,7 +283,7 @@ namespace std::string& into = panel.title == "Graph" ? graphState : logState; panel.restoreState = [&into](std::string_view state) { into = state; }; } - app.PersistDocking("dock", *fresh); + docking::PersistDocking(app, dockingContext, "dock", *fresh); ASSERT_TRUE(app.RestoreUIState(saved)); EXPECT_EQ(graphState, "pan 10 20 zoom 2"); EXPECT_EQ(logState, "untouched") << "it saved nothing"; @@ -292,33 +294,33 @@ namespace TEST_F(UIStateTest, TwoPanelsOfOneKindKeepTheirOwnState) { auto layoutOf = [](std::initializer_list titles) { - auto layout = std::make_unique(); + auto layout = std::make_unique(); std::vector ids; uint32_t n = 1; for (const char* title : titles) { ID id = ID::Invalid(); id.value.integer = 3000 + n++; - layout->panels[id] = Panel{ .id = id, .title = title }; + layout->panels[id] = docking::Panel{ .id = id, .title = title }; ids.push_back(id); } - layout->root = MakeLeaf({}); + layout->root = docking::MakeLeaf({}); layout->root->panelIds = std::move(ids); return layout; }; auto first = layoutOf({ "Graph", "Graph", "Log" }); const ID a = first->root->panelIds[0], b = first->root->panelIds[1], log = first->root->panelIds[2]; - first->root = MakeSplit(DockSplitMode::LeftPinned, 300, MakeLeaf({ a, log }), MakeLeaf({ b })); + first->root = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 300, docking::MakeLeaf({ a, log }), docking::MakeLeaf({ b })); first->panels[a].saveState = [] { return std::string("zoom 2"); }; first->panels[b].saveState = [] { return std::string("zoom 5"); }; - app.PersistDocking("dock", *first); + docking::PersistDocking(app, dockingContext, "dock", *first); const std::string saved = app.SaveUIState(); auto fresh = layoutOf({ "Graph", "Log", "Graph" }); std::unordered_map states; for (auto& [id, panel] : fresh->panels) panel.restoreState = [&states, id = id](std::string_view state) { states[id] = state; }; - app.PersistDocking("dock", *fresh); + docking::PersistDocking(app, dockingContext, "dock", *fresh); ASSERT_TRUE(app.RestoreUIState(saved)); ASSERT_FALSE(fresh->root->isLeaf); @@ -526,19 +528,19 @@ namespace // ---- Documents ---- // A document with panels titled `titles`, all in one leaf. - Document& AddDocument(HeadlessGUIApp& app, DocumentSet& set, std::string name, std::string extension, std::string kind, + docking::Document& AddDocument(HeadlessGUIApp& app, docking::Context& dockingContext, docking::DocumentSet& set, std::string name, std::string extension, std::string kind, std::initializer_list titles) { - Document& document = app.CreateDocument(set, std::move(name), std::move(extension), std::move(kind), IconID::Invalid); + docking::Document& document = docking::CreateDocument(app, dockingContext, set, std::move(name), std::move(extension), std::move(kind), IconID::Invalid); std::vector ids; for (const char* title : titles) - ids.push_back(app.CreatePanel(document.layout.panels, title, IconID::Invalid, [] {})); - document.layout.root = MakeLeaf({}); + ids.push_back(docking::CreatePanel(app, dockingContext, document.layout.panels, title, IconID::Invalid, [] {})); + document.layout.root = docking::MakeLeaf({}); document.layout.root->panelIds = std::move(ids); return document; } - std::vector TitlesOf(const Document& document, const DockNode* leaf) + std::vector TitlesOf(const docking::Document& document, const docking::DockNode* leaf) { std::vector titles; for (const ID id : leaf->panelIds) @@ -550,22 +552,22 @@ namespace // one's panel layout; the app makes them again. TEST_F(UIStateTest, DocumentsComeBackPerWindow) { - DocumentSet first, second; - Document& forest = AddDocument(app, first, "Forest", ".level", "level", { "Scene", "Details", "Log" }); - forest.layout.root = MakeSplit(DockSplitMode::LeftPinned, 250, MakeLeaf({ forest.layout.root->panelIds[0] }), - MakeLeaf({ forest.layout.root->panelIds[1], forest.layout.root->panelIds[2] })); - AddDocument(app, first, "Terrain", ".mat", "material", { "Graph" }); - AddDocument(app, second, "Hud", ".layout", "layout", { "Canvas" }); + docking::DocumentSet first, second; + docking::Document& forest = AddDocument(app, dockingContext, first, "Forest", ".level", "level", { "Scene", "Details", "Log" }); + forest.layout.root = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 250, docking::MakeLeaf({ forest.layout.root->panelIds[0] }), + docking::MakeLeaf({ forest.layout.root->panelIds[1], forest.layout.root->panelIds[2] })); + AddDocument(app, dockingContext, first, "Terrain", ".mat", "material", { "Graph" }); + AddDocument(app, dockingContext, second, "Hud", ".layout", "layout", { "Canvas" }); first.active = 1; const ID firstWindow = app.idManager.CreateStaticID(), secondWindow = app.idManager.CreateStaticID(); - app.PersistDocuments("documents", [&] { - return std::vector{ { firstWindow, &first }, { secondWindow, &second } }; + docking::PersistDocuments(app, dockingContext, "documents", [&] { + return std::vector{ { firstWindow, &first }, { secondWindow, &second } }; }); const std::string saved = app.SaveUIState(); ASSERT_TRUE(app.RestoreUIState(saved)); - std::vector windows = app.TakeSavedDocuments("documents"); - EXPECT_TRUE(app.TakeSavedDocuments("documents").empty()) << "taken once"; + std::vector windows = docking::TakeSavedDocuments(dockingContext, "documents"); + EXPECT_TRUE(docking::TakeSavedDocuments(dockingContext, "documents").empty()) << "taken once"; ASSERT_EQ(windows.size(), 2u); ASSERT_EQ(windows[0].documents.size(), 2u); EXPECT_EQ(windows[0].documents[0].name, "Forest"); @@ -578,9 +580,9 @@ namespace EXPECT_EQ(windows[1].rect, IntRect{}) << "not open: no place kept"; // A new run: the document made again, its panels in one leaf, a new one among them. - DocumentSet fresh; - Document& again = AddDocument(app, fresh, "Forest", ".level", "level", { "Log", "Details", "Scene", "Help" }); - ASSERT_TRUE(app.RestoreDocumentLayout(again, windows[0].documents[0])); + docking::DocumentSet fresh; + docking::Document& again = AddDocument(app, dockingContext, fresh, "Forest", ".level", "level", { "Log", "Details", "Scene", "Help" }); + ASSERT_TRUE(docking::RestoreDocumentLayout(app, dockingContext, again, windows[0].documents[0])); ASSERT_FALSE(again.layout.root->isLeaf); EXPECT_EQ(again.layout.root->splitSize, CssPx(250)); EXPECT_EQ(TitlesOf(again, again.layout.root->first.get()), (std::vector{ "Scene", "Help" })) << "Scene, then the new Help"; @@ -590,25 +592,25 @@ namespace // Each document's panels keep their own view state with the document's layout. TEST_F(UIStateTest, ADocumentsPanelsGetTheirOwnStateBack) { - DocumentSet set; - Document& forest = AddDocument(app, set, "Forest", ".level", "level", { "Viewport", "Log" }); + docking::DocumentSet set; + docking::Document& forest = AddDocument(app, dockingContext, set, "Forest", ".level", "level", { "Viewport", "Log" }); for (auto& [id, panel] : forest.layout.panels) if (panel.title == "Viewport") panel.saveState = [] { return std::string("camera 1 2 3"); }; const ID window = app.idManager.CreateStaticID(); - app.PersistDocuments("documents", [&] { return std::vector{ { window, &set } }; }); + docking::PersistDocuments(app, dockingContext, "documents", [&] { return std::vector{ { window, &set } }; }); const std::string saved = app.SaveUIState(); ASSERT_TRUE(app.RestoreUIState(saved)); - std::vector windows = app.TakeSavedDocuments("documents"); + std::vector windows = docking::TakeSavedDocuments(dockingContext, "documents"); ASSERT_EQ(windows.size(), 1u); - DocumentSet fresh; - Document& again = AddDocument(app, fresh, "Forest", ".level", "level", { "Log", "Viewport" }); + docking::DocumentSet fresh; + docking::Document& again = AddDocument(app, dockingContext, fresh, "Forest", ".level", "level", { "Log", "Viewport" }); std::string camera; for (auto& [id, panel] : again.layout.panels) if (panel.title == "Viewport") panel.restoreState = [&camera](std::string_view state) { camera = state; }; - ASSERT_TRUE(app.RestoreDocumentLayout(again, windows[0].documents[0])); + ASSERT_TRUE(docking::RestoreDocumentLayout(app, dockingContext, again, windows[0].documents[0])); EXPECT_EQ(camera, "camera 1 2 3"); } @@ -616,31 +618,31 @@ namespace // for it, and each gets its own state back. TEST_F(UIStateTest, ADocumentsSecondPanelOfAKindIsMadeAgain) { - DocumentSet set; - Document& forest = AddDocument(app, set, "Forest", ".level", "level", { "Viewport", "Viewport" }); + docking::DocumentSet set; + docking::Document& forest = AddDocument(app, dockingContext, set, "Forest", ".level", "level", { "Viewport", "Viewport" }); const ID a = forest.layout.root->panelIds[0], b = forest.layout.root->panelIds[1]; - forest.layout.root = MakeSplit(DockSplitMode::LeftPinned, 500, MakeLeaf({ a }), MakeLeaf({ b })); + forest.layout.root = docking::MakeSplit(docking::DockSplitMode::LeftPinned, 500, docking::MakeLeaf({ a }), docking::MakeLeaf({ b })); forest.layout.panels[a].saveState = [] { return std::string("camera left"); }; forest.layout.panels[b].saveState = [] { return std::string("camera right"); }; const ID window = app.idManager.CreateStaticID(); - app.PersistDocuments("documents", [&] { return std::vector{ { window, &set } }; }); + docking::PersistDocuments(app, dockingContext, "documents", [&] { return std::vector{ { window, &set } }; }); const std::string saved = app.SaveUIState(); ASSERT_TRUE(app.RestoreUIState(saved)); - std::vector windows = app.TakeSavedDocuments("documents"); + std::vector windows = docking::TakeSavedDocuments(dockingContext, "documents"); ASSERT_EQ(windows.size(), 1u); - DocumentSet fresh; - Document& again = AddDocument(app, fresh, "Forest", ".level", "level", { "Viewport" }); + docking::DocumentSet fresh; + docking::Document& again = AddDocument(app, dockingContext, fresh, "Forest", ".level", "level", { "Viewport" }); std::unordered_map cameras; - auto keep = [&cameras](Panel& panel) { + auto keep = [&cameras](docking::Panel& panel) { panel.restoreState = [&cameras, id = panel.id](std::string_view state) { cameras[id] = state; }; }; for (auto& [id, panel] : again.layout.panels) keep(panel); std::vector made; - ASSERT_TRUE(app.RestoreDocumentLayout(again, windows[0].documents[0], [&](std::string_view key) -> std::optional { + ASSERT_TRUE(docking::RestoreDocumentLayout(app, dockingContext, again, windows[0].documents[0], [&](std::string_view key) -> std::optional { made.emplace_back(key); - const ID id = app.CreatePanel(again.layout.panels, std::string(key), IconID::Invalid, [] {}); + const ID id = docking::CreatePanel(app, dockingContext, again.layout.panels, std::string(key), IconID::Invalid, [] {}); keep(again.layout.panels.at(id)); return id; })); @@ -655,26 +657,26 @@ namespace TEST_F(UIStateTest, WhatCantBeReadOfSavedDocumentsIsSkipped) { const ID windowID = app.idManager.CreateStaticID(); - DocumentSet set; - app.PersistDocuments("documents", [&] { return std::vector{ { windowID, &set } }; }); + docking::DocumentSet set; + docking::PersistDocuments(app, dockingContext, "documents", [&] { return std::vector{ { windowID, &set } }; }); ASSERT_TRUE(app.RestoreUIState(R"({"documents":{"documents":[ {"active":9,"documents":[{"name":"Forest","kind":"level","layout":"not a tree"},{"kind":"level"},{"name":"Desert"}]}, {"active":0,"documents":[]}, "not a window" ]}})")); - std::vector windows = app.TakeSavedDocuments("documents"); + std::vector windows = docking::TakeSavedDocuments(dockingContext, "documents"); ASSERT_EQ(windows.size(), 1u) << "a window without documents is left out"; ASSERT_EQ(windows[0].documents.size(), 2u) << "a document without a name is left out"; EXPECT_EQ(windows[0].documents[1].name, "Desert"); EXPECT_EQ(windows[0].documents[1].extension, ""); EXPECT_EQ(windows[0].active, 1) << "the last one, as there's no tenth"; - Document& forest = AddDocument(app, set, "Forest", ".level", "level", { "Scene" }); - const DockNode* before = forest.layout.root.get(); - EXPECT_FALSE(app.RestoreDocumentLayout(forest, windows[0].documents[0])); + docking::Document& forest = AddDocument(app, dockingContext, set, "Forest", ".level", "level", { "Scene" }); + const docking::DockNode* before = forest.layout.root.get(); + EXPECT_FALSE(docking::RestoreDocumentLayout(app, dockingContext, forest, windows[0].documents[0])); EXPECT_EQ(forest.layout.root.get(), before) << "its own layout stays"; - EXPECT_FALSE(app.RestoreDocumentLayout(forest, windows[0].documents[1])) << "none saved"; - EXPECT_TRUE(app.TakeSavedDocuments("other").empty()); + EXPECT_FALSE(docking::RestoreDocumentLayout(app, dockingContext, forest, windows[0].documents[1])) << "none saved"; + EXPECT_TRUE(docking::TakeSavedDocuments(dockingContext, "other").empty()); } // A document window's place is kept, and comes back like a persisted window's. @@ -688,20 +690,20 @@ namespace ON_CALL(app.MockBackend(), GetWindowRect(_)).WillByDefault(::testing::Return(IntRect{ 2100, 150, 800, 600 })); const ID documentWindow = app.idManager.CreateStaticID(); app.Frame([&] { (void)app.windowManager->GetOrCreateWindow(documentWindow, "Docs", IntRect{ 2100, 150, 800, 600 }, nullptr); }); - DocumentSet set; - AddDocument(app, set, "Forest", ".level", "level", { "Scene" }); - app.PersistDocuments("documents", [&] { return std::vector{ { documentWindow, &set } }; }); + docking::DocumentSet set; + AddDocument(app, dockingContext, set, "Forest", ".level", "level", { "Scene" }); + docking::PersistDocuments(app, dockingContext, "documents", [&] { return std::vector{ { documentWindow, &set } }; }); const std::string saved = app.SaveUIState(); ASSERT_TRUE(app.RestoreUIState(saved)); - std::vector windows = app.TakeSavedDocuments("documents"); + std::vector windows = docking::TakeSavedDocuments(dockingContext, "documents"); ASSERT_EQ(windows.size(), 1u); EXPECT_EQ(windows[0].rect, (IntRect{ 2100, 150, 800, 600 })); EXPECT_EQ(windows[0].monitor, (IntRect{ 1920, 0, 2560, 1440 })); // Made again in a new run, at a new ID: where it was. const ID again = app.idManager.CreateStaticID(); - app.RestoreWindowPlace(again, windows[0]); + docking::RestoreWindowPlace(app, again, windows[0]); app.Frame([&] { if (app.BeginWindow(again, "Docs", LayoutOverride{}.Size(300, 200).Position(10, 20))) app.Label("inside"); @@ -713,11 +715,11 @@ namespace EXPECT_EQ(r.w, 800); // Saved with the big monitor on the left, now on the right: the same place on it. - SavedDocumentWindow moved = windows[0]; + docking::SavedDocumentWindow moved = windows[0]; moved.rect = IntRect{ -2460, 150, 800, 600 }; moved.monitor = IntRect{ -2560, 0, 2560, 1440 }; const ID rearranged = app.idManager.CreateStaticID(); - app.RestoreWindowPlace(rearranged, moved); + docking::RestoreWindowPlace(app, rearranged, moved); app.Frame([&] { if (app.BeginWindow(rearranged, "Docs", LayoutOverride{}.Size(300, 200).Position(10, 20))) app.Label("inside"); @@ -727,7 +729,7 @@ namespace // No place saved: the app's own. const ID unplaced = app.idManager.CreateStaticID(); - app.RestoreWindowPlace(unplaced, SavedDocumentWindow{}); + docking::RestoreWindowPlace(app, unplaced, docking::SavedDocumentWindow{}); app.Frame([&] { if (app.BeginWindow(unplaced, "Docs", LayoutOverride{}.Size(300, 200).Position(10, 20))) app.Label("inside"); diff --git a/tests/view_state_test.cpp b/tests/view_state_test.cpp index 9c57c85c..6ba9e168 100644 --- a/tests/view_state_test.cpp +++ b/tests/view_state_test.cpp @@ -1,4 +1,4 @@ -// A view's own state as text, for a panel to keep with its layout (Panel::saveState): a node +// A view's own state as text, for a panel to keep with its layout (docking::Panel::saveState): a node // view's pan and zoom, the part of a curve plot in view, the settings page open. Each comes back as it was; text that can't be read changes nothing. #include @@ -7,6 +7,7 @@ #include #include #include +#include namespace tachyon { From 3f6911488b0f0b78826c7b430c664b896865523a Mon Sep 17 00:00:00 2001 From: Sander van Rossen Date: Fri, 4 Dec 2026 18:08:09 +0100 Subject: [PATCH 8/9] Say which library each control is in (#350) The controls index has a library column and says how the libraries' controls are called; the build page and README list the libraries; the contributor guide covers frame hooks, PersistJson and the public helpers for controls outside GUIApplication; the tutorial links gui_docking. --- README.md | 4 +- docs/contributing/writing-controls.md | 45 +++++++++++++++++++- docs/controls.md | 59 ++++++++++++++++----------- docs/integration/build.md | 8 ++++ docs/tutorial/app.md | 3 +- docs/tutorial/buttons.md | 5 ++- docs/tutorial/setup.md | 3 +- examples/tutorial/my_app.h | 1 - 8 files changed, 95 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index 77447094..9e028fb4 100644 --- a/README.md +++ b/README.md @@ -178,7 +178,9 @@ target_link_libraries(my_app PRIVATE TachyonUI::gui_controls TachyonUI::gui_back ``` `gui_backend_default` brings in the graphics and window backends; an app with backends of its -own leaves it out. The shaders, default themes and fonts are built into the libraries and SDL +own leaves it out. The controls beyond the basic ones are libraries of their own, linked when +used: `gui_views` (lists, trees, grids, tables), `gui_docking` (docked panels and documents), +`gui_nodes` (the node view), `gui_color`, `gui_curves` and `gui_dialogs`. The shaders, default themes and fonts are built into the libraries and SDL is linked statically, so there are no extra files or DLLs to ship. Packaging, subprojects, your own themes and system libraries are covered in [docs/integration.md](docs/integration.md). diff --git a/docs/contributing/writing-controls.md b/docs/contributing/writing-controls.md index 1f198faa..ba800c02 100644 --- a/docs/contributing/writing-controls.md +++ b/docs/contributing/writing-controls.md @@ -972,8 +972,8 @@ A pen on a tablet or pen display drives the pointer as a mouse does. ## Controls outside GUIApplication -A library of controls on top of `gui_controls` (such as `gui_dialogs`), or an app's own, -can't add members to `GUIApplication`. Its controls are free functions in a namespace of its +A library of controls on top of `gui_controls` (such as `gui_views` or `gui_dialogs`), or an +app's own, can't add members to `GUIApplication`. Its controls are free functions in a namespace of its own, and they take the app. - The app comes first, then the library's context; the rest is as a member control's @@ -1016,6 +1016,29 @@ own, and they take the app. - A lambda that runs later (an event handler, a post-layout callback) holds a pointer to the context, which lives as long as the app. + - `std::function` keeps what a lambda holds inline up to 48 bytes (MSVC); beyond that, it + allocates. For a handler made for every row or node each frame, keep its captures small: + a reference to the context, and values, rather than a reference to each part of it. +- Work at points of the frame `OnGUI` doesn't reach (before the frame is built, after its + input, before a theme reload clears the styles) is registered once, after `Initialize`, + with the hooks the app offers. `docking::Install` does it this way: + + ```cpp + app.OnFrameStage(FrameStage::PreConstruct, [&app, &context] { BeginFrame(app, context); }); + app.OnInputDispatched([&app, &context](std::span actedOn) { ReportChangedPanels(app, context, actedOn); }); + app.OnBeforeStylesCleared([&app, &context] { + for (DockingLayout* layout : context.layoutsThisFrame) + if (layout) DisableAllPanels(app, context, *layout); + }); + ``` + + - A hook holds the context by reference, so the context can't move: delete its copy + constructor. + - Cleanup stays a function the app calls: `GUIApplication`'s destructor may run its + `Cleanup` after the app's own members are gone. +- What it keeps in the saved UI state goes through `PersistJson`: what its `save` function + gives is kept under a section and a key, and `RestoreUIState` hands it to its `restore` + function. `views::PersistTable` is built on it. - What a control inside `GUIApplication` uses that isn't otherwise public is in the "For controls outside GUIApplication" group of `gui_application.h`: - `ScheduleFrameAt`: a frame at a later time, for a control that changes by itself @@ -1025,6 +1048,24 @@ own, and they take the app. - `ButtonGroupItemStyle` and `NoteButtonGroupItem`: a button of its own inside `BeginButtonGroup` - `LastStatusBar`: where a window's status bar is + - `StylesGeneration`: when to look the styles up again + - `ReportMisuse`: an End without its Begin, and the like + - `RegisterTabStop`: a control in the Tab order + - `TitleBarCaption`: a strip in the title bar that drags the window + - `ClaimCommandMode`: the command mode while the focus is in the control + - `RebuildCachedScopesAbove`: a cached scope around the control built again + - `ContextMenuScreenPos`: where the context menu opening was asked for + - `PendingLabelText`: the label just before the control, for a popup's title + - `BeginFieldBox` and `EndFieldBox`: a field with a caption or a unit + - `SetFieldRowFill`: fields that fill their row (a node's property row) + - `ClaimSwatchStyle`, `NoteSwatchClaim` and `ReplayedSwatches`: color swatches + - `CollectPropagatedAncestors`: the elements around one that show its state + - `ReorderDrag`, `CurrentTabBar`, `CurrentTab` and `CurrentWindowID`: the drag and the + tab bar, tab and window being built + - `OnFrameStage`, `OnInputDispatched` and `OnBeforeStylesCleared`: the hooks above + - `PersistJson`, `SaveWindowPlace`, `ReadWindowPlace` and `RestoreWindowPlace`: saved UI state +- In `GUITheme`: `VariableColor`, a theme color looked up again after each load, and + `RegisterDropdownParts`, a dropdown trigger's text and arrow parts. ## Decide for each control diff --git a/docs/controls.md b/docs/controls.md index a0960e79..26e6007c 100644 --- a/docs/controls.md +++ b/docs/controls.md @@ -1,8 +1,19 @@ # Controls -Every control is a member function of `tachyon::GUIApplication`. Your application is a -subclass of it and builds its whole UI again each frame, in `OnGUI()`. The examples on -these pages are written as if inside that `OnGUI()`, with `using namespace tachyon;`. +Your application is a subclass of `tachyon::GUIApplication` and builds its whole UI again +each frame, in `OnGUI()`. The examples on these pages are written as if inside that +`OnGUI()`, with `using namespace tachyon;`. + +- The basic controls (windows, buttons, fields, menus, tab bars, toolbars and more) are + member functions of `GUIApplication`, in `gui_controls`. +- The others are in libraries of their own, built on `gui_controls`: + - each library has a namespace: `views`, `nodes`, `docking`, `color`, `curves`, `dialogs` + - its controls are free functions that take the app first, then a context your app owns + (a member of your app class), for example `views::Cell(*this, viewsContext, name)` + - link its target and include its header: `TachyonUI::gui_views` and + ``, say + - each page says what its controls need: some libraries want a call at the end of + `OnGUI` or before `Cleanup` ```cpp class MyApp : public tachyon::GUIApplication @@ -23,27 +34,27 @@ public: Read [Common conventions](controls/conventions.md) first: it explains the parameters and results all controls share. -| Page | Covers | -| --- | --- | -| [Common conventions](controls/conventions.md) | Parameter order, return values, callbacks, `LayoutOverride`, state scopes | -| [Windows and layout](controls/windows-and-layout.md) | Windows, horizontal and vertical groups, areas, scroll bars, caching, label and button groups, `Segmented` | -| [Text and images](controls/text-and-images.md) | `Text`, `Label`, `DragLabel`, `SelectableText`, `Image` | -| [Buttons and toggles](controls/buttons-and-toggles.md) | `Button`, `CommandButton`, `Toggle`, `Switch`, `Checkbox` | -| [Fields](controls/fields.md) | Text, search, numeric, vector and typed fields, edge, corner and shadow fields, dropdowns, lists, dictionaries | -| [Sliders](controls/sliders.md) | `SliderField`, `Slider`, `RangeField` | -| [Color and gradient fields](controls/color-and-gradient.md) | `ColorField`, `GradientField` and their pickers | -| [Curves](controls/curves.md) | `CurveField` and its curve editor, `EvaluateCurve` | -| [Plots](controls/plots.md) | `Plot`: histograms and other series, with handles (Levels) | -| [Menus](controls/menus.md) | Menus, menu items, menu bar, title bar, context menus | -| [Tooltips and message dialogs](controls/tooltips-and-dialogs.md) | Tooltips, modal `MessageDialog` | -| [Lists and reorderable groups](controls/lists.md) | List views, drag-to-reorder groups | -| [Tables](controls/tables.md) | Tables, virtual tables, tree cells | -| [Tree and grid views](controls/trees-and-grids.md) | `VirtualTreeView`, grid views, virtual grid views | -| [Tabs, docking and toolbars](controls/tabs-docking-toolbars.md) | Tab bars, docking containers, toolbars, toolbar dock | -| [Node view](controls/node-view.md) | `RenderNodeView` node graph editor | -| [Other controls](controls/other-controls.md) | Breadcrumb, status bar, progress bars, spinners and skeletons, task progress and background tasks, command search, settings panel | -| [Custom drawing](controls/custom-drawing.md) | Drawing shapes and text inside an element | -| [Default CSS classes](controls/css-classes.md) | Each control's class when you pass no style | +| Page | Library | Covers | +| --- | --- | --- | +| [Common conventions](controls/conventions.md) | | Parameter order, return values, callbacks, `LayoutOverride`, state scopes | +| [Windows and layout](controls/windows-and-layout.md) | `gui_controls` | Windows, horizontal and vertical groups, areas, scroll bars, caching, label and button groups, `Segmented` | +| [Text and images](controls/text-and-images.md) | `gui_controls` | `Text`, `Label`, `DragLabel`, `SelectableText`, `Image` | +| [Buttons and toggles](controls/buttons-and-toggles.md) | `gui_controls` | `Button`, `CommandButton`, `Toggle`, `Switch`, `Checkbox` | +| [Fields](controls/fields.md) | `gui_controls`; the shadow field `gui_color` | Text, search, numeric, vector and typed fields, edge, corner and shadow fields, dropdowns, lists, dictionaries | +| [Sliders](controls/sliders.md) | `gui_controls` | `SliderField`, `Slider`, `RangeField` | +| [Color and gradient fields](controls/color-and-gradient.md) | `gui_color` | `ColorField`, `GradientField` and their pickers | +| [Curves](controls/curves.md) | `gui_curves` | `CurveField` and its curve editor, `EvaluateCurve` | +| [Plots](controls/plots.md) | `gui_curves` | `Plot`: histograms and other series, with handles (Levels) | +| [Menus](controls/menus.md) | `gui_controls` | Menus, menu items, menu bar, title bar, context menus | +| [Tooltips and message dialogs](controls/tooltips-and-dialogs.md) | `gui_controls`; message dialogs `gui_dialogs` | Tooltips, modal `MessageDialog` | +| [Lists and reorderable groups](controls/lists.md) | `gui_views`; reorderable groups `gui_controls` | List views, drag-to-reorder groups | +| [Tables](controls/tables.md) | `gui_views` | Tables, virtual tables, tree cells | +| [Tree and grid views](controls/trees-and-grids.md) | `gui_views` | `VirtualTreeView`, grid views, virtual grid views | +| [Tabs, docking and toolbars](controls/tabs-docking-toolbars.md) | `gui_controls`; docking `gui_docking` | Tab bars, docking containers, toolbars, toolbar dock | +| [Node view](controls/node-view.md) | `gui_nodes` | `RenderNodeView` node graph editor | +| [Other controls](controls/other-controls.md) | `gui_controls`; progress and toasts `gui_dialogs`, the settings panel `gui_views` | Breadcrumb, status bar, progress bars, spinners and skeletons, task progress and background tasks, command search, settings panel | +| [Custom drawing](controls/custom-drawing.md) | `gui_controls` | Drawing shapes and text inside an element | +| [Default CSS classes](controls/css-classes.md) | | Each control's class when you pass no style | Two more controls are example code rather than the library. They're in `examples/app_controls`, and show how an app writes controls of its own; copy them, or use them as a model: diff --git a/docs/integration/build.md b/docs/integration/build.md index 0f64f800..320ee882 100644 --- a/docs/integration/build.md +++ b/docs/integration/build.md @@ -7,6 +7,11 @@ TachyonUI is a set of static libraries: - the extensions, more controls on top of `gui_controls`, each a library of its own that an app links only when it uses it: - `gui_dialogs`: message dialogs, toasts, banners and progress (bars, spinners, tasks) + - `gui_views`: list views, tree views, grid views, tables and the settings panel + - `gui_docking`: docked and floating panels, documents and layout presets + - `gui_nodes`: the node view and state machines + - `gui_color`: color and gradient fields and their pickers, shadow fields + - `gui_curves`: curve fields, the curve editor and plots - the backends, each a library of its own: - `gui_backend_vulkan`, `gui_backend_d3d12`, `gui_backend_metal` and `gui_backend_sdlgpu`: the graphics backends, the part that draws @@ -20,6 +25,9 @@ target_link_libraries(my_app PRIVATE TachyonUI::gui_controls TachyonUI::gui_back ``` - `gui_controls` brings in `gui_core`. +- Add the extensions the app uses, for example + `target_link_libraries(my_app PRIVATE TachyonUI::gui_docking TachyonUI::gui_views)`. + - Each brings in `gui_controls`. - `gui_backend_default` brings in the backends the build has (see the options below). - Link it to the program itself, not to a library of yours that the program links. - It's an object library: CMake adds its object file only to the targets that link it diff --git a/docs/tutorial/app.md b/docs/tutorial/app.md index b45d6319..ee973e0e 100644 --- a/docs/tutorial/app.md +++ b/docs/tutorial/app.md @@ -3,8 +3,7 @@ ## The app class The app class owns the panels, the window and the dock layout. The dock layout describes -how the panels are arranged in the window. At the end of `my_app.h`, after -`#include ` at its top: +how the panels are arranged in the window. At the end of `my_app.h`: ```cpp diff --git a/docs/tutorial/buttons.md b/docs/tutorial/buttons.md index 38440955..d18a4df8 100644 --- a/docs/tutorial/buttons.md +++ b/docs/tutorial/buttons.md @@ -6,10 +6,11 @@ Each panel is a class: - It holds the panel's values. - Its `Draw` function builds the panel's controls. -- Controls are members of `tachyon::GUIApplication`, so `Draw` takes the app. +- The basic controls, such as buttons and fields, are members of `tachyon::GUIApplication`, + so `Draw` takes the app. In `my_app.h`, after `#include `, -`#include ` and `#include `: +`#include ` and `#include `: ```cpp namespace my_app diff --git a/docs/tutorial/setup.md b/docs/tutorial/setup.md index 96acc1e1..25ea6f01 100644 --- a/docs/tutorial/setup.md +++ b/docs/tutorial/setup.md @@ -38,11 +38,12 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON) add_subdirectory(external/TachyonUI) add_executable(my_app main.cpp my_app.cpp my_app.h) -target_link_libraries(my_app PRIVATE TachyonUI::gui_controls TachyonUI::gui_backend_default) +target_link_libraries(my_app PRIVATE TachyonUI::gui_docking TachyonUI::gui_controls TachyonUI::gui_backend_default) ``` - `gui_controls` is the UI, and `gui_backend_default` the backends it draws and opens windows with: Vulkan (Metal on macOS) and SDL. +- `gui_docking` is the docked panels the app is made of, a library on top of `gui_controls`. - Shaders, theme and fonts are built in, and SDL is linked in. No files or DLLs go next to the program. diff --git a/examples/tutorial/my_app.h b/examples/tutorial/my_app.h index c8f45f19..6396715d 100644 --- a/examples/tutorial/my_app.h +++ b/examples/tutorial/my_app.h @@ -4,7 +4,6 @@ #pragma once #include -#include #include #include From a981b2b69533f7efa9cfa76e97c2fe38379cbe73 Mon Sep 17 00:00:00 2001 From: Sander van Rossen Date: Fri, 4 Dec 2026 18:12:02 +0100 Subject: [PATCH 9/9] Close the docking context in the static ID test (#350) --- tests/static_id_release_test.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/static_id_release_test.cpp b/tests/static_id_release_test.cpp index 328f8a19..724d3076 100644 --- a/tests/static_id_release_test.cpp +++ b/tests/static_id_release_test.cpp @@ -25,7 +25,7 @@ namespace tachyon color::Context colorContext; dialogs::Context dialogContext; void SetUp() override { ASSERT_TRUE(app.Initialize()); } - void TearDown() override { dialogs::Cleanup(app, dialogContext); color::Cleanup(app, colorContext); app.Cleanup(); } + void TearDown() override { docking::Cleanup(app, dockingContext); dialogs::Cleanup(app, dialogContext); color::Cleanup(app, colorContext); app.Cleanup(); } }; // A panel CreatePanel made an ID for goes with that ID when its tab is closed; one given @@ -114,7 +114,7 @@ namespace tachyon dockingContext.floatingDockWindows.push_back(std::move(fw)); ASSERT_GT(app.idManager.GetStaticIDCount(), 0u); - dialogs::Cleanup(app, dialogContext); color::Cleanup(app, colorContext); app.Cleanup(); + docking::Cleanup(app, dockingContext); dialogs::Cleanup(app, dialogContext); color::Cleanup(app, colorContext); app.Cleanup(); EXPECT_EQ(app.idManager.GetStaticIDCount(), 0u); EXPECT_TRUE(dockingContext.floatingDockWindows.empty()); }