diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ea2e1fb..e315cdb8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,9 +14,15 @@ 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` 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)`. +- Curves are an extension, `gui_curves` (`TachyonUI::gui_curves`, ``, namespace `tachyon::curves`): `CurveField`, `CurveEditor` and `Plot` take the app and a `curves::Context` the app owns, `curves::CurveField(app, curvesContext, curve)`, and their types and functions (`curves::CurveView`, `curves::EvaluateCurve`, `curves::HistogramBins` and the rest) are in the namespace. Their styles moved from `GUITheme` to `curves::GetStyles`. `GUIApplication::ContextMenuScreenPos` is public for them. +- Color is an extension, `gui_color` (`TachyonUI::gui_color`, ``, namespace `tachyon::color`): `ColorField`, `GradientField`, `ShadowField`, `SetColorSwatches`, `ColorSwatches` and `AddRecentColor` take the app and a `color::Context` the app owns, which holds the picker's and the gradient editor's state; the app calls `color::EndGUI` last in `OnGUI` and `color::Cleanup` before its own cleanup. Their styles moved from `GUITheme` to `color::GetStyles`. The swatch slots stay in `gui_controls`: `ClaimSwatchStyle`, `NoteSwatchClaim` and `ReplayedSwatches` are public, as are `SetColorStyle` (`gui_core/style/gui_style_manager.h`), `PendingLabelText`, `BeginFieldBox`, `EndFieldBox` and `ReportMisuse`. +- Views are an extension, `gui_views` (`TachyonUI::gui_views`, ``, namespace `tachyon::views`): the list view, the tree views, the grid views, the tables and the settings panel take the app and a `views::Context` the app owns, `views::VirtualTable(app, viewsContext, id, tableState, columns, rowCount)`, which holds the rename in progress, the column and tree drags and what's being built; the app calls `views::EndGUI` last in `OnGUI`. The scopes are `views::Table`, `views::Row`, `views::ListView` and `views::GridView`. Their types (`views::TableState`, `views::TreeViewRow`, `views::SettingsPanelState` and the rest) and `views::TreeUtils` are in the namespace. Their styles and the table and tree-table sizes moved from `GUITheme` to `views::GetStyles`; `GUITheme::gridViewItemLineHeight`, which nothing read, is gone. `PersistTable` is `views::PersistTable`, built on the new `GUIApplication::PersistJson`, which keeps a library's own state in the saved UI state; saved tables load as before. `RegisterTabStop` is public. +- The node view is an extension, `gui_nodes` (`TachyonUI::gui_nodes`, ``, namespace `tachyon::nodes`), state machines included: `RenderNodeView` and `NodeText` take the app and a `nodes::Context` the app owns, `nodes::RenderNodeView(app, nodesContext, view)`, and the graph's types and functions (`nodes::NodeView`, `nodes::CommitNodeViewEdit` and the rest) are in the namespace. Their styles, colors and sizes (`nodeGridSize`, `socketSize`, `nodeTints`) moved from `GUITheme` to `nodes::GetStyles`. A text-only property's alignments are the CSS classes `.node-text`, `.node-text-center` and `.node-text-end`. `SaveViewState` and `RestoreViewState` for each library's views are in that library; `gui_controls/gui_view_state.h` is gone. `BeginTooltip` takes a `TooltipBox` look, `SetFieldRowFill` makes the fields built fill their row, and `CollectPropagatedAncestors` is public. +- Docking is an extension, `gui_docking` (`TachyonUI::gui_docking`, ``, namespace `tachyon::docking`): docked and floating panels, documents and layout presets. `CreatePanel`, `BeginDockingContainer`, `EmitFloatingDockWindows`, `Documents`, `ClosePanel`, `ApplyDockLayout` and the rest take the app and a `docking::Context` the app owns, and the dock tree's types and functions (`docking::DockingLayout`, `docking::MakeLeaf` and the rest) are in the namespace. It works at points of the frame `OnGUI` doesn't reach, so the app calls `docking::Install` once after `Initialize` and `docking::Cleanup` before its own cleanup. `PersistDocking`, `PersistDocuments`, `PersistLayoutPresets`, `TakeSavedDocuments` and `RestoreDocumentLayout` are docking's, on `GUIApplication::PersistJson`; saved files load as before. Its styles moved from `GUITheme` to `docking::GetStyles`. The tab bar stays in `gui_controls`, its types in ``. For libraries that hook into the frame, `GUIApplication` has `OnFrameStage`, `OnInputDispatched` and `OnBeforeStylesCleared`; and `WindowPlace`, `SaveWindowPlace`, `ReadWindowPlace` and `RestoreWindowPlace`, `TitleBarCaption`, `ReorderDrag`, `CurrentWindowID`, `CurrentTabBar` and `CurrentTab` are public. - 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 +141,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 +153,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 +262,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 +271,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/CMakeLists.txt b/CMakeLists.txt index 3688861e..1e14d77f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -150,7 +150,7 @@ if(TACHYON_INSTALL) # gui_backend_default is an object library: its object file is installed, and a program # that links it gets that file on its link line. - install(TARGETS gui_core gui_controls gui_dialogs ${TACHYON_BACKEND_TARGETS} + install(TARGETS gui_core gui_controls gui_dialogs gui_curves gui_color gui_views gui_nodes gui_docking ${TACHYON_BACKEND_TARGETS} EXPORT TachyonUITargets ARCHIVE DESTINATION "lib/$" OBJECTS DESTINATION "lib/$/objects") @@ -160,7 +160,7 @@ if(TACHYON_INSTALL) if(NOT TACHYON_SDL) list(APPEND _tachyon_header_excludes PATTERN "sdl" EXCLUDE) endif() - install(DIRECTORY src/gui_core src/gui_controls src/gui_dialogs + install(DIRECTORY src/gui_core src/gui_controls src/gui_dialogs src/gui_curves src/gui_color src/gui_views src/gui_nodes src/gui_docking DESTINATION include FILES_MATCHING PATTERN "*.h" ${_tachyon_header_excludes}) @@ -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/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/cmake/TachyonUIConfig.cmake.in b/cmake/TachyonUIConfig.cmake.in index a4b21e96..51427c6e 100644 --- a/cmake/TachyonUIConfig.cmake.in +++ b/cmake/TachyonUIConfig.cmake.in @@ -8,6 +8,11 @@ # Provides: # TachyonUI::gui_core, TachyonUI::gui_controls static libraries: the UI, with no backend # TachyonUI::gui_dialogs message dialogs, toasts, banners and progress +# TachyonUI::gui_curves curve fields, the curve editor and plots +# TachyonUI::gui_color color and gradient fields, their pickers, shadow fields +# TachyonUI::gui_views list, tree and grid views, tables, the settings panel +# TachyonUI::gui_nodes the node view and state machines +# TachyonUI::gui_docking docked and floating panels, documents, layout presets # TachyonUI::gui_backend_default the backends the package has, registered # before main (link it directly) # TachyonUI::gui_backend_vulkan, _d3d12, _sdlgpu, each backend on its own, for an app that diff --git a/docs/Doxyfile b/docs/Doxyfile index 67d68d83..1f73962f 100644 --- a/docs/Doxyfile +++ b/docs/Doxyfile @@ -6,7 +6,7 @@ PROJECT_NUMBER = $(TACHYON_VERSION) PROJECT_BRIEF = "High-performance UI for building tools." PROJECT_LOGO = docs/doxygen/logo.svg OUTPUT_DIRECTORY = $(DOXYGEN_OUTPUT) -INPUT = src/gui_core src/gui_controls src/gui_dialogs docs +INPUT = src/gui_core src/gui_controls src/gui_dialogs src/gui_curves src/gui_color src/gui_views src/gui_nodes src/gui_docking docs RECURSIVE = YES FILE_PATTERNS = *.h *.md *.dox EXCLUDE = docs/design docs/doxygen docs/contributing diff --git a/docs/contributing/writing-controls.md b/docs/contributing/writing-controls.md index d183a959..ba800c02 100644 --- a/docs/contributing/writing-controls.md +++ b/docs/contributing/writing-controls.md @@ -584,15 +584,15 @@ For a control that opens a popup, such as a list, a picker or a menu: const auto trackRef = RegisterControl(std::move(track), std::move(constraints).FlexGrow(1)); ``` -- [ ] In a node row, a field fills the row like the others. `nodeRowFieldMinWidth` is set - while a node row is drawn. +- [ ] In a row that fills, a field fills the row like the others. The node view sets + `SetFieldRowFill` while it draws a node's property row. For example, in `Field`: ```cpp - // Inside a node row, fill the body after the label so the node stays grid-aligned. - if (nodeRowFieldMinWidth > 0 && !constraints.HasFixedWidth()) - constraints.FlexGrow(1).MinWidth(Pixels{ nodeRowFieldMinWidth }); + // In a row that fills (SetFieldRowFill), fill the body after the label. + if (m_fieldRowFill > 0 && !constraints.HasFixedWidth()) + constraints.FlexGrow(1).MinWidth(Pixels{ m_fieldRowFill }); ``` **Frame and cache** @@ -972,46 +972,75 @@ 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. +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; 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. + - `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 - 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 @@ -1019,6 +1048,24 @@ can't add members to `GUIApplication`. Its controls are free functions that take - `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 e7337b2c..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,29 +34,35 @@ public: Read [Common conventions](controls/conventions.md) first: it explains the parameters and results all controls share. +| 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: + | 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) | | [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 | -| [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 | | [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 | +```cpp +void MyApp::Cleanup() +{ + docking::Cleanup(*this, m_docking); // the floated panels' windows, before the library's own + GUIApplication::Cleanup(); +} +``` + ## Every frame @@ -68,9 +88,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..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/app_controls/CMakeLists.txt b/examples/app_controls/CMakeLists.txt index 18f8a4f8..2eeabcb3 100644 --- a/examples/app_controls/CMakeLists.txt +++ b/examples/app_controls/CMakeLists.txt @@ -1,6 +1,18 @@ # App-level parts the examples build on, which belong to one kind of app rather than the -# library: the file system, file icons and thumbnails of the showcase's Files panel. +# library: the file system, file icons and thumbnails of the showcase's Files panel, and a +# timeline and a 3D viewport, written on the library's public API. Their styles are in +# themes/app_controls.css. add_library(tachyon_app_controls STATIC + gui_app_controls.h + gui_app_controls.cpp + gui_timeline_types.h + gui_timeline_internal.h + gui_timeline_helpers.cpp + controls_timeline.cpp + controls_timeline_editor.cpp + gui_viewport_types.h + gui_viewport_helpers.cpp + controls_viewport.cpp gui_file_system.h gui_file_system.cpp gui_file_icons.h @@ -9,6 +21,6 @@ add_library(tachyon_app_controls STATIC gui_file_thumbnails.cpp) # Included as . target_include_directories(tachyon_app_controls PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/..") -target_link_libraries(tachyon_app_controls PUBLIC gui_core) +target_link_libraries(tachyon_app_controls PUBLIC gui_controls) tachyon_apply_compile_options(tachyon_app_controls) set_target_properties(tachyon_app_controls PROPERTIES FOLDER "Examples") diff --git a/src/gui_controls/controls_timeline.cpp b/examples/app_controls/controls_timeline.cpp similarity index 74% rename from src/gui_controls/controls_timeline.cpp rename to examples/app_controls/controls_timeline.cpp index d2fad6c4..0990bcc9 100644 --- a/src/gui_controls/controls_timeline.cpp +++ b/examples/app_controls/controls_timeline.cpp @@ -1,5 +1,5 @@ -#include -#include +#include +#include #include #include @@ -8,7 +8,7 @@ #include #include -namespace tachyon +namespace tachyon::app_controls { // --------------------------------------------------------------------------- @@ -81,8 +81,9 @@ namespace tachyon return state.time != before; } - bool GUIApplication::Timeline(ID id, TimelineState& state, const TimelineOptions& options, LayoutOverride&& constraints) + bool Timeline(GUIApplication& app, Context& context, ID id, TimelineState& state, const TimelineOptions& options, LayoutOverride&& constraints) { + const Styles& styles = GetStyles(app, context); const float length = LengthOf(options); const float frame = FrameOf(options); const float step = StepOf(options); @@ -92,32 +93,32 @@ namespace tachyon TimelineState* s = &state; bool changed = false; - BeginHorizontal(id, theme.timelineStyleRef, std::move(constraints)); - [[maybe_unused]] const bool pushed = idManager.PushParent(id); + app.BeginHorizontal(id, styles.timelineStyleRef, std::move(constraints)); + [[maybe_unused]] const bool pushed = app.idManager.PushParent(id); - BeginHorizontal(idManager.AllocateDynamicID("transport"), theme.timelineTransportStyleRef); - changed |= Button(idManager.AllocateDynamicID("start"), GUIContent(theme.timelineStartIcon, {}, "Go to the start"), - [s] { s->time = 0.0f; }, theme.timelineButtonStyleRef); - changed |= Button(idManager.AllocateDynamicID("back"), GUIContent(theme.timelineStepBackIcon, {}, "A frame back"), - [s, step] { s->time = std::max(0.0f, s->time - step); s->playing = false; }, theme.timelineButtonStyleRef); - changed |= Button(idManager.AllocateDynamicID("play"), - state.playing ? GUIContent(theme.timelinePauseIcon, {}, "Pause") : GUIContent(theme.timelinePlayIcon, {}, "Play"), - [s, length] { TogglePlay(*s, length); }, theme.timelinePlayStyleRef); - changed |= Button(idManager.AllocateDynamicID("step"), GUIContent(theme.timelineStepIcon, {}, "A frame on"), - [s, step, length] { s->time = std::min(length, s->time + step); s->playing = false; }, theme.timelineButtonStyleRef); - changed |= Button(idManager.AllocateDynamicID("end"), GUIContent(theme.timelineEndIcon, {}, "Go to the end"), - [s, length] { s->time = length; s->playing = false; }, theme.timelineButtonStyleRef); - changed |= Toggle(idManager.AllocateDynamicID("loop"), state.loop, GUIContent(theme.timelineLoopIcon, {}, "Loop"), - [s](bool loop) { s->loop = loop; }, theme.timelineLoopStyleRef); - EndHorizontal(); + app.BeginHorizontal(app.idManager.AllocateDynamicID("transport"), styles.timelineTransportStyleRef); + changed |= app.Button(app.idManager.AllocateDynamicID("start"), GUIContent(styles.timelineStartIcon, {}, "Go to the start"), + [s] { s->time = 0.0f; }, styles.timelineButtonStyleRef); + changed |= app.Button(app.idManager.AllocateDynamicID("back"), GUIContent(styles.timelineStepBackIcon, {}, "A frame back"), + [s, step] { s->time = std::max(0.0f, s->time - step); s->playing = false; }, styles.timelineButtonStyleRef); + changed |= app.Button(app.idManager.AllocateDynamicID("play"), + state.playing ? GUIContent(app.theme.timelinePauseIcon, {}, "Pause") : GUIContent(app.theme.timelinePlayIcon, {}, "Play"), + [s, length] { TogglePlay(*s, length); }, styles.timelinePlayStyleRef); + changed |= app.Button(app.idManager.AllocateDynamicID("step"), GUIContent(styles.timelineStepIcon, {}, "A frame on"), + [s, step, length] { s->time = std::min(length, s->time + step); s->playing = false; }, styles.timelineButtonStyleRef); + changed |= app.Button(app.idManager.AllocateDynamicID("end"), GUIContent(styles.timelineEndIcon, {}, "Go to the end"), + [s, length] { s->time = length; s->playing = false; }, styles.timelineButtonStyleRef); + changed |= app.Toggle(app.idManager.AllocateDynamicID("loop"), state.loop, GUIContent(styles.timelineLoopIcon, {}, "Loop"), + [s](bool loop) { s->loop = loop; }, styles.timelineLoopStyleRef); + app.EndHorizontal(); // The time now, of the length, and the frame. - BeginHorizontal(idManager.AllocateDynamicID("time"), theme.timelineTimeStyleRef); - Text(idManager.AllocateDynamicID("now"), ClockText(state.time), theme.timelineTimeCurrentStyleRef); - Text(idManager.AllocateDynamicID("length"), "/ " + ClockText(length), theme.timelineTimeTotalStyleRef); + app.BeginHorizontal(app.idManager.AllocateDynamicID("time"), styles.timelineTimeStyleRef); + app.Text(app.idManager.AllocateDynamicID("now"), ClockText(state.time), styles.timelineTimeCurrentStyleRef); + app.Text(app.idManager.AllocateDynamicID("length"), "/ " + ClockText(length), styles.timelineTimeTotalStyleRef); if (frame > 0.0f) - Text(idManager.AllocateDynamicID("frame"), FrameText(state.time, frame, length), theme.timelineFrameStyleRef); - EndHorizontal(); + app.Text(app.idManager.AllocateDynamicID("frame"), FrameText(state.time, frame, length), styles.timelineFrameStyleRef); + app.EndHorizontal(); // The scrubber. Its handler runs from the input, after this call: copies of the markers. std::vector markers; @@ -127,13 +128,13 @@ namespace tachyon markers.push_back(marker); std::sort(markers.begin(), markers.end()); - const ID scrubberID = idManager.AllocateDynamicID("scrubber"); - const ElementState scrubberState = guiStateManager.GetCurrentState(scrubberID); + const ID scrubberID = app.idManager.AllocateDynamicID("scrubber"); + const ElementState scrubberState = app.guiStateManager.GetCurrentState(scrubberID); EventHandler scrub; - if (!guiStateManager.Construction().IsDisabled()) + if (!app.guiStateManager.Construction().IsDisabled()) { - GUIStateManager& gsm = guiStateManager; - const ElementStorage& es = elementStorage; + GUIStateManager& gsm = app.guiStateManager; + const ElementStorage& es = app.elementStorage; scrub = ReportingChanges(gsm, s, [&gsm, &es, s, length, frame, step, markers](ElementEvent&& event) -> bool { @@ -222,24 +223,24 @@ namespace tachyon } // Playing, the app moves the playhead on every frame: a cached scope holding it is // rebuilt every frame. - const ElementRef scrubberRef = RegisterControl( - Element{ .id = scrubberID, .eventHandler = std::move(scrub), .styleRef = theme.timelineScrubberStyleRef, + const ElementRef scrubberRef = app.RegisterControl( + Element{ .id = scrubberID, .eventHandler = std::move(scrub), .styleRef = styles.timelineScrubberStyleRef, .flags = state.playing ? ElementFlags::Animated : ElementFlags::None, .state = scrubberState }, LayoutOverride{}.FlexGrow(1)); - changed |= guiStateManager.Interaction().HasBeenClicked(scrubberID); + changed |= app.guiStateManager.Interaction().HasBeenClicked(scrubberID); const float progress = Finite(options.progress, -1.0f); const float time = state.time; - const VisualBoxStyleIndex readyStyle = theme.timelineReadyStyleRef.visualBoxStyleIndex; - const VisualBoxStyleIndex tickStyle = theme.timelineTickStyleRef.visualBoxStyleIndex; - const VisualBoxStyleIndex majorStyle = theme.timelineTickMajorStyleRef.visualBoxStyleIndex; - const VisualBoxStyleIndex markerStyle = theme.timelineMarkerStyleRef.visualBoxStyleIndex; - const VisualBoxStyleIndex playheadStyle = theme.timelinePlayheadStyleRef.visualBoxStyleIndex; - const int32_t px1 = std::max(1, styleManager.Px(1)), px2 = std::max(1, styleManager.Px(2)); - const int32_t minorHeight = styleManager.Px(4), majorHeight = styleManager.Px(8); - const int32_t headWidth = styleManager.Px(9), headHeight = styleManager.Px(5); - const float majorGap = float(styleManager.Px(48)), minorGap = float(styleManager.Px(6)); - VERIFY(elementStorage.AddCustomDraw(scrubberRef, + const VisualBoxStyleIndex readyStyle = styles.timelineReadyStyleRef.visualBoxStyleIndex; + const VisualBoxStyleIndex tickStyle = styles.timelineTickStyleRef.visualBoxStyleIndex; + const VisualBoxStyleIndex majorStyle = styles.timelineTickMajorStyleRef.visualBoxStyleIndex; + const VisualBoxStyleIndex markerStyle = styles.timelineMarkerStyleRef.visualBoxStyleIndex; + const VisualBoxStyleIndex playheadStyle = styles.timelinePlayheadStyleRef.visualBoxStyleIndex; + const int32_t px1 = std::max(1, app.styleManager.Px(1)), px2 = std::max(1, app.styleManager.Px(2)); + const int32_t minorHeight = app.styleManager.Px(4), majorHeight = app.styleManager.Px(8); + const int32_t headWidth = app.styleManager.Px(9), headHeight = app.styleManager.Px(5); + const float majorGap = float(app.styleManager.Px(48)), minorGap = float(app.styleManager.Px(6)); + VERIFY(app.elementStorage.AddCustomDraw(scrubberRef, [=](CustomDrawContext& ctx) { const IntRect outer = ctx.ElementRect(), inner = ctx.ElementInnerRect(); @@ -285,10 +286,10 @@ namespace tachyon })); if (pushed) - (void)idManager.PopParent(); - EndHorizontal(); + (void)app.idManager.PopParent(); + app.EndHorizontal(); - guiStateManager.SetModified(changed); + app.guiStateManager.SetModified(changed); return changed; } } diff --git a/src/gui_controls/controls_timeline_editor.cpp b/examples/app_controls/controls_timeline_editor.cpp similarity index 81% rename from src/gui_controls/controls_timeline_editor.cpp rename to examples/app_controls/controls_timeline_editor.cpp index 3f76213d..79efeb8b 100644 --- a/src/gui_controls/controls_timeline_editor.cpp +++ b/examples/app_controls/controls_timeline_editor.cpp @@ -1,5 +1,5 @@ -#include -#include +#include +#include #include #include @@ -12,7 +12,7 @@ #include #include -namespace tachyon +namespace tachyon::app_controls { // --------------------------------------------------------------------------- @@ -383,8 +383,9 @@ namespace tachyon }; } - void GUIApplication::TimelineEditor(ID id, TimelineViewRef view, LayoutOverride&& constraints) + void TimelineEditor(GUIApplication& app, Context& context, ID id, TimelineViewRef view, LayoutOverride&& constraints) { + const Styles& styles = GetStyles(app, context); // The tracks changed since this view last built (an edit here, or in another view of // them): let go of what's gone. PruneTimelineSelection(view); @@ -393,7 +394,7 @@ namespace tachyon const float frame = FrameOf(view); view.data.playback.time = std::clamp(Finite(view.data.playback.time, 0.0f), 0.0f, length); TimelineViewRef v = view; - const bool disabled = guiStateManager.Construction().IsDisabled(); + const bool disabled = app.guiStateManager.Construction().IsDisabled(); // The zoom slider moved last frame: show that much, round the playhead. Then the // slider shows the zoom, however it got there. @@ -412,121 +413,121 @@ namespace tachyon } const TimelineRange range = ViewRangeOf(view); const std::vector rows = ShownRows(view); - const int32_t rowHeight = styleManager.Px(28); + const int32_t rowHeight = app.styleManager.Px(28); - BeginVertical(id, theme.timelineEditorStyleRef, std::move(constraints)); - [[maybe_unused]] const bool pushed = idManager.PushParent(id); + app.BeginVertical(id, styles.timelineEditorStyleRef, std::move(constraints)); + [[maybe_unused]] const bool pushed = app.idManager.PushParent(id); auto playbackChanged = [v] { if (v.data.onPlaybackChanged) v.data.onPlaybackChanged(); }; // ---- The toolbar ---------------------------------------------------------- - BeginHorizontal(idManager.AllocateDynamicID("toolbar"), theme.timelineToolbarStyleRef); - BeginHorizontal(idManager.AllocateDynamicID("transport"), theme.timelineTransportStyleRef); - Button(idManager.AllocateDynamicID("start"), GUIContent(theme.timelineStartIcon, {}, "Go to the start"), - [v, playbackChanged] { v.data.playback.time = 0.0f; playbackChanged(); }, theme.timelineButtonStyleRef); - Button(idManager.AllocateDynamicID("prev"), GUIContent(theme.timelinePrevKeyIcon, {}, "The previous key"), + app.BeginHorizontal(app.idManager.AllocateDynamicID("toolbar"), styles.timelineToolbarStyleRef); + app.BeginHorizontal(app.idManager.AllocateDynamicID("transport"), styles.timelineTransportStyleRef); + app.Button(app.idManager.AllocateDynamicID("start"), GUIContent(styles.timelineStartIcon, {}, "Go to the start"), + [v, playbackChanged] { v.data.playback.time = 0.0f; playbackChanged(); }, styles.timelineButtonStyleRef); + app.Button(app.idManager.AllocateDynamicID("prev"), GUIContent(styles.timelinePrevKeyIcon, {}, "The previous key"), [v, playbackChanged] { const std::vector times = AllKeyTimes(v); const auto it = std::lower_bound(times.begin(), times.end(), v.data.playback.time - 1e-4f); v.data.playback.time = it == times.begin() ? 0.0f : *std::prev(it); v.data.playback.playing = false; playbackChanged(); - }, theme.timelineButtonStyleRef); - Button(idManager.AllocateDynamicID("play"), - view.data.playback.playing ? GUIContent(theme.timelinePauseIcon, {}, "Pause") : GUIContent(theme.timelinePlayIcon, {}, "Play"), - [v, length, playbackChanged] { TogglePlay(v.data.playback, length); playbackChanged(); }, theme.timelinePlayStyleRef); - Button(idManager.AllocateDynamicID("next"), GUIContent(theme.timelineNextKeyIcon, {}, "The next key"), + }, styles.timelineButtonStyleRef); + app.Button(app.idManager.AllocateDynamicID("play"), + view.data.playback.playing ? GUIContent(app.theme.timelinePauseIcon, {}, "Pause") : GUIContent(app.theme.timelinePlayIcon, {}, "Play"), + [v, length, playbackChanged] { TogglePlay(v.data.playback, length); playbackChanged(); }, styles.timelinePlayStyleRef); + app.Button(app.idManager.AllocateDynamicID("next"), GUIContent(styles.timelineNextKeyIcon, {}, "The next key"), [v, length, playbackChanged] { const std::vector times = AllKeyTimes(v); const auto it = std::upper_bound(times.begin(), times.end(), v.data.playback.time + 1e-4f); v.data.playback.time = it == times.end() ? length : *it; v.data.playback.playing = false; playbackChanged(); - }, theme.timelineButtonStyleRef); - Button(idManager.AllocateDynamicID("end"), GUIContent(theme.timelineEndIcon, {}, "Go to the end"), + }, styles.timelineButtonStyleRef); + app.Button(app.idManager.AllocateDynamicID("end"), GUIContent(styles.timelineEndIcon, {}, "Go to the end"), [v, length, playbackChanged] { v.data.playback.time = length; v.data.playback.playing = false; playbackChanged(); }, - theme.timelineButtonStyleRef); - Toggle(idManager.AllocateDynamicID("loop"), view.data.playback.loop, GUIContent(theme.timelineLoopIcon, {}, "Loop"), - [v](bool loop) { v.data.playback.loop = loop; }, theme.timelineLoopStyleRef); - EndHorizontal(); - RegisterElement(Element{ .id = idManager.AllocateDynamicID("divider"), .styleRef = theme.timelineDividerStyleRef, + styles.timelineButtonStyleRef); + app.Toggle(app.idManager.AllocateDynamicID("loop"), view.data.playback.loop, GUIContent(styles.timelineLoopIcon, {}, "Loop"), + [v](bool loop) { v.data.playback.loop = loop; }, styles.timelineLoopStyleRef); + app.EndHorizontal(); + app.RegisterElement(Element{ .id = app.idManager.AllocateDynamicID("divider"), .styleRef = styles.timelineDividerStyleRef, .flags = ElementFlags::NoInput }, LayoutOverride{}); - BeginHorizontal(idManager.AllocateDynamicID("time"), theme.timelineTimeStyleRef); - Text(idManager.AllocateDynamicID("now"), ClockText(view.data.playback.time), theme.timelineTimeCurrentStyleRef); - Text(idManager.AllocateDynamicID("length"), "/ " + ClockText(length), theme.timelineTimeTotalStyleRef); + app.BeginHorizontal(app.idManager.AllocateDynamicID("time"), styles.timelineTimeStyleRef); + app.Text(app.idManager.AllocateDynamicID("now"), ClockText(view.data.playback.time), styles.timelineTimeCurrentStyleRef); + app.Text(app.idManager.AllocateDynamicID("length"), "/ " + ClockText(length), styles.timelineTimeTotalStyleRef); if (frame > 0.0f) - Text(idManager.AllocateDynamicID("frame"), FrameText(view.data.playback.time, frame, length), theme.timelineFrameStyleRef); - EndHorizontal(); + app.Text(app.idManager.AllocateDynamicID("frame"), FrameText(view.data.playback.time, frame, length), styles.timelineFrameStyleRef); + app.EndHorizontal(); // The frame rate: the usual ones, and the view's own if it's another. { const std::string shown = std::format("{:g} fps", Finite(view.data.fps, 0.0f)); - if (BeginMenu(idManager.AllocateDynamicID("fps"), shown, theme.timelineFpsStyleRef, theme.menuStyleRef, theme.menuItemRowStyleRef)) + if (app.BeginMenu(app.idManager.AllocateDynamicID("fps"), shown, styles.timelineFpsStyleRef, app.theme.menuStyleRef, app.theme.menuItemRowStyleRef)) { for (const float fps : { 12.0f, 24.0f, 25.0f, 30.0f, 48.0f, 50.0f, 60.0f }) - MenuItem(std::format("{:g} fps", fps), [v, fps] { v.data.fps = fps; }); + app.MenuItem(std::format("{:g} fps", fps), [v, fps] { v.data.fps = fps; }); } - EndMenu(); + app.EndMenu(); } - Toggle(idManager.AllocateDynamicID("snap"), view.data.snap, GUIContent(theme.timelineSnapIcon, "Snap", "Keys and the loop range land on frames"), - [v](bool snap) { v.data.snap = snap; }, theme.timelineSnapStyleRef); + app.Toggle(app.idManager.AllocateDynamicID("snap"), view.data.snap, GUIContent(styles.timelineSnapIcon, "Snap", "Keys and the loop range land on frames"), + [v](bool snap) { v.data.snap = snap; }, styles.timelineSnapStyleRef); - BeginHorizontal(idManager.AllocateDynamicID("zoom"), theme.timelineZoomStyleRef); - RegisterElement(Element{ .id = idManager.AllocateDynamicID("zoomOut"), .iconID = theme.timelineZoomOutIcon, - .styleRef = theme.timelineZoomIconStyleRef, .flags = ElementFlags::NoInput }, LayoutOverride{}); - Slider(idManager.AllocateDynamicID("zoomSlider"), view.state.zoom, 0, 100, LayoutOverride{}.Width(110)); - SetTooltip("Zoom (the wheel over the lanes)"); - RegisterElement(Element{ .id = idManager.AllocateDynamicID("zoomIn"), .iconID = theme.timelineZoomInIcon, - .styleRef = theme.timelineZoomIconStyleRef, .flags = ElementFlags::NoInput }, LayoutOverride{}); - EndHorizontal(); - EndHorizontal(); + app.BeginHorizontal(app.idManager.AllocateDynamicID("zoom"), styles.timelineZoomStyleRef); + app.RegisterElement(Element{ .id = app.idManager.AllocateDynamicID("zoomOut"), .iconID = styles.timelineZoomOutIcon, + .styleRef = styles.timelineZoomIconStyleRef, .flags = ElementFlags::NoInput }, LayoutOverride{}); + app.Slider(app.idManager.AllocateDynamicID("zoomSlider"), view.state.zoom, 0, 100, LayoutOverride{}.Width(110)); + app.SetTooltip("Zoom (the wheel over the lanes)"); + app.RegisterElement(Element{ .id = app.idManager.AllocateDynamicID("zoomIn"), .iconID = styles.timelineZoomInIcon, + .styleRef = styles.timelineZoomIconStyleRef, .flags = ElementFlags::NoInput }, LayoutOverride{}); + app.EndHorizontal(); + app.EndHorizontal(); // ---- The header: the list's, and the ruler --------------------------------- - const ID lanesID = idManager.AllocateDynamicID("lanes"); - BeginHorizontal(idManager.AllocateDynamicID("header"), theme.timelineHeaderStyleRef); - BeginHorizontal(idManager.AllocateDynamicID("listHeader"), theme.timelineListHeaderStyleRef); - Text(idManager.AllocateDynamicID("tracks"), "Tracks", theme.timelineListTitleStyleRef); - SearchField(idManager.AllocateDynamicID("filter"), view.state.filter, theme.searchIcon, TextEditBehavior::ContinuousUpdate, - theme.timelineFilterStyleRef); + const ID lanesID = app.idManager.AllocateDynamicID("lanes"); + app.BeginHorizontal(app.idManager.AllocateDynamicID("header"), styles.timelineHeaderStyleRef); + app.BeginHorizontal(app.idManager.AllocateDynamicID("listHeader"), styles.timelineListHeaderStyleRef); + app.Text(app.idManager.AllocateDynamicID("tracks"), "Tracks", styles.timelineListTitleStyleRef); + app.SearchField(app.idManager.AllocateDynamicID("filter"), view.state.filter, app.theme.searchIcon, TextEditBehavior::ContinuousUpdate, + styles.timelineFilterStyleRef); if (view.state.onAddTrack) - Button(idManager.AllocateDynamicID("addTrack"), GUIContent(theme.addIcon, {}, "Add a track"), - [v] { if (v.state.onAddTrack) v.state.onAddTrack(); }, theme.timelineAddTrackStyleRef); - EndHorizontal(); + app.Button(app.idManager.AllocateDynamicID("addTrack"), GUIContent(app.theme.addIcon, {}, "Add a track"), + [v] { if (v.state.onAddTrack) v.state.onAddTrack(); }, styles.timelineAddTrackStyleRef); + app.EndHorizontal(); // The labels of the ruler's major ticks, for the width it had last frame. - const float lastWidth = float(view.state.lanesWidth > 0 ? view.state.lanesWidth : styleManager.Px(600)); - const float minLabelGap = float(styleManager.Px(56)); + const float lastWidth = float(view.state.lanesWidth > 0 ? view.state.lanesWidth : app.styleManager.Px(600)); + const float minLabelGap = float(app.styleManager.Px(56)); const float labelStep = MajorTickStep(lastWidth / std::max(1e-6f, range.end - range.start), minLabelGap); std::vector rulerLabels; if (labelStep > 0.0f) { const int first = int(std::ceil(range.start / labelStep - 1e-3f)), last = int(std::floor(range.end / labelStep + 1e-3f)); - const ID labelsID = last >= first ? idManager.AllocateRangedID(uint32_t(last - first + 1), "rulerLabels") : ID::Invalid(); + const ID labelsID = last >= first ? app.idManager.AllocateRangedID(uint32_t(last - first + 1), "rulerLabels") : ID::Invalid(); for (int i = first; i <= last; ++i) { const float t = float(i) * labelStep; - const ID labelID = idManager.GetSubID(labelsID, uint32_t(i - first)); - const TextID text = textSystem->RegisterText(labelID, std::format("{:g}s", t), theme.timelineRulerLabelStyleRef, ElementState::None); - const TextMeasurement m = textSystem->MeasureText(text, TextWrapContext{}); + const ID labelID = app.idManager.GetSubID(labelsID, uint32_t(i - first)); + const TextID text = app.textSystem->RegisterText(labelID, std::format("{:g}s", t), styles.timelineRulerLabelStyleRef, ElementState::None); + const TextMeasurement m = app.textSystem->MeasureText(text, TextWrapContext{}); rulerLabels.push_back({ text, t, { m.maxWidth, m.maxHeight } }); } } - const ID pillID = idManager.AllocateDynamicID("playheadLabel"); - const TextID pillText = textSystem->RegisterText(pillID, std::format("{:.2f}", view.data.playback.time), - theme.timelinePlayheadLabelStyleRef, ElementState::None); - const TextMeasurement pillSize = textSystem->MeasureText(pillText, TextWrapContext{}); + const ID pillID = app.idManager.AllocateDynamicID("playheadLabel"); + const TextID pillText = app.textSystem->RegisterText(pillID, std::format("{:.2f}", view.data.playback.time), + styles.timelinePlayheadLabelStyleRef, ElementState::None); + const TextMeasurement pillSize = app.textSystem->MeasureText(pillText, TextWrapContext{}); // The ruler: a press moves the playhead, Shift + a drag sets the loop range, its ends // drag, Ctrl + a click clears it. - const ID rulerID = idManager.AllocateDynamicID("ruler"); + const ID rulerID = app.idManager.AllocateDynamicID("ruler"); EventHandler rulerHandler; if (!disabled) { - GUIStateManager& gsm = guiStateManager; - const ElementStorage& es = elementStorage; - const int32_t edgeReach = styleManager.Px(4); - const int32_t dragDistance = styleManager.Px(kDragStartDistance); - rulerHandler = [&gsm, &es, v, lanesID, edgeReach, dragDistance, playbackChanged, wheelMode = GetWheelMode()](ElementEvent&& event) -> bool + GUIStateManager& gsm = app.guiStateManager; + const ElementStorage& es = app.elementStorage; + const int32_t edgeReach = app.styleManager.Px(4); + const int32_t dragDistance = app.styleManager.Px(kDragStartDistance); + rulerHandler = [&gsm, &es, v, lanesID, edgeReach, dragDistance, playbackChanged, wheelMode = app.GetWheelMode()](ElementEvent&& event) -> bool { if (event.rect == nullptr) return false; @@ -630,8 +631,8 @@ namespace tachyon } }; } - const ElementRef rulerRef = RegisterElement( - Element{ .id = rulerID, .eventHandler = std::move(rulerHandler), .styleRef = theme.timelineRulerStyleRef, + const ElementRef rulerRef = app.RegisterElement( + Element{ .id = rulerID, .eventHandler = std::move(rulerHandler), .styleRef = styles.timelineRulerStyleRef, .flags = view.data.playback.playing ? ElementFlags::Animated : ElementFlags::None }, LayoutOverride{}); { @@ -639,18 +640,18 @@ namespace tachyon const float time = view.data.playback.time; // A press anywhere on the ruler moves the playhead, so its pill lights up while // the ruler is hovered; a loop edge within reach, or being dragged, does too. - const bool rulerHovered = (guiStateManager.GetCurrentState(rulerID) & ElementState::Hover) != ElementState::None; + const bool rulerHovered = (app.guiStateManager.GetCurrentState(rulerID) & ElementState::Hover) != ElementState::None; const bool scrubbing = view.state.scrub.IsHeld(); const int litEdge = view.state.loopDrag.IsHeld() ? view.state.loopEdge : view.state.loopEdgeHover.Shown(rulerHovered); const ElementState pillState = (rulerHovered && litEdge == 0) || scrubbing ? ElementState::Hover : ElementState::None; - const VisualBoxStyleIndex tick = theme.timelineTickStyleRef.visualBoxStyleIndex, major = theme.timelineTickMajorStyleRef.visualBoxStyleIndex; - const VisualBoxStyleIndex band = theme.timelineLoopRangeStyleRef.visualBoxStyleIndex, edge = theme.timelineLoopEdgeStyleRef.visualBoxStyleIndex; - const VisualBoxStyleIndex line = theme.timelinePlayheadStyleRef.visualBoxStyleIndex, pill = theme.timelinePlayheadLabelStyleRef.visualBoxStyleIndex; - const int32_t px1 = std::max(1, styleManager.Px(1)), px2 = std::max(1, styleManager.Px(2)), px4 = styleManager.Px(4); - const int32_t minorHeight = styleManager.Px(5), majorHeight = styleManager.Px(10); - const int32_t pillHeight = styleManager.Px(18), pillMin = styleManager.Px(40), pillPad = styleManager.Px(12); + const VisualBoxStyleIndex tick = styles.timelineTickStyleRef.visualBoxStyleIndex, major = styles.timelineTickMajorStyleRef.visualBoxStyleIndex; + const VisualBoxStyleIndex band = styles.timelineLoopRangeStyleRef.visualBoxStyleIndex, edge = styles.timelineLoopEdgeStyleRef.visualBoxStyleIndex; + const VisualBoxStyleIndex line = styles.timelinePlayheadStyleRef.visualBoxStyleIndex, pill = styles.timelinePlayheadLabelStyleRef.visualBoxStyleIndex; + const int32_t px1 = std::max(1, app.styleManager.Px(1)), px2 = std::max(1, app.styleManager.Px(2)), px4 = app.styleManager.Px(4); + const int32_t minorHeight = app.styleManager.Px(5), majorHeight = app.styleManager.Px(10); + const int32_t pillHeight = app.styleManager.Px(18), pillMin = app.styleManager.Px(40), pillPad = app.styleManager.Px(12); const int2 pillTextSize{ pillSize.maxWidth, pillSize.maxHeight }; - VERIFY(elementStorage.AddCustomDraw(rulerRef, [=](CustomDrawContext& ctx) + VERIFY(app.elementStorage.AddCustomDraw(rulerRef, [=](CustomDrawContext& ctx) { const IntRect outer = ctx.ElementRect(), inner = ctx.ElementInnerRect(); const Geometry g{ range, float(inner.x), float(v.state.lanesWidth > 0 ? v.state.lanesWidth : inner.w) }; @@ -692,13 +693,13 @@ namespace tachyon } })); } - EndHorizontal(); + app.EndHorizontal(); // ---- The body: the track list and the lanes, scrolled together ------------ - const ID bodyID = idManager.AllocateDynamicID("body"); - BeginArea(bodyID, theme.timelineBodyStyleRef, LayoutOverride{}.FlexGrow(1)); - BeginVertical(idManager.AllocateDynamicID("list"), theme.timelineListStyleRef); - const int32_t indent = styleManager.Px(24); + const ID bodyID = app.idManager.AllocateDynamicID("body"); + app.BeginArea(bodyID, styles.timelineBodyStyleRef, LayoutOverride{}.FlexGrow(1)); + app.BeginVertical(app.idManager.AllocateDynamicID("list"), styles.timelineListStyleRef); + const int32_t indent = app.styleManager.Px(24); for (const int t : rows) { const TimelineTrack& track = view.data.tracks[size_t(t)]; @@ -706,24 +707,24 @@ namespace tachyon const ID trackID = track.stableID; const ID rowID = IDManager::ScopedID(id, trackID); const bool locked = IsTrackLocked(view.data, t); - const ElementState rowState = guiStateManager.GetCurrentState(rowID) + const ElementState rowState = app.guiStateManager.GetCurrentState(rowID) | (view.state.selectedTrack == trackID ? ElementState::Selected : ElementState::None); EventHandler rowHandler; if (!disabled) - rowHandler = [this, v, trackID, lanesID](ElementEvent&& event) -> bool { + rowHandler = [&app, v, trackID, lanesID](ElementEvent&& event) -> bool { if (event.type != EventType::MouseDown || !event.state.LeftPressed()) return false; v.state.selectedTrack = trackID; - TakeFocus(guiStateManager, lanesID); + TakeFocus(app.guiStateManager, lanesID); return true; }; - RegisterElement(Element{ .id = rowID, .eventHandler = std::move(rowHandler), .styleRef = theme.timelineRowStyleRef, + app.RegisterElement(Element{ .id = rowID, .eventHandler = std::move(rowHandler), .styleRef = styles.timelineRowStyleRef, .flags = ElementFlags::PropagatesDescendantState, .state = rowState }, LayoutOverride{}.Height(Pixels{ rowHeight })); - VERIFY(elementStorage.BeginChildren()); - [[maybe_unused]] const bool inRow = idManager.PushParent(rowID); + VERIFY(app.elementStorage.BeginChildren()); + [[maybe_unused]] const bool inRow = app.idManager.PushParent(rowID); if (track.depth > 0) - RegisterElement(Element{ .id = idManager.AllocateDynamicID("indent"), .styleRef = theme.emptyHorzStyleRef, + app.RegisterElement(Element{ .id = app.idManager.AllocateDynamicID("indent"), .styleRef = app.theme.emptyHorzStyleRef, .flags = ElementFlags::NoInput }, LayoutOverride{}.Width(Pixels{ indent * track.depth }).FlexGrow(0)); // A change to this track, as an edit: what it was and what it'll be. @@ -739,66 +740,66 @@ namespace tachyon { case TimelineTrackKind::Group: { - Button(idManager.AllocateDynamicID("chevron"), - GUIContent(track.expanded ? theme.treeArrowDown : theme.treeArrowRight, {}, track.expanded ? "Collapse" : "Expand"), + app.Button(app.idManager.AllocateDynamicID("chevron"), + GUIContent(track.expanded ? app.theme.treeArrowDown : app.theme.treeArrowRight, {}, track.expanded ? "Collapse" : "Expand"), [v, t] { if (t < (int)v.data.tracks.size()) v.data.tracks[size_t(t)].expanded = !v.data.tracks[size_t(t)].expanded; }, - theme.timelineChevronStyleRef); + styles.timelineChevronStyleRef); const VisualColorStyleIndex chip = track.color.a > 0.0f - ? AppColorStyle(idManager.AllocateDynamicID("chip-color"), track.color) : VisualColorStyleIndex{}; - RegisterElement(Element{ .id = idManager.AllocateDynamicID("chip"), .styleRef = theme.timelineChipStyleRef, + ? app.AppColorStyle(app.idManager.AllocateDynamicID("chip-color"), track.color) : VisualColorStyleIndex{}; + app.RegisterElement(Element{ .id = app.idManager.AllocateDynamicID("chip"), .styleRef = styles.timelineChipStyleRef, .flags = ElementFlags::NoInput, .colorStyleIndex = chip }, LayoutOverride{}); - Text(idManager.AllocateDynamicID("name"), track.name, theme.timelineGroupNameStyleRef); - Button(idManager.AllocateDynamicID("eye"), - GUIContent(track.visible ? theme.timelineEyeIcon : theme.timelineEyeOffIcon, {}, track.visible ? "Hide" : "Show"), - changeTrack([](TimelineTrack& to) { to.visible = !to.visible; }), theme.timelineRowButtonStyleRef); - Button(idManager.AllocateDynamicID("lock"), - GUIContent(track.locked ? theme.timelineLockIcon : theme.timelineUnlockIcon, {}, track.locked ? "Unlock" : "Lock"), - changeTrack([](TimelineTrack& to) { to.locked = !to.locked; }), theme.timelineRowButtonStyleRef); + app.Text(app.idManager.AllocateDynamicID("name"), track.name, styles.timelineGroupNameStyleRef); + app.Button(app.idManager.AllocateDynamicID("eye"), + GUIContent(track.visible ? app.theme.timelineEyeIcon : app.theme.timelineEyeOffIcon, {}, track.visible ? "Hide" : "Show"), + changeTrack([](TimelineTrack& to) { to.visible = !to.visible; }), app.theme.timelineRowButtonStyleRef); + app.Button(app.idManager.AllocateDynamicID("lock"), + GUIContent(track.locked ? styles.timelineLockIcon : styles.timelineUnlockIcon, {}, track.locked ? "Unlock" : "Lock"), + changeTrack([](TimelineTrack& to) { to.locked = !to.locked; }), app.theme.timelineRowButtonStyleRef); break; } case TimelineTrackKind::Property: { - Text(idManager.AllocateDynamicID("name"), track.name, theme.timelineTrackNameStyleRef); - if (locked) BeginDisabled(); - Button(idManager.AllocateDynamicID("key"), GUIContent(theme.timelineKeyIcon, {}, "Key at the playhead"), - [this, v, t] { (void)CommitNewKey(idManager, v, t, v.data.playback.time); }, - theme.timelineRowButtonStyleRef); - if (locked) EndDisabled(); + app.Text(app.idManager.AllocateDynamicID("name"), track.name, styles.timelineTrackNameStyleRef); + if (locked) app.BeginDisabled(); + app.Button(app.idManager.AllocateDynamicID("key"), GUIContent(styles.timelineKeyIcon, {}, "Key at the playhead"), + [&app, v, t] { (void)CommitNewKey(app.idManager, v, t, v.data.playback.time); }, + app.theme.timelineRowButtonStyleRef); + if (locked) app.EndDisabled(); break; } case TimelineTrackKind::Audio: { - const ID nameID = idManager.AllocateDynamicID("name"); - RegisterElement(Element{ .id = nameID, - .textID = textSystem->RegisterText(nameID, theme.timelineAudioIcon, track.name, theme.timelineTrackNameStyleRef, ElementState::None), - .styleRef = theme.timelineTrackNameStyleRef, .flags = ElementFlags::NoInput }, LayoutOverride{}); - Toggle(idManager.AllocateDynamicID("mute"), track.muted, GUIContent("M", "Mute"), - [changeTrack](bool) { changeTrack([](TimelineTrack& to) { to.muted = !to.muted; })(); }, theme.timelineMuteStyleRef); - Toggle(idManager.AllocateDynamicID("solo"), track.solo, GUIContent("S", "Solo"), - [changeTrack](bool) { changeTrack([](TimelineTrack& to) { to.solo = !to.solo; })(); }, theme.timelineSoloStyleRef); + const ID nameID = app.idManager.AllocateDynamicID("name"); + app.RegisterElement(Element{ .id = nameID, + .textID = app.textSystem->RegisterText(nameID, styles.timelineAudioIcon, track.name, styles.timelineTrackNameStyleRef, ElementState::None), + .styleRef = styles.timelineTrackNameStyleRef, .flags = ElementFlags::NoInput }, LayoutOverride{}); + app.Toggle(app.idManager.AllocateDynamicID("mute"), track.muted, GUIContent("M", "Mute"), + [changeTrack](bool) { changeTrack([](TimelineTrack& to) { to.muted = !to.muted; })(); }, styles.timelineMuteStyleRef); + app.Toggle(app.idManager.AllocateDynamicID("solo"), track.solo, GUIContent("S", "Solo"), + [changeTrack](bool) { changeTrack([](TimelineTrack& to) { to.solo = !to.solo; })(); }, styles.timelineSoloStyleRef); break; } case TimelineTrackKind::Events: { - const ID nameID = idManager.AllocateDynamicID("name"); - RegisterElement(Element{ .id = nameID, - .textID = textSystem->RegisterText(nameID, theme.timelineEventsIcon, track.name, theme.timelineTrackNameStyleRef, ElementState::None), - .styleRef = theme.timelineTrackNameStyleRef, .flags = ElementFlags::NoInput }, LayoutOverride{}); + const ID nameID = app.idManager.AllocateDynamicID("name"); + app.RegisterElement(Element{ .id = nameID, + .textID = app.textSystem->RegisterText(nameID, styles.timelineEventsIcon, track.name, styles.timelineTrackNameStyleRef, ElementState::None), + .styleRef = styles.timelineTrackNameStyleRef, .flags = ElementFlags::NoInput }, LayoutOverride{}); break; } } if (inRow) - (void)idManager.PopParent(); - VERIFY(elementStorage.EndChildren()); - if (view.state.onTrackContextMenu && BeginContextMenu(rowID)) + (void)app.idManager.PopParent(); + VERIFY(app.elementStorage.EndChildren()); + if (view.state.onTrackContextMenu && app.BeginContextMenu(rowID)) { v.state.selectedTrack = trackID; view.state.onTrackContextMenu(t); } if (view.state.onTrackContextMenu) - EndContextMenu(); + app.EndContextMenu(); } - EndVertical(); + app.EndVertical(); // The event names, for the draw. struct EventLabel { int row; float time; TextID text; int2 size; bool selected; }; @@ -806,25 +807,25 @@ namespace tachyon // Where each label is beside its event's line, for the lanes to take it as the event. struct LabelSpan { int track; ID event; float time; int32_t from, to; }; std::vector labelSpans; - const int32_t labelFrom = std::max(1, styleManager.Px(2)) + styleManager.Px(4), labelPad = 2 * styleManager.Px(5); + const int32_t labelFrom = std::max(1, app.styleManager.Px(2)) + app.styleManager.Px(4), labelPad = 2 * app.styleManager.Px(5); for (int r = 0; r < (int)rows.size(); ++r) { const TimelineTrack& track = view.data.tracks[size_t(rows[size_t(r)])]; if (track.kind != TimelineTrackKind::Events) continue; - [[maybe_unused]] const bool inTrack = idManager.PushParent(IDManager::ScopedID(id, track.stableID)); - const ID labelsID = track.events.empty() ? ID::Invalid() : idManager.AllocateRangedID(uint32_t(track.events.size()), "events"); + [[maybe_unused]] const bool inTrack = app.idManager.PushParent(IDManager::ScopedID(id, track.stableID)); + const ID labelsID = track.events.empty() ? ID::Invalid() : app.idManager.AllocateRangedID(uint32_t(track.events.size()), "events"); for (size_t e = 0; e < track.events.size(); ++e) { const TimelineEvent& event = track.events[e]; - const TextID text = textSystem->RegisterText(idManager.GetSubID(labelsID, uint32_t(e)), event.name, - theme.timelineEventLabelStyleRef, ElementState::None); - const TextMeasurement m = textSystem->MeasureText(text, TextWrapContext{}); + const TextID text = app.textSystem->RegisterText(app.idManager.GetSubID(labelsID, uint32_t(e)), event.name, + styles.timelineEventLabelStyleRef, ElementState::None); + const TextMeasurement m = app.textSystem->MeasureText(text, TextWrapContext{}); eventLabels.push_back({ r, event.time, text, { m.maxWidth, m.maxHeight }, view.state.selectedKeys.contains(event.stableID) }); labelSpans.push_back({ rows[size_t(r)], event.stableID, event.time, labelFrom, labelFrom + m.maxWidth + labelPad }); } if (inTrack) - (void)idManager.PopParent(); + (void)app.idManager.PopParent(); } // The lanes: keys, clips and events by row. A press on a key selects it and drags @@ -832,13 +833,13 @@ namespace tachyon EventHandler lanesHandler; if (!disabled) { - GUIStateManager& gsm = guiStateManager; - const ElementStorage& es = elementStorage; - const float reach = float(styleManager.Px(6)); - const int32_t dragDistance = styleManager.Px(kDragStartDistance); - const float edgeReach = float(styleManager.Px(5)); - lanesHandler = [this, &gsm, &es, v, rows, rowHeight, reach, edgeReach, dragDistance, bodyID, playbackChanged, labelSpans, - wheelMode = GetWheelMode()](ElementEvent&& event) -> bool + GUIStateManager& gsm = app.guiStateManager; + const ElementStorage& es = app.elementStorage; + const float reach = float(app.styleManager.Px(6)); + const int32_t dragDistance = app.styleManager.Px(kDragStartDistance); + const float edgeReach = float(app.styleManager.Px(5)); + lanesHandler = [&app, &gsm, &es, v, rows, rowHeight, reach, edgeReach, dragDistance, bodyID, playbackChanged, labelSpans, + wheelMode = app.GetWheelMode()](ElementEvent&& event) -> bool { if (event.rect == nullptr) return false; @@ -1123,7 +1124,7 @@ namespace tachyon { for (int t = 0; t < (int)v.data.tracks.size(); ++t) if (v.data.tracks[size_t(t)].stableID == v.state.selectedTrack) - (void)CommitNewKey(idManager, v, t, v.data.playback.time); + (void)CommitNewKey(app.idManager, v, t, v.data.playback.time); return true; } case KeyCode::KeyI: case KeyCode::KeyO: @@ -1171,20 +1172,20 @@ namespace tachyon }; } const int lanesHeight = rowHeight * std::max(1, (int)rows.size()); - const ElementRef lanesRef = RegisterControl( - Element{ .id = lanesID, .eventHandler = std::move(lanesHandler), .styleRef = theme.timelineLanesStyleRef, + const ElementRef lanesRef = app.RegisterControl( + Element{ .id = lanesID, .eventHandler = std::move(lanesHandler), .styleRef = styles.timelineLanesStyleRef, .flags = view.data.playback.playing ? ElementFlags::Animated : ElementFlags::None, - .state = guiStateManager.GetCurrentState(lanesID) }, + .state = app.guiStateManager.GetCurrentState(lanesID) }, LayoutOverride{}.MinHeight(Pixels{ lanesHeight }).FlexGrow(1)); - VERIFY(elementStorage.AddPostLayout(lanesRef, [v](PostLayoutContext& ctx) { v.state.lanesWidth = ctx.ElementInnerRect().w; })); + VERIFY(app.elementStorage.AddPostLayout(lanesRef, [v](PostLayoutContext& ctx) { v.state.lanesWidth = ctx.ElementInnerRect().w; })); // The lanes' menu: on a key or event, delete it (the selection, when it's in it); on a // lane, a key there, the playhead there, select all. - if (!disabled && BeginContextMenu(lanesID)) + if (!disabled && app.BeginContextMenu(lanesID)) { - if (view.state.menuOpening != ContextMenuOpenings()) + if (view.state.menuOpening != app.ContextMenuOpenings()) { - view.state.menuOpening = ContextMenuOpenings(); + view.state.menuOpening = app.ContextMenuOpenings(); if (!view.state.menuByPointer) { // From the keyboard: the selection, or the selected track at the playhead. @@ -1205,7 +1206,7 @@ namespace tachyon for (const TimelineEvent& e : tr.events) isEvent |= e.stableID == view.state.menuKeys[0]; const std::string label = count > 1 ? std::format("Delete {} keys", count) : isEvent ? "Delete event" : "Delete key"; - MenuItem(label, CommandManager::FormatShortcut(KeyCode::Delete, KeyModifier::None), [v] { CommitTimelineEdit(v.data, DeleteSelectedKeysEdit(v)); }); + app.MenuItem(label, CommandManager::FormatShortcut(KeyCode::Delete, KeyModifier::None), [v] { CommitTimelineEdit(v.data, DeleteSelectedKeysEdit(v)); }); } else { @@ -1213,20 +1214,20 @@ namespace tachyon if (t >= 0 && t < (int)view.data.tracks.size() && view.data.tracks[size_t(t)].kind == TimelineTrackKind::Property) { const bool locked = IsTrackLocked(view.data, t); // shown, but it can't add one - if (locked) BeginDisabled(); - MenuItem("Add key", [this, v, t] { - if (const ID keyID = CommitNewKey(idManager, v, t, v.state.menuTime); keyID != ID::Invalid()) + if (locked) app.BeginDisabled(); + app.MenuItem("Add key", [&app, v, t] { + if (const ID keyID = CommitNewKey(app.idManager, v, t, v.state.menuTime); keyID != ID::Invalid()) v.state.selectedKeys = { keyID }; }); - if (locked) EndDisabled(); + if (locked) app.EndDisabled(); } - MenuItem("Move playhead here", [v, playbackChanged] { + app.MenuItem("Move playhead here", [v, playbackChanged] { v.data.playback.time = std::clamp(SnappedTime(v, v.state.menuTime), 0.0f, LengthOf(v)); v.data.playback.playing = false; playbackChanged(); }); - MenuSeparator(); - MenuItem("Select all", CommandManager::FormatShortcut(KeyCode::KeyA, KeyModifier::Control), [v] { + app.MenuSeparator(); + app.MenuItem("Select all", CommandManager::FormatShortcut(KeyCode::KeyA, KeyModifier::Control), [v] { for (const TimelineTrack& tr : v.data.tracks) { for (const TimelineKey& key : tr.keys) v.state.selectedKeys.insert(key.stableID); @@ -1236,7 +1237,7 @@ namespace tachyon } } if (!disabled) - EndContextMenu(); + app.EndContextMenu(); { // What the draw needs, by row: the track, whether it's selected, its keys. struct RowDraw @@ -1252,7 +1253,7 @@ namespace tachyon }; std::vector drawn; drawn.reserve(rows.size()); - const bool lanesHovered = (guiStateManager.GetCurrentState(lanesID) & ElementState::Hover) != ElementState::None; + const bool lanesHovered = (app.guiStateManager.GetCurrentState(lanesID) & ElementState::Hover) != ElementState::None; const TimelineViewState::LaneHover laneHover = view.state.hover.Shown(lanesHovered); for (const int t : rows) { @@ -1273,7 +1274,7 @@ namespace tachyon const int boxR0 = std::min(view.state.boxFromRow, view.state.boxToRow), boxR1 = std::max(view.state.boxFromRow, view.state.boxToRow); const TimelineRange loop = view.data.loopRange; const float time = view.data.playback.time; - const GUITheme& th = theme; + const Styles& th = GetStyles(app, context); const VisualBoxStyleIndex laneSelected = th.timelineLaneSelectedStyleRef.visualBoxStyleIndex, rowLine = th.timelineRowLineStyleRef.visualBoxStyleIndex; const VisualBoxStyleIndex outside = th.timelineOutsideStyleRef.visualBoxStyleIndex, clipBox = th.timelineClipStyleRef.visualBoxStyleIndex; const VisualBoxStyleIndex clipEdge = th.timelineLoopEdgeStyleRef.visualBoxStyleIndex; @@ -1281,12 +1282,12 @@ namespace tachyon const VisualBoxStyleIndex selectedLine = th.timelinePlayheadStyleRef.visualBoxStyleIndex, boxStyle = th.timelineBoxSelectStyleRef.visualBoxStyleIndex; const VisualColorStyleIndex keyFill = th.timelineKeyColor, keyEdge = th.timelineKeyEdgeColor, keySelected = th.timelineKeySelectedColor, keySelectedEdge = th.timelineKeySelectedEdgeColor, summary = th.timelineSummaryKeyColor, wave = th.timelineWaveColor; - const float keyHalf = float(styleManager.Px(10)) * 0.7071f, selectedHalf = float(styleManager.Px(11)) * 0.7071f; - const float summaryHalf = float(styleManager.Px(8)) * 0.7071f, edgeWidth = float(std::max(1, styleManager.Px(1))) * 1.4142f; - const float hoverGrow = float(std::max(1, styleManager.Px(2))) * 0.7071f; // a hovered diamond, 2px larger across - const int32_t px1 = std::max(1, styleManager.Px(1)), px2 = std::max(1, styleManager.Px(2)), px3 = styleManager.Px(3), px4 = styleManager.Px(4); - const int32_t px5 = styleManager.Px(5), barGap = std::max(1, styleManager.Px(1)), barWidth = std::max(1, styleManager.Px(2)); - VERIFY(elementStorage.AddCustomDraw(lanesRef, [=](CustomDrawContext& ctx) + const float keyHalf = float(app.styleManager.Px(10)) * 0.7071f, selectedHalf = float(app.styleManager.Px(11)) * 0.7071f; + const float summaryHalf = float(app.styleManager.Px(8)) * 0.7071f, edgeWidth = float(std::max(1, app.styleManager.Px(1))) * 1.4142f; + const float hoverGrow = float(std::max(1, app.styleManager.Px(2))) * 0.7071f; // a hovered diamond, 2px larger across + const int32_t px1 = std::max(1, app.styleManager.Px(1)), px2 = std::max(1, app.styleManager.Px(2)), px3 = app.styleManager.Px(3), px4 = app.styleManager.Px(4); + const int32_t px5 = app.styleManager.Px(5), barGap = std::max(1, app.styleManager.Px(1)), barWidth = std::max(1, app.styleManager.Px(2)); + VERIFY(app.elementStorage.AddCustomDraw(lanesRef, [=](CustomDrawContext& ctx) { const IntRect outer = ctx.ElementRect(), inner = ctx.ElementInnerRect(); const Geometry g{ range, float(inner.x), float(inner.w) }; @@ -1381,15 +1382,15 @@ namespace tachyon ctx.RenderBox(IntRect{ int32_t(g.XAt(time)), outer.y, px1, outer.h }, outer, selectedLine); })); } - EndArea(); + app.EndArea(); // ---- The scroll bar: the part in view, along the whole ---------------------- - const ID scrollID = idManager.AllocateDynamicID("scroll"); + const ID scrollID = app.idManager.AllocateDynamicID("scroll"); EventHandler scrollHandler; if (!disabled) { - const ElementStorage& es = elementStorage; - GUIStateManager& gsm = guiStateManager; + const ElementStorage& es = app.elementStorage; + GUIStateManager& gsm = app.guiStateManager; scrollHandler = [&gsm, &es, v](ElementEvent&& event) -> bool { if (event.rect == nullptr) @@ -1429,16 +1430,16 @@ namespace tachyon } }; } - const ElementRef scrollRef = RegisterElement( - Element{ .id = scrollID, .eventHandler = std::move(scrollHandler), .styleRef = theme.timelineScrollStyleRef }, + const ElementRef scrollRef = app.RegisterElement( + Element{ .id = scrollID, .eventHandler = std::move(scrollHandler), .styleRef = styles.timelineScrollStyleRef }, LayoutOverride{}); { - const VisualBoxStyleIndex thumb = theme.timelineScrollThumbStyleRef.visualBoxStyleIndex; - const int32_t thick = styleManager.Px(6); + const VisualBoxStyleIndex thumb = styles.timelineScrollThumbStyleRef.visualBoxStyleIndex; + const int32_t thick = app.styleManager.Px(6); // A press anywhere on the bar takes the thumb, so it lights up while the bar is hovered. - const ElementState thumbState = view.state.pan.IsHeld() || (guiStateManager.GetCurrentState(scrollID) & ElementState::Hover) != ElementState::None + const ElementState thumbState = view.state.pan.IsHeld() || (app.guiStateManager.GetCurrentState(scrollID) & ElementState::Hover) != ElementState::None ? ElementState::Hover : ElementState::None; - VERIFY(elementStorage.AddCustomDraw(scrollRef, [=](CustomDrawContext& ctx) + VERIFY(app.elementStorage.AddCustomDraw(scrollRef, [=](CustomDrawContext& ctx) { const IntRect inner = ctx.ElementInnerRect(); if (length <= 0.0f || inner.w <= 0) @@ -1450,7 +1451,7 @@ namespace tachyon } if (pushed) - (void)idManager.PopParent(); - EndVertical(); + (void)app.idManager.PopParent(); + app.EndVertical(); } } diff --git a/src/gui_controls/controls_viewport.cpp b/examples/app_controls/controls_viewport.cpp similarity index 83% rename from src/gui_controls/controls_viewport.cpp rename to examples/app_controls/controls_viewport.cpp index 0729cf75..d65dc341 100644 --- a/src/gui_controls/controls_viewport.cpp +++ b/examples/app_controls/controls_viewport.cpp @@ -1,5 +1,5 @@ -#include -#include +#include +#include #include #include @@ -10,7 +10,7 @@ // camera's mouse and keys; the move, rotate and scale gizmos over the selection; the tools // down the left and the axes at the top right. -namespace tachyon +namespace tachyon::app_controls { namespace { @@ -66,10 +66,11 @@ namespace tachyon } } - bool GUIApplication::Viewport(ID id, ViewportView& view, LayoutOverride&& constraints) + bool Viewport(GUIApplication& app, Context& context, ID id, ViewportView& view, LayoutOverride&& constraints) { + const Styles& styles = GetStyles(app, context); ViewportView* v = &view; - const bool disabled = guiStateManager.Construction().IsDisabled(); + const bool disabled = app.guiStateManager.Construction().IsDisabled(); if (disabled && (v->gizmoDrag.IsHeld() || v->cameraDrag.IsHeld())) { if (v->gizmoDrag.IsHeld()) v->selection = v->gizmoDrag.before; @@ -85,11 +86,11 @@ namespace tachyon // Flying: the camera moves while fly keys are held, by the time the frame took. if (v->cameraMove == ViewportView::CameraMove::Look) - FlyCamera(*v, std::min(frameTime, 0.1f)); + FlyCamera(*v, std::min(app.frameTime, 0.1f)); else v->flyKeys = 0; - const ElementState state = guiStateManager.GetCurrentState(id); + const ElementState state = app.guiStateManager.GetCurrentState(id); if ((state & ElementState::Hover) == ElementState::None && !v->gizmoDrag.IsHeld()) v->hover.Clear(); @@ -97,10 +98,10 @@ namespace tachyon // frame is recorded, after this frame's input, as the gizmo drawn over it is. ImageIndex image = ImageIndex::Invalid; const IntRect last = view.viewRect; - if (view.onRender && graphicsContext != nullptr && last.w > 0 && last.h > 0) + if (view.onRender && app.graphicsContext != nullptr && last.w > 0 && last.h > 0) { const uint2 size{ uint32_t(last.w), uint32_t(last.h) }; - image = graphicsContext->RenderScene(id, windowRegistry.GetCurrentWindowID(), size, view.background, + image = app.graphicsContext->RenderScene(id, app.windowRegistry.GetCurrentWindowID(), size, view.background, [v, size](const ScenePayload& payload) { if (!v->onRender) return; const float aspect = float(size.x) / float(size.y); @@ -113,14 +114,14 @@ namespace tachyon EventHandler handler; if (!disabled) { - GUIStateManager& gsm = guiStateManager; - const ElementStorage& es = elementStorage; - const WheelMode wheelMode = GetWheelMode(); - const float axisRadius = float(styleManager.Px(int32_t(kAxisGizmoRadius))); - const float axisMargin = float(styleManager.Px(int32_t(kAxisGizmoMargin))); - const float axisReach = float(styleManager.Px(9)); - const float notch = float(styleManager.Px(40)); // a wheel notch scrolls this far - const int32_t dragDistance = styleManager.Px(kDragStartDistance); + GUIStateManager& gsm = app.guiStateManager; + const ElementStorage& es = app.elementStorage; + const WheelMode wheelMode = app.GetWheelMode(); + const float axisRadius = float(app.styleManager.Px(int32_t(kAxisGizmoRadius))); + const float axisMargin = float(app.styleManager.Px(int32_t(kAxisGizmoMargin))); + const float axisReach = float(app.styleManager.Px(9)); + const float notch = float(app.styleManager.Px(40)); // a wheel notch scrolls this far + const int32_t dragDistance = app.styleManager.Px(kDragStartDistance); handler = [&gsm, &es, v, wheelMode, axisRadius, axisMargin, axisReach, notch, dragDistance](ElementEvent&& event) -> bool { if (event.rect == nullptr) @@ -305,70 +306,70 @@ namespace tachyon }; } - Element element{ .id = id, .eventHandler = std::move(handler), .styleRef = theme.viewportStyleRef, .state = state }; - const ElementRef ref = RegisterControl(std::move(element), std::move(constraints)); + Element element{ .id = id, .eventHandler = std::move(handler), .styleRef = styles.viewportStyleRef, .state = state }; + const ElementRef ref = app.RegisterControl(std::move(element), std::move(constraints)); if (!ref.IsValid()) return changed; // Laid out: the size the scene is drawn at next, and, in a cached panel, the panel // built again next frame. Asked for now rather than while building, as building's // request is cleared when the panel is captured after layout. - VERIFY(elementStorage.AddPostLayout(ref, [this, v, id](PostLayoutContext& ctx) { + VERIFY(app.elementStorage.AddPostLayout(ref, [&app, v, id](PostLayoutContext& ctx) { v->viewRect = ctx.ElementInnerRect(); - RebuildCachedScopesAbove(id); + app.RebuildCachedScopesAbove(id); })); // The tools down the left: a button each, the one in use selected. - VERIFY(elementStorage.BeginChildren()); - const bool pushed = idManager.PushParent(id); + VERIFY(app.elementStorage.BeginChildren()); + const bool pushed = app.idManager.PushParent(id); if (view.showTools) { - BeginVertical(idManager.AllocateDynamicID("viewport_tools"), theme.viewportToolsStyleRef, - LayoutOverride{}.Absolute(styleManager.Px(8), styleManager.Px(8))); + app.BeginVertical(app.idManager.AllocateDynamicID("viewport_tools"), styles.viewportToolsStyleRef, + LayoutOverride{}.Absolute(app.styleManager.Px(8), app.styleManager.Px(8))); struct ToolButton { ViewportTool tool; IconID icon; const char* tip; const char* name; }; const ToolButton tools[] = { - { ViewportTool::Select, theme.viewportSelectIcon, "Select (Q)", "viewport_select" }, - { ViewportTool::Move, theme.viewportMoveIcon, "Move (W)", "viewport_move" }, - { ViewportTool::Rotate, theme.viewportRotateIcon, "Rotate (E)", "viewport_rotate" }, - { ViewportTool::Scale, theme.viewportScaleIcon, "Scale (R)", "viewport_scale" } }; + { ViewportTool::Select, styles.viewportSelectIcon, "Select (Q)", "viewport_select" }, + { ViewportTool::Move, styles.viewportMoveIcon, "Move (W)", "viewport_move" }, + { ViewportTool::Rotate, styles.viewportRotateIcon, "Rotate (E)", "viewport_rotate" }, + { ViewportTool::Scale, styles.viewportScaleIcon, "Scale (R)", "viewport_scale" } }; for (const ToolButton& t : tools) { const bool active = view.tool == t.tool; - if (active) BeginSelected(); - Button(idManager.AllocateDynamicID(t.name), GUIContent{ t.icon, {}, t.tip }, [v, tool = t.tool]() { v->tool = tool; }, - theme.viewportToolStyleRef); - if (active) EndSelected(); + if (active) app.BeginSelected(); + app.Button(app.idManager.AllocateDynamicID(t.name), GUIContent{ t.icon, {}, t.tip }, [v, tool = t.tool]() { v->tool = tool; }, + styles.viewportToolStyleRef); + if (active) app.EndSelected(); } - EndVertical(); + app.EndVertical(); } // The axes' letters, for the top right. std::array axisLabels{}; - const ID labelsID = idManager.AllocateRangedID(3, "viewport_axis_labels"); + const ID labelsID = app.idManager.AllocateRangedID(3, "viewport_axis_labels"); for (uint32_t a = 0; a < 3; ++a) - axisLabels[a] = textSystem->RegisterText(idManager.GetSubID(labelsID, a), a == 0 ? "X" : a == 1 ? "Y" : "Z", - theme.viewportAxisLabelStyleRef, ElementState::None); + axisLabels[a] = app.textSystem->RegisterText(app.idManager.GetSubID(labelsID, a), a == 0 ? "X" : a == 1 ? "Y" : "Z", + styles.viewportAxisLabelStyleRef, ElementState::None); std::array labelSizes{}; for (size_t a = 0; a < 3; ++a) { - const TextMeasurement m = textSystem->MeasureText(axisLabels[a], TextWrapContext{}); + const TextMeasurement m = app.textSystem->MeasureText(axisLabels[a], TextWrapContext{}); labelSizes[a] = { m.maxWidth, m.maxHeight }; } if (pushed) - (void)idManager.PopParent(); - VERIFY(elementStorage.EndChildren()); + (void)app.idManager.PopParent(); + VERIFY(app.elementStorage.EndChildren()); // ---- Drawing: the scene, the gizmo over it, the axes ---------------------- - const int32_t px1 = std::max(1, styleManager.Px(1)); - const float axisRadius = float(styleManager.Px(int32_t(kAxisGizmoRadius))); - const float axisMargin = float(styleManager.Px(int32_t(kAxisGizmoMargin))); - const VisualColorStyleIndex background = AppColorStyle(idManager.AllocateDynamicID("viewport-background"), view.background); - VERIFY(elementStorage.AddCustomDraw(ref, [=, this](CustomDrawContext& ctx) + const int32_t px1 = std::max(1, app.styleManager.Px(1)); + const float axisRadius = float(app.styleManager.Px(int32_t(kAxisGizmoRadius))); + const float axisMargin = float(app.styleManager.Px(int32_t(kAxisGizmoMargin))); + const VisualColorStyleIndex background = app.AppColorStyle(app.idManager.AllocateDynamicID("viewport-background"), view.background); + VERIFY(app.elementStorage.AddCustomDraw(ref, [=, &app, &styles](CustomDrawContext& ctx) { const IntRect inner = ctx.ElementInnerRect(); const IntRect area{ 0, 0, inner.w, inner.h }; const float2 size{ float(inner.w), float(inner.h) }; if (image != ImageIndex::Invalid) - ctx.RenderQuad(area, theme.imageFillColorStyle, 0.0f, image); + ctx.RenderQuad(area, app.theme.imageFillColorStyle, 0.0f, image); else ctx.RenderQuad(area, background); @@ -377,7 +378,7 @@ namespace tachyon auto pt = [](float2 p) { return int2{ int32_t(std::lround(p.x)), int32_t(std::lround(p.y)) }; }; auto colorOf = [&](GizmoPart part, int axis) { const bool lit = part == v->activePart || (v->activePart == GizmoPart::None && part == v->hover.part); - return lit ? theme.curveChannelColors[0] : theme.curveChannelColors[size_t(1 + axis)]; + return lit ? styles.axisColors[0] : styles.axisColors[size_t(1 + axis)]; }; // The gizmo over the selection. @@ -430,8 +431,8 @@ namespace tachyon const VisualColorStyleIndex color = colorOf(planes[n], n); const int2 outline[4] = { pt(q[0]), pt(q[1]), pt(q[2]), pt(q[3]) }; ctx.RenderPolyline(outline, /*closed*/ true, LineStyle{ .colorStyleIndex = color, .lineWidth = float(px1) }); - ctx.RenderTriangle(q[0], q[1], q[2], theme.curveChannelFadedColors[size_t(1 + n)]); - ctx.RenderTriangle(q[0], q[2], q[3], theme.curveChannelFadedColors[size_t(1 + n)]); + ctx.RenderTriangle(q[0], q[1], q[2], styles.axisFadedColors[size_t(1 + n)]); + ctx.RenderTriangle(q[0], q[2], q[3], styles.axisFadedColors[size_t(1 + n)]); } } for (int a = 0; a < 3; ++a) @@ -442,7 +443,7 @@ namespace tachyon const VisualColorStyleIndex color = colorOf(PartOfAxis(a), a); ctx.RenderLine(pt(center), pt(end), LineStyle{ .colorStyleIndex = color, .lineWidth = width }); const float2 dir = Normalize2(end - center); - const float head = float(styleManager.Px(10)); + const float head = float(app.styleManager.Px(10)); if (v->tool == ViewportTool::Move) { const float2 side{ -dir.y, dir.x }; @@ -459,8 +460,8 @@ namespace tachyon if (v->tool != ViewportTool::Rotate) { const bool lit = v->activePart == GizmoPart::Center || (v->activePart == GizmoPart::None && v->hover.part == GizmoPart::Center); - const float dot = float(styleManager.Px(6)); - ctx.RenderDisc(pt(center), dot, lit ? theme.curveChannelColors[0] : theme.curveSelectedKeyColor); + const float dot = float(app.styleManager.Px(6)); + ctx.RenderDisc(pt(center), dot, lit ? styles.axisColors[0] : styles.selectionColor); } } } @@ -468,7 +469,7 @@ namespace tachyon // The axes at the top right: each world axis as the camera sees it; the positive // ends lettered, the negative ones faded. A click on one looks along it. const float2 axisCenter{ size.x - axisMargin, axisMargin }; - const float dotRadius = float(styleManager.Px(8)); + const float dotRadius = float(app.styleManager.Px(8)); std::array order{ 0, 1, 2, 3, 4, 5 }; // The ends farther away first, so the nearer ones are drawn over them. std::sort(order.begin(), order.end(), [&](int i, int j) { @@ -482,13 +483,13 @@ namespace tachyon const float2 end = AxisGizmoEnd(camera, axisCenter, axisRadius, dir); if (i < 3) { - ctx.RenderLine(pt(axisCenter), pt(end), LineStyle{ .colorStyleIndex = theme.curveChannelColors[size_t(1 + a)], .lineWidth = float(px1) * 2.0f }); - ctx.RenderDisc(pt(end), dotRadius, theme.curveChannelColors[size_t(1 + a)]); + ctx.RenderLine(pt(axisCenter), pt(end), LineStyle{ .colorStyleIndex = styles.axisColors[size_t(1 + a)], .lineWidth = float(px1) * 2.0f }); + ctx.RenderDisc(pt(end), dotRadius, styles.axisColors[size_t(1 + a)]); const int2 s = labelSizes[size_t(a)]; ctx.RenderText(axisLabels[size_t(a)], IntRect{ int32_t(end.x) - s.x / 2, int32_t(end.y) - s.y / 2, s.x, s.y }); } else - ctx.RenderDisc(pt(end), dotRadius * 0.7f, theme.curveChannelFadedColors[size_t(1 + a)]); + ctx.RenderDisc(pt(end), dotRadius * 0.7f, styles.axisFadedColors[size_t(1 + a)]); } })); return changed; diff --git a/examples/app_controls/gui_app_controls.cpp b/examples/app_controls/gui_app_controls.cpp new file mode 100644 index 00000000..9136b235 --- /dev/null +++ b/examples/app_controls/gui_app_controls.cpp @@ -0,0 +1,199 @@ +#include + +#include +#include + +#include +#include +#include +#include + +namespace tachyon::app_controls +{ + 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("app_controls/") + name; + return textSystem->RegisterIconFromSVG(fullName.c_str(), svg.data(), svg.size()); + } + } + + void Styles::Load(GUIApplication& app) + { + GUITheme& theme = app.theme; + StyleManager& styleManager = app.styleManager; + ITextSystem* textSystem = app.textSystem; + timelineStyleRef = theme.GetStyle("timeline"); + timelineTransportStyleRef = theme.GetStyle("timeline-transport"); + timelineButtonStyleRef = theme.GetStyle("timeline-button"); + timelinePlayStyleRef = theme.GetStyle("timeline-play"); + timelineLoopStyleRef = theme.GetStyle("timeline-loop"); + timelineTimeStyleRef = theme.GetStyle("timeline-time"); + timelineTimeCurrentStyleRef = theme.GetStyle("timeline-time-current"); + timelineTimeTotalStyleRef = theme.GetStyle("timeline-time-total"); + timelineFrameStyleRef = theme.GetStyle("timeline-frame"); + timelineScrubberStyleRef = theme.GetStyle("timeline-scrubber"); + timelineReadyStyleRef = theme.GetStyle("timeline-ready"); + timelineTickStyleRef = theme.GetStyle("timeline-tick"); + timelineTickMajorStyleRef = theme.GetStyle("timeline-tick-major"); + timelineMarkerStyleRef = theme.GetStyle("timeline-marker"); + timelinePlayheadStyleRef = theme.GetStyle("timeline-playhead"); + timelineEditorStyleRef = theme.GetStyle("timeline-editor"); + timelineToolbarStyleRef = theme.GetStyle("timeline-toolbar"); + timelineDividerStyleRef = theme.GetStyle("timeline-divider"); + timelineSnapStyleRef = theme.GetStyle("timeline-snap"); + viewportStyleRef = theme.GetStyle("viewport"); + viewportToolsStyleRef = theme.GetStyle("viewport-tools"); + viewportToolStyleRef = theme.GetStyle("viewport-tool"); + viewportAxisLabelStyleRef = theme.GetStyle("viewport-axis-label"); + timelineZoomStyleRef = theme.GetStyle("timeline-zoom"); + timelineZoomIconStyleRef = theme.GetStyle("timeline-zoom-icon"); + timelineHeaderStyleRef = theme.GetStyle("timeline-header"); + timelineListHeaderStyleRef = theme.GetStyle("timeline-list-header"); + timelineListTitleStyleRef = theme.GetStyle("timeline-list-title"); + timelineFilterStyleRef = theme.GetStyle("timeline-filter"); + timelineAddTrackStyleRef = theme.GetStyle("timeline-add-track"); + timelineBodyStyleRef = theme.GetStyle("timeline-body"); + timelineListStyleRef = theme.GetStyle("timeline-list"); + timelineRowStyleRef = theme.GetStyle("timeline-row"); + timelineChevronStyleRef = theme.GetStyle("timeline-chevron"); + timelineChipStyleRef = theme.GetStyle("timeline-chip"); + timelineGroupNameStyleRef = theme.GetStyle("timeline-group-name"); + timelineTrackNameStyleRef = theme.GetStyle("timeline-track-name"); + timelineMuteStyleRef = theme.GetStyle("timeline-mute"); + timelineSoloStyleRef = theme.GetStyle("timeline-solo"); + timelineRulerStyleRef = theme.GetStyle("timeline-ruler"); + timelineRulerLabelStyleRef = theme.GetStyle("timeline-ruler-label"); + timelinePlayheadLabelStyleRef = theme.GetStyle("timeline-playhead-label"); + timelineLanesStyleRef = theme.GetStyle("timeline-lanes"); + timelineLaneSelectedStyleRef = theme.GetStyle("timeline-lane-selected"); + timelineRowLineStyleRef = theme.GetStyle("timeline-row-line"); + timelineOutsideStyleRef = theme.GetStyle("timeline-outside"); + timelineLoopRangeStyleRef = theme.GetStyle("timeline-loop-range"); + timelineLoopEdgeStyleRef = theme.GetStyle("timeline-loop-edge"); + timelineClipStyleRef = theme.GetStyle("timeline-clip"); + timelineEventStyleRef = theme.GetStyle("timeline-event"); + timelineEventChipStyleRef = theme.GetStyle("timeline-event-chip"); + timelineEventLabelStyleRef = theme.GetStyle("timeline-event-label"); + timelineBoxSelectStyleRef = theme.GetStyle("timeline-box-select"); + timelineScrollStyleRef = theme.GetStyle("timeline-scroll"); + timelineScrollThumbStyleRef = theme.GetStyle("timeline-scroll-thumb"); + timelineStartIcon = RegisterIcon(textSystem, "timeline-start", R"()"); + timelineStepBackIcon = RegisterIcon(textSystem, "timeline-step-back", R"()"); + timelineStepIcon = RegisterIcon(textSystem, "timeline-step", R"()"); + timelineEndIcon = RegisterIcon(textSystem, "timeline-end", R"()"); + timelineLoopIcon = RegisterIcon(textSystem, "timeline-loop", R"()"); + timelinePrevKeyIcon = RegisterIcon(textSystem, "timeline-prev-key", R"()"); + timelineNextKeyIcon = RegisterIcon(textSystem, "timeline-next-key", R"()"); + timelineSnapIcon = RegisterIcon(textSystem, "timeline-snap", R"()"); + timelineZoomInIcon = RegisterIcon(textSystem, "timeline-zoom-in", R"()"); + timelineZoomOutIcon = RegisterIcon(textSystem, "timeline-zoom-out", R"()"); + timelineLockIcon = RegisterIcon(textSystem, "timeline-lock", R"()"); + timelineUnlockIcon = RegisterIcon(textSystem, "timeline-unlock", R"()"); + timelineKeyIcon = RegisterIcon(textSystem, "timeline-key", R"()"); + timelineAudioIcon = RegisterIcon(textSystem, "timeline-audio", R"()"); + timelineEventsIcon = RegisterIcon(textSystem, "timeline-events", R"()"); + viewportSelectIcon = RegisterIcon(textSystem, "viewport-select", R"()"); + viewportMoveIcon = RegisterIcon(textSystem, "viewport-move", R"()"); + viewportRotateIcon = RegisterIcon(textSystem, "viewport-rotate", R"()"); + viewportScaleIcon = RegisterIcon(textSystem, "viewport-scale", R"()"); + timelineKeyColor = theme.VariableColor(styleManager, "--timeline-key", color4f{ 0.79f, 0.81f, 0.85f, 1.0f }); + timelineKeyEdgeColor = theme.VariableColor(styleManager, "--bg-panel", color4f{ 0.07f, 0.08f, 0.09f, 1.0f }); + timelineKeySelectedColor = theme.VariableColor(styleManager, "--accent", color4f{ 0.42f, 0.61f, 1.0f, 1.0f }); + timelineKeySelectedEdgeColor = theme.VariableColor(styleManager, "--text-1", color4f{ 0.91f, 0.92f, 0.94f, 1.0f }); + timelineSummaryKeyColor = theme.VariableColor(styleManager, "--timeline-summary", color4f{ 0.42f, 0.45f, 0.5f, 1.0f }); + timelineWaveColor = theme.VariableColor(styleManager, "--timeline-wave", color4f{ 0.2f, 0.82f, 0.75f, 0.65f }); + { + static constexpr const char* kAxisVars[5] = { "--warn", "--axis-x", "--axis-y", "--axis-z", "--text-1" }; + static constexpr color4f kFallbacks[5] = { { 0.9f, 0.7f, 0.33f, 1.0f }, { 0.94f, 0.42f, 0.42f, 1.0f }, + { 0.31f, 0.77f, 0.54f, 1.0f }, { 0.42f, 0.61f, 1.0f, 1.0f }, + { 0.91f, 0.92f, 0.94f, 1.0f } }; + for (int c = 0; c < 5; ++c) + { + axisColors[c] = theme.VariableColor(styleManager, kAxisVars[c], kFallbacks[c]); + color4f faded = theme.GetColor(kAxisVars[c], kFallbacks[c]); + faded.a *= 0.55f; + axisFadedColors[c] = styleManager.RegisterColorStyle(ColorStyle::Create(faded)); + } + } + selectionColor = theme.VariableColor(styleManager, "--text-1", color4f{ 0.91f, 0.92f, 0.94f, 1.0f }); + timelineFpsStyleRef = theme.GetStyle("timeline-fps"); + theme.RegisterDropdownParts(timelineFpsStyleRef, "timeline-fps"); + } + + const Styles& GetStyles(GUIApplication& app, Context& context) + { + if (context.stylesGeneration != app.StylesGeneration()) + { + context.styles.Load(app); + context.stylesGeneration = app.StylesGeneration(); + } + return context.styles; + } + + std::string SaveViewState(const TimelineViewState& view) + { + JsonValue state = JsonValue::MakeObject(); + state.Set("start", double(view.viewStart)); + state.Set("length", double(view.viewLength)); + state.Set("zoom", view.zoom); + return state.Write(); + } + + bool RestoreViewState(TimelineViewState& view, std::string_view state) + { + const std::optional object = ParseJsonObject(state); + if (!object) + return false; + const std::optional start = JsonFloat(*object, "start"), length = JsonFloat(*object, "length"), zoom = JsonFloat(*object, "zoom"); + if (!start || !length || !zoom) + return false; + // A damaged state: no negative span (0 shows the whole duration), nothing that isn't a number. + if (!std::isfinite(*start) || !std::isfinite(*length) || *length < 0.0f) + return false; + view.viewStart = *start; + view.viewLength = *length; + view.zoom = std::clamp(int(std::lround(*zoom)), 0, 100); + return true; + } + + std::string SaveViewState(const ViewportCamera& camera) + { + JsonValue state = JsonValue::MakeObject(); + state.Set("target", JsonFloatArray({ camera.target.x, camera.target.y, camera.target.z })); + state.Set("distance", double(camera.distance)); + state.Set("yaw", double(camera.yaw)); + state.Set("pitch", double(camera.pitch)); + state.Set("fovY", double(camera.fovY)); + state.Set("orthographic", camera.orthographic); + return state.Write(); + } + + bool RestoreViewState(ViewportCamera& camera, std::string_view state) + { + const std::optional object = ParseJsonObject(state); + if (!object) + return false; + float target[3]; + const std::optional distance = JsonFloat(*object, "distance"), yaw = JsonFloat(*object, "yaw"), + pitch = JsonFloat(*object, "pitch"), fovY = JsonFloat(*object, "fovY"); + const JsonValue* orthographic = object->Find("orthographic"); + if (!JsonFloats(*object, "target", target) || !distance || !yaw || !pitch || !fovY || !(*distance > 0.0f) + || !(*fovY > 0.0f && *fovY < 3.14f) || !orthographic || !orthographic->IsBool()) + return false; + camera.target = float3{ target[0], target[1], target[2] }; + camera.distance = *distance; + camera.yaw = *yaw; + camera.pitch = *pitch; + camera.fovY = *fovY; + camera.orthographic = orthographic->AsBool(); + return true; + } +} diff --git a/examples/app_controls/gui_app_controls.h b/examples/app_controls/gui_app_controls.h new file mode 100644 index 00000000..e6954aca --- /dev/null +++ b/examples/app_controls/gui_app_controls.h @@ -0,0 +1,193 @@ +#pragma once + +// App-level controls the examples build on: a timeline and its editor, and a 3D viewport. They +// belong to one kind of app rather than to the library, and show how an app writes controls +// of its own on the library's public API: free functions that take the app and a Context the +// app owns. Their styles are in themes/app_controls.css, which an app adds to its style files. +// +// app_controls::Context controlsContext; // a member of the app class +// +// app_controls::Timeline(*this, controlsContext, playback, options); + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace tachyon::app_controls +{ + /// The controls' styles, icons and colors, looked up in the theme after each load. + struct Styles + { + StyleRef timelineStyleRef {}; ///< Timeline: the row + StyleRef timelineTransportStyleRef {}; ///< its buttons + StyleRef timelineButtonStyleRef {}; ///< a transport button: start, step, end + StyleRef timelinePlayStyleRef {}; ///< play / pause, in the accent + StyleRef timelineLoopStyleRef {}; ///< the loop toggle; selected while looping + StyleRef timelineTimeStyleRef {}; ///< the time's well + StyleRef timelineTimeCurrentStyleRef {}; ///< the time now, monospace + StyleRef timelineTimeTotalStyleRef {}; ///< "/ " and the length + StyleRef timelineFrameStyleRef {}; ///< the frame chip + StyleRef timelineScrubberStyleRef {}; ///< the scrubber + StyleRef timelineReadyStyleRef {}; ///< drawn: the progress fill + StyleRef timelineTickStyleRef {}; ///< drawn: a tick every quarter second (or the like) + StyleRef timelineTickMajorStyleRef {}; ///< drawn: a tick every second (or the like) + StyleRef timelineMarkerStyleRef {}; ///< drawn: a marker's line + StyleRef timelinePlayheadStyleRef {}; ///< drawn: the playhead's line and its head + StyleRef timelineEditorStyleRef {}; ///< TimelineEditor: the whole + StyleRef timelineToolbarStyleRef {}; ///< its toolbar: transport, time, fps, snap, zoom + StyleRef timelineDividerStyleRef {}; ///< a line between the toolbar's groups + StyleRef timelineFpsStyleRef {}; ///< the fps dropdown + StyleRef timelineSnapStyleRef {}; ///< the Snap toggle; selected while snapping + StyleRef viewportStyleRef {}; ///< Viewport: the view + StyleRef viewportToolsStyleRef {}; ///< the tools' strip down its left + StyleRef viewportToolStyleRef {}; ///< a tool's button; selected for the one in use + StyleRef viewportAxisLabelStyleRef {}; ///< drawn: an axis's letter at the top right + StyleRef timelineZoomStyleRef {}; ///< the zoom slider and its icons + StyleRef timelineZoomIconStyleRef {}; ///< a magnifier beside the zoom slider + StyleRef timelineHeaderStyleRef {}; ///< the row over the track list and the ruler + StyleRef timelineListHeaderStyleRef {}; ///< "Tracks", the filter and the add button + StyleRef timelineListTitleStyleRef {}; ///< "Tracks" + StyleRef timelineFilterStyleRef {}; ///< the filter field + StyleRef timelineAddTrackStyleRef {}; ///< the add-track button + StyleRef timelineBodyStyleRef {}; ///< the track list and lanes, scrolled together + StyleRef timelineListStyleRef {}; ///< the track list + StyleRef timelineRowStyleRef {}; ///< a track's row; selected while it's the selected track + StyleRef timelineChevronStyleRef {}; ///< a group's expand / collapse + StyleRef timelineChipStyleRef {}; ///< a group's color chip + StyleRef timelineGroupNameStyleRef {}; ///< a group's name + StyleRef timelineTrackNameStyleRef {}; ///< another track's name, with its icon + StyleRef timelineMuteStyleRef {}; ///< an audio track's M; selected while muted + StyleRef timelineSoloStyleRef {}; ///< an audio track's S; selected while solo + StyleRef timelineRulerStyleRef {}; ///< the ruler over the lanes + StyleRef timelineRulerLabelStyleRef {}; ///< drawn: a second's label on the ruler + StyleRef timelinePlayheadLabelStyleRef {}; ///< drawn: the playhead's time on the ruler + StyleRef timelineLanesStyleRef {}; ///< the lanes + StyleRef timelineLaneSelectedStyleRef {}; ///< drawn: the selected track's lane + StyleRef timelineRowLineStyleRef {}; ///< drawn: the line under a row + StyleRef timelineOutsideStyleRef {}; ///< drawn: the lanes outside the loop range + StyleRef timelineLoopRangeStyleRef {}; ///< drawn: the loop range on the ruler + StyleRef timelineLoopEdgeStyleRef {}; ///< drawn: its ends + StyleRef timelineClipStyleRef {}; ///< drawn: an audio clip + StyleRef timelineEventStyleRef {}; ///< drawn: an event's line + StyleRef timelineEventChipStyleRef {}; ///< drawn: the chip under an event's name + StyleRef timelineEventLabelStyleRef {}; ///< drawn: an event's name + StyleRef timelineBoxSelectStyleRef {}; ///< drawn: the box being dragged to select keys + StyleRef timelineScrollStyleRef {}; ///< the scroll bar under the lanes + StyleRef timelineScrollThumbStyleRef {}; ///< drawn: its thumb + IconID timelineStartIcon {}; ///< Timeline: go to the start + IconID timelineStepBackIcon {}; ///< Timeline: a frame back + IconID timelineStepIcon {}; ///< Timeline: a frame on + IconID timelineEndIcon {}; ///< Timeline: go to the end + IconID timelineLoopIcon {}; ///< Timeline: loop + IconID timelinePrevKeyIcon {}; ///< TimelineEditor: the previous key + IconID timelineNextKeyIcon {}; ///< TimelineEditor: the next key + IconID timelineSnapIcon {}; ///< TimelineEditor: snap (a magnet) + IconID timelineZoomInIcon {}; ///< TimelineEditor: zoom in + IconID timelineZoomOutIcon {}; ///< TimelineEditor: zoom out + IconID timelineLockIcon {}; ///< TimelineEditor: a group locked + IconID timelineUnlockIcon {}; ///< TimelineEditor: a group unlocked + IconID timelineKeyIcon {}; ///< TimelineEditor: add a key (a diamond) + IconID timelineAudioIcon {}; ///< TimelineEditor: an audio track + IconID timelineEventsIcon {}; ///< TimelineEditor: an events track (a flag) + IconID viewportSelectIcon {}; ///< Viewport's tools: select (a pointer) + IconID viewportMoveIcon {}; ///< move (four arrows) + IconID viewportRotateIcon {}; ///< rotate (a turning arrow) + IconID viewportScaleIcon {}; ///< scale (a corner pulled out) + /// TimelineEditor's keys: a key, its edge, a selected key and its edge, a group's + /// summary key, and an audio clip's waveform. + VisualColorStyleIndex timelineKeyColor {}, timelineKeyEdgeColor {}, timelineKeySelectedColor {}, + timelineKeySelectedEdgeColor {}, timelineSummaryKeyColor {}, timelineWaveColor {}; + /// The viewport's axes: [0] the warning color an axis turns under the pointer, then x, + /// y and z (--axis-x, --axis-y, --axis-z), and white; each faded for the far side. + VisualColorStyleIndex axisColors[5] {}, axisFadedColors[5] {}; + VisualColorStyleIndex selectionColor {}; ///< --text-1: a selected object's dot + + /// Looks them all up in `app`'s theme, after it loads. + void Load(GUIApplication& app); + }; + + /// What the controls keep from frame to frame, the app's to own and pass to each of them. + struct Context + { + Styles styles; + uint32_t stylesGeneration = 0; ///< the app's StylesGeneration the styles were looked up at + }; + + /// The controls' styles in `app`'s theme, looked up again after each theme load. + const Styles& GetStyles(GUIApplication& app, Context& context); + + /// @name Timeline + ///@{ + + /// Playback on one row: go to the start, step back a frame, play or pause, step on a + /// frame, go to the end and loop; the time and frame; and a scrubber with ticks (every + /// second when there's room), the `progress` fill, a line per marker and the playhead. + /// A press or drag on the scrubber moves the playhead there, onto a frame. Keys on the + /// focused scrubber: Space plays or pauses, Left / Right step a frame, Page Down / + /// Page Up go to the previous / next marker, Home / End to the ends; Escape during a + /// drag puts the playhead back. A step is a frame, or a hundredth of the length + /// without frames; stepping pauses. + /// Edits `state`; the app moves it on while it plays (AdvanceTimeline). Returns true + /// on the frame the user changed it. + bool Timeline(GUIApplication& app, Context& context, ID id, TimelineState& state, const TimelineOptions& options, LayoutOverride&& constraints = {}); + /// As above, with the call site as the ID. + inline bool Timeline(GUIApplication& app, Context& context, TimelineState& state, const TimelineOptions& options, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return Timeline(app, context, app.idManager.AllocateDynamicID(site), state, options, std::move(constraints)); } + + /// A timeline editor over `view`: a toolbar (the transport, with the previous and next + /// key in place of the frame steps; the time; the frame rate; Snap; zoom), the track + /// list beside the ruler and the lanes, and a scroll bar under them. + /// - The track list: groups (a chevron, a color chip, eye and lock), properties (a + /// button to key them at the playhead), audio (mute, solo) and events; a filter and + /// an add button (`onAddTrack`) over it; a right click opens `onTrackContextMenu`. + /// - The ruler: a press or drag moves the playhead; Shift + drag sets the loop range, + /// its ends drag, Ctrl + click clears it. + /// - The lanes: keys (a group's summed up), audio clips with their waveform, events. + /// A click selects a key (Shift adds, Ctrl toggles), a drag on the empty lanes + /// selects those in a box, and a drag on a selected key moves them all, onto frames + /// while Snap is on; Escape puts them back. + /// - Over the ruler and the lanes, the wheel zooms round the pointer and Shift + the + /// wheel pans; a drag with the right button pans along the time and scrolls the + /// rows. + /// - Keys on the focused lanes: Delete removes the selected keys, Left / Right move + /// them a frame, Ctrl+A selects them all, K keys the selected track at the playhead, + /// Space plays or pauses, Home / End go to the ends, Escape clears the selection. + /// Every change to the tracks or the loop range is a TimelineEdit, handed to the data's + /// `onEdit` for undo; the playhead and selection change directly. `view` is a + /// TimelineView, or `{ data, state }` for one of several editors of the same tracks. + void TimelineEditor(GUIApplication& app, Context& context, ID id, TimelineViewRef view, LayoutOverride&& constraints = {}); + /// As above, with the call site as the ID. + inline void TimelineEditor(GUIApplication& app, Context& context, TimelineViewRef view, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { TimelineEditor(app, context, app.idManager.AllocateDynamicID(site), view, std::move(constraints)); } + + ///@} + + + /// A 3D view: the app's scene, drawn by `view.onRender` into an image the library keeps + /// at the view's size, a camera the mouse moves round it, the move, rotate and scale + /// gizmos over the selection, the tools down the left and the axes at the top right. + /// True on the frame after a gizmo's drag changed the selection. + /// + /// ViewportView scene; // a member + /// scene.onRender = [this](const ViewportRenderContext& ctx) { DrawScene(ctx); }; + /// scene.onClick = [this](const Ray& ray, KeyModifier) { Pick(ray); }; + /// if (Viewport(app, context, app.idManager.AllocateDynamicID("scene"), scene, LayoutOverride{}.FlexGrow(1))) + /// MoveSelected(scene.selection); + bool Viewport(GUIApplication& app, Context& context, ID id, ViewportView& view, LayoutOverride&& constraints = {}); + /// 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 (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); + /// A viewport's camera: where it looks, from how far and which way, its field of view and + /// whether it's orthographic. + std::string SaveViewState(const ViewportCamera& camera); + bool RestoreViewState(ViewportCamera& camera, std::string_view state); +} diff --git a/examples/app_controls/gui_file_icons.cpp b/examples/app_controls/gui_file_icons.cpp index 4777403d..1615779e 100644 --- a/examples/app_controls/gui_file_icons.cpp +++ b/examples/app_controls/gui_file_icons.cpp @@ -20,7 +20,7 @@ #pragma comment(lib, "ole32.lib") #endif -namespace tachyon +namespace tachyon::app_controls { #ifdef _WIN32 bool detail::IconPixels(void* icon, uint32_t& width, uint32_t& height, std::vector& rgba) diff --git a/examples/app_controls/gui_file_icons.h b/examples/app_controls/gui_file_icons.h index daf5410c..2428f287 100644 --- a/examples/app_controls/gui_file_icons.h +++ b/examples/app_controls/gui_file_icons.h @@ -10,9 +10,10 @@ #include #include -namespace tachyon +namespace tachyon { class ITextSystem; } + +namespace tachyon::app_controls { - class ITextSystem; /// @addtogroup controls_data /// @{ diff --git a/examples/app_controls/gui_file_system.cpp b/examples/app_controls/gui_file_system.cpp index 993c2a05..c588c5a6 100644 --- a/examples/app_controls/gui_file_system.cpp +++ b/examples/app_controls/gui_file_system.cpp @@ -3,7 +3,7 @@ #include #include -namespace tachyon +namespace tachyon::app_controls { struct MemoryFileSystem::Node { diff --git a/examples/app_controls/gui_file_system.h b/examples/app_controls/gui_file_system.h index 00452f0f..86689f95 100644 --- a/examples/app_controls/gui_file_system.h +++ b/examples/app_controls/gui_file_system.h @@ -12,7 +12,7 @@ #include #include -namespace tachyon +namespace tachyon::app_controls { /// @addtogroup controls_data /// @{ diff --git a/examples/app_controls/gui_file_thumbnails.cpp b/examples/app_controls/gui_file_thumbnails.cpp index 12194906..eb9e36f7 100644 --- a/examples/app_controls/gui_file_thumbnails.cpp +++ b/examples/app_controls/gui_file_thumbnails.cpp @@ -19,7 +19,7 @@ #pragma comment(lib, "ole32.lib") #endif -namespace tachyon +namespace tachyon::app_controls { #ifdef _WIN32 bool detail::BitmapPixels(void* bitmap, uint32_t& width, uint32_t& height, std::vector& rgba) diff --git a/examples/app_controls/gui_file_thumbnails.h b/examples/app_controls/gui_file_thumbnails.h index ee2b85fd..85a6b7ac 100644 --- a/examples/app_controls/gui_file_thumbnails.h +++ b/examples/app_controls/gui_file_thumbnails.h @@ -18,9 +18,10 @@ #include #include -namespace tachyon +namespace tachyon { class ITextSystem; } + +namespace tachyon::app_controls { - class ITextSystem; /// @addtogroup controls_data /// @{ diff --git a/src/gui_controls/gui_timeline_helpers.cpp b/examples/app_controls/gui_timeline_helpers.cpp similarity index 98% rename from src/gui_controls/gui_timeline_helpers.cpp rename to examples/app_controls/gui_timeline_helpers.cpp index 2806e186..912c3478 100644 --- a/src/gui_controls/gui_timeline_helpers.cpp +++ b/examples/app_controls/gui_timeline_helpers.cpp @@ -1,10 +1,11 @@ -#include +#include +#include #include #include #include -namespace tachyon +namespace tachyon::app_controls { // --------------------------------------------------------------------------- diff --git a/src/gui_controls/gui_timeline_internal.h b/examples/app_controls/gui_timeline_internal.h similarity index 96% rename from src/gui_controls/gui_timeline_internal.h rename to examples/app_controls/gui_timeline_internal.h index 0f1a2d07..bcc79a1c 100644 --- a/src/gui_controls/gui_timeline_internal.h +++ b/examples/app_controls/gui_timeline_internal.h @@ -2,14 +2,14 @@ // Helpers the Timeline row and the TimelineEditor share: times as text, ticks, frames. -#include +#include #include #include #include #include -namespace tachyon::timeline_internal +namespace tachyon::app_controls::timeline_internal { inline float Finite(float value, float fallback) { diff --git a/src/gui_controls/gui_timeline_types.h b/examples/app_controls/gui_timeline_types.h similarity index 99% rename from src/gui_controls/gui_timeline_types.h rename to examples/app_controls/gui_timeline_types.h index 2942bfb8..10d866bf 100644 --- a/src/gui_controls/gui_timeline_types.h +++ b/examples/app_controls/gui_timeline_types.h @@ -14,7 +14,7 @@ #include #include -namespace tachyon +namespace tachyon::app_controls { /// @addtogroup app /// @{ diff --git a/src/gui_controls/gui_viewport_helpers.cpp b/examples/app_controls/gui_viewport_helpers.cpp similarity index 99% rename from src/gui_controls/gui_viewport_helpers.cpp rename to examples/app_controls/gui_viewport_helpers.cpp index 8455048e..36af3a3d 100644 --- a/src/gui_controls/gui_viewport_helpers.cpp +++ b/examples/app_controls/gui_viewport_helpers.cpp @@ -1,11 +1,12 @@ -#include +#include +#include #include #include #include #include -namespace tachyon +namespace tachyon::app_controls { namespace { diff --git a/src/gui_controls/gui_viewport_types.h b/examples/app_controls/gui_viewport_types.h similarity index 99% rename from src/gui_controls/gui_viewport_types.h rename to examples/app_controls/gui_viewport_types.h index 7228ed1b..7b1201f8 100644 --- a/src/gui_controls/gui_viewport_types.h +++ b/examples/app_controls/gui_viewport_types.h @@ -11,7 +11,7 @@ #include -namespace tachyon +namespace tachyon::app_controls { /// @addtogroup controls /// @{ diff --git a/examples/app_controls/tests/app_controls_test.h b/examples/app_controls/tests/app_controls_test.h new file mode 100644 index 00000000..ea6db844 --- /dev/null +++ b/examples/app_controls/tests/app_controls_test.h @@ -0,0 +1,22 @@ +#pragma once + +// What the app-level controls' tests share: the style files that hold their styles, and their +// styles in a test's app. + +#include "headless_gui_app.h" + +#include + +#include + +namespace tachyon::app_controls +{ + /// The library's styles and the app-level controls' own; set before Initialize. + inline constexpr std::string_view kStyleFiles[] = { "styles.css", "app_controls.css" }; + + /// The controls' styles in `app`, from a fixture's const member functions too. + inline const Styles& ControlStyles(const GUITest::HeadlessGUIApp& app, Context& context) + { + return GetStyles(const_cast(app), context); + } +} diff --git a/examples/app_controls/tests/app_edit_id_release_test.cpp b/examples/app_controls/tests/app_edit_id_release_test.cpp new file mode 100644 index 00000000..374504b7 --- /dev/null +++ b/examples/app_controls/tests/app_edit_id_release_test.cpp @@ -0,0 +1,87 @@ +// What a timeline edit gives back as it leaves the undo history: the static IDs that only the +// side of it not in effect holds. Done, the items its undo would bring back; undone, the items +// its redo would add. IDs both sides hold stay. + +#include + +#include +#include + +#include + +namespace tachyon::app_controls +{ + namespace + { + TimelineTrack Track(ID id, std::vector keys, std::vector events = {}) + { + TimelineTrack track; + track.stableID = id; + for (ID key : keys) track.keys.push_back({ .stableID = key }); + for (ID event : events) track.events.push_back({ .stableID = event }); + return track; + } + + // Deletes key b from a track, removes a whole track, and moves a third one: removed + // from one place and added at another, so both sides hold it. + struct TimelineDeletion + { + IDManager ids; + ID kept = ids.CreateStaticID(), a = ids.CreateStaticID(), b = ids.CreateStaticID(); + ID gone = ids.CreateStaticID(), goneKey = ids.CreateStaticID(), goneEvent = ids.CreateStaticID(); + ID moved = ids.CreateStaticID(), movedKey = ids.CreateStaticID(); + TimelineEdit edit; + + TimelineDeletion() + { + edit.changes.push_back({ .track = 0, .from = Track(kept, { a, b }), .to = Track(kept, { a }) }); + edit.tracks.push_back({ .index = 1, .added = false, .track = Track(gone, { goneKey }, { goneEvent }) }); + edit.tracks.push_back({ .index = 2, .added = false, .track = Track(moved, { movedKey }) }); + edit.tracks.push_back({ .index = 0, .added = true, .track = Track(moved, { movedKey }) }); + } + }; + + TEST(EditIDRelease, ADoneTimelineEditGivesBackWhatItsUndoWouldBringBack) + { + TimelineDeletion t; + ReleaseTimelineEditIDs(t.ids, t.edit, /*undone*/ false); + EXPECT_FALSE(t.ids.IsStaticIDValid(t.b)); + EXPECT_FALSE(t.ids.IsStaticIDValid(t.gone)); + EXPECT_FALSE(t.ids.IsStaticIDValid(t.goneKey)); + EXPECT_FALSE(t.ids.IsStaticIDValid(t.goneEvent)); + for (ID id : { t.kept, t.a, t.moved, t.movedKey }) + EXPECT_TRUE(t.ids.IsStaticIDValid(id)) << "both sides hold it"; + EXPECT_EQ(t.ids.GetStaticIDCount(), 4u); + } + + TEST(EditIDRelease, AnUndoneTimelineEditGivesBackWhatItsRedoWouldAdd) + { + TimelineDeletion t; + ReleaseTimelineEditIDs(t.ids, t.edit, /*undone*/ true); + EXPECT_EQ(t.ids.GetStaticIDCount(), 8u) << "a deletion's redo adds nothing"; + + IDManager ids; + const ID key = ids.CreateStaticID(), added = ids.CreateStaticID(), track = ids.CreateStaticID(); + TimelineEdit add; + add.changes.push_back({ .track = 0, .from = Track(track, { key }), .to = Track(track, { key, added }) }); + ReleaseTimelineEditIDs(ids, add, /*undone*/ true); + EXPECT_FALSE(ids.IsStaticIDValid(added)); + EXPECT_TRUE(ids.IsStaticIDValid(key)); + EXPECT_TRUE(ids.IsStaticIDValid(track)); + } + + // An edit that neither adds nor removes anything gives nothing back. + TEST(EditIDRelease, AMoveGivesNothingBack) + { + IDManager ids; + const ID track = ids.CreateStaticID(), key = ids.CreateStaticID(); + TimelineEdit edit; + TimelineTrack later = Track(track, { key }); + later.keys[0].time = 1.0f; + edit.changes.push_back({ .track = 0, .from = Track(track, { key }), .to = later }); + ReleaseTimelineEditIDs(ids, edit, false); + ReleaseTimelineEditIDs(ids, edit, true); + EXPECT_EQ(ids.GetStaticIDCount(), 2u); + } + } +} diff --git a/examples/app_controls/tests/app_view_state_test.cpp b/examples/app_controls/tests/app_view_state_test.cpp new file mode 100644 index 00000000..dc6a337d --- /dev/null +++ b/examples/app_controls/tests/app_view_state_test.cpp @@ -0,0 +1,65 @@ +// A timeline's and a viewport's own state as text, for a panel to keep with its layout: the +// part of a timeline in view, a viewport's camera. Each comes back as it was; text that can't +// be read changes nothing. + +#include + +#include + +namespace tachyon::app_controls +{ + namespace + { + TEST(ViewState, ATimelinesViewComesBack) + { + TimelineView view; + view.viewStart = 2.5f; + view.viewLength = 4.0f; + view.zoom = 60; + TimelineView again; + ASSERT_TRUE(RestoreViewState(again, SaveViewState(view))); + EXPECT_EQ(again.viewStart, 2.5f); + EXPECT_EQ(again.viewLength, 4.0f); + EXPECT_EQ(again.zoom, 60); + } + + // A damaged state: numbers that would leave the view unusable are refused. + TEST(ViewState, AnUnusableTimelineViewIsRefused) + { + TimelineView timeline; + timeline.viewLength = 3.0f; + EXPECT_FALSE(RestoreViewState(timeline, R"({"start":0,"length":-2,"zoom":10})")); + EXPECT_EQ(timeline.viewLength, 3.0f); + EXPECT_TRUE(RestoreViewState(timeline, R"({"start":0,"length":0,"zoom":10})")) << "0: the whole duration"; + } + + TEST(ViewState, AViewportsCameraComesBack) + { + ViewportCamera camera; + camera.target = float3{ 1.0f, 2.0f, 3.0f }; + camera.distance = 12.0f; + camera.yaw = -0.3f; + camera.pitch = -0.8f; + camera.fovY = 1.0f; + camera.orthographic = true; + ViewportCamera again; + ASSERT_TRUE(RestoreViewState(again, SaveViewState(camera))); + EXPECT_EQ(again.target, camera.target); + EXPECT_EQ(again.distance, 12.0f); + EXPECT_EQ(again.yaw, -0.3f); + EXPECT_EQ(again.pitch, -0.8f); + EXPECT_EQ(again.fovY, 1.0f); + EXPECT_TRUE(again.orthographic); + } + + // The page open, by its name: IDs change between runs, names don't. A page that's + // gone keeps the one open. + + TEST(ViewState, TextACameraCantReadChangesNothing) + { + ViewportCamera camera; + EXPECT_FALSE(RestoreViewState(camera, R"({"distance":-5})")) << "a camera behind its target"; + EXPECT_EQ(camera.distance, ViewportCamera{}.distance); + } + } +} diff --git a/examples/app_controls/tests/file_system_test.cpp b/examples/app_controls/tests/file_system_test.cpp index 0a3971f3..91083121 100644 --- a/examples/app_controls/tests/file_system_test.cpp +++ b/examples/app_controls/tests/file_system_test.cpp @@ -24,7 +24,7 @@ #include #include -namespace tachyon +namespace tachyon::app_controls { namespace { diff --git a/examples/app_controls/tests/file_thumbnails_test.cpp b/examples/app_controls/tests/file_thumbnails_test.cpp index e97003ad..0e61c119 100644 --- a/examples/app_controls/tests/file_thumbnails_test.cpp +++ b/examples/app_controls/tests/file_thumbnails_test.cpp @@ -28,7 +28,7 @@ #include #include -namespace tachyon +namespace tachyon::app_controls { namespace { diff --git a/tests/timeline_editor_test.cpp b/examples/app_controls/tests/timeline_editor_test.cpp similarity index 93% rename from tests/timeline_editor_test.cpp rename to examples/app_controls/tests/timeline_editor_test.cpp index 04a4873e..77d6326a 100644 --- a/tests/timeline_editor_test.cpp +++ b/examples/app_controls/tests/timeline_editor_test.cpp @@ -3,17 +3,18 @@ #include -#include "headless_gui_app.h" +#include "app_controls_test.h" #include "skribidi_test_fixture.h" #include #include +#include #include #include #include -namespace tachyon +namespace tachyon::app_controls { using GUITest::HeadlessGUIApp; using GUITest::StubGUIRenderer; @@ -24,6 +25,8 @@ namespace tachyon { protected: HeadlessGUIApp app; + docking::Context dockingContext; + mutable Context controlsContext; TimelineView view; ID editorID{}; std::vector edits; @@ -35,7 +38,9 @@ namespace tachyon void SetUp() override { + 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(); @@ -68,7 +73,7 @@ namespace tachyon app.Frame([&] { app.BeginRootWindow({ 1600, 900 }, ElementFlags::None, app.theme.mainWindowStyleRef); if (disabled) app.BeginDisabled(); - app.TimelineEditor(editorID, view); + TimelineEditor(app, controlsContext, editorID, view); if (disabled) app.EndDisabled(); app.EndRootWindow(); }); @@ -126,7 +131,7 @@ namespace tachyon int2 RulerPoint(float time) const { const ElementRect* r = app.elementStorage.GetElementRectPtr( - app.elementStorage.FindElementRefByID(WithStyle(app.theme.timelineRulerStyleRef))); + app.elementStorage.FindElementRefByID(WithStyle(ControlStyles(app, controlsContext).timelineRulerStyleRef))); const TimelineRange shown = InView(); const float x = float(r->innerRect.x) + (time - shown.start) / (shown.end - shown.start) * float(r->innerRect.w); return { int32_t(std::lround(x)), r->innerRect.y + r->innerRect.h / 2 }; @@ -162,7 +167,7 @@ namespace tachyon IntRect LanesRange() const { const ElementRect* r = app.elementStorage.GetElementRectPtr( - app.elementStorage.FindElementRefByID(WithStyle(app.theme.timelineLanesStyleRef))); + app.elementStorage.FindElementRefByID(WithStyle(ControlStyles(app, controlsContext).timelineLanesStyleRef))); return r ? r->innerRect : IntRect{}; } TimelineRange InView() const @@ -207,8 +212,8 @@ namespace tachyon 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.TimelineEditor(editorID, view, LayoutOverride{}.FlexGrow(1)); + app.BeginArea(panel, docking::GetStyles(app, dockingContext).dockContentStyleRef); + TimelineEditor(app, controlsContext, editorID, view, LayoutOverride{}.FlexGrow(1)); app.EndArea(); app.EndRootWindow(); }); @@ -216,11 +221,11 @@ namespace tachyon EXPECT_GT(inner.h, 800) << "test setup: the panel fills the window"; EXPECT_EQ(app.GetElementRect(editorID).h, inner.h); // The scroll bar at its bottom: the body between grows. - const IntRect e = app.GetElementRect(editorID), s = app.GetElementRect(WithStyle(app.theme.timelineScrollStyleRef)); + const IntRect e = app.GetElementRect(editorID), s = app.GetElementRect(WithStyle(ControlStyles(app, controlsContext).timelineScrollStyleRef)); EXPECT_NEAR(s.y + s.h, e.y + e.h, 2); // The lanes and the list run down to it, however few the rows. - const IntRect lanes = app.GetElementRect(WithStyle(app.theme.timelineLanesStyleRef)); - const IntRect list = app.GetElementRect(WithStyle(app.theme.timelineListStyleRef)); + const IntRect lanes = app.GetElementRect(WithStyle(ControlStyles(app, controlsContext).timelineLanesStyleRef)); + const IntRect list = app.GetElementRect(WithStyle(ControlStyles(app, controlsContext).timelineListStyleRef)); EXPECT_NEAR(lanes.y + lanes.h, s.y, 2); EXPECT_NEAR(list.y + list.h, s.y, 2); } @@ -230,7 +235,7 @@ namespace tachyon TEST_F(TimelineEditorTest, TheZoomMagnifiersAreSmall) { Settle(); - const std::vector icons = AllWithStyle(app.theme.timelineZoomIconStyleRef); + const std::vector icons = AllWithStyle(ControlStyles(app, controlsContext).timelineZoomIconStyleRef); ASSERT_EQ(icons.size(), 2u) << "zoom out and zoom in"; for (const ID id : icons) { @@ -272,7 +277,7 @@ namespace tachyon EXPECT_EQ(view.viewStart, 0.0f); // Over the ruler, the same. - const IntRect ruler = Rect(app.theme.timelineRulerStyleRef); + const IntRect ruler = Rect(ControlStyles(app, controlsContext).timelineRulerStyleRef); app.InjectMouseScroll({ ruler.x + ruler.w / 2, ruler.y + ruler.h / 2 }, { 0, 1 }); Frame(); EXPECT_GT(view.viewLength, 0.0f); @@ -289,7 +294,7 @@ namespace tachyon view.viewLength = 2.0f; Settle(); auto& scrolling = app.guiStateManager.GetScrollManagement(); - const ScrollOffsetHandle body = scrolling.GetOrCreateScrollOffsetHandle(WithStyle(app.theme.timelineBodyStyleRef)); + const ScrollOffsetHandle body = scrolling.GetOrCreateScrollOffsetHandle(WithStyle(ControlStyles(app, controlsContext).timelineBodyStyleRef)); const int2 from = LanesPoint(3.0f, 3); app.InjectMouseMove(from); @@ -382,7 +387,7 @@ namespace tachyon view.viewLength = 2.0f; Settle(); auto& scrolling = app.guiStateManager.GetScrollManagement(); - const ScrollOffsetHandle body = scrolling.GetOrCreateScrollOffsetHandle(WithStyle(app.theme.timelineBodyStyleRef)); + const ScrollOffsetHandle body = scrolling.GetOrCreateScrollOffsetHandle(WithStyle(ControlStyles(app, controlsContext).timelineBodyStyleRef)); const int2 at = LanesPoint(3.0f, 2); app.InjectMouseMove(at); app.InjectMouseScroll(at, { 0, -1 }); @@ -528,14 +533,14 @@ namespace tachyon EXPECT_TRUE(app.HasElement(Row(music))); EXPECT_TRUE(app.HasElement(Row(events))); - Click(InRow(light, app.theme.timelineChevronStyleRef)); + Click(InRow(light, ControlStyles(app, controlsContext).timelineChevronStyleRef)); Settle(); EXPECT_TRUE(view.tracks[3].expanded); EXPECT_TRUE(app.HasElement(Row(intensity))); EXPECT_TRUE(edits.empty()) << "how it's shown, not a change to undo"; // A collapsed group hides only its own tracks: the next group's show. - Click(InRow(sphere, app.theme.timelineChevronStyleRef)); + Click(InRow(sphere, ControlStyles(app, controlsContext).timelineChevronStyleRef)); Settle(); EXPECT_FALSE(view.tracks[0].expanded); EXPECT_FALSE(app.HasElement(Row(position))); @@ -561,9 +566,9 @@ namespace tachyon EXPECT_FALSE(view.tracks[0].visible); Click(InRow(sphere, app.theme.timelineRowButtonStyleRef, 1)); EXPECT_TRUE(view.tracks[0].locked); - Click(InRow(music, app.theme.timelineMuteStyleRef)); + Click(InRow(music, ControlStyles(app, controlsContext).timelineMuteStyleRef)); EXPECT_TRUE(view.tracks[5].muted); - Click(InRow(music, app.theme.timelineSoloStyleRef)); + Click(InRow(music, ControlStyles(app, controlsContext).timelineSoloStyleRef)); EXPECT_TRUE(view.tracks[5].solo); ASSERT_EQ(edits.size(), 4u); for (auto it = edits.rbegin(); it != edits.rend(); ++it) @@ -594,7 +599,7 @@ namespace tachyon Settle(); Click(app.CenterOf(Row(music))); EXPECT_EQ(view.selectedTrack, music); - Click(Rect(app.theme.timelineAddTrackStyleRef)); + Click(Rect(ControlStyles(app, controlsContext).timelineAddTrackStyleRef)); EXPECT_EQ(added, 1); app.InjectMouseMove(app.CenterOf(Row(scale))); Frame(); @@ -960,7 +965,7 @@ namespace tachyon { Settle(); Click(LanesPoint(2.0f, 1)); - ASSERT_EQ(Focused(), WithStyle(app.theme.timelineLanesStyleRef)); + ASSERT_EQ(Focused(), WithStyle(ControlStyles(app, controlsContext).timelineLanesStyleRef)); // Right / Left move the selected keys a frame, as edits. Key(KeyCode::Right); @@ -1039,7 +1044,7 @@ namespace tachyon { view.playback.time = atEnd ? InView().end : InView().start; Settle(); - const ElementRef ruler = app.elementStorage.FindElementRefByID(WithStyle(app.theme.timelineRulerStyleRef)); + const ElementRef ruler = app.elementStorage.FindElementRefByID(WithStyle(ControlStyles(app, controlsContext).timelineRulerStyleRef)); const ElementCustomDraw* draw = app.elementStorage.GetCustomDraw(ruler); ASSERT_TRUE(draw != nullptr && draw->callback); const ElementRect* rects = app.elementStorage.GetElementRectPtr(ruler); @@ -1110,7 +1115,7 @@ namespace tachyon view.viewStart = 0.0f; view.viewLength = 2.0f; Settle(); - const ElementRect* bar = app.elementStorage.GetElementRectPtr(app.elementStorage.FindElementRefByID(WithStyle(app.theme.timelineScrollStyleRef))); + const ElementRect* bar = app.elementStorage.GetElementRectPtr(app.elementStorage.FindElementRefByID(WithStyle(ControlStyles(app, controlsContext).timelineScrollStyleRef))); ASSERT_NE(bar, nullptr); const IntRect track = bar->innerRect; const int y = track.y + track.h / 2; @@ -1128,7 +1133,7 @@ namespace tachyon { view.playback.time = 2.0f; Settle(); - const std::vector buttons = AllWithStyle(app.theme.timelineButtonStyleRef); + const std::vector buttons = AllWithStyle(ControlStyles(app, controlsContext).timelineButtonStyleRef); ASSERT_EQ(buttons.size(), 4u) << "start, previous, next, end"; Click(app.CenterOf(buttons[2])); EXPECT_FLOAT_EQ(view.playback.time, 3.0f) << "Intensity's, in the collapsed Light"; @@ -1144,9 +1149,9 @@ namespace tachyon EXPECT_FLOAT_EQ(view.playback.time, 8.0f) << "none after"; Click(app.CenterOf(buttons[0])); EXPECT_FLOAT_EQ(view.playback.time, 0.0f); - Click(app.CenterOf(One(app.theme.timelinePlayStyleRef))); + Click(app.CenterOf(One(ControlStyles(app, controlsContext).timelinePlayStyleRef))); EXPECT_TRUE(view.playback.playing); - Click(app.CenterOf(One(app.theme.timelineSnapStyleRef))); + Click(app.CenterOf(One(ControlStyles(app, controlsContext).timelineSnapStyleRef))); EXPECT_FALSE(view.snap); } @@ -1157,7 +1162,7 @@ namespace tachyon Settle(); Click(LanesPoint(2.0f, 1)); Click(RulerPoint(3.0f)); - app.guiStateManager.Interaction().SetFocusID(WithStyle(app.theme.timelineLanesStyleRef)); + app.guiStateManager.Interaction().SetFocusID(WithStyle(ControlStyles(app, controlsContext).timelineLanesStyleRef)); Frame(); Key(KeyCode::KeyA, KeyModifier::Control); Key(KeyCode::Delete); @@ -1173,7 +1178,7 @@ namespace tachyon view.selectedKeys = { positionKeys[0] }; Settle(); GUITest::StubGUIRenderer drawn; - const ElementRef ref = app.elementStorage.FindElementRefByID(WithStyle(app.theme.timelineLanesStyleRef)); + const ElementRef ref = app.elementStorage.FindElementRefByID(WithStyle(ControlStyles(app, controlsContext).timelineLanesStyleRef)); const ElementCustomDraw* draw = app.elementStorage.GetCustomDraw(ref); ASSERT_NE(draw, nullptr); const ElementRect* rects = app.elementStorage.GetElementRectPtr(ref); @@ -1185,14 +1190,30 @@ namespace tachyon }; // A diamond is two triangles; Position 3 keys + Scale 2; the summaries of Sphere (0, 1, // 2, 4 s) and of the collapsed Light (3 s). - EXPECT_EQ(trianglesIn(app.theme.timelineKeySelectedColor), 2); - EXPECT_EQ(trianglesIn(app.theme.timelineKeyColor), 2 * 4); - EXPECT_EQ(trianglesIn(app.theme.timelineSummaryKeyColor), 2 * 5); + EXPECT_EQ(trianglesIn(ControlStyles(app, controlsContext).timelineKeySelectedColor), 2); + EXPECT_EQ(trianglesIn(ControlStyles(app, controlsContext).timelineKeyColor), 2 * 4); + EXPECT_EQ(trianglesIn(ControlStyles(app, controlsContext).timelineSummaryKeyColor), 2 * 5); EXPECT_EQ(std::count(drawn.boxStyles.begin(), drawn.boxStyles.end(), - GUIRenderer::StyleIndex(app.theme.timelineClipStyleRef.visualBoxStyleIndex, ElementState::None)), 1); + GUIRenderer::StyleIndex(ControlStyles(app, controlsContext).timelineClipStyleRef.visualBoxStyleIndex, ElementState::None)), 1); EXPECT_EQ(std::count(drawn.boxStyles.begin(), drawn.boxStyles.end(), - GUIRenderer::StyleIndex(app.theme.timelineEventStyleRef.visualBoxStyleIndex, ElementState::None)), 2); + GUIRenderer::StyleIndex(ControlStyles(app, controlsContext).timelineEventStyleRef.visualBoxStyleIndex, ElementState::None)), 2); EXPECT_GE(drawn.quads.size(), 4u) << "the waveform's bars"; } + + // A track row's background changes under the pointer. + TEST(TimelineEditorStyle, ARowShowsHover) + { + HeadlessGUIApp app; + app.SetStyleFiles(kStyleFiles); + ASSERT_TRUE(app.Initialize()); + const StyleRef style = app.theme.GetStyle("timeline-row"); + auto background = [&](ElementState s) { + const VisualBoxStyle* box = app.styleManager.GetVisualBoxStyle(style.visualBoxStyleIndex, s); + return box ? box->backgroundColorIndex : VisualColorStyleIndex::Invalid; + }; + EXPECT_NE(background(ElementState::Hover), background(ElementState::None)); + app.Cleanup(); + } + } } diff --git a/examples/app_controls/tests/timeline_focus_test.cpp b/examples/app_controls/tests/timeline_focus_test.cpp new file mode 100644 index 00000000..b350cef8 --- /dev/null +++ b/examples/app_controls/tests/timeline_focus_test.cpp @@ -0,0 +1,113 @@ +// Keyboard focus in the timeline and its editor: Tab reaches their parts, and each part it +// reaches shows it has the focus (its style changes when focused, or that of a box around it +// that takes its state). + +#include + +#include "app_controls_test.h" + +#include + +#include +#include + +namespace tachyon::app_controls +{ + using GUITest::HeadlessGUIApp; + + namespace + { + class TimelineFocusTest : public ::testing::Test + { + protected: + void SetUp() override + { + app.SetStyleFiles(kStyleFiles); + ASSERT_TRUE(app.Initialize()); + timelineID = app.idManager.CreateStaticID(); + editorID = app.idManager.CreateStaticID(); + } + void TearDown() override { app.Cleanup(); } + + void Frame() + { + app.Frame([&] { + app.BeginRootWindow(); + Timeline(app, controlsContext, timelineID, playback, TimelineOptions{ .duration = 4.0f }); + TimelineEditor(app, controlsContext, editorID, animation, LayoutOverride{}.Height(240)); + app.EndRootWindow(); + }); + } + + // Whether `id` is `control` or inside it. + bool PartOf(ID id, ID control) const + { + const auto& storage = app.elementStorage; + for (ElementRef ref = storage.FindElementRefByID(id); ref.IsValid(); ref = storage.GetParentRef(ref)) + if (storage.GetElementUnsafe(ref).id == control) + return true; + return false; + } + + // Whether `id`'s element, or a box around it that takes its state, looks different + // when focused. + bool ShowsFocus(ID id) const + { + const auto& storage = app.elementStorage; + auto looksFocused = [&](const Element& e) { + const VisualBoxStyle* normal = app.styleManager.GetVisualBoxStyle(e.styleRef.visualBoxStyleIndex, ElementState::None); + const VisualBoxStyle* focused = app.styleManager.GetVisualBoxStyle(e.styleRef.visualBoxStyleIndex, ElementState::Focused); + return normal && focused && !(*normal == *focused); + }; + const ElementRef self = storage.FindElementRefByID(id); + for (ElementRef ref = self; ref.IsValid(); ref = storage.GetParentRef(ref)) + { + const Element& e = storage.GetElementUnsafe(ref); + if (e.id != id && (e.flags & ElementFlags::PropagatesDescendantState) == ElementFlags::None) + continue; + if (looksFocused(e)) + return true; + } + if (self.IsValid()) + for (const Element& part : storage.GetChildrenSpan(self)) + if ((part.state & ElementState::Focused) != ElementState::None && looksFocused(part)) + return true; + return false; + } + + HeadlessGUIApp app; + Context controlsContext; + ID timelineID, editorID; + TimelineState playback; + TimelineView animation; + }; + + TEST_F(TimelineFocusTest, TabReachesTheirPartsAndEachShowsTheFocus) + { + Frame(); + Frame(); + std::vector visited; + for (int i = 0; i < 80; ++i) + { + app.InjectKey(KeyCode::Tab, KeyAction::KeyDown); + Frame(); + app.InjectKey(KeyCode::Tab, KeyAction::KeyUp); + Frame(); + const ID focused = app.guiStateManager.Interaction().GetFocusedID(); + if (focused == ID::Invalid() || (!visited.empty() && focused == visited.front())) + break; + visited.push_back(focused); + } + // The Timeline's buttons and scrubber: its six buttons and the scrubber. + EXPECT_EQ(std::count_if(visited.begin(), visited.end(), [&](ID id) { return PartOf(id, timelineID); }), 7); + // The editor's: its toolbar, its filter and its lanes at least. + EXPECT_GE(std::count_if(visited.begin(), visited.end(), [&](ID id) { return PartOf(id, editorID); }), 10); + for (const ID id : visited) + { + app.guiStateManager.Interaction().SetFocusID(id); + Frame(); + EXPECT_TRUE(ShowsFocus(id)) << "a Tab stop shows no focus"; + } + } + } +} diff --git a/tests/timeline_internal_test.cpp b/examples/app_controls/tests/timeline_internal_test.cpp similarity index 96% rename from tests/timeline_internal_test.cpp rename to examples/app_controls/tests/timeline_internal_test.cpp index 577715aa..59928556 100644 --- a/tests/timeline_internal_test.cpp +++ b/examples/app_controls/tests/timeline_internal_test.cpp @@ -3,9 +3,9 @@ #include -#include +#include -namespace tachyon +namespace tachyon::app_controls { namespace { diff --git a/tests/timeline_test.cpp b/examples/app_controls/tests/timeline_test.cpp similarity index 89% rename from tests/timeline_test.cpp rename to examples/app_controls/tests/timeline_test.cpp index d305ddf5..9bf8bbe3 100644 --- a/tests/timeline_test.cpp +++ b/examples/app_controls/tests/timeline_test.cpp @@ -3,7 +3,7 @@ #include -#include "headless_gui_app.h" +#include "app_controls_test.h" #include "skribidi_test_fixture.h" #include @@ -13,7 +13,7 @@ #include #include -namespace tachyon +namespace tachyon::app_controls { using GUITest::HeadlessGUIApp; using GUITest::StubGUIRenderer; @@ -26,6 +26,7 @@ namespace tachyon { protected: HeadlessGUIApp app; + mutable Context controlsContext; TimelineState state; std::vector markers{ 1.5f, 5.2f }; TimelineOptions options{ .duration = 8.0f, .fps = 30.0f }; @@ -35,6 +36,7 @@ namespace tachyon void SetUp() override { + app.SetStyleFiles(kStyleFiles); ASSERT_TRUE(app.Initialize()); timelineID = app.idManager.CreateStaticID(); options.markers = markers; @@ -46,7 +48,7 @@ namespace tachyon app.Frame([&] { app.BeginRootWindow({ 1920, 1080 }, ElementFlags::None, app.theme.mainWindowStyleRef); if (disabled) app.BeginDisabled(); - changed = app.Timeline(timelineID, state, options); + changed = Timeline(app, controlsContext, timelineID, state, options); if (disabled) app.EndDisabled(); app.EndRootWindow(); }); @@ -74,10 +76,10 @@ namespace tachyon // The transport buttons without a style of their own: start, back, step, end. ID Button(int i) const { - const std::vector ids = WithStyle(app.theme.timelineButtonStyleRef); + const std::vector ids = WithStyle(ControlStyles(app, controlsContext).timelineButtonStyleRef); return i < (int)ids.size() ? ids[size_t(i)] : ID::Invalid(); } - ID Scrubber() const { return One(app.theme.timelineScrubberStyleRef); } + ID Scrubber() const { return One(ControlStyles(app, controlsContext).timelineScrubberStyleRef); } IntRect ScrubberRange() const { const ElementRect* rects = app.elementStorage.GetElementRectPtr(app.elementStorage.FindElementRefByID(Scrubber())); @@ -137,9 +139,9 @@ namespace tachyon state.time = 0.2f; Settle(); EXPECT_NE(app.FindByText("f 6"), ID::Invalid()) << "as wide as the last frame's, 240"; - EXPECT_EQ(WithStyle(app.theme.timelineButtonStyleRef).size(), 4u); - EXPECT_NE(One(app.theme.timelinePlayStyleRef), ID::Invalid()); - EXPECT_NE(One(app.theme.timelineLoopStyleRef), ID::Invalid()); + EXPECT_EQ(WithStyle(ControlStyles(app, controlsContext).timelineButtonStyleRef).size(), 4u); + EXPECT_NE(One(ControlStyles(app, controlsContext).timelinePlayStyleRef), ID::Invalid()); + EXPECT_NE(One(ControlStyles(app, controlsContext).timelineLoopStyleRef), ID::Invalid()); EXPECT_NE(Scrubber(), ID::Invalid()); // Over a minute; without frames, no frame chip. @@ -149,10 +151,10 @@ namespace tachyon Settle(); EXPECT_NE(app.FindByText("01:01.01"), ID::Invalid()); EXPECT_NE(app.FindByText("/ 02:05.00"), ID::Invalid()); - EXPECT_EQ(WithStyle(app.theme.timelineFrameStyleRef).size(), 0u); + EXPECT_EQ(WithStyle(ControlStyles(app, controlsContext).timelineFrameStyleRef).size(), 0u); options.fps = -30.0f; Settle(); - EXPECT_EQ(WithStyle(app.theme.timelineFrameStyleRef).size(), 0u) << "nor with a negative rate"; + EXPECT_EQ(WithStyle(ControlStyles(app, controlsContext).timelineFrameStyleRef).size(), 0u) << "nor with a negative rate"; } // A time outside the length, or not a number, is put inside it; so is any time when @@ -181,7 +183,7 @@ namespace tachyon state.time = 2.0f; Settle(); EXPECT_FALSE(changed); - Click(One(app.theme.timelinePlayStyleRef)); + Click(One(ControlStyles(app, controlsContext).timelinePlayStyleRef)); EXPECT_TRUE(state.playing); EXPECT_EQ(state.time, 2.0f); Frame(); @@ -190,12 +192,12 @@ namespace tachyon Frame(); EXPECT_FALSE(changed) << "only on the frame it changed"; - Click(One(app.theme.timelinePlayStyleRef)); + Click(One(ControlStyles(app, controlsContext).timelinePlayStyleRef)); EXPECT_FALSE(state.playing); state.time = 8.0f; Settle(); - Click(One(app.theme.timelinePlayStyleRef)); + Click(One(ControlStyles(app, controlsContext).timelinePlayStyleRef)); EXPECT_TRUE(state.playing); EXPECT_EQ(state.time, 0.0f) << "from the start again"; } @@ -244,11 +246,11 @@ namespace tachyon TEST_F(TimelineTest, TheLoopToggleSetsLooping) { Settle(); - Click(One(app.theme.timelineLoopStyleRef)); + Click(One(ControlStyles(app, controlsContext).timelineLoopStyleRef)); EXPECT_TRUE(state.loop); Frame(); EXPECT_TRUE(changed); - Click(One(app.theme.timelineLoopStyleRef)); + Click(One(ControlStyles(app, controlsContext).timelineLoopStyleRef)); EXPECT_FALSE(state.loop); } @@ -377,7 +379,7 @@ namespace tachyon Settle(); app.ClickAt(OnScrubber(0.75f)); Frame(); - Click(One(app.theme.timelinePlayStyleRef)); + Click(One(ControlStyles(app, controlsContext).timelinePlayStyleRef)); Click(Button(3)); Frame(); EXPECT_EQ(state.time, 2.0f); @@ -418,17 +420,17 @@ namespace tachyon const float perSecond = float(range.w) / 8.0f; const StubGUIRenderer drawn = Draw(); - const std::vector ready = BoxesIn(drawn, app.theme.timelineReadyStyleRef); + const std::vector ready = BoxesIn(drawn, ControlStyles(app, controlsContext).timelineReadyStyleRef); ASSERT_EQ(ready.size(), 1u); EXPECT_LT(ready[0].x, 0) << "from the scrubber's own start, before the padding"; EXPECT_NEAR(float(ready[0].x + ready[0].w), 6.0f * perSecond, 1.0f); - const std::vector lines = BoxesIn(drawn, app.theme.timelineMarkerStyleRef); + const std::vector lines = BoxesIn(drawn, ControlStyles(app, controlsContext).timelineMarkerStyleRef); ASSERT_EQ(lines.size(), 2u) << "only the two inside the length"; EXPECT_NEAR(float(lines[0].x) + float(lines[0].w) / 2.0f, 1.5f * perSecond, 1.0f) << "in order"; EXPECT_NEAR(float(lines[1].x) + float(lines[1].w) / 2.0f, 5.2f * perSecond, 1.0f); - const std::vector head = BoxesIn(drawn, app.theme.timelinePlayheadStyleRef); + const std::vector head = BoxesIn(drawn, ControlStyles(app, controlsContext).timelinePlayheadStyleRef); ASSERT_EQ(head.size(), 2u) << "the line and its head"; EXPECT_NEAR(float(head[0].x) + float(head[0].w) / 2.0f, 2.0f * perSecond, 1.0f); EXPECT_EQ(head[0].h, range.h); @@ -436,7 +438,7 @@ namespace tachyon // Major ticks one of the usual steps apart, at least 48px, from the start to the // end; three minor ones between. - const std::vector major = BoxesIn(drawn, app.theme.timelineTickMajorStyleRef); + const std::vector major = BoxesIn(drawn, ControlStyles(app, controlsContext).timelineTickMajorStyleRef); ASSERT_GE(major.size(), 2u); const float step = float(major[1].x - major[0].x) / perSecond; EXPECT_GE(major[1].x - major[0].x, app.styleManager.Px(48)); @@ -444,12 +446,12 @@ namespace tachyon EXPECT_EQ(major.size(), size_t(std::lround(8.0f / step)) + 1); EXPECT_EQ(major.front().x, 0); EXPECT_NEAR(float(major.back().x), float(range.w), 1.0f); - EXPECT_EQ(BoxesIn(drawn, app.theme.timelineTickStyleRef).size(), (major.size() - 1) * 3); + EXPECT_EQ(BoxesIn(drawn, ControlStyles(app, controlsContext).timelineTickStyleRef).size(), (major.size() - 1) * 3); // Without progress, no fill. options.progress = -1.0f; Settle(); - EXPECT_TRUE(BoxesIn(Draw(), app.theme.timelineReadyStyleRef).empty()); + EXPECT_TRUE(BoxesIn(Draw(), ControlStyles(app, controlsContext).timelineReadyStyleRef).empty()); } // Fewer, farther apart ticks where a second is too short to tick. @@ -457,7 +459,7 @@ namespace tachyon { options.duration = 3600.0f; Settle(); - const std::vector major = BoxesIn(Draw(), app.theme.timelineTickMajorStyleRef); + const std::vector major = BoxesIn(Draw(), ControlStyles(app, controlsContext).timelineTickMajorStyleRef); ASSERT_GE(major.size(), 2u); EXPECT_LE(major.size(), 61u); EXPECT_GE(major[1].x - major[0].x, app.styleManager.Px(48)); diff --git a/tests/timeline_two_views_test.cpp b/examples/app_controls/tests/timeline_two_views_test.cpp similarity index 91% rename from tests/timeline_two_views_test.cpp rename to examples/app_controls/tests/timeline_two_views_test.cpp index 122f5a19..4df6a64c 100644 --- a/tests/timeline_two_views_test.cpp +++ b/examples/app_controls/tests/timeline_two_views_test.cpp @@ -4,12 +4,12 @@ #include -#include "headless_gui_app.h" +#include "app_controls_test.h" #include "misuse_reports.h" -#include +#include -namespace tachyon +namespace tachyon::app_controls { using GUITest::HeadlessGUIApp; @@ -19,6 +19,7 @@ namespace tachyon { protected: HeadlessGUIApp app; + mutable Context controlsContext; TimelineData data; TimelineViewState top, bottom; ID topID{}, bottomID{}; @@ -27,6 +28,7 @@ namespace tachyon void SetUp() override { + app.SetStyleFiles(kStyleFiles); ASSERT_TRUE(app.Initialize()); auto make = [&] { return app.idManager.CreateStaticID(); }; topID = make(); bottomID = make(); @@ -47,8 +49,8 @@ namespace tachyon { app.Frame([&] { app.BeginRootWindow({ 1600, 1000 }, ElementFlags::None, app.theme.mainWindowStyleRef); - app.TimelineEditor(topID, { data, top }, LayoutOverride{}.FlexGrow(1)); - app.TimelineEditor(bottomID, { data, bottom }, LayoutOverride{}.FlexGrow(1)); + TimelineEditor(app, controlsContext, topID, { data, top }, LayoutOverride{}.FlexGrow(1)); + TimelineEditor(app, controlsContext, bottomID, { data, bottom }, LayoutOverride{}.FlexGrow(1)); app.EndRootWindow(); }); } diff --git a/tests/viewport_test.cpp b/examples/app_controls/tests/viewport_test.cpp similarity index 97% rename from tests/viewport_test.cpp rename to examples/app_controls/tests/viewport_test.cpp index e4b6d8ea..fa75c3f3 100644 --- a/tests/viewport_test.cpp +++ b/examples/app_controls/tests/viewport_test.cpp @@ -2,15 +2,15 @@ #include -#include "headless_gui_app.h" +#include "app_controls_test.h" -#include +#include #include #include #include -namespace tachyon +namespace tachyon::app_controls { using GUITest::HeadlessGUIApp; @@ -327,6 +327,7 @@ namespace tachyon { protected: HeadlessGUIApp app; + mutable Context controlsContext; ViewportView view; ID viewID{}; int changes = 0; @@ -335,6 +336,7 @@ namespace tachyon void SetUp() override { + app.SetStyleFiles(kStyleFiles); ASSERT_TRUE(app.Initialize()); app.runPostLayoutCallbacks = true; viewID = app.idManager.CreateStaticID(); @@ -352,7 +354,7 @@ namespace tachyon { app.Frame([&] { app.BeginRootWindow({ 1000, 700 }, ElementFlags::None, app.theme.mainWindowStyleRef); - if (app.Viewport(viewID, view, LayoutOverride{}.Size(800, 600))) + if (Viewport(app, controlsContext, viewID, view, LayoutOverride{}.Size(800, 600))) ++changes; app.EndRootWindow(); }); @@ -387,7 +389,7 @@ namespace tachyon const auto& storage = app.elementStorage; for (auto it = storage.TopDownDepthScanBegin(); it != storage.TopDownDepthScanEnd(); ++it) for (const Element& e : it->GetChildren(storage)) - if (e.styleRef.visualBoxStyleIndex == app.theme.viewportToolStyleRef.visualBoxStyleIndex) + if (e.styleRef.visualBoxStyleIndex == ControlStyles(app, controlsContext).viewportToolStyleRef.visualBoxStyleIndex) buttons.push_back(e.id); return buttons; } @@ -408,7 +410,7 @@ namespace tachyon if (app.BeginCached(scope, app.theme.emptyVertStyleRef, 0, LayoutOverride{}.Size(width, 600))) { ++builds; - app.Viewport(viewID, view, LayoutOverride{}.FlexGrow(1)); + Viewport(app, controlsContext, viewID, view, LayoutOverride{}.FlexGrow(1)); } app.EndCached(); app.EndRootWindow(); @@ -637,7 +639,7 @@ namespace tachyon app.Frame([&] { app.BeginRootWindow({ 1000, 700 }, ElementFlags::None, app.theme.mainWindowStyleRef); app.BeginDisabled(); - app.Viewport(viewID, view, LayoutOverride{}.Size(800, 600)); + Viewport(app, controlsContext, viewID, view, LayoutOverride{}.Size(800, 600)); app.EndDisabled(); app.EndRootWindow(); }); diff --git a/examples/controls/CMakeLists.txt b/examples/controls/CMakeLists.txt index fe89dbf9..17f3bfdc 100644 --- a/examples/controls/CMakeLists.txt +++ b/examples/controls/CMakeLists.txt @@ -1 +1 @@ -tachyon_add_example(controls controls.cpp) +tachyon_add_example(controls controls.cpp LIBS gui_color) diff --git a/examples/controls/controls.cpp b/examples/controls/controls.cpp index 8fe46055..896b8f0c 100644 --- a/examples/controls/controls.cpp +++ b/examples/controls/controls.cpp @@ -1,5 +1,6 @@ // Controls overview: the common controls, laid out as label/value rows. #include +#include #include @@ -18,6 +19,19 @@ class ControlsApp : public tachyon::GUIApplication } void OnGUI() override + { + BuildWindow(); + tachyon::color::EndGUI(*this, colorContext); // last, every frame + } + + void Cleanup() override + { + tachyon::color::Cleanup(*this, colorContext); + GUIApplication::Cleanup(); + } + +private: + void BuildWindow() { // The scope ends the window when it leaves, open or not. auto window = Window(windowID, "Controls", tachyon::LayoutOverride{}.Size(480, 560)); @@ -64,7 +78,7 @@ class ControlsApp : public tachyon::GUIApplication SliderField(volume, 0.0f, 100.0f, "Volume"); Label("Color"); - ColorField(color); + tachyon::color::ColorField(*this, colorContext, color); Label("Menu"); if (BeginMenu(menuID, "Choose...", tachyon::LayoutOverride{}.NoGrow().NoShrink())) @@ -89,7 +103,7 @@ class ControlsApp : public tachyon::GUIApplication EndVertical(); } -private: + tachyon::color::Context colorContext; // the color field's picker tachyon::ID windowID = tachyon::ID::Invalid(); tachyon::ID menuID = tachyon::ID::Invalid(); int clicks = 0; 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 45503070..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 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 46fde286..f0339f7d 100644 --- a/examples/showcase/application.cpp +++ b/examples/showcase/application.cpp @@ -4,14 +4,17 @@ #include #include // CommandMode enum (why is this defined here?) #include // Diagnostics::IsProfilingEnabled (profiler panel cache opt-out) -#include // ApplyNodeViewEdit (node-view undo) -#include +#include // ApplyNodeViewEdit (node-view undo) #include #if TACHYON_D3D12 #include #endif #if TACHYON_VULKAN #include +#include +#include +#include +#include #endif #include @@ -34,13 +37,14 @@ namespace tachyon Result Application::Initialize(const InitializeOptions& options) { - const std::string_view styleFiles[] = { "styles.css", "showcase.css" }; + const std::string_view styleFiles[] = { "styles.css", "app_controls.css", "showcase.css" }; SetStyleFiles(styleFiles); // The showcase shows text in many scripts, so it loads the optional Noto fallbacks. InitializeOptions withFallbacks = options; 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() || @@ -64,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) @@ -164,6 +168,9 @@ namespace tachyon void Application::Cleanup() { + dialogs::Cleanup(*this, dialogContext); + color::Cleanup(*this, colorContext); + docking::Cleanup(*this, dockingContext); if (pastedImage != nullptr && graphicsContext != nullptr) { graphicsContext->UnregisterImage(pastedImageIndex); @@ -172,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(); @@ -199,21 +206,21 @@ namespace tachyon // Made on first use, so some may never have been. const auto release = [this](ID id) { if (id != ID::Invalid()) idManager.ReleaseStaticID(id); }; - for (const NodeGraph* view : { &showcase.nodeGraph, &showcase.enemyMachine, &showcase.combatMachine }) + for (const nodes::NodeGraph* view : { &showcase.nodeGraph, &showcase.enemyMachine, &showcase.combatMachine }) { - for (const NodeModel& node : view->nodes) release(node.stableID); - for (const NodeFrame& frame : view->frames) release(frame.stableID); - for (const StateTransition& transition : view->transitions) release(transition.stableID); + for (const nodes::NodeModel& node : view->nodes) release(node.stableID); + for (const nodes::NodeFrame& frame : view->frames) release(frame.stableID); + for (const nodes::StateTransition& transition : view->transitions) release(transition.stableID); } - for (const TimelineTrack& track : animation.tracks) + for (const app_controls::TimelineTrack& track : animation.tracks) { release(track.stableID); - for (const TimelineKey& key : track.keys) release(key.stableID); - for (const TimelineEvent& event : track.events) release(event.stableID); + for (const app_controls::TimelineKey& key : track.keys) release(key.stableID); + for (const app_controls::TimelineEvent& event : track.events) release(event.stableID); } - for (const CurveData* view : { &animationCurves, &showcase.demoCurve, &showcase.demoColorCurves }) - for (const CurveChannel& channel : view->channels) - for (const CurveKey& key : channel.curve.keys) + for (const curves::CurveData* view : { &animationCurves, &showcase.demoCurve, &showcase.demoColorCurves }) + for (const curves::CurveChannel& channel : view->channels) + for (const curves::CurveKey& key : channel.curve.keys) release(key.stableID); release(m_capture.windowID); release(m_capture.areaID); @@ -245,33 +252,33 @@ namespace tachyon GUIApplication::Cleanup(); } - void Application::SetUpNodeGraphView(NodeViewState& view) + void Application::SetUpNodeGraphView(nodes::NodeViewState& view) { - NodeViewState* const self = &view; + nodes::NodeViewState* const self = &view; view.commandMode = nodeViewMode; view.breadcrumb = { "Graphs", "Terrain material" }; // A new wire dropped on the empty canvas: a reroute there, of the wire's kind, wired // to where the wire came from. An app would offer the nodes it could take. - self->onWireDroppedOnCanvas = [this, self](PropertyEndpoint from, bool fromOutput, float2 at) + self->onWireDroppedOnCanvas = [this, self](nodes::PropertyEndpoint from, bool fromOutput, float2 at) { - const NodeViewRef shown{ showcase.nodeGraph, *self }; + const nodes::NodeViewRef shown{ showcase.nodeGraph, *self }; // Added and wired in one step, so one undo takes both back. - NodeViewEdit edit = AddNodeEdit(shown, RerouteNode(at, + nodes::NodeViewEdit edit = nodes::AddNodeEdit(shown, RerouteNode(at, shown.graph.nodes[size_t(from.nodeIdx)].properties[size_t(from.propIdx)].socketColor)); - const PropertyEndpoint added{ edit.nodes[0].index, 0 }; + const nodes::PropertyEndpoint added{ edit.nodes[0].index, 0 }; if (fromOutput) edit.rewires.push_back({ .input = added, .from = {}, .to = from }); else edit.rewires.push_back({ .input = from, .from = {}, .to = added }); - CommitNodeViewEdit(shown, edit); + nodes::CommitNodeViewEdit(shown, edit); }; // The selection changing, as a properties panel would follow it. self->onSelectionChanged = [this, self] { std::string titles; - for (const NodeModel& node : showcase.nodeGraph.nodes) + for (const nodes::NodeModel& node : showcase.nodeGraph.nodes) if (self->selectedNodeIDs.contains(node.stableID)) titles += (titles.empty() ? "" : ", ") + node.title; TACHYON_LOG_INFO(kLogShowcase, "Node selection: {}", titles.empty() ? std::string("none") : titles); @@ -291,19 +298,19 @@ namespace tachyon } EndMenu(); // also while it's closed MenuItem("Add Reroute here", [this, self, at] { - CommitNodeViewEdit({ showcase.nodeGraph, *self }, AddNodeEdit({ showcase.nodeGraph, *self }, RerouteNode(at, { 0.20f, 0.75f, 0.72f, 1.0f }))); + nodes::CommitNodeViewEdit({ showcase.nodeGraph, *self }, nodes::AddNodeEdit({ showcase.nodeGraph, *self }, RerouteNode(at, { 0.20f, 0.75f, 0.72f, 1.0f }))); }); MenuSeparator(); const bool selection = !self->selectedNodeIDs.empty(); - MenuItem(selection ? "Frame selection" : "Frame all", [this, self] { FrameSelectedNodes({ showcase.nodeGraph, *self }); }); - const bool curved = showcase.nodeGraph.wireShape == NodeWireShape::Curved; + MenuItem(selection ? "Frame selection" : "Frame all", [this, self] { nodes::FrameSelectedNodes({ showcase.nodeGraph, *self }); }); + const bool curved = showcase.nodeGraph.wireShape == nodes::NodeWireShape::Curved; MenuItem(curved ? "Show grid aligned wires" : "Show curved wires", [this, curved] { - showcase.nodeGraph.wireShape = curved ? NodeWireShape::Orthogonal : NodeWireShape::Curved; + showcase.nodeGraph.wireShape = curved ? nodes::NodeWireShape::Orthogonal : nodes::NodeWireShape::Curved; }); // An empty frame where it was clicked, its title bar's left end there. MenuItem("Add frame here", [this, self, at] { - const int g = std::max(1, theme.nodeGridSize); - CommitNodeViewEdit({ showcase.nodeGraph, *self }, AddFrameEdit({ showcase.nodeGraph, *self }, NodeFrame{ + const int g = std::max(1, nodes::GetStyles(*this, nodesContext).nodeGridSize); + nodes::CommitNodeViewEdit({ showcase.nodeGraph, *self }, nodes::AddFrameEdit({ showcase.nodeGraph, *self }, nodes::NodeFrame{ .stableID = idManager.CreateStaticID(), .title = "Frame", .pos = { int32_t(at.x), int32_t(at.y) }, .size = { 24 * g, 14 * g } })); }); @@ -311,10 +318,10 @@ namespace tachyon // A frame's menu: rename it, tint it, or take it away (its nodes stay). self->onFrameContextMenu = [this, self](int frame) { - MenuItem("Rename", [this, self, frame] { RenameFrame({ showcase.nodeGraph, *self }, frame); }); + MenuItem("Rename", [this, self, frame] { nodes::RenameFrame({ showcase.nodeGraph, *self }, frame); }); const bool collapsed = showcase.nodeGraph.frames[size_t(frame)].collapsed; MenuItem(collapsed ? "Expand" : "Collapse", [this, self, frame, collapsed] { - CommitNodeViewEdit({ showcase.nodeGraph, *self }, CollapseFrameEdit({ showcase.nodeGraph, *self }, frame, !collapsed)); + nodes::CommitNodeViewEdit({ showcase.nodeGraph, *self }, nodes::CollapseFrameEdit({ showcase.nodeGraph, *self }, frame, !collapsed)); }); if (BeginMenu("Color")) { @@ -332,10 +339,10 @@ namespace tachyon const bool current = showcase.nodeGraph.frames[size_t(frame)].color == tint.color; if (current) BeginSelected(); MenuItem(tint.name, [this, self, frame, color = tint.color] { - const NodeViewRef shown{ showcase.nodeGraph, *self }; - NodeFrame tinted = shown.graph.frames[size_t(frame)]; + const nodes::NodeViewRef shown{ showcase.nodeGraph, *self }; + nodes::NodeFrame tinted = shown.graph.frames[size_t(frame)]; tinted.color = color; - CommitNodeViewEdit(shown, NodeViewEdit{ .frameChanges = { { frame, shown.graph.frames[size_t(frame)], tinted } } }); + nodes::CommitNodeViewEdit(shown, nodes::NodeViewEdit{ .frameChanges = { { frame, shown.graph.frames[size_t(frame)], tinted } } }); }); if (current) EndSelected(); } @@ -344,7 +351,7 @@ namespace tachyon MenuSeparator(); MenuItem({ showcase.deleteIcon, "Delete frame" }, [this, self, frame] { const int only[] = { frame }; - CommitNodeViewEdit({ showcase.nodeGraph, *self }, RemoveFramesEdit({ showcase.nodeGraph, *self }, only)); + nodes::CommitNodeViewEdit({ showcase.nodeGraph, *self }, nodes::RemoveFramesEdit({ showcase.nodeGraph, *self }, only)); }); }; self->onNodeContextMenu = [this, self](int node) @@ -353,13 +360,13 @@ namespace tachyon // node, reroutes aside, or delete it, saying how much that is. const bool collapse = !showcase.nodeGraph.nodes[size_t(node)].collapsed; MenuItem(collapse ? "Collapse" : "Expand", [this, self, collapse] { - const NodeViewRef shown{ showcase.nodeGraph, *self }; - NodeViewEdit edit; + const nodes::NodeViewRef shown{ showcase.nodeGraph, *self }; + nodes::NodeViewEdit edit; for (int n = 0; n < int(shown.graph.nodes.size()); ++n) - if (const NodeModel& other = shown.graph.nodes[size_t(n)]; + if (const nodes::NodeModel& other = shown.graph.nodes[size_t(n)]; shown.state.selectedNodeIDs.contains(other.stableID) && !other.reroute && other.collapsed != collapse) edit.collapses.push_back({ n, other.collapsed, collapse }); - CommitNodeViewEdit(shown, edit); + nodes::CommitNodeViewEdit(shown, edit); }); // A frame round the selection, the selected frames in it too. MenuItem("Group selection", "Ctrl G", [this, self] { GroupSelection(*self); }); @@ -389,7 +396,7 @@ namespace tachyon for (const color4f recent : { color4f{ 0.290f, 0.761f, 0.549f, 1.0f }, color4f{ 0.180f, 0.290f, 1.000f, 1.0f }, color4f{ 0.545f, 0.176f, 0.839f, 0.5f }, color4f{ 1.000f, 0.180f, 0.180f, 1.0f }, color4f{ 0.231f, 0.510f, 0.965f, 1.0f } }) - AddRecentColor(recent); + color::AddRecentColor(*this, colorContext, recent); // Files or text dropped from another application where nothing takes them (the Files // panel does): noted in the log. @@ -409,7 +416,7 @@ namespace tachyon commandManager.RegisterCommand(stateMachineMode, showcase.deleteIcon, tachyon::KeyCode::Delete, tachyon::KeyModifier::None, [this]() { if (FocusedStateMachine()) DeleteSelectedStates(FocusedMachineView()); }, "Delete States"); commandManager.RegisterCommand(stateMachineMode, showcase.frameSelectedIcon, tachyon::KeyCode::KeyF, tachyon::KeyModifier::None, - [this]() { if (FocusedStateMachine()) FrameSelectedNodes(FocusedMachineView()); }, + [this]() { if (FocusedStateMachine()) nodes::FrameSelectedNodes(FocusedMachineView()); }, "Frame Selected"); hierarchyMode = commandManager.RegisterMode("Hierarchy"); hierarchyDelete = commandManager.RegisterCommand(hierarchyMode, showcase.deleteIcon, tachyon::KeyCode::Delete, tachyon::KeyModifier::None, @@ -421,7 +428,7 @@ namespace tachyon [this]() { TACHYON_LOG_INFO(kLogShowcase, "Reset view"); - if (NodeViewState* view = FocusedGraphView()) + if (nodes::NodeViewState* view = FocusedGraphView()) view->transform = tachyon::float3x2::Identity(); }, "Reset view" @@ -482,11 +489,11 @@ namespace tachyon []() { TACHYON_LOG_INFO(kLogShowcase, "Hold end: Pan View"); }, "Pan View (hold)"); - // NodeView - graph navigation - commandManager.RegisterCommand(nodeViewMode, showcase.frameSelectedIcon, tachyon::KeyCode::KeyF, tachyon::KeyModifier::None, [this]() { if (NodeViewState* view = FocusedGraphView()) FrameSelectedNodes({ showcase.nodeGraph, *view }); }, "Frame Selected"); + // nodes::NodeView - graph navigation + commandManager.RegisterCommand(nodeViewMode, showcase.frameSelectedIcon, tachyon::KeyCode::KeyF, tachyon::KeyModifier::None, [this]() { if (nodes::NodeViewState* view = FocusedGraphView()) nodes::FrameSelectedNodes({ showcase.nodeGraph, *view }); }, "Frame Selected"); commandManager.RegisterCommand(nodeViewMode, tachyon::KeyCode::KeyA, tachyon::KeyModifier::None, []() { TACHYON_LOG_INFO(kLogShowcase, "Command: {}", "Frame All"); }, "Frame All"); commandManager.RegisterCommand(nodeViewMode, tachyon::KeyCode::Space, tachyon::KeyModifier::None, []() { TACHYON_LOG_INFO(kLogShowcase, "Command: {}", "Search Nodes"); }, "Search Nodes"); - commandManager.RegisterCommand(nodeViewMode, tachyon::KeyCode::KeyG, tachyon::KeyModifier::Control, [this]() { if (NodeViewState* view = FocusedGraphView()) GroupSelection(*view); }, "Group Selection"); + commandManager.RegisterCommand(nodeViewMode, tachyon::KeyCode::KeyG, tachyon::KeyModifier::Control, [this]() { if (nodes::NodeViewState* view = FocusedGraphView()) GroupSelection(*view); }, "Group Selection"); // Sculpt - brush operations. commandManager.RegisterCommand(sculptMode, tachyon::KeyCode::LeftBracket, tachyon::KeyModifier::None, []() { TACHYON_LOG_INFO(kLogShowcase, "Command: {}", "Decrease Brush Size"); }, "Decrease Brush Size"); @@ -506,92 +513,92 @@ namespace tachyon // NodeText aligns to its socket (output => right, input => left, // pass-through => centred); editable rows use Label + Field. - NodeModel src; + nodes::NodeModel src; src.title = "Source"; src.pos = { styleManager.Px(-340), styleManager.Px(-140) }; - src.properties.push_back(NodeProperty + src.properties.push_back(nodes::NodeProperty { .output = true, - .renderBody = [this]() { NodeText(showcase.nodeName); }, // output => right-aligned + .renderBody = [this]() { nodes::NodeText(*this, nodesContext, showcase.nodeName); }, // output => right-aligned .socketColor = kTeal }); - src.properties.push_back(NodeProperty + src.properties.push_back(nodes::NodeProperty { .output = true, .renderBody = [this]() { Label("Seed"); Field(showcase.nodeSeed); }, .socketColor = kAmber }); - src.properties.push_back(NodeProperty + src.properties.push_back(nodes::NodeProperty { .output = true, .renderBody = [this]() { Label("Enabled"); Switch(showcase.nodeEnabled); }, .socketColor = kPurple }); - NodeModel mix; + nodes::NodeModel mix; mix.title = "Mix"; mix.pos = { styleManager.Px(40), styleManager.Px(-60) }; - mix.properties.push_back(NodeProperty + mix.properties.push_back(nodes::NodeProperty { - .input = PropertyEndpoint{}, - .renderBody = [this]() { NodeText("Strength"); }, // input => left-aligned + .input = nodes::PropertyEndpoint{}, + .renderBody = [this]() { nodes::NodeText(*this, nodesContext, "Strength"); }, // input => left-aligned .socketColor = kTeal }); - mix.properties.push_back(NodeProperty + mix.properties.push_back(nodes::NodeProperty { - .input = PropertyEndpoint{}, + .input = nodes::PropertyEndpoint{}, .renderBody = [this]() { Label("Gain"); Field(showcase.nodeGain, TextEditBehavior::ContinuousUpdate, NumericFieldConfig{ .decimals = 2 }); }, .socketColor = kAmber }); - mix.properties.push_back(NodeProperty + mix.properties.push_back(nodes::NodeProperty { - .input = PropertyEndpoint{}, + .input = nodes::PropertyEndpoint{}, .output = true, - .renderBody = [this]() { NodeText("Bypass"); }, // both dots => centred + .renderBody = [this]() { nodes::NodeText(*this, nodesContext, "Bypass"); }, // both dots => centred .socketColor = kPurple }); - mix.properties.push_back(NodeProperty + mix.properties.push_back(nodes::NodeProperty { .output = true, - .renderBody = [this]() { NodeText("Result"); }, // output => right-aligned + .renderBody = [this]() { nodes::NodeText(*this, nodesContext, "Result"); }, // output => right-aligned .socketColor = kTeal }); - NodeModel out; + nodes::NodeModel out; out.title = "Output"; out.pos = { styleManager.Px(180), styleManager.Px(100) }; - out.properties.push_back(NodeProperty + out.properties.push_back(nodes::NodeProperty { - .input = PropertyEndpoint{}, - .renderBody = [this]() { NodeText("Value"); }, // input => left-aligned + .input = nodes::PropertyEndpoint{}, + .renderBody = [this]() { nodes::NodeText(*this, nodesContext, "Value"); }, // input => left-aligned .socketColor = kTeal // accepts Mix.Result / Source.Name }); - out.properties.push_back(NodeProperty + out.properties.push_back(nodes::NodeProperty { - .input = PropertyEndpoint{}, + .input = nodes::PropertyEndpoint{}, .renderBody = [this]() { Label("Tint"); Field(showcase.nodeGain); }, .socketColor = kPurple // accepts Source.Enabled }); - out.properties.push_back(NodeProperty + out.properties.push_back(nodes::NodeProperty { .output = true, - .renderBody = [this]() { NodeText("Level"); }, // output => right-aligned + .renderBody = [this]() { nodes::NodeText(*this, nodesContext, "Level"); }, // output => right-aligned .socketColor = kAmber // can feed Mix.Gain (a backward wire) }); // Texture node: a square Image() preview filling its rows exactly. The // node sizes to it in whole grid cells; the output dot sits on the // image row's bottom grid line. - NodeModel tex; + nodes::NodeModel tex; tex.title = "Texture"; tex.pos = { styleManager.Px(-340), styleManager.Px(100) }; { - const int rowPitch = 2 * theme.nodeGridSize; + const int rowPitch = 2 * nodes::GetStyles(*this, nodesContext).nodeGridSize; const int margin = styleManager.Px(8); // matches the image style's margin const int border = styleManager.Px(1); // .node border each side; subtract so image+margin const int rowSpan = 4; // +border lands the node on a clean grid multiple - const int imgSide = std::max(theme.nodeGridSize, rowSpan * rowPitch - 2 * margin - 2 * border); - tex.properties.push_back(NodeProperty + const int imgSide = std::max(nodes::GetStyles(*this, nodesContext).nodeGridSize, rowSpan * rowPitch - 2 * margin - 2 * border); + tex.properties.push_back(nodes::NodeProperty { .output = true, // Color output - the dot sits at the image's bottom grid line .renderBody = [this, imgSide]() { Image(demoImageIndex, tachyon::uint2{ 64, 64 }, tachyon::LayoutOverride::FixedSize(Pixels{ imgSide }, Pixels{ imgSide })); }, @@ -613,7 +620,7 @@ namespace tachyon // Connection rule (delegate): only sockets of the same colour may // connect. Endpoints are bounds-checked before this is called. showcase.nodeGraph.canConnect = - [](const NodeGraph& v, PropertyEndpoint o, PropertyEndpoint i) + [](const nodes::NodeGraph& v, nodes::PropertyEndpoint o, nodes::PropertyEndpoint i) { return v.nodes[o.nodeIdx].properties[o.propIdx].socketColor == v.nodes[i.nodeIdx].properties[i.propIdx].socketColor; @@ -621,27 +628,27 @@ namespace tachyon // The view reports each edit once it is made; it goes on the app's undo history, // with the text edits. - showcase.nodeGraph.onEdit = [this](const NodeViewEdit& edit) + showcase.nodeGraph.onEdit = [this](const nodes::NodeViewEdit& edit) { - const auto shared = std::make_shared(edit); + const auto shared = std::make_shared(edit); commandManager.History().Push({ .description = "Edit node graph", - .undo = [this, shared] { ApplyNodeViewEdit({ showcase.nodeGraph, showcase.noView }, *shared, /*undo*/ true); }, - .redo = [this, shared] { ApplyNodeViewEdit({ showcase.nodeGraph, showcase.noView }, *shared, /*undo*/ false); }, - .drop = [this, shared](bool undone) { ReleaseNodeViewEditIDs(idManager, *shared, undone); } }); + .undo = [this, shared] { nodes::ApplyNodeViewEdit({ showcase.nodeGraph, showcase.noView }, *shared, /*undo*/ true); }, + .redo = [this, shared] { nodes::ApplyNodeViewEdit({ showcase.nodeGraph, showcase.noView }, *shared, /*undo*/ false); }, + .drop = [this, shared](bool undone) { nodes::ReleaseNodeViewEditIDs(idManager, *shared, undone); } }); commandManager.History().EndMerge(); }; // Delete removes the selected nodes, their wires with them, as one edit. Their IDs // stay taken while the edit can be undone; its step gives them back once it can't. commandManager.RegisterCommand(nodeViewMode, showcase.deleteIcon, tachyon::KeyCode::Delete, tachyon::KeyModifier::None, - [this]() { if (NodeViewState* view = FocusedGraphView()) DeleteSelectedNodes(*view); }, "Delete Nodes"); + [this]() { if (nodes::NodeViewState* view = FocusedGraphView()) DeleteSelectedNodes(*view); }, "Delete Nodes"); // One initial connection: Source.Name (0,0) output -> Mix.Strength (1,0) input, // through a reroute between them. - showcase.nodeGraph.nodes[1].properties[0].input = PropertyEndpoint{ 0, 0 }; - const NodeViewEdit reroute = RerouteWireEdit({ showcase.nodeGraph, showcase.noView }, WireKey(1, 0), idManager.CreateStaticID(), + showcase.nodeGraph.nodes[1].properties[0].input = nodes::PropertyEndpoint{ 0, 0 }; + const nodes::NodeViewEdit reroute = nodes::RerouteWireEdit({ showcase.nodeGraph, showcase.noView }, nodes::WireKey(1, 0), idManager.CreateStaticID(), { styleManager.Px(-120), styleManager.Px(-180) }); - ApplyNodeViewEdit({ showcase.nodeGraph, showcase.noView }, reroute); + nodes::ApplyNodeViewEdit({ showcase.nodeGraph, showcase.noView }, reroute); } return true; @@ -1136,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"()") @@ -1331,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. @@ -1359,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] { @@ -1524,20 +1531,20 @@ 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()) { // 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; - for (const Document* document : unsaved) + std::vector items; + for (const docking::Document* document : unsaved) { names.push_back(document->name + document->extension); const auto checked = showcase.exitSave.try_emplace(document, true).first; @@ -1547,11 +1554,11 @@ 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) + for (docking::Document* document : unsaved) if (showcase.exitSave[document]) SaveShowcaseDocument(*document); if (choice == 0 || choice == 2) applicationQuit = true; @@ -1559,9 +1566,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 +1577,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 @@ -1588,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()); }; @@ -1601,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); @@ -1624,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); @@ -1638,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); @@ -1647,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). - auto view = std::make_shared(); - const ID id = CreatePanel(panels, name, theme.curveBezierIcon, [this, view] { RenderCurvesPanel(*view); }); + // the layout (docking::Panel::saveState). + auto view = std::make_shared(); + 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); }; @@ -1664,9 +1671,9 @@ namespace tachyon { // The simulation's fill grows every frame, playing or not: never cached. Its zoom // goes with the layout. - auto view = std::make_shared(); + 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); }; @@ -1679,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; @@ -1688,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 @@ -1716,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", @@ -1743,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; @@ -1770,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; @@ -1796,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); @@ -1812,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(); @@ -1826,25 +1833,25 @@ 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."; - 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", + 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) @@ -1854,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)); @@ -1872,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"); @@ -1905,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(); @@ -1917,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)); @@ -1946,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) @@ -1954,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) { @@ -1978,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; } @@ -1988,26 +1995,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 +2023,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); @@ -2028,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; @@ -2059,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(); @@ -2080,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) @@ -2108,11 +2115,11 @@ 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) - 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(); } @@ -2121,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()) @@ -2132,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); @@ -2142,22 +2149,22 @@ 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 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 +2181,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) @@ -2189,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; @@ -2201,19 +2208,19 @@ 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); 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; } @@ -2344,8 +2351,8 @@ namespace tachyon // The animation plays whichever of its panels shows, Timeline or Curves. if (!animationSeeded) SeedAnimation(); - AdvanceTimeline(animation.playback, - TimelineOptions{ .duration = animation.duration, .fps = animation.fps, .loopRange = animation.loopRange }, + app_controls::AdvanceTimeline(animation.playback, + app_controls::TimelineOptions{ .duration = animation.duration, .fps = animation.fps, .loopRange = animation.loopRange }, frameTime); // What runs at startup runs from the first frame; captures hold each at one moment. if (progress.startedAt < 0.0f) @@ -2357,6 +2364,9 @@ namespace tachyon if (!m_captureDir.empty()) { RenderCapture(); + dialogs::EndGUI(*this, dialogContext); + color::EndGUI(*this, colorContext); + views::EndGUI(*this, viewsContext); return; } auto&& sizeConstraints = LayoutOverride::FixedSize(1700, 900); @@ -2371,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 @@ -2394,17 +2404,17 @@ 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(); - Toasts(*this); + dialogs::Toasts(*this, dialogContext); } else { // BeginWindow returned false - window is closing @@ -2414,5 +2424,8 @@ namespace tachyon } } RenderDocumentWindows(); + dialogs::EndGUI(*this, dialogContext); + color::EndGUI(*this, colorContext); + views::EndGUI(*this, viewsContext); } } diff --git a/examples/showcase/application.h b/examples/showcase/application.h index a3831a11..d1af5bbd 100644 --- a/examples/showcase/application.h +++ b/examples/showcase/application.h @@ -2,8 +2,14 @@ #include #include +#include #include #include +#include +#include +#include +#include +#include #include "scene.h" #if TACHYON_VULKAN || TACHYON_D3D12 || TACHYON_SDLGPU || TACHYON_METAL @@ -20,8 +26,7 @@ namespace tachyon { enum class CommandMode : uint32_t; - struct FileEntry; - class MemoryFileSystem; + namespace app_controls { struct FileEntry; class MemoryFileSystem; } // Each panel's own view (panel_*.cpp): two panels of a kind don't share it. struct FilesPanel; struct HierarchyPanel; @@ -87,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 }; @@ -117,7 +122,7 @@ namespace tachyon struct SettingsView { IDManager* ids = nullptr; // its pages' static IDs and the Reset dialog's go back to it - SettingsPanelState settings; + views::SettingsPanelState settings; // The theme editor on the Appearance page: its search, which categories are open, // and the Reset dialog. @@ -140,29 +145,29 @@ namespace tachyon // Category-list VirtualTreeView. Rows / visible rows are rebuilt each frame; // catInternalMulti is the table's sub-range selection, mapped to/from // catSelection's IDs. - std::vector catRows; + std::vector catRows; std::vector catVisibleIdx; - TableState catTableState; + views::TableState catTableState; MultiSelectState catInternalMulti; // Must persist across frames: the column-sizer double-click handler // holds &column.internal.maxContentWidth and fires after OnGUI returns. struct VisRow { uint32_t mode; uint32_t entryIdx; }; - std::vector columns; // persistent column template (built once) - std::vector activeColumns; // per-frame active subset (Context dropped in single-category view) + std::vector columns; // persistent column template (built once) + std::vector activeColumns; // per-frame active subset (Context dropped in single-category view) std::vector visRows; // Filter fingerprint: visRows are rebuilt only when it changes. A mask // of 0 never occurs, so it forces a rebuild on the first frame. uint64_t filterMask = 0; std::string filterQuery; - TableState tableState; // Category/Command/Shortcut + views::TableState tableState; // Category/Command/Shortcut } shortcuts; ~SettingsView() { if (!ids) return; - for (const SettingsPanelState::Page& page : settings.pages) + for (const views::SettingsPanelState::Page& page : settings.pages) ids->ReleaseStaticID(page.id); if (themeEditor.resetDialogID != ID::Invalid()) ids->ReleaseStaticID(themeEditor.resetDialogID); @@ -180,9 +185,9 @@ namespace tachyon bool isOpen = true; IconID icon = IconID::Invalid; tachyon::ID id = tachyon::ID::Invalid(); - // Descendant count. Recomputed by TreeUtils::RebuildTreeIndex after edits. + // Descendant count. Recomputed by views::TreeUtils::RebuildTreeIndex after edits. int skipCount = 0; - // Guide-line metadata (also recomputed by TreeUtils::RebuildTreeIndex): + // Guide-line metadata (also recomputed by views::TreeUtils::RebuildTreeIndex): // ancestorLineMask - bit d set iff the ancestor at depth d+1 has // a next sibling, so its connector line passes this row at column d. // isLastSibling - last child of its parent; the own-depth guide @@ -191,7 +196,7 @@ namespace tachyon bool isLastSibling = true; }; - CommandMode nodeViewMode = CommandMode::Default; // the node view's shortcuts; copied into each NodeView's commandMode + CommandMode nodeViewMode = CommandMode::Default; // the node view's shortcuts; copied into each nodes::NodeView's commandMode CommandMode stateMachineMode = CommandMode::Default; // the state machines' shortcuts (Delete) CommandMode hierarchyMode = CommandMode::Default; // a Hierarchy's shortcuts while its tree has the focus CommandID hierarchyDelete{}; @@ -326,10 +331,10 @@ namespace tachyon uint64_t ProgressLook(); // The timeline editor demo: its tracks, set up the first time it's drawn. Each Timeline // panel shows them with a view of its own. - TimelineData animation; + app_controls::TimelineData animation; bool animationSeeded = false; /// The Curves panels' curves: the animated sphere's, their playhead the timeline's. - CurveData animationCurves; + curves::CurveData animationCurves; // The scene the Viewport panels show (each from its own camera): its shapes, the one // picked, and what draws them. std::vector sceneObjects; @@ -380,12 +385,12 @@ namespace tachyon }(); // CurveField demos: a falloff, and a color's red, green and blue curves. // Each Inspector shows them with views of its own. - tachyon::CurveData demoCurve; - tachyon::CurveData demoColorCurves; + tachyon::curves::CurveData demoCurve; + tachyon::curves::CurveData demoColorCurves; bool curvesSeeded = false; // Plot demo: the demo image's levels, its R, G and B counted into 64 bins. - tachyon::PlotData demoLevels; - int demoLevelsKind = 1; // a PlotSeriesKind: bars, area or line + tachyon::curves::PlotData demoLevels; + int demoLevelsKind = 1; // a curves::PlotSeriesKind: bars, area or line bool demoLevelsLog = false; int listSelected = 0; @@ -448,16 +453,16 @@ namespace tachyon ID textBoxId1 { ID::Invalid() }; ID textBoxId2 { ID::Invalid() }; - // The NodeView panels' graph; each panel has a view of it of its own (NodeGraphPanel). - NodeGraph nodeGraph; + // The nodes::NodeView panels' graph; each panel has a view of it of its own (NodeGraphPanel). + nodes::NodeGraph nodeGraph; bool nodeFramesSeeded = false; // the "Inputs" frame, put round its nodes once they're laid out // The StateMachine panels' machines: an enemy's behaviour, and the machine its Combat // state holds. Each panel has its views of them, and which it shows (StateMachinePanel). - NodeGraph enemyMachine; - NodeGraph combatMachine; + nodes::NodeGraph enemyMachine; + nodes::NodeGraph combatMachine; // What an edit made outside every view (undo, redo) goes through; the views of the // graph catch up by its revision. - NodeViewState noView; + nodes::NodeViewState noView; bool stateMachinesSeeded = false; uint32_t stateMachineSteps = 0; // Step takes the transitions out of a state in turn // When each machine (Enemy, Combat) entered the state it's in, in seconds on the @@ -476,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. @@ -492,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. @@ -680,13 +685,13 @@ 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; - 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; @@ -699,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 @@ -745,11 +750,25 @@ namespace tachyon } void OnGUI() override; + /// The dialogs' state: toasts, message dialogs, progress. + dialogs::Context dialogContext; + /// The color controls' state: their pickers, gradient swatches. + color::Context colorContext; + /// The views' state: lists, trees, grids, tables, the settings panel. + 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. + app_controls::Context controlsContext; 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); @@ -760,7 +779,7 @@ namespace tachyon void SetFontScale(float percent); void RenderSettingsShortcuts(SettingsView::Shortcuts& page); /// A table's selection mode as a "Select" label and a Row | Cell segmented control. - void SelectionModeSwitch(TableSelectionMode& mode); + void SelectionModeSwitch(views::TableSelectionMode& mode); /// Reduced motion as settingsMotionIndex says. void ApplyMotionSetting(); /// The wheel mode settingsWheelIndex says. @@ -775,8 +794,8 @@ namespace tachyon // Dock-panel body renderers (one per panel_*.cpp), called each frame // while the panel is the active tab. void RenderReorderablePanel(ReorderablePanel& panel); - void RenderTimelinePanel(TimelineViewState& view); - void RenderCurvesPanel(CurveViewState& view); + void RenderTimelinePanel(app_controls::TimelineViewState& view); + void RenderCurvesPanel(curves::CurveViewState& view); void RenderSketchPanel(SketchPanel& panel); void EraseSketchAt(float2 at, float radius); /// The Appearance page's theme editor: the theme's colors and sizes by category, each @@ -790,7 +809,7 @@ namespace tachyon /// history. void SeedAnimation(); /// A Timeline panel's view of the tracks: its first selection, "+" and the rows' menu. - void SetUpTimelineView(TimelineViewState& view); + void SetUpTimelineView(app_controls::TimelineViewState& view); /// The Curves panel's channels: the sphere's position, rotation and scale. void SeedAnimationCurves(); /// The Inspector's curves: a falloff, and a color's channels; their edits on the undo history. @@ -807,33 +826,33 @@ 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 NodeView panel's view of the graph: its menus, what its selection shows, its shortcuts. - void SetUpNodeGraphView(NodeViewState& view); + /// 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 /// its selected transitions, as one edit. - void DeleteSelectedStates(NodeViewRef view); - /// A reroute (NodeModel::reroute) in `color`, unwired, its dot on the grid point + void DeleteSelectedStates(nodes::NodeViewRef view); + /// A reroute (nodes::NodeModel::reroute) in `color`, unwired, its dot on the grid point /// nearest `at` (node.pos space). - NodeModel RerouteNode(float2 at, color4f color); + nodes::NodeModel RerouteNode(float2 at, color4f color); /// Removes the nodes selected in `view`, their wires with them, and its selected /// frames, as one edit. - void DeleteSelectedNodes(NodeViewState& view); + void DeleteSelectedNodes(nodes::NodeViewState& view); /// A frame round the nodes and frames selected in `view`, then selected itself. - void GroupSelection(NodeViewState& view); + void GroupSelection(nodes::NodeViewState& view); /// The kinds of node the canvas menu adds. enum class GraphNodeKind { Value, Math, Noise, Switch }; /// Adds a node of `kind` with its top-left at `at` (node.pos space), as one edit. - void AddGraphNode(NodeViewState& view, GraphNodeKind kind, float2 at); - /// The NodeView / StateMachine panel whose canvas has the keyboard: what their + void AddGraphNode(nodes::NodeViewState& view, GraphNodeKind kind, float2 at); + /// The nodes::NodeView / StateMachine panel whose canvas has the keyboard: what their /// shortcuts (F, Home, Delete, Ctrl+G) act on. Null when none has. - NodeViewState* FocusedGraphView(); - NodeViewRef FocusedMachineView(); ///< valid only while FocusedStateMachine() isn't null + nodes::NodeViewState* FocusedGraphView(); + nodes::NodeViewRef FocusedMachineView(); ///< valid only while FocusedStateMachine() isn't null StateMachinePanel* FocusedStateMachine(); void RenderBoxTestPanel(); @@ -883,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 @@ -923,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. @@ -952,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); @@ -976,7 +995,7 @@ namespace tachyon IconID FileIcon(const FilesPanel& panel, std::string_view name, bool isFolder, bool open = false); /// The folder tree's folder icon, open or closed. IconID TreeFolderIcon(bool open) const; - IconID FileIcon(const FilesPanel& panel, const FileEntry& file, bool open = false); + IconID FileIcon(const FilesPanel& panel, const app_controls::FileEntry& file, bool open = false); // Build/tear down panel data; wired into CreatePanel's onEnable/onDisable. void EnableHierarchyPanel(HierarchyPanel& panel); @@ -989,11 +1008,11 @@ namespace tachyon std::vector> m_filesPanels; // What every Files panel shows, and what every Hierarchy panel shows: made by the first // one to show, kept while any of them is open. - std::weak_ptr m_files; + std::weak_ptr m_files; std::weak_ptr m_hierarchyScene; // The Viewport panels made, whose torn-off toolbars are emitted each frame. std::vector> m_viewportPanels; - // The NodeView and StateMachine panels made: their shortcuts act on the one with the focus. + // The nodes::NodeView and StateMachine panels made: their shortcuts act on the one with the focus. std::vector> m_nodeGraphPanels; std::vector> m_stateMachinePanels; /// A panel made by CreateShowcasePanel, by the data it shows. `alive` goes with the @@ -1006,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 @@ -1039,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); @@ -1052,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 75e07387..39bfe3b4 100644 --- a/examples/showcase/capture.cpp +++ b/examples/showcase/capture.cpp @@ -2,6 +2,8 @@ #include #include +#include +#include #include #include @@ -260,9 +262,9 @@ namespace tachyon bool match = false; switch (target) { - 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::ColorSwatch: match = element.styleRef == color::GetStyles(*this, colorContext).colorSwatchStyleRef; break; + case CaptureTarget::GradientSwatch: match = element.styleRef == color::GetStyles(*this, colorContext).gradientSwatchStyleRef; 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: @@ -387,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) @@ -466,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(); @@ -506,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) @@ -527,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; } @@ -585,21 +587,21 @@ 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) { UpdateDemoToasts(); - Toasts(*this); + dialogs::Toasts(*this, dialogContext); } } 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(); } @@ -610,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()); @@ -631,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 3e8b05af..fc079cba 100644 --- a/examples/showcase/panel_console.cpp +++ b/examples/showcase/panel_console.cpp @@ -1,6 +1,8 @@ #include "application.h" #include +#include +#include #include #include @@ -76,8 +78,8 @@ namespace tachyon // panel); logLastSequence is the newest record already pulled. std::vector logEntries; uint64_t logLastSequence = 0; - std::vector logColumns; - tachyon::TableState logTableState; + std::vector logColumns; + tachyon::views::TableState logTableState; std::string logSearch; // One entry per visible row, rebuilt only when the filter changes: @@ -214,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); }); } @@ -242,18 +244,18 @@ namespace tachyon p.logColumns.resize(3); // Timestamp - fixed-width, first column. p.logColumns[0].column = { .initialWidth = 104, .minWidth = 104, .maxWidth = 104, - .sizing = ColumnSizing::Fixed }; + .sizing = views::ColumnSizing::Fixed }; p.logColumns[0].generateCell = [this, &p](int rowIdx) { if (rowIdx < 0 || rowIdx >= int(p.logVisible.size())) return; - Cell(p.logEntries[p.logVisible[rowIdx]].timestamp.c_str()); + views::Cell(*this, viewsContext, p.logEntries[p.logVisible[rowIdx]].timestamp.c_str()); }; // Level - a dot in the level's color, after the timestamp. p.logColumns[1].column = { .initialWidth = 24, .minWidth = 24, .maxWidth = 24, - .sizing = ColumnSizing::Fixed }; + .sizing = views::ColumnSizing::Fixed }; p.logColumns[1].generateCell = [this, &p](int rowIdx) { if (rowIdx < 0 || rowIdx >= int(p.logVisible.size())) return; const StyleRef dotStyle = logLevelDotStyleRefs[int(p.logEntries[p.logVisible[rowIdx]].level)]; - Cell([this, dotStyle]() { + views::Cell(*this, viewsContext, [this, dotStyle]() { const tachyon::ID iconID = idManager.AllocateDynamicID(); tachyon::Element iconElem{}; iconElem.id = iconID; @@ -270,11 +272,11 @@ namespace tachyon // Message - stretches to fill the remaining width, single line. A // collapsed row (repeat > 1) trails a count bubble pushed to the right. p.logColumns[2].column = { .initialWidth = 240, .minWidth = 120, - .sizing = ColumnSizing::Stretch }; + .sizing = views::ColumnSizing::Stretch }; p.logColumns[2].generateCell = [this, &p](int rowIdx) { if (rowIdx < 0 || rowIdx >= int(p.logVisible.size())) return; // Copy into the cell lambda - Cell may defer it for record/replay. - Cell([this, msg = p.logEntries[p.logVisible[rowIdx]].message, + views::Cell(*this, viewsContext, [this, msg = p.logEntries[p.logVisible[rowIdx]].message, count = p.logRepeat[rowIdx]]() { // Message text fills the cell so the bubble lands at the right edge. { @@ -402,20 +404,20 @@ namespace tachyon p.logFilterDirty = false; } - std::span columnSpan(p.logColumns.data(), p.logColumns.size()); + std::span columnSpan(p.logColumns.data(), p.logColumns.size()); // flex-fill-row (flex-basis:0) bounds the table to the panel height so // its body scrolls instead of overflowing. BeginHorizontal(idManager.AllocateDynamicID("consoleFill"), theme.flexFillRowStyleRef, LayoutOverride::Auto().FlexGrow(1)); - p.logTableState.rowStyle = theme.listRowStyleRef; + p.logTableState.rowStyle = views::GetStyles(*this, viewsContext).listRowStyleRef; p.logTableState.cellStyle = logCellStyleRef; if (!p.logColumns.empty()) p.logColumns[0].column.cellStyle = logCellTimeStyleRef; // styles change on a theme reload p.logTableState.showHeaders = false; p.logTableState.columnSeparators = false; - VirtualTable(idManager.AllocateDynamicID("consoleLog"), + views::VirtualTable(*this, viewsContext, idManager.AllocateDynamicID("consoleLog"), p.logTableState, columnSpan, int(p.logVisible.size()), 0, logTableStyleRef, LayoutOverride{}.FlexGrow(1)); diff --git a/examples/showcase/panel_files.cpp b/examples/showcase/panel_files.cpp index 3242a529..fc743a88 100644 --- a/examples/showcase/panel_files.cpp +++ b/examples/showcase/panel_files.cpp @@ -1,5 +1,7 @@ #include "application.h" #include +#include +#include #include #include #include @@ -15,7 +17,7 @@ // // This file is a file browser panel demo, meant to test and demonstrate the grid view and // drag & drop features - including dragging files and folders between the grid and the -// folder tree, and dropping them in from other applications. It browses an IFileSystem: a +// folder tree, and dropping them in from other applications. It browses an app_controls::IFileSystem: a // copy of a folder on the disk (the showcase's workdirectory, or the one given with // --files), read as it's browsed. Moves, renames and dropped files change only the copy; // the disk is never written. Files on the disk show their thumbnails, as Explorer does. @@ -43,7 +45,7 @@ namespace tachyon } // Flat row index a tree's single-selection points at (-1 if none). - static int SelectedFlat(const tachyon::TableState& state, + static int SelectedFlat(const tachyon::views::TableState& state, const std::vector& visibleIdx) { if (state.selectedRowID.GetMode() != tachyon::IDMode::SubRange) return -1; @@ -53,7 +55,7 @@ namespace tachyon } // Folders first, then by name (case-insensitive): the view is sorted, not ordered by hand. - static bool EntryBefore(const FileEntry& a, const FileEntry& b) + static bool EntryBefore(const app_controls::FileEntry& a, const app_controls::FileEntry& b) { if (a.isFolder != b.isFolder) return a.isFolder; @@ -79,20 +81,20 @@ namespace tachyon // the icons it made in the text system (DisableFilesPanel). struct FilesPanel { - std::shared_ptr files; // shared with the other Files panels - std::unique_ptr fileIcons; // the OS's icons, where there are any - std::unique_ptr fileThumbnails; // and its pictures of what's in the files on the disk + std::shared_ptr files; // shared with the other Files panels + std::unique_ptr fileIcons; // the OS's icons, where there are any + std::unique_ptr fileThumbnails; // and its pictures of what's in the files on the disk uint64_t filesGeneration = 0; tachyon::ItemDragDropConfig gridDnD; tachyon::ItemDragDropConfig folderDnD; - tachyon::GridViewVirtualState gridScrollState; + tachyon::views::GridViewVirtualState gridScrollState; tachyon::MultiSelectState gridMultiSelect; // What the grid shows for the folder on view: its folders, then its files, each by name, // reduced to the ones that match the search. struct GridEntry { - FileEntry file; + app_controls::FileEntry file; std::string renameBuffer; // a rename edits this; it goes to the file system once it's done }; std::vector gridEntries; @@ -109,10 +111,10 @@ namespace tachyon // Folder tree left of the grid (flat VirtualTreeView rows): the root, the folders of the // open folders, and one level further, so a closed folder shows whether it holds any. // folderPaths is parallel to folderRows. - std::vector folderRows; + std::vector folderRows; std::vector folderPaths; std::vector folderVisibleIdx; - tachyon::TableState folderTreeState; + tachyon::views::TableState folderTreeState; int folderTreeWidth = 180; // CSS pixels std::unordered_set openFolders; // paths std::string currentFolder; // the path of the folder on view @@ -125,9 +127,9 @@ namespace tachyon std::string filesSearch; std::string filesQueryLower; bool gridFilterDirty = true; - std::vector filteredFolderRows; + std::vector filteredFolderRows; std::vector filteredFolderVisibleIdx; - tachyon::TableState filteredFolderState; + tachyon::views::TableState filteredFolderState; std::vector filteredToMaster; // filtered flat idx -> master flat idx const GridEntry* GridEntryAt(int visiblePos) const @@ -138,7 +140,7 @@ namespace tachyon // Whether the folder tree has flat row `flat` open. bool FolderOpen(size_t flat) const { - return folderTreeState.openRows.contains(tachyon::TreeViewRowKey(folderRows[flat], flat)); + return folderTreeState.openRows.contains(tachyon::views::TreeViewRowKey(folderRows[flat], flat)); } // The flat row index of a tree row's ID (-1 if not one of the rows). @@ -149,9 +151,9 @@ namespace tachyon return (visIdx >= 0 && visIdx < static_cast(folderVisibleIdx.size())) ? folderVisibleIdx[visIdx] : -1; } - std::vector SortedList(std::string_view folder) const + std::vector SortedList(std::string_view folder) const { - std::vector list = files->List(folder); + std::vector list = files->List(folder); std::sort(list.begin(), list.end(), EntryBefore); return list; } @@ -173,12 +175,12 @@ namespace tachyon // seen, so their folders are listed too (each row knows whether it has children). void AddFolderRows(const std::string& path, int depth, bool shown) { - for (const FileEntry& entry : SortedList(path)) + for (const app_controls::FileEntry& entry : SortedList(path)) { if (!entry.isFolder) continue; - const std::string child = JoinPath(path, entry.name); - tachyon::TreeViewRow row{}; + const std::string child = app_controls::JoinPath(path, entry.name); + tachyon::views::TreeViewRow row{}; row.name = entry.name; row.depth = depth; const bool open = openFolders.contains(child); @@ -193,18 +195,18 @@ namespace tachyon { folderRows.clear(); folderPaths.clear(); - tachyon::TreeViewRow root{}; + tachyon::views::TreeViewRow root{}; root.name = rootName; folderRows.push_back(std::move(root)); folderPaths.push_back(""); AddFolderRows("", 1, openFolders.contains("")); - GUIApplication::RebuildTreeViewIndex(folderRows); + views::RebuildTreeViewIndex(folderRows); // The rows are named by position, which a rebuild changes: the tree opens what // openFolders, by path, says. folderTreeState.openRows.clear(); for (size_t i = 0; i < folderRows.size(); ++i) if (openFolders.contains(folderPaths[i])) - folderTreeState.openRows.insert(tachyon::TreeViewRowKey(folderRows[i], i)); + folderTreeState.openRows.insert(tachyon::views::TreeViewRowKey(folderRows[i], i)); // Visible indices moved - the render pass re-selects currentFolder. folderTreeState.selectedRowID = tachyon::ID::Invalid(); } @@ -213,7 +215,7 @@ namespace tachyon void RebuildGridVisible() { gridEntries.clear(); - for (FileEntry& file : SortedList(currentFolder)) + for (app_controls::FileEntry& file : SortedList(currentFolder)) if (SearchMatches(file.name, filesQueryLower)) { std::string name = file.name; @@ -237,7 +239,7 @@ namespace tachyon chain.resize(folderRows[i].depth); chain.push_back(i); bool hasHit = false; - for (const FileEntry& entry : files->List(folderPaths[i])) + for (const app_controls::FileEntry& entry : files->List(folderPaths[i])) if (SearchMatches(entry.name, filesQueryLower)) { hasHit = true; break; } if (hasHit) for (int a : chain) keep[a] = 1; @@ -245,15 +247,15 @@ namespace tachyon for (int i = 0; i < int(folderRows.size()); ++i) { if (!keep[i]) continue; - tachyon::TreeViewRow r = folderRows[i]; + tachyon::views::TreeViewRow r = folderRows[i]; r.renameBuffer = nullptr; // copies don't write back - no rename filteredFolderRows.push_back(std::move(r)); filteredToMaster.push_back(i); } - GUIApplication::RebuildTreeViewIndex(filteredFolderRows); + views::RebuildTreeViewIndex(filteredFolderRows); filteredFolderState.openRows.clear(); for (size_t i = 0; i < filteredFolderRows.size(); ++i) - filteredFolderState.openRows.insert(tachyon::TreeViewRowKey(filteredFolderRows[i], i)); + filteredFolderState.openRows.insert(tachyon::views::TreeViewRowKey(filteredFolderRows[i], i)); } // The path a drag payload stands for; false for none (the root doesn't move). @@ -270,7 +272,7 @@ namespace tachyon } const GridEntry* entry = GridEntryAt(static_cast(payload)); if (!entry) return false; - path = JoinPath(currentFolder, entry->file.name); + path = app_controls::JoinPath(currentFolder, entry->file.name); return true; } @@ -284,10 +286,10 @@ namespace tachyon }; for (const auto& [id, index] : gridItemIDs) if (index < int(gridEntries.size()) && under(id)) - return gridEntries[size_t(index)].file.isFolder ? JoinPath(currentFolder, gridEntries[size_t(index)].file.name) + return gridEntries[size_t(index)].file.isFolder ? app_controls::JoinPath(currentFolder, gridEntries[size_t(index)].file.name) : currentFolder; const bool searching = !filesQueryLower.empty(); - const tachyon::TableState& state = searching ? filteredFolderState : folderTreeState; + const tachyon::views::TableState& state = searching ? filteredFolderState : folderTreeState; const std::vector& visibleIdx = searching ? filteredFolderVisibleIdx : folderVisibleIdx; for (size_t vi = 0; vi < visibleIdx.size(); ++vi) if (under(state.RowIDForIndex(static_cast(vi)))) @@ -303,18 +305,18 @@ namespace tachyon bool CanDropInto(uintptr_t payload, const std::string& folder) const { std::string path; - if (!PayloadPath(payload, path) || ParentPath(path) == folder) return false; + if (!PayloadPath(payload, path) || app_controls::ParentPath(path) == folder) return false; std::string inside = folder; return !Retarget(inside, path, ""); } }; - 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(); }; @@ -335,10 +337,10 @@ 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(app_controls::FileName(path)) + "\"", .body = error }); return; } - FolderMoved(path, JoinPath(folder, FileName(path))); + FolderMoved(path, app_controls::JoinPath(folder, app_controls::FileName(path))); } // Renames whose editors closed: a name that's changed goes to the file system; one it @@ -348,17 +350,17 @@ namespace tachyon std::vector> renames; // path, new name for (const FilesPanel::GridEntry& entry : p.gridEntries) if (entry.renameBuffer != entry.file.name) - renames.emplace_back(JoinPath(p.currentFolder, entry.file.name), entry.renameBuffer); + renames.emplace_back(app_controls::JoinPath(p.currentFolder, entry.file.name), entry.renameBuffer); for (size_t i = 1; i < p.folderRows.size(); ++i) - if (p.folderRows[i].name != FileName(p.folderPaths[i])) + if (p.folderRows[i].name != app_controls::FileName(p.folderPaths[i])) renames.emplace_back(p.folderPaths[i], p.folderRows[i].name); for (const auto& [path, name] : renames) { std::string error; if (p.files->Rename(path, name, error)) - FolderMoved(path, JoinPath(ParentPath(path), name)); + FolderMoved(path, app_controls::JoinPath(app_controls::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(app_controls::FileName(path)) + "\"", .body = error }); } // Back to the file system's names, the refused ones too. p.treeDirty = true; @@ -366,8 +368,8 @@ namespace tachyon void Application::EnableFilesPanel(FilesPanel& p) { - p.fileIcons = std::make_unique(*textSystem, 48); - p.fileThumbnails = std::make_unique(*textSystem); + p.fileIcons = std::make_unique(*textSystem, 48); + p.fileThumbnails = std::make_unique(*textSystem); // A thumbnail read while the app sleeps: draw it. p.fileThumbnails->SetOnRead([this] { RequestRedraw(); }); if (p.files) @@ -393,7 +395,7 @@ namespace tachyon p.files = m_files.lock(); if (!p.files) { - p.files = std::make_shared(root); + p.files = std::make_shared(root); m_files = p.files; // Some documents to open with a double-click, in the copy only. if (m_filesRoot.empty()) @@ -412,7 +414,7 @@ namespace tachyon std::string path; if (!p.PayloadPath(visual.payloadValue, path)) return; const FilesPanel::GridEntry* entry = IsFolderPayload(visual.payloadValue) ? nullptr : p.GridEntryAt(static_cast(visual.payloadValue)); - const IconID icon = entry ? FileIcon(p, entry->file) : FileIcon(p, FileName(path), true); + const IconID icon = entry ? FileIcon(p, entry->file) : FileIcon(p, app_controls::FileName(path), true); if (icon == IconID::Invalid) return; if (BeginCursorGhostWindow(showcase.dragGhostWindowID, visual.screenPos)) { @@ -428,8 +430,8 @@ namespace tachyon return; if (entry->file.isFolder) { - p.currentFolder = JoinPath(p.currentFolder, entry->file.name); - p.openFolders.insert(std::string(ParentPath(p.currentFolder))); + p.currentFolder = app_controls::JoinPath(p.currentFolder, entry->file.name); + p.openFolders.insert(std::string(app_controls::ParentPath(p.currentFolder))); p.folderTreeState.selectedRowID = tachyon::ID::Invalid(); // re-selected from currentFolder p.treeDirty = true; p.gridFilterDirty = true; @@ -439,7 +441,7 @@ namespace tachyon if (entry->file.name.ends_with(".spv")) { showcase.openErrorFile = entry->file.name; - showcase.openErrorDetails = std::format("No reader for .spv files (compiled SPIR-V shaders)\n at {}", JoinPath(p.currentFolder, entry->file.name)); + showcase.openErrorDetails = std::format("No reader for .spv files (compiled SPIR-V shaders)\n at {}", app_controls::JoinPath(p.currentFolder, entry->file.name)); showcase.openErrorWindow = p.windowID; return; } @@ -457,7 +459,7 @@ namespace tachyon // folder on view (where a file from this grid already is). auto dropFolder = [&p](tachyon::ID targetID) { const FilesPanel::GridEntry* target = p.GridEntryAt(GridItemIndex(targetID)); - return (target && target->file.isFolder) ? JoinPath(p.currentFolder, target->file.name) : p.currentFolder; + return (target && target->file.isFolder) ? app_controls::JoinPath(p.currentFolder, target->file.name) : p.currentFolder; }; p.gridDnD.canDrop = [&p, dropFolder](uintptr_t payloadValue, tachyon::ID targetID) { return p.CanDropInto(payloadValue, dropFolder(targetID)); @@ -513,8 +515,8 @@ namespace tachyon refused += (refused.empty() ? "" : "\n") + error; } if (!refused.empty()) - ShowToast(*this, ToastDesc{ .severity = Severity::Warning, - .title = "Not added to " + (folder.empty() ? p.rootName : std::string(FileName(folder))), + dialogs::ShowToast(*this, dialogContext, dialogs::ToastDesc{ .severity = dialogs::Severity::Warning, + .title = "Not added to " + (folder.empty() ? p.rootName : std::string(app_controls::FileName(folder))), .body = refused }); } @@ -532,7 +534,7 @@ namespace tachyon return open ? showcase.folderOpenIcon : showcase.folderClosedIcon; // the grid's filled folders if (const IconID os = p.fileIcons ? p.fileIcons->Get(name, false) : IconID::Invalid; os != IconID::Invalid) return os; - const std::string ext = FileIcons::Extension(name); + const std::string ext = app_controls::FileIcons::Extension(name); if (ext == ".fbx" || ext == ".obj" || ext == ".gltf" || ext == ".glb") return showcase.fileModelIcon; if (ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".gif" || ext == ".bmp") return showcase.fileImageIcon; if (ext == ".mp3" || ext == ".wav" || ext == ".ogg" || ext == ".flac") return showcase.fileAudioIcon; @@ -543,7 +545,7 @@ namespace tachyon // A file on the disk in its thumbnail, at the grid's icon size, once it's read; until then, // and for a file without one, its type's icon. - IconID Application::FileIcon(const FilesPanel& p, const FileEntry& file, bool open) + IconID Application::FileIcon(const FilesPanel& p, const app_controls::FileEntry& file, bool open) { if (!file.isFolder && p.fileThumbnails) if (const IconID thumbnail = p.fileThumbnails->Get(file.disk, file.modified, uint32_t(styleManager.Px(kFileIconSize))); @@ -559,9 +561,9 @@ namespace tachyon p.windowID = windowRegistry.GetCurrentWindowID(); // A rename moves the item to its new place in the sorted view once it's done. - if (p.wasRenaming && !IsRenaming()) + if (p.wasRenaming && !views::IsRenaming(viewsContext)) ApplyFileRenames(p); - p.wasRenaming = IsRenaming(); + p.wasRenaming = views::IsRenaming(viewsContext); // A folder opened or closed in the tree: its folders' rows are read in (or left). for (size_t i = 0; i < p.folderRows.size(); ++i) @@ -575,7 +577,7 @@ namespace tachyon // Rebuilt on demand: only when the files, the tree or the search changed. if (p.files->Generation() != p.filesGeneration || p.treeDirty) { - if (!IsRenaming()) // not under an open editor, whose buffer is a row's name + if (!views::IsRenaming(viewsContext)) // not under an open editor, whose buffer is a row's name { p.filesGeneration = p.files->Generation(); p.RebuildFolderTree(); @@ -583,7 +585,7 @@ namespace tachyon p.gridFilterDirty = true; } } - if (p.gridFilterDirty && !IsRenaming()) + if (p.gridFilterDirty && !views::IsRenaming(viewsContext)) { p.filesQueryLower = SearchToLower(p.filesSearch); p.RebuildFolderFilter(); @@ -627,9 +629,9 @@ namespace tachyon for (size_t i = 0; i < p.filteredFolderRows.size(); ++i) p.filteredFolderRows[i].icon = TreeFolderIcon(p.filteredFolderRows[i].HasChildren() || (p.fileDropFolder && p.folderPaths[size_t(p.filteredToMaster[i])] == *p.fileDropFolder)); - VirtualTreeView(idManager.AllocateDynamicID("filesFolderTree"), + views::VirtualTreeView(*this, viewsContext, idManager.AllocateDynamicID("filesFolderTree"), p.filteredFolderRows, p.filteredFolderVisibleIdx, p.filteredFolderState, - theme.treeViewStyleRef, + views::GetStyles(*this, viewsContext).treeViewStyleRef, tachyon::LayoutOverride::Auto().FixedWidth(CssPx(p.folderTreeWidth)).NoGrow()); const int selFiltered = SelectedFlat(p.filteredFolderState, p.filteredFolderVisibleIdx); @@ -646,7 +648,7 @@ namespace tachyon // Open-folder icon while expanded or hovered as a drop target. The // rename pointer is refreshed every frame because rebuilds move rows; // the root's name is the disk folder's, which stays. - const int dropFlat = guiStateManager.Drag().IsDragging() ? p.RowFlat(TreeDropTargetRow()) : -1; + const int dropFlat = guiStateManager.Drag().IsDragging() ? p.RowFlat(views::TreeDropTargetRow(viewsContext)) : -1; for (size_t i = 0; i < p.folderRows.size(); ++i) { auto& row = p.folderRows[i]; @@ -655,9 +657,9 @@ namespace tachyon row.renameBuffer = i == 0 ? nullptr : &row.name; } - VirtualTreeView(idManager.AllocateDynamicID("filesFolderTree"), + views::VirtualTreeView(*this, viewsContext, idManager.AllocateDynamicID("filesFolderTree"), p.folderRows, p.folderVisibleIdx, p.folderTreeState, - theme.treeViewStyleRef, + views::GetStyles(*this, viewsContext).treeViewStyleRef, tachyon::LayoutOverride::Auto().FixedWidth(CssPx(p.folderTreeWidth)).NoGrow()); const int selFlat = SelectedFlat(p.folderTreeState, p.folderVisibleIdx); @@ -737,8 +739,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 +748,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)); } } @@ -805,7 +807,7 @@ namespace tachyon const float imported = ImportElapsed(); const bool importing = !listMode && imported >= 0.0f && progress.importCancelledAt < 0.0f && imported < ProgressDemos::kImportSecs; - VirtualGridView(idManager.AllocateDynamicID("filesGrid"), p.gridScrollState, + views::VirtualGridView(*this, viewsContext, idManager.AllocateDynamicID("filesGrid"), p.gridScrollState, static_cast(p.gridEntries.size()) + (importing ? 1 : 0), cellSize, [this, &p, listMode, itemStyleFor, cellW, cellH, rowH, imported](int i, tachyon::ID itemID) { @@ -814,7 +816,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(); @@ -826,7 +828,7 @@ namespace tachyon // Open-folder icon while hovered by a drag this folder accepts, or one // from another application would drop into it. - const std::string path = JoinPath(p.currentFolder, entry.file.name); + const std::string path = app_controls::JoinPath(p.currentFolder, entry.file.name); const bool dropTarget = entry.file.isFolder && ((guiStateManager.Drag().IsDropTargetFor(itemID, kGridPayload) && p.CanDropInto(guiStateManager.Drag().GetPayloadValue(), path)) || @@ -835,7 +837,7 @@ namespace tachyon std::string_view name = entry.file.name; if (listMode) - GridViewItem(itemID, { icon, name }, tachyon::ElementState::None, + views::GridViewItem(*this, viewsContext, itemID, { icon, name }, tachyon::ElementState::None, &entry.renameBuffer, theme.gridViewListItemStyleRef, LayoutOverride{}.Height(Pixels{ rowH }).FlexGrow(1)); @@ -843,7 +845,7 @@ namespace tachyon // Stretched width: the grid's columns split the // viewport evenly, so the cells fill each row // instead of leaving a gap on the right. - GridViewItem(itemID, { icon, name }, tachyon::ElementState::None, + views::GridViewItem(*this, viewsContext, itemID, { icon, name }, tachyon::ElementState::None, &entry.renameBuffer, itemStyleFor(icon), LayoutOverride{}.Size( diff --git a/examples/showcase/panel_hierarchy.cpp b/examples/showcase/panel_hierarchy.cpp index 5e63bea0..8052c0a3 100644 --- a/examples/showcase/panel_hierarchy.cpp +++ b/examples/showcase/panel_hierarchy.cpp @@ -1,6 +1,8 @@ #include "application.h" #include -#include +#include +#include +#include #include #include @@ -11,7 +13,7 @@ // // This file is for testing and prototyping the VirtualTreeView control. -// Data is a flat std::vector with a depth field; reorders call +// Data is a flat std::vector with a depth field; reorders call // RebuildTreeViewIndex to refresh the derived fields. // @@ -35,11 +37,11 @@ namespace tachyon ~HierarchyScene() { if (ids) - for (const tachyon::TreeViewRow& row : treeRows) + for (const tachyon::views::TreeViewRow& row : treeRows) ids->ReleaseStaticID(row.id); } - std::vector treeRows; + std::vector treeRows; std::string renameBuffer; // TreeCell rename scratch std::vector startOpen; // the rows a new panel opens // Raised by each change to the rows: a panel showing a filtered copy makes it again. @@ -62,7 +64,7 @@ namespace tachyon // After rows were added, removed or moved. void RowsChanged() { - GUIApplication::RebuildTreeViewIndex(treeRows); + views::RebuildTreeViewIndex(treeRows); RebuildHierarchyIdToFlat(); ++revision; } @@ -151,15 +153,15 @@ namespace tachyon tachyon::ID windowID = tachyon::ID::Invalid(); // the window it was last built in, which asks about it std::vector treeVisibleIdx; - tachyon::TableState treeViewState; + tachyon::views::TableState treeViewState; tachyon::MultiSelectState treeMultiSelect; // Search: a filtered copy of the scene's rows (matches plus ancestors, forced open), // rebuilt when the query or the rows change. Rendered with its own state, no // drag-drop or rename. - std::vector filteredRows; + std::vector filteredRows; std::vector filteredVisibleIdx; - tachyon::TableState filteredState; + tachyon::views::TableState filteredState; tachyon::MultiSelectState filteredMultiSelect; std::string hierarchySearch; bool filterDirty = true; @@ -173,9 +175,9 @@ namespace tachyon // The tree on show: the filtered copy while searching. Both carry the nodes' IDs. bool Searching() const { return !hierarchySearch.empty(); } - std::vector& ShownRows() { return Searching() ? filteredRows : scene->treeRows; } + std::vector& ShownRows() { return Searching() ? filteredRows : scene->treeRows; } std::vector& ShownVisibleIdx() { return Searching() ? filteredVisibleIdx : treeVisibleIdx; } - tachyon::TableState& ShownState() { return Searching() ? filteredState : treeViewState; } + tachyon::views::TableState& ShownState() { return Searching() ? filteredState : treeViewState; } // The node a shown row stands for; Invalid when the row isn't one of this frame's. tachyon::ID NodeAtRow(int row) @@ -187,7 +189,7 @@ namespace tachyon bool RowIsSelected(int row) { - tachyon::TableState& state = ShownState(); + tachyon::views::TableState& state = ShownState(); const tachyon::ID rowID = state.RowIDInRange(row); if (rowID == tachyon::ID::Invalid()) return false; return state.multiSelect ? state.multiSelect->selectedIDs.contains(rowID) : state.selectedRowID == rowID; @@ -196,7 +198,7 @@ namespace tachyon // The nodes selected in the shown tree. std::vector SelectedNodes() { - tachyon::TableState& state = ShownState(); + tachyon::views::TableState& state = ShownState(); std::vector nodes; auto add = [&](tachyon::ID rowID) { if (rowID.GetMode() != tachyon::IDMode::SubRange) return; @@ -214,7 +216,7 @@ namespace tachyon void ClearSelection() { - for (tachyon::TableState* state : { &treeViewState, &filteredState }) + for (tachyon::views::TableState* state : { &treeViewState, &filteredState }) { state->selectedRowID = tachyon::ID::Invalid(); if (state->multiSelect) @@ -237,9 +239,9 @@ namespace tachyon // Selects `node` in the shown tree if it's one of its rows this frame. bool SelectNode(tachyon::ID node) { - tachyon::TableState& state = ShownState(); + tachyon::views::TableState& state = ShownState(); const std::vector& visibleIdx = ShownVisibleIdx(); - const std::vector& rows = ShownRows(); + const std::vector& rows = ShownRows(); if (state.RowIDInRange(0) == tachyon::ID::Invalid()) return false; for (int row = 0; row < int(visibleIdx.size()); ++row) { @@ -258,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; @@ -284,7 +286,7 @@ namespace tachyon { "Folder", showcase.treeFolderIcon } }; for (const auto& [name, icon] : kinds) MenuItem({ icon, name }, [this, &p, name, icon, parent] { - TreeViewRow row{}; + views::TreeViewRow row{}; row.id = idManager.CreateStaticID(); row.name = name; row.icon = icon; @@ -294,7 +296,7 @@ namespace tachyon auto it = scene.idToFlat.find(parent); if (it != scene.idToFlat.end()) { - const TreeViewRow& under = scene.treeRows[it->second]; + const views::TreeViewRow& under = scene.treeRows[it->second]; p.treeViewState.openRows.insert(under.id); row.depth = under.depth + 1; at = size_t(it->second + under.skipCount + 1); @@ -347,15 +349,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) @@ -381,7 +383,7 @@ namespace tachyon // ---- Dataset ------------------------------------------------------ auto add = [&](const char* name, int depth, IconID icon, bool isOpen) { - TreeViewRow r{}; + views::TreeViewRow r{}; r.id = idManager.CreateStaticID(); r.name = name; r.depth = depth; @@ -438,12 +440,12 @@ namespace tachyon if (visual.sourceID.GetMode() != tachyon::IDMode::SubRange) return; const int visIdx = static_cast(visual.sourceID.value.subRangeParts.index); if (visIdx < 0 || visIdx >= int(p.treeVisibleIdx.size())) return; - const std::vector& rows = p.scene->treeRows; + const std::vector& rows = p.scene->treeRows; const int flatIdx = p.treeVisibleIdx[visIdx]; if (flatIdx < 0 || flatIdx >= int(rows.size())) return; const IconID icon = rows[flatIdx].icon != IconID::Invalid ? rows[flatIdx].icon : showcase.circleIcon; - const int2 size{ theme.treeTableIconSize, theme.treeTableIconSize }; + const int2 size{ views::GetStyles(*this, viewsContext).treeTableIconSize, views::GetStyles(*this, viewsContext).treeTableIconSize }; if (BeginCursorGhostWindow(showcase.dragGhostWindowID, visual.screenPos, size)) AddGhostIcon(icon, size); EndGhostWindow(); @@ -458,7 +460,7 @@ namespace tachyon const int dstDs = p.treeVisibleIdx[targetVis]; HierarchyScene& scene = *p.scene; const tachyon::ID target = dstDs >= 0 && dstDs < int(scene.treeRows.size()) ? scene.treeRows[size_t(dstDs)].id : tachyon::ID::Invalid(); - const int newFlatIdx = TreeUtils::ReorderTreeRow(scene.treeRows, srcDs, dstDs, pos); + const int newFlatIdx = views::TreeUtils::ReorderTreeRow(scene.treeRows, srcDs, dstDs, pos); if (newFlatIdx < 0) return; if (pos == TreeDropPosition::Inside || pos == TreeDropPosition::InsideLast) p.treeViewState.openRows.insert(target); // it shows what went into it @@ -493,7 +495,7 @@ namespace tachyon // forced open so matches under collapsed parents show. Depths are // preserved, so the copy is a valid forest for RebuildTreeViewIndex. // Rows added, removed or moved, here or in another Hierarchy, make the copy again. - const std::vector& sceneRows = p.scene->treeRows; + const std::vector& sceneRows = p.scene->treeRows; if (p.seenRevision != p.scene->revision) { p.seenRevision = p.scene->revision; @@ -515,13 +517,13 @@ namespace tachyon for (int i = 0; i < int(sceneRows.size()); ++i) { if (!keep[i]) continue; - TreeViewRow r = sceneRows[i]; + views::TreeViewRow r = sceneRows[i]; r.renameBuffer = nullptr; // copies don't write back - no rename p.filteredRows.push_back(std::move(r)); } - RebuildTreeViewIndex(p.filteredRows); + views::RebuildTreeViewIndex(p.filteredRows); p.filteredState.openRows.clear(); - for (const TreeViewRow& r : p.filteredRows) + for (const views::TreeViewRow& r : p.filteredRows) p.filteredState.openRows.insert(r.id); p.filteredState.multiSelect = &p.filteredMultiSelect; // A new copy: its rows aren't the old one's, so nothing of its selection carries over. @@ -541,13 +543,13 @@ namespace tachyon // to add the leading column. Neither column has a sizer, so the on-stack // `cols` array needn't outlive the VirtualTable call. auto renderTree = [&](tachyon::ID id, - std::vector& rows, + std::vector& rows, std::vector& visibleIdx, - TableState& state) + views::TableState& state) { - WalkTreeViewVisibility(rows, visibleIdx, state); // a collapse keeps the selection on its nodes + views::WalkTreeViewVisibility(rows, visibleIdx, state); // a collapse keeps the selection on its nodes bool anyExpandable = false; - for (TreeViewRow& r : rows) + for (views::TreeViewRow& r : rows) { if (r.HasChildren()) anyExpandable = true; if (r.icon == showcase.treeFolderOpenIcon || r.icon == showcase.treeFolderIcon) @@ -559,13 +561,13 @@ namespace tachyon const bool propsLoading = sinceStart < ProgressDemos::kPropsLoadSecs; const bool streaming = sinceStart < ProgressDemos::kTerrainStreamSecs; - VirtualTableColumn cols[3]; + views::VirtualTableColumn cols[3]; // Col 0 - visibility toggle. Shows the "on" eye only on hover (so // a fully-visible tree shows no icons); "off"/"mixed" show always. - cols[0].column = TableColumn{ .header = {}, + cols[0].column = views::TableColumn{ .header = {}, .initialWidth = kVizColWidth, .minWidth = kVizColWidth, - .maxWidth = kVizColWidth, .sizing = ColumnSizing::Fixed, + .maxWidth = kVizColWidth, .sizing = views::ColumnSizing::Fixed, .interactiveContent = true }; cols[0].generateCell = [this, &p, &rows, &visibleIdx, &state, eyeHeight](int rowIdx) { @@ -573,7 +575,7 @@ namespace tachyon const tachyon::ID nodeId = rows[visibleIdx[rowIdx]].id; const tachyon::ID rowID = state.RowIDInRange(rowIdx); const HierarchyScene::VizAgg agg = p.scene->HierComputeAgg(nodeId); - Cell([this, &p, nodeId, rowID, agg, eyeHeight]() + views::Cell(*this, viewsContext, [this, &p, nodeId, rowID, agg, eyeHeight]() { // The column is interactiveContent, so the table makes this cell part of // the row: hovering the eye highlights the row, and the eye keeps its own @@ -643,31 +645,31 @@ namespace tachyon }; // Col 1 - the tree (mirrors VirtualTreeView's single column). - cols[1].column = TableColumn{ .header = {} }; + cols[1].column = views::TableColumn{ .header = {} }; cols[1].generateCell = [this, &p, &rows, &visibleIdx, &state, anyExpandable, propsLoading](int rowIdx) { if (rowIdx < 0 || rowIdx >= int(visibleIdx.size())) return; const size_t flat = size_t(visibleIdx[rowIdx]); - TreeViewRow& r = rows[flat]; + views::TreeViewRow& r = rows[flat]; // A row still loading: a placeholder where its icon and name will be, indented as // its row will be. if (propsLoading && p.scene->loadingRows.contains(r.id)) { - const int32_t indent = r.depth * theme.treeTableIndent + (anyExpandable ? theme.treeTableExpanderWidth : 0); + const int32_t indent = r.depth * views::GetStyles(*this, viewsContext).treeTableIndent + (anyExpandable ? views::GetStyles(*this, viewsContext).treeTableExpanderWidth : 0); const int32_t width = styleManager.Px(70 + int((r.id.Value() * 37u) % 60u)); - Cell([this, indent, width] { + views::Cell(*this, viewsContext, [this, indent, width] { BeginHorizontal(idManager.AllocateDynamicID("loadingRow"), hierarchySkeletonRowStyleRef, 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; } - TreeCell(r.name, r.depth, - TreeViewOpenRef(rows, flat, state), + views::TreeCell(*this, viewsContext, r.name, r.depth, + views::TreeViewOpenRef(rows, flat, state), r.icon, r.ancestorLineMask, r.isLastSibling, r.renameBuffer, anyExpandable); }; @@ -678,7 +680,7 @@ namespace tachyon state.showHeaders = false; state.columnSeparators = false; // the eye column reads as part of the row state.cellStyle = hierarchyVizCellStyleRef; - state.rowStyle = theme.listRowStyleRef; // rounded, no stripes + state.rowStyle = views::GetStyles(*this, viewsContext).listRowStyleRef; // rounded, no stripes state.commandMode = hierarchyMode; // Delete // On a row: add under it, and delete it, or the whole selection when it's part of it. // Below the rows: add to the scene. @@ -696,23 +698,23 @@ 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 = {}, + cols[2].column = views::TableColumn{ .header = {}, .initialWidth = streamingWidth, .minWidth = streamingWidth, - .maxWidth = streamingWidth, .sizing = ColumnSizing::Fixed }; + .maxWidth = streamingWidth, .sizing = views::ColumnSizing::Fixed }; cols[2].generateCell = [this, &p, &rows, &visibleIdx](int rowIdx) { const bool here = rowIdx >= 0 && rowIdx < int(visibleIdx.size()) && rows[visibleIdx[rowIdx]].id == p.scene->streamingRow; - Cell([this, here] { + views::Cell(*this, viewsContext, [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(); }); }; - VirtualTable(id, state, std::span(cols, streaming ? 3 : 2), + views::VirtualTable(*this, viewsContext, id, state, std::span(cols, streaming ? 3 : 2), int(visibleIdx.size()), 0, hierarchyTableStyleRef, tachyon::LayoutOverride::Auto().FlexGrow(1).MinHeight(0)); p.treeHasFocus = guiStateManager.Interaction().IsFocusWithin(id); diff --git a/examples/showcase/panel_inspector.cpp b/examples/showcase/panel_inspector.cpp index 92de0ffb..263cb473 100644 --- a/examples/showcase/panel_inspector.cpp +++ b/examples/showcase/panel_inspector.cpp @@ -2,6 +2,9 @@ #include #include +#include +#include +#include #include #include @@ -37,8 +40,8 @@ namespace tachyon bool inspectorSectionOpen[SectionCount] = { true, true, true, true, true }; // Its views of the demo curves and levels: its own zoom, selection and editor windows. - CurveViewState curve, colorCurves; - PlotViewState levels; + curves::CurveViewState curve, colorCurves; + curves::PlotViewState levels; // Its lists' and menus' static IDs, its own so another Inspector's don't share them. IDManager* ids = nullptr; @@ -58,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); }); } @@ -70,67 +73,67 @@ namespace tachyon if (showcase.curvesSeeded) return; showcase.curvesSeeded = true; - auto withIDs = [this](Curve curve) { - for (CurveKey& k : curve.keys) + auto withIDs = [this](curves::Curve curve) { + for (curves::CurveKey& k : curve.keys) k.stableID = idManager.CreateStaticID(); return curve; }; - auto onEdit = [this](CurveData* view, const char* what) { - return [this, view, what](const CurveEdit& edit) { - const auto shared = std::make_shared(edit); + auto onEdit = [this](curves::CurveData* view, const char* what) { + return [this, view, what](const curves::CurveEdit& edit) { + const auto shared = std::make_shared(edit); commandManager.History().Push({ .description = what, - .undo = [view, shared] { ApplyCurveEdit(*view, *shared, /*undo*/ true); }, - .redo = [view, shared] { ApplyCurveEdit(*view, *shared, /*undo*/ false); }, - .drop = [this, shared](bool undone) { ReleaseCurveEditIDs(idManager, *shared, undone); } }); + .undo = [view, shared] { curves::ApplyCurveEdit(*view, *shared, /*undo*/ true); }, + .redo = [view, shared] { curves::ApplyCurveEdit(*view, *shared, /*undo*/ false); }, + .drop = [this, shared](bool undone) { curves::ReleaseCurveEditIDs(idManager, *shared, undone); } }); commandManager.History().EndMerge(); }; }; // A falloff: full at the center, easing out to nothing at the edge. static constexpr float2 kFalloff[] = { { 0.0f, 1.0f }, { 0.35f, 0.85f }, { 1.0f, 0.0f } }; - CurveData& falloff = showcase.demoCurve; - falloff.channels = { CurveChannel{ .name = "Falloff", .curve = withIDs(MakeCurve(kFalloff)) } }; - falloff.channels[0].curve.keys.back().tangents = CurveTangentMode::Flat; - UpdateCurveTangents(falloff.channels[0].curve); + curves::CurveData& falloff = showcase.demoCurve; + falloff.channels = { curves::CurveChannel{ .name = "Falloff", .curve = withIDs(curves::MakeCurve(kFalloff)) } }; + falloff.channels[0].curve.keys.back().tangents = curves::CurveTangentMode::Flat; + curves::UpdateCurveTangents(falloff.channels[0].curve); falloff.clampValues = true; falloff.onEdit = onEdit(&falloff, "Edit curve"); // A grade's red, green and blue: the red lifted, the green with more contrast, the blue // lifted in the shadows. - CurveData& color = showcase.demoColorCurves; + curves::CurveData& color = showcase.demoColorCurves; static constexpr float2 kRed[] = { { 0.0f, 0.0f }, { 0.5f, 0.62f }, { 1.0f, 1.0f } }; static constexpr float2 kGreen[] = { { 0.0f, 0.0f }, { 0.3f, 0.16f }, { 0.7f, 0.86f }, { 1.0f, 1.0f } }; static constexpr float2 kBlue[] = { { 0.0f, 0.0f }, { 0.25f, 0.36f }, { 1.0f, 1.0f } }; - color.channels = { CurveChannel{ .name = "R", .color = CurveChannelColor::Red, .curve = withIDs(MakeCurve(kRed)) }, - CurveChannel{ .name = "G", .color = CurveChannelColor::Green, .curve = withIDs(MakeCurve(kGreen)) }, - CurveChannel{ .name = "B", .color = CurveChannelColor::Blue, .curve = withIDs(MakeCurve(kBlue)) } }; + color.channels = { curves::CurveChannel{ .name = "R", .color = curves::CurveChannelColor::Red, .curve = withIDs(curves::MakeCurve(kRed)) }, + curves::CurveChannel{ .name = "G", .color = curves::CurveChannelColor::Green, .curve = withIDs(curves::MakeCurve(kGreen)) }, + curves::CurveChannel{ .name = "B", .color = curves::CurveChannelColor::Blue, .curve = withIDs(curves::MakeCurve(kBlue)) } }; color.clampValues = true; color.onEdit = onEdit(&color, "Edit color curves"); } void Application::SeedLevels() { - PlotData& levels = showcase.demoLevels; + curves::PlotData& levels = showcase.demoLevels; if (!levels.series.empty() || demoImagePixels.empty()) return; // The demo image's channels, each counted into 64 bins over 0 to 255. - const std::pair channels[] = { - { "R", CurveChannelColor::Red }, { "G", CurveChannelColor::Green }, { "B", CurveChannelColor::Blue } }; + const std::pair channels[] = { + { "R", curves::CurveChannelColor::Red }, { "G", curves::CurveChannelColor::Green }, { "B", curves::CurveChannelColor::Blue } }; for (int c = 0; c < 3; ++c) { std::vector samples; for (size_t i = size_t(c); i < demoImagePixels.size(); i += 4) samples.push_back(float(demoImagePixels[i])); - levels.series.push_back(PlotSeries{ .name = channels[c].first, .kind = PlotSeriesKind::Area, - .color = channels[c].second, .values = HistogramBins(samples, 64, 0.0f, 255.0f) }); + levels.series.push_back(curves::PlotSeries{ .name = channels[c].first, .kind = curves::PlotSeriesKind::Area, + .color = channels[c].second, .values = curves::HistogramBins(samples, 64, 0.0f, 255.0f) }); } levels.xMax = 255.0f; levels.handles = { { "Black", 0.0f, { 0.0f, 0.0f, 0.0f, 1.0f } }, { "Gray", 128.0f, { 0.5f, 0.5f, 0.5f, 1.0f } }, { "White", 255.0f, { 1.0f, 1.0f, 1.0f, 1.0f } } }; - levels.onEdit = [this](const PlotEdit& edit) { + levels.onEdit = [this](const curves::PlotEdit& edit) { commandManager.History().Push({ .description = "Move a level", - .undo = [this, edit] { ApplyPlotEdit(showcase.demoLevels, edit, /*undo*/ true); }, - .redo = [this, edit] { ApplyPlotEdit(showcase.demoLevels, edit, /*undo*/ false); } }); + .undo = [this, edit] { curves::ApplyPlotEdit(showcase.demoLevels, edit, /*undo*/ true); }, + .redo = [this, edit] { curves::ApplyPlotEdit(showcase.demoLevels, edit, /*undo*/ false); } }); commandManager.History().EndMerge(); }; } @@ -289,26 +292,26 @@ namespace tachyon // ---- Color & vectors ------------------------------------------------ section = InspectorPanel::ColorAndVectors; // Named as a material's are: the picker and the editor name what they edit after their title. - add("Tint", [this]() { DragLabel("Tint"); ColorField(showcase.demoColor); }); - add("Sky ramp", [this]() { DragLabel("Sky ramp"); GradientField(showcase.demoGradient); }); - add("HDR gradient", [this]() { DragLabel("HDR gradient"); GradientField(showcase.demoGradientF); }); + add("Tint", [this]() { DragLabel("Tint"); color::ColorField(*this, colorContext, showcase.demoColor); }); + add("Sky ramp", [this]() { DragLabel("Sky ramp"); color::GradientField(*this, colorContext, showcase.demoGradient); }); + add("HDR gradient", [this]() { DragLabel("HDR gradient"); color::GradientField(*this, colorContext, showcase.demoGradientF); }); SeedCurves(); - add("Curve", [this, &p]() { DragLabel("Curve"); CurveField({ showcase.demoCurve, p.curve }); }); - add("Color curves", [this, &p]() { DragLabel("Color curves"); CurveField({ showcase.demoColorCurves, p.colorCurves }); }); + add("Curve", [this, &p]() { DragLabel("Curve"); curves::CurveField(*this, curvesContext, { showcase.demoCurve, p.curve }); }); + add("Color curves", [this, &p]() { DragLabel("Color curves"); curves::CurveField(*this, curvesContext, { showcase.demoColorCurves, p.colorCurves }); }); add("Levels", [this, &p]() { SeedLevels(); // once the demo image is made Label("Levels", "of the image"); BeginVertical(idManager.AllocateDynamicID("levelsColumn"), theme.emptyVertStyleRef, LayoutOverride{}.FlexGrow(1)); - Plot({ showcase.demoLevels, p.levels }, LayoutOverride{}.Height(190)); + curves::Plot(*this, curvesContext, { showcase.demoLevels, p.levels }, LayoutOverride{}.Height(190)); BeginHorizontal(idManager.AllocateDynamicID("levelsOptions"), inspectorPairHalfStyleRef, LayoutOverride{}.FlexGrow(1)); // The image whose colors the plot counts. Image(demoImageIndex, LayoutOverride::FixedSize(32, 32)); static constexpr std::string_view kKinds[] = { "Bars", "Area", "Line" }; if (Dropdown(showcase.demoLevelsKind, kKinds)) - for (PlotSeries& series : showcase.demoLevels.series) - series.kind = PlotSeriesKind(showcase.demoLevelsKind); + for (curves::PlotSeries& series : showcase.demoLevels.series) + series.kind = curves::PlotSeriesKind(showcase.demoLevelsKind); if (Checkbox(showcase.demoLevelsLog, "Log scale")) - showcase.demoLevels.yScale = showcase.demoLevelsLog ? PlotScale::Log : PlotScale::Linear; + showcase.demoLevels.yScale = showcase.demoLevelsLog ? curves::PlotScale::Log : curves::PlotScale::Linear; EndHorizontal(); EndVertical(); }); @@ -417,19 +420,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..974122e0 100644 --- a/examples/showcase/panel_misc.cpp +++ b/examples/showcase/panel_misc.cpp @@ -1,8 +1,9 @@ #include "application.h" #include #include -#include +#include #include +#include // // The Misc panel: drawing, icon buttons, rich text, image thumbnails and the clipboard's image @@ -35,7 +36,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 +44,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 }); @@ -52,11 +53,11 @@ namespace tachyon void Application::PasteImageFile(const std::string& path) { // The shell's picture of the file, as large as the well can use. - static const FileThumbnails::Reader reader = FileThumbnails::ShellReader(); - FileThumbnails::Picture picture; + static const app_controls::FileThumbnails::Reader reader = app_controls::FileThumbnails::ShellReader(); + app_controls::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 +70,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; } @@ -111,7 +112,7 @@ namespace tachyon { const StyleManager& sm = styleManager; const IntRect inner = ctx.ElementInnerRect(); - RenderCanvasGrid(ctx, sm.Px(16), theme.GetColor("--canvas-dot"), sm.Px(2.0f), int2{ sm.Px(8), sm.Px(8) }, + nodes::RenderCanvasGrid(ctx, sm.Px(16), theme.GetColor("--canvas-dot"), sm.Px(2.0f), int2{ sm.Px(8), sm.Px(8) }, IntRect{ 0, 0, inner.w, inner.h }); const float s = std::min(float(inner.w) / 420.0f, float(inner.h) / 200.0f); @@ -351,8 +352,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/panel_node_view.cpp b/examples/showcase/panel_node_view.cpp index d26b0586..867df0b9 100644 --- a/examples/showcase/panel_node_view.cpp +++ b/examples/showcase/panel_node_view.cpp @@ -1,7 +1,8 @@ #include "application.h" +#include +#include -#include // AddNodeEdit, RemoveNodesEdit, GridLineNearest -#include +#include // AddNodeEdit, RemoveNodesEdit, GridLineNearest #include #include @@ -16,19 +17,19 @@ namespace tachyon { - // A NodeView panel's own view of the showcase's graph: its pan and zoom, selection and menus. + // A nodes::NodeView panel's own view of the showcase's graph: its pan and zoom, selection and menus. struct NodeGraphPanel { - NodeViewState view; + 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); }; @@ -37,7 +38,7 @@ namespace tachyon return id; } - NodeViewState* Application::FocusedGraphView() + nodes::NodeViewState* Application::FocusedGraphView() { for (const std::weak_ptr& weak : m_nodeGraphPanels) if (const std::shared_ptr panel = weak.lock(); @@ -50,22 +51,22 @@ namespace tachyon { // The "Inputs" frame round Source and Texture, once their sizes are known. Not an edit: // it's where the graph starts, not something to undo. - const NodeViewRef view{ showcase.nodeGraph, panel.view }; - NodeGraph& graph = showcase.nodeGraph; + const nodes::NodeViewRef view{ showcase.nodeGraph, panel.view }; + nodes::NodeGraph& graph = showcase.nodeGraph; if (!showcase.nodeFramesSeeded && graph.nodes.size() >= 4 && graph.nodes[0].lastSize.x > 0 && graph.nodes[3].lastSize.x > 0) { const int inputs[] = { 0, 3 }; - NodeFrame frame = FrameAroundNodes(view, inputs); + nodes::NodeFrame frame = nodes::FrameAroundNodes(view, inputs); frame.stableID = idManager.CreateStaticID(); frame.title = "Inputs"; frame.color = { 0.20f, 0.75f, 0.72f, 1.0f }; - ApplyNodeViewEdit(view, AddFrameEdit(view, std::move(frame))); + nodes::ApplyNodeViewEdit(view, nodes::AddFrameEdit(view, std::move(frame))); showcase.nodeFramesSeeded = true; } - RenderNodeView(view); + nodes::RenderNodeView(*this, nodesContext, view); } - void Application::AddGraphNode(NodeViewState& view, GraphNodeKind kind, float2 at) + void Application::AddGraphNode(nodes::NodeViewState& view, GraphNodeKind kind, float2 at) { // The graph's socket colors double as its types (canConnect lets only the same color // connect): teal for colors and images, amber for numbers, purple for switches. @@ -73,7 +74,7 @@ namespace tachyon const color4f kAmber { 0.95f, 0.62f, 0.20f, 1.0f }; const color4f kPurple{ 0.62f, 0.45f, 0.92f, 1.0f }; - NodeModel node; + nodes::NodeModel node; node.stableID = idManager.CreateStaticID(); node.pos = { int32_t(at.x), int32_t(at.y) }; const ID id = node.stableID; @@ -81,7 +82,7 @@ namespace tachyon // Its values, looked up each time: the map may have grown since. auto values = [this, id]() -> ShowcaseState::GraphNodeValues& { return showcase.graphNodeValues[id]; }; auto row = [](std::string name, std::string type, color4f color, bool input, bool output, std::function body) { - return NodeProperty{ .input = input ? std::optional(PropertyEndpoint{}) : std::nullopt, .output = output, + return nodes::NodeProperty{ .input = input ? std::optional(nodes::PropertyEndpoint{}) : std::nullopt, .output = output, .renderBody = std::move(body), .socketColor = color, .name = std::move(name), .type = std::move(type) }; }; switch (kind) @@ -102,9 +103,9 @@ namespace tachyon node.properties.push_back(row("Operation", "", kAmber, false, false, [this, values] { Dropdown(idManager.AllocateDynamicID("math-op"), values().op, kOps); })); - node.properties.push_back(row("A", "float", kAmber, true, false, [this] { NodeText("A"); })); - node.properties.push_back(row("B", "float", kAmber, true, false, [this] { NodeText("B"); })); - node.properties.push_back(row("Result", "float", kAmber, false, true, [this] { NodeText("Result"); })); + node.properties.push_back(row("A", "float", kAmber, true, false, [this] { nodes::NodeText(*this, nodesContext, "A"); })); + node.properties.push_back(row("B", "float", kAmber, true, false, [this] { nodes::NodeText(*this, nodesContext, "B"); })); + node.properties.push_back(row("Result", "float", kAmber, false, true, [this] { nodes::NodeText(*this, nodesContext, "Result"); })); break; } case GraphNodeKind::Noise: @@ -118,56 +119,56 @@ namespace tachyon Label("Seed"); Field(values().seed); })); - node.properties.push_back(row("Color", "color", kTeal, false, true, [this] { NodeText("Color"); })); + node.properties.push_back(row("Color", "color", kTeal, false, true, [this] { nodes::NodeText(*this, nodesContext, "Color"); })); break; case GraphNodeKind::Switch: node.title = "Switch"; node.category = "Operator"; - node.properties.push_back(row("Condition", "bool", kPurple, true, false, [this] { NodeText("Condition"); })); - node.properties.push_back(row("True", "color", kTeal, true, false, [this] { NodeText("True"); })); - node.properties.push_back(row("False", "color", kTeal, true, false, [this] { NodeText("False"); })); - node.properties.push_back(row("Result", "color", kTeal, false, true, [this] { NodeText("Result"); })); + node.properties.push_back(row("Condition", "bool", kPurple, true, false, [this] { nodes::NodeText(*this, nodesContext, "Condition"); })); + node.properties.push_back(row("True", "color", kTeal, true, false, [this] { nodes::NodeText(*this, nodesContext, "True"); })); + node.properties.push_back(row("False", "color", kTeal, true, false, [this] { nodes::NodeText(*this, nodesContext, "False"); })); + node.properties.push_back(row("Result", "color", kTeal, false, true, [this] { nodes::NodeText(*this, nodesContext, "Result"); })); break; } // The category's color, from the palette as the seeded nodes' are; an operator's is // left unset, which shows the accent. if (node.category == "Input") node.categoryColor = theme.GetColor("--node-input"); if (node.category == "Texture") node.categoryColor = theme.GetColor("--node-generator"); - const NodeViewRef shown{ showcase.nodeGraph, view }; - CommitNodeViewEdit(shown, AddNodeEdit(shown, std::move(node))); + const nodes::NodeViewRef shown{ showcase.nodeGraph, view }; + nodes::CommitNodeViewEdit(shown, nodes::AddNodeEdit(shown, std::move(node))); } - void Application::GroupSelection(NodeViewState& view) + void Application::GroupSelection(nodes::NodeViewState& view) { if (view.selectedNodeIDs.empty() && view.selectedFrameIDs.empty()) return; const ID group = idManager.CreateStaticID(); - const NodeViewRef shown{ showcase.nodeGraph, view }; - const NodeViewEdit edit = GroupSelectionEdit(shown, NodeFrame{ .stableID = group, .title = "Group" }); + const nodes::NodeViewRef shown{ showcase.nodeGraph, view }; + const nodes::NodeViewEdit edit = nodes::GroupSelectionEdit(shown, nodes::NodeFrame{ .stableID = group, .title = "Group" }); if (edit.frames.empty()) return; - CommitNodeViewEdit(shown, edit); + nodes::CommitNodeViewEdit(shown, edit); // The new frame selected, so Ctrl+G again puts it in another. view.selectedNodeIDs.clear(); view.selectedFrameIDs = { group }; } - NodeModel Application::RerouteNode(float2 at, color4f color) + nodes::NodeModel Application::RerouteNode(float2 at, color4f color) { // Its dot on the grid point nearest `at`: the square's top-left one grid cell up and left. - const int grid = std::max(1, theme.nodeGridSize); - NodeModel reroute; + const int grid = std::max(1, nodes::GetStyles(*this, nodesContext).nodeGridSize); + nodes::NodeModel reroute; reroute.stableID = idManager.CreateStaticID(); reroute.title = "Reroute"; reroute.reroute = true; - reroute.pos = { GridLineNearest(int32_t(at.x) - grid, 0, grid), GridLineNearest(int32_t(at.y) - grid, 0, grid) }; - reroute.properties.push_back(NodeProperty{ .input = PropertyEndpoint{}, .output = true, .socketColor = color }); + reroute.pos = { nodes::GridLineNearest(int32_t(at.x) - grid, 0, grid), nodes::GridLineNearest(int32_t(at.y) - grid, 0, grid) }; + reroute.properties.push_back(nodes::NodeProperty{ .input = nodes::PropertyEndpoint{}, .output = true, .socketColor = color }); return reroute; } - void Application::DeleteSelectedNodes(NodeViewState& state) + void Application::DeleteSelectedNodes(nodes::NodeViewState& state) { - const NodeViewRef view{ showcase.nodeGraph, state }; + const nodes::NodeViewRef view{ showcase.nodeGraph, state }; std::vector selected; for (int n = 0; n < int(view.graph.nodes.size()); ++n) if (view.state.selectedNodeIDs.contains(view.graph.nodes[size_t(n)].stableID)) @@ -177,9 +178,9 @@ namespace tachyon if (view.state.selectedFrameIDs.contains(view.graph.frames[size_t(f)].stableID)) frames.push_back(f); // One edit, so one undo puts both back. - NodeViewEdit edit = RemoveNodesEdit(view, selected); - edit.frames = RemoveFramesEdit(view, frames).frames; - CommitNodeViewEdit(view, edit); + nodes::NodeViewEdit edit = nodes::RemoveNodesEdit(view, selected); + edit.frames = nodes::RemoveFramesEdit(view, frames).frames; + nodes::CommitNodeViewEdit(view, edit); } } diff --git a/examples/showcase/panel_profiler_tree.cpp b/examples/showcase/panel_profiler_tree.cpp index ac9bb622..45b3e978 100644 --- a/examples/showcase/panel_profiler_tree.cpp +++ b/examples/showcase/panel_profiler_tree.cpp @@ -1,11 +1,13 @@ #include "application.h" -#include +#include #include // MakeVerticalSizerHandler #include #include #include #include +#include +#include #include #include @@ -48,7 +50,7 @@ namespace tachyon return 1 + int(key % (kPaletteN - 1)); } - // Flat tree row (TreeUtils::TreeRowLike). Numbers are pre-formatted so the + // Flat tree row (views::TreeUtils::TreeRowLike). Numbers are pre-formatted so the // cell lambdas hand VirtualTable stable storage. struct ProfRow { @@ -136,8 +138,8 @@ namespace tachyon std::vector rows; std::unordered_map openState; std::vector visibleIdx; - tachyon::TableState tableState; - std::vector columns; + tachyon::views::TableState tableState; + std::vector columns; tachyon::ID prevSelectedRow = tachyon::ID::Invalid(); uint64_t prevSelectedKey = 0; // The selected scope's stable call-path hash (0 = nothing selected). @@ -170,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); }; @@ -185,7 +187,7 @@ namespace tachyon std::vector& rows = p.rows; std::unordered_map& openState = p.openState; std::vector& visibleIdx = p.visibleIdx; - tachyon::TableState& tableState = p.tableState; + tachyon::views::TableState& tableState = p.tableState; int& frameGraphRef = p.frameGraphRef; auto& collector = Diagnostics::MainThreadCollector(); @@ -247,7 +249,7 @@ namespace tachyon r.isOpen = openState.try_emplace(s.key, true).first->second; rows.push_back(std::move(r)); } - TreeUtils::RebuildTreeIndex(rows); + views::TreeUtils::RebuildTreeIndex(rows); // ---- Visibility walk: skip closed subtrees in O(1) ----------------- visibleIdx.clear(); @@ -415,7 +417,7 @@ namespace tachyon flameStylesInit = true; } - const int rowH = theme.tableRowHeight > 0 ? theme.tableRowHeight : styleManager.Px(18); + const int rowH = views::GetStyles(*this, viewsContext).tableRowHeight > 0 ? views::GetStyles(*this, viewsContext).tableRowHeight : styleManager.Px(18); int maxDepth = 0; for (const auto& s : samples) maxDepth = (s.depth > maxDepth) ? s.depth : maxDepth; const int W = p.flameWidth > 0 ? p.flameWidth : styleManager.Px(600); @@ -516,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, @@ -529,49 +531,49 @@ namespace tachyon // ---- Columns ------------------------------------------------------- // Made the first time it's built; the cells read this panel's rows. - std::vector& columns = p.columns; + std::vector& columns = p.columns; if (columns.empty()) columns = { { // Scope takes the width the numbers leave; they keep theirs. - { .header = "Scope", .initialWidth = 200, .minWidth = 100, .maxWidth = 600, .locked = true, .sizing = ColumnSizing::Stretch }, + { .header = "Scope", .initialWidth = 200, .minWidth = 100, .maxWidth = 600, .locked = true, .sizing = views::ColumnSizing::Stretch }, [this, &p](int rowIdx) { std::vector& rows = p.rows; std::vector& visibleIdx = p.visibleIdx; if (rowIdx < 0 || rowIdx >= int(visibleIdx.size())) return; ProfRow& r = rows[visibleIdx[rowIdx]]; const bool branch = (r.skipCount > 0); - TreeCell(r.name, r.depth, branch ? &p.openState[r.key] : nullptr, + views::TreeCell(*this, viewsContext, r.name, r.depth, branch ? &p.openState[r.key] : nullptr, IconID::Invalid, r.ancestorLineMask, r.isLastSibling); } }, { - { .header = "Total ms", .initialWidth = 72, .minWidth = 56, .maxWidth = 160, .sizing = ColumnSizing::Fixed }, + { .header = "Total ms", .initialWidth = 72, .minWidth = 56, .maxWidth = 160, .sizing = views::ColumnSizing::Fixed }, [this, &p](int rowIdx) { std::vector& rows = p.rows; std::vector& visibleIdx = p.visibleIdx; if (rowIdx < 0 || rowIdx >= int(visibleIdx.size())) return; - Cell(rows[visibleIdx[rowIdx]].totalStr); + views::Cell(*this, viewsContext, rows[visibleIdx[rowIdx]].totalStr); } }, { - { .header = "Self ms", .initialWidth = 72, .minWidth = 56, .maxWidth = 160, .sizing = ColumnSizing::Fixed }, + { .header = "Self ms", .initialWidth = 72, .minWidth = 56, .maxWidth = 160, .sizing = views::ColumnSizing::Fixed }, [this, &p](int rowIdx) { std::vector& rows = p.rows; std::vector& visibleIdx = p.visibleIdx; if (rowIdx < 0 || rowIdx >= int(visibleIdx.size())) return; - Cell(rows[visibleIdx[rowIdx]].selfStr); + views::Cell(*this, viewsContext, rows[visibleIdx[rowIdx]].selfStr); } }, { - { .header = "% frame", .initialWidth = 108, .minWidth = 96, .maxWidth = 160, .sizing = ColumnSizing::Fixed }, + { .header = "% frame", .initialWidth = 108, .minWidth = 96, .maxWidth = 160, .sizing = views::ColumnSizing::Fixed }, [this, &p](int rowIdx) { std::vector& rows = p.rows; std::vector& visibleIdx = p.visibleIdx; if (rowIdx < 0 || rowIdx >= int(visibleIdx.size())) return; // A bar at the cell's left (so the bars line up), the number right-aligned. const ProfRow& r = rows[visibleIdx[rowIdx]]; - Cell([this, pct = r.pctFrame, text = r.pctStr]() { + views::Cell(*this, viewsContext, [this, pct = r.pctFrame, text = r.pctStr]() { BeginHorizontal(idManager.AllocateDynamicID("pctTrack"), profilerPctTrackStyleRef, LayoutOverride{}.NoGrow().NoShrink()); const int trackW = styleManager.Px(36); @@ -586,35 +588,35 @@ namespace tachyon } }, { - { .header = "Calls", .initialWidth = 52, .minWidth = 40, .maxWidth = 100, .sizing = ColumnSizing::Fixed }, + { .header = "Calls", .initialWidth = 52, .minWidth = 40, .maxWidth = 100, .sizing = views::ColumnSizing::Fixed }, [this, &p](int rowIdx) { std::vector& rows = p.rows; std::vector& visibleIdx = p.visibleIdx; if (rowIdx < 0 || rowIdx >= int(visibleIdx.size())) return; - Cell(rows[visibleIdx[rowIdx]].callsStr); + views::Cell(*this, viewsContext, rows[visibleIdx[rowIdx]].callsStr); } }, }; // Numbers right-aligned; set each frame as styles reload. for (size_t i = 1; i < columns.size(); ++i) - columns[i].column.cellStyle = theme.tableCellNumberStyleRef; + columns[i].column.cellStyle = views::GetStyles(*this, viewsContext).tableCellNumberStyleRef; columns[3].column.cellStyle = profilerPctCellStyleRef; // Plain rows (no stripes) and no lines between the columns. - tableState.rowStyle = theme.tableRowStyleRef; + tableState.rowStyle = views::GetStyles(*this, viewsContext).tableRowStyleRef; tableState.columnSeparators = false; // The flex-fill row (flex-basis:0) bounds the table to the panel height // so its body scrolls internally instead of overflowing the panel. - std::span columnSpan(columns.data(), columns.size()); + std::span columnSpan(columns.data(), columns.size()); BeginHorizontal(idManager.AllocateDynamicID("profilerFill"), theme.flexFillRowStyleRef, LayoutOverride::Auto().FlexGrow(1)); // A stable static id keeps the table's scroll state put: AllocateDynamicID // folds a per-parent counter, so the flame graph's varying element count // would otherwise shift the table id each frame and reset its scroll. - VirtualTable(p.tableID, + views::VirtualTable(*this, viewsContext, p.tableID, tableState, columnSpan, - int(visibleIdx.size()), 0, theme.tableStyleRef, + int(visibleIdx.size()), 0, views::GetStyles(*this, viewsContext).tableStyleRef, LayoutOverride{}.FlexGrow(1)); EndHorizontal(); EndVertical(); 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 8b377c08..0c604bcc 100644 --- a/examples/showcase/panel_settings.cpp +++ b/examples/showcase/panel_settings.cpp @@ -1,12 +1,13 @@ #include "application.h" // The showcase's Settings pages and their registration with `showcase.settings`. The panel -// chrome lives in gui_controls/controls_settings.cpp. +// chrome lives in gui_views/controls_settings.cpp. -#include #include #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] { RenderSettingsPanel(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); }; @@ -272,7 +273,7 @@ namespace tachyon catRows.clear(); catRows.reserve(1 + cappedCount); { - TreeViewRow r{}; + views::TreeViewRow r{}; r.id = allCatID; r.name = "All"; r.icon = tachyon::IconID::Invalid; @@ -280,13 +281,13 @@ namespace tachyon } for (uint32_t m = 0; m < cappedCount; m++) { - TreeViewRow r{}; + views::TreeViewRow r{}; r.id = catIDs[m]; r.name = commandManager.GetModeName(tachyon::CommandMode(m)); r.icon = tachyon::IconID::Invalid; catRows.push_back(std::move(r)); } - RebuildTreeViewIndex(catRows); + views::RebuildTreeViewIndex(catRows); // Reverse sync (catInternal -> selection) must run before the forward // sync: clicks only mutate catInternal, and the forward sync would @@ -321,7 +322,7 @@ namespace tachyon const bool allSelected = selection.selectedIDs.count(allCatID) > 0; - VirtualTreeView(idManager.AllocateDynamicID("shortcutCatTree"), + views::VirtualTreeView(*this, viewsContext, idManager.AllocateDynamicID("shortcutCatTree"), catRows, catVisibleIdx, catTableState, shortcutCategoryStyleRef, tachyon::LayoutOverride::Auto().FixedWidth(CssPx(page.categoryWidth)).NoGrow(), @@ -331,7 +332,7 @@ namespace tachyon tachyon::ID sizerID = idManager.AllocateDynamicID("shortcutSizer"); tachyon::Element sizer{}; sizer.id = sizerID; - sizer.styleRef = theme.settingsSizerStyleRef; + sizer.styleRef = views::GetStyles(*this, viewsContext).settingsSizerStyleRef; sizer.state = guiStateManager.GetCurrentState(sizerID); sizer.eventHandler = tachyon::MakeHorizontalSizerHandler( guiStateManager, elementStorage, page.categoryWidth, 100, 400, nullptr, nullptr, false, styleManager.GetUIScale()); @@ -401,7 +402,7 @@ namespace tachyon // Command - optional per-command icon shown inline before the name. It takes the // width the other columns leave. cols[0].column = { .header = "Command", .initialWidth = 180, .minWidth = 80, .maxWidth = 600, - .sizing = ColumnSizing::Stretch }; + .sizing = views::ColumnSizing::Stretch }; cols[0].sortAscending = [this, &page](int a, int b) { const auto& vr = page.visRows; const auto& cmds = commandManager.GetCommands(); @@ -423,7 +424,7 @@ namespace tachyon const tachyon::IconID icon = e.icon; const tachyon::StyleRef labelStyle = (icon != tachyon::IconID::Invalid) ? theme.iconLabelStyleRef : theme.iconLabelNoIconStyleRef; - Cell([this, icon, labelStyle, label = std::move(label)]() { + views::Cell(*this, viewsContext, [this, icon, labelStyle, label = std::move(label)]() { const tachyon::ID id = idManager.AllocateDynamicID(); tachyon::Element el{}; el.id = id; @@ -448,7 +449,7 @@ namespace tachyon cols[1].generateCell = [this, &page](int rowIdx) { auto& vr = page.visRows; if (rowIdx < 0 || rowIdx >= int(vr.size())) return; - Cell(commandManager.GetModeName(tachyon::CommandMode(vr[rowIdx].mode))); + views::Cell(*this, viewsContext, commandManager.GetModeName(tachyon::CommandMode(vr[rowIdx].mode))); }; // Shortcut - the bound keys as keycaps; a click rebinds them. @@ -465,7 +466,7 @@ namespace tachyon const uint32_t i = vr[rowIdx].entryIdx; // A click starts a rebind, or cancels the one in progress; while one is, the // cell asks for the keys. - Cell([this, i]() { + views::Cell(*this, viewsContext, [this, i]() { auto toggleRebind = [this, i]() { if (commandManager.RebindTarget() == CommandManager::IDAt(i)) commandManager.CancelRebind(); @@ -492,7 +493,7 @@ namespace tachyon cols[3].generateCell = [this, &page](int rowIdx) { auto& vr = page.visRows; if (rowIdx < 0 || rowIdx >= int(vr.size())) return; - Cell(commandManager.GetCommands()[vr[rowIdx].entryIdx].IsHeld() ? "Hold" : "Instant"); + views::Cell(*this, viewsContext, commandManager.GetCommands()[vr[rowIdx].entryIdx].IsHeld() ? "Hold" : "Instant"); }; } @@ -517,9 +518,9 @@ namespace tachyon } page.tableState.cellStyle = shortcutCellStyleRef; - VirtualTable(idManager.AllocateDynamicID("shortcutTable"), + views::VirtualTable(*this, viewsContext, idManager.AllocateDynamicID("shortcutTable"), page.tableState, - std::span(active.data(), colCount), + std::span(active.data(), colCount), int(visRows.size()), /*rowHeight*/0, shortcutTableStyleRef, // bound to the pane; columns scroll instead of growing the table diff --git a/examples/showcase/panel_sketch.cpp b/examples/showcase/panel_sketch.cpp index 0f2505e4..718d9781 100644 --- a/examples/showcase/panel_sketch.cpp +++ b/examples/showcase/panel_sketch.cpp @@ -1,4 +1,6 @@ #include "application.h" +#include +#include #include #include @@ -65,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; @@ -165,7 +167,7 @@ namespace tachyon VERIFY(windowRegistry.Add(added.ref)); VERIFY(elementStorage.AddCustomDraw(added.ref, [this, &panel, hovered](CustomDrawContext& ctx) { - const VisualColorStyleIndex ink = theme.curveChannelColors[4]; + const VisualColorStyleIndex ink = curves::GetStyles(*this, curvesContext).curveChannelColors[4]; for (const SketchStroke& stroke : sketchStrokes) { const std::vector& points = stroke.points; diff --git a/examples/showcase/panel_split_scroll.cpp b/examples/showcase/panel_split_scroll.cpp index 9dac4793..cf5ce04f 100644 --- a/examples/showcase/panel_split_scroll.cpp +++ b/examples/showcase/panel_split_scroll.cpp @@ -1,4 +1,6 @@ #include "application.h" +#include +#include #include #include @@ -26,11 +28,11 @@ namespace tachyon // A FrozenTable panel's own: its sort, widths, selection and column order. struct FrozenTablePanel { - TableState state; - std::vector columns; + views::TableState state; + 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 = @@ -38,43 +40,43 @@ namespace tachyon // ---- Section 0 (2 columns, fit-content - no H scrollbar) ---- { .column = { .header = "#", .initialWidth = 60, .minWidth = 40, .maxWidth = 160, .locked = true }, - .generateCell = [this](int r) { char b[16]; std::snprintf(b, sizeof(b), "%d", r); Cell(b); }, + .generateCell = [this](int r) { char b[16]; std::snprintf(b, sizeof(b), "%d", r); views::Cell(*this, viewsContext, b); }, .sectionId = 0, - .sectionSizing = SectionSizing::FitContent + .sectionSizing = views::SectionSizing::FitContent }, { .column = { .header = "Type", .initialWidth = 80, .minWidth = 40, .maxWidth = 200, .locked = true }, - .generateCell = [this](int r){ static const char* kT[]={"int","f32","str","bool"}; Cell(kT[r & 3]); }, + .generateCell = [this](int r){ static const char* kT[]={"int","f32","str","bool"}; views::Cell(*this, viewsContext, kT[r & 3]); }, .sectionId = 0 }, // ---- Section 1 (3 columns) ---------------------------------- { .column = { .header = "Name", .initialWidth = 160, .minWidth = 60, .maxWidth = 400 }, - .generateCell = [this](int r) { char b[32]; std::snprintf(b, sizeof(b), "Row %05d", r); Cell(b); }, + .generateCell = [this](int r) { char b[32]; std::snprintf(b, sizeof(b), "Row %05d", r); views::Cell(*this, viewsContext, b); }, .sectionId = 1 }, { .column = { .header = "Hex", .initialWidth = 120, .minWidth = 60, .maxWidth = 200 }, - .generateCell = [this](int r) { char b[16]; std::snprintf(b, sizeof(b), "0x%06X", r); Cell(b); }, + .generateCell = [this](int r) { char b[16]; std::snprintf(b, sizeof(b), "0x%06X", r); views::Cell(*this, viewsContext, b); }, .sectionId = 1 }, { .column = { .header = "Multiple", .initialWidth = 140, .minWidth = 60, .maxWidth = 400 }, - .generateCell = [this](int r){ char b[40]; std::snprintf(b, sizeof(b), "%d x 7 = %d", r, r * 7); Cell(b); }, + .generateCell = [this](int r){ char b[40]; std::snprintf(b, sizeof(b), "%d x 7 = %d", r, r * 7); views::Cell(*this, viewsContext, b); }, .sectionId = 1 }, // ---- Section 2 (2 columns) ---------------------------------- // Tag is Stretch - its trailing boundary becomes a 1px // separator (Stretch columns stop sizers). { - .column = { .header = "Tag", .initialWidth = 60, .minWidth = 40, .maxWidth = 200, .locked = true, .sizing = ColumnSizing::Stretch }, - .generateCell = [this](int r) { static const char* kG[] = { "A","B","C" }; Cell(kG[r % 3]); }, + .column = { .header = "Tag", .initialWidth = 60, .minWidth = 40, .maxWidth = 200, .locked = true, .sizing = views::ColumnSizing::Stretch }, + .generateCell = [this](int r) { static const char* kG[] = { "A","B","C" }; views::Cell(*this, viewsContext, kG[r % 3]); }, .sectionId = 2, - .sectionSizing = SectionSizing::FitContent + .sectionSizing = views::SectionSizing::FitContent }, { .column = { .header = "Status", .initialWidth = 80, .minWidth = 60, .maxWidth = 200, .locked = true }, - .generateCell = [this](int r){ Cell((r % 7 == 0) ? "ALERT" : "ok"); }, + .generateCell = [this](int r){ views::Cell(*this, viewsContext, (r % 7 == 0) ? "ALERT" : "ok"); }, .sectionId = 2 } }; @@ -87,14 +89,14 @@ 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) { constexpr int kTotalRows = 50000; - TableState& tableStyle = panel.state; - std::span columnSpan(panel.columns.data(), panel.columns.size()); + views::TableState& tableStyle = panel.state; + std::span columnSpan(panel.columns.data(), panel.columns.size()); SelectionModeSwitch(tableStyle.selectionMode); @@ -104,9 +106,9 @@ namespace tachyon BeginHorizontal(idManager.AllocateDynamicID("splitScrollFill"), theme.flexFillRowStyleRef, LayoutOverride::Auto().FlexGrow(1)); - VirtualTable(idManager.AllocateDynamicID("multiSectionTable"), + views::VirtualTable(*this, viewsContext, idManager.AllocateDynamicID("multiSectionTable"), tableStyle, - columnSpan, kTotalRows, 0, theme.tableFillStyleRef); + columnSpan, kTotalRows, 0, views::GetStyles(*this, viewsContext).tableFillStyleRef); EndHorizontal(); } } diff --git a/examples/showcase/panel_state_machine.cpp b/examples/showcase/panel_state_machine.cpp index 37ba88d2..d9ab73f0 100644 --- a/examples/showcase/panel_state_machine.cpp +++ b/examples/showcase/panel_state_machine.cpp @@ -1,7 +1,8 @@ #include "application.h" -#include -#include +#include +#include +#include #include // AddTransitionEdit, SetInitialStateEdit, ... #include @@ -11,7 +12,7 @@ #include // -// Demo panel for a node view as a state machine (NodeViewKind::StateMachine): an enemy's +// Demo panel for a node view as a state machine (nodes::NodeViewKind::StateMachine): an enemy's // behaviour, its Combat state holding a machine of its own. Step runs it along a transition. // @@ -19,11 +20,11 @@ namespace tachyon { namespace { - NodeModel State(IDManager& ids, std::string title, int2 pos, bool subMachine = false) + nodes::NodeModel State(IDManager& ids, std::string title, int2 pos, bool subMachine = false) { - return NodeModel{ .stableID = ids.CreateStaticID(), .title = std::move(title), .pos = pos, .subMachine = subMachine }; + return nodes::NodeModel{ .stableID = ids.CreateStaticID(), .title = std::move(title), .pos = pos, .subMachine = subMachine }; } - ID Join(IDManager& ids, NodeGraph& view, int from, int to, std::string label) + ID Join(IDManager& ids, nodes::NodeGraph& view, int from, int to, std::string label) { const ID id = ids.CreateStaticID(); view.transitions.push_back({ .stableID = id, .from = view.nodes[size_t(from)].stableID, @@ -45,8 +46,8 @@ namespace tachyon { "Sleep", "--state-indigo" }, { "Patrol", "--state-teal" }, { "Chase", "--state-amber" }, { "Hurt", "--state-red" }, { "Combat", "--state-violet" }, { "Attack", "--state-red" }, { "Block", "--state-indigo" }, { "Dodge", "--state-teal" } }; - for (NodeGraph* machine : { &showcase.enemyMachine, &showcase.combatMachine }) - for (NodeModel& state : machine->nodes) + for (nodes::NodeGraph* machine : { &showcase.enemyMachine, &showcase.combatMachine }) + for (nodes::NodeModel& state : machine->nodes) for (const StateColor& c : colors) if (state.title == c.title) state.categoryColor = theme.GetColor(c.color); @@ -56,8 +57,8 @@ namespace tachyon { // The enemy: asleep until it hears something, then patrols, chases what it sees, and // fights once it's close; hurt from patrolling or chasing, it goes back to chasing. - NodeGraph& enemy = showcase.enemyMachine; - enemy.kind = NodeViewKind::StateMachine; + nodes::NodeGraph& enemy = showcase.enemyMachine; + enemy.kind = nodes::NodeViewKind::StateMachine; enemy.nodes = { State(idManager, "Sleep", { -320, -140 }), State(idManager, "Patrol", { 80, -140 }), @@ -80,8 +81,8 @@ namespace tachyon enemy.activeState = enemy.initialState; // Combat, inside: attack, block, dodge, round and round. - NodeGraph& combat = showcase.combatMachine; - combat.kind = NodeViewKind::StateMachine; + nodes::NodeGraph& combat = showcase.combatMachine; + combat.kind = nodes::NodeViewKind::StateMachine; combat.nodes = { State(idManager, "Attack", { -200, -100 }), State(idManager, "Block", { 160, -100 }), @@ -98,14 +99,14 @@ namespace tachyon showcase.stateEnteredAt[0] = showcase.stateEnteredAt[1] = Now(); // Each edit on the app's undo history, as the node graph's are. - for (NodeGraph* machine : { &enemy, &combat }) - machine->onEdit = [this, machine](const NodeViewEdit& edit) + for (nodes::NodeGraph* machine : { &enemy, &combat }) + machine->onEdit = [this, machine](const nodes::NodeViewEdit& edit) { - const auto shared = std::make_shared(edit); + const auto shared = std::make_shared(edit); commandManager.History().Push({ .description = "Edit state machine", - .undo = [this, machine, shared] { ApplyNodeViewEdit({ *machine, showcase.noView }, *shared, /*undo*/ true); }, - .redo = [this, machine, shared] { ApplyNodeViewEdit({ *machine, showcase.noView }, *shared, /*undo*/ false); }, - .drop = [this, shared](bool undone) { ReleaseNodeViewEditIDs(idManager, *shared, undone); } }); + .undo = [this, machine, shared] { nodes::ApplyNodeViewEdit({ *machine, showcase.noView }, *shared, /*undo*/ true); }, + .redo = [this, machine, shared] { nodes::ApplyNodeViewEdit({ *machine, showcase.noView }, *shared, /*undo*/ false); }, + .drop = [this, shared](bool undone) { nodes::ReleaseNodeViewEditIDs(idManager, *shared, undone); } }); commandManager.History().EndMerge(); }; } @@ -113,11 +114,11 @@ namespace tachyon // A StateMachine panel's own: its views of the two machines, and which one it shows. struct StateMachinePanel { - NodeViewState enemy, combat; + nodes::NodeViewState enemy, combat; 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) { @@ -126,17 +127,17 @@ namespace tachyon } auto panel = std::make_shared(); StateMachinePanel* const self = panel.get(); - for (NodeGraph* machine : { &showcase.enemyMachine, &showcase.combatMachine }) + for (nodes::NodeGraph* machine : { &showcase.enemyMachine, &showcase.combatMachine }) { - NodeViewState* const view = machine == &showcase.enemyMachine ? &self->enemy : &self->combat; + nodes::NodeViewState* const view = machine == &showcase.enemyMachine ? &self->enemy : &self->combat; view->commandMode = stateMachineMode; view->showMinimap = false; // A state where the right click was. view->onCanvasContextMenu = [this, machine, view](float2 at) { MenuItem("Add state", [this, machine, view, at] { - NodeModel state = State(idManager, "State", { int32_t(at.x), int32_t(at.y) }); - CommitNodeViewEdit({ *machine, *view }, AddNodeEdit({ *machine, *view }, std::move(state))); + nodes::NodeModel state = State(idManager, "State", { int32_t(at.x), int32_t(at.y) }); + nodes::CommitNodeViewEdit({ *machine, *view }, nodes::AddNodeEdit({ *machine, *view }, std::move(state))); }); }; // The state's: start here, or go. @@ -144,7 +145,7 @@ namespace tachyon { const ID id = machine->nodes[size_t(node)].stableID; if (id != machine->initialState) - MenuItem("Set as initial state", [machine, view, id] { CommitNodeViewEdit({ *machine, *view }, SetInitialStateEdit({ *machine, *view }, id)); }); + MenuItem("Set as initial state", [machine, view, id] { nodes::CommitNodeViewEdit({ *machine, *view }, nodes::SetInitialStateEdit({ *machine, *view }, id)); }); MenuItem({ showcase.deleteIcon, "Delete state" }, "Delete", [this, machine, view] { DeleteSelectedStates({ *machine, *view }); }); }; } @@ -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(); @@ -190,17 +191,17 @@ namespace tachyon return nullptr; } - NodeViewRef Application::FocusedMachineView() + nodes::NodeViewRef Application::FocusedMachineView() { StateMachinePanel& panel = *FocusedStateMachine(); - return panel.combatOpen ? NodeViewRef{ showcase.combatMachine, panel.combat } : NodeViewRef{ showcase.enemyMachine, panel.enemy }; + return panel.combatOpen ? nodes::NodeViewRef{ showcase.combatMachine, panel.combat } : nodes::NodeViewRef{ showcase.enemyMachine, panel.enemy }; } void Application::RenderStateMachinePanel(StateMachinePanel& panel) { - const NodeViewRef view = panel.combatOpen ? NodeViewRef{ showcase.combatMachine, panel.combat } - : NodeViewRef{ showcase.enemyMachine, panel.enemy }; - NodeGraph& machine = view.graph; + const nodes::NodeViewRef view = panel.combatOpen ? nodes::NodeViewRef{ showcase.combatMachine, panel.combat } + : nodes::NodeViewRef{ showcase.enemyMachine, panel.enemy }; + nodes::NodeGraph& machine = view.graph; double& enteredAt = showcase.stateEnteredAt[panel.combatOpen ? 1 : 0]; BeginVertical(theme.emptyVertStyleRef, LayoutOverride{}.FlexGrow(1)); @@ -208,8 +209,8 @@ namespace tachyon BeginHorizontal(idManager.AllocateDynamicID("state-machine-toolbar"), stateMachineToolbarStyleRef, LayoutOverride::Auto().NoShrink()); // Step: the machine takes the next transition out of the state it's in, in turn. Button(idManager.AllocateDynamicID("state-machine-step"), { showcase.stepIcon, "Step" }, [this, &machine, &enteredAt] { - std::vector out; - for (const StateTransition& t : machine.transitions) + std::vector out; + for (const nodes::StateTransition& t : machine.transitions) if (t.from == machine.activeState) out.push_back(&t); if (out.empty()) return; machine.activeState = out[showcase.stateMachineSteps++ % out.size()]->to; @@ -241,11 +242,11 @@ namespace tachyon machine.activeStateTime = running ? float(Now() - enteredAt) : -1.0f; if (running) RequestRedrawIn(0.1f); - RenderNodeView(view); + nodes::RenderNodeView(*this, nodesContext, view); EndVertical(); } - void Application::DeleteSelectedStates(NodeViewRef view) + void Application::DeleteSelectedStates(nodes::NodeViewRef view) { // The selected states, their transitions with them, and the selected transitions, as // one edit. @@ -253,21 +254,21 @@ namespace tachyon for (int n = 0; n < (int)view.graph.nodes.size(); ++n) if (view.state.selectedNodeIDs.contains(view.graph.nodes[size_t(n)].stableID)) selected.push_back(n); - NodeViewEdit edit = RemoveNodesEdit(view, selected); + nodes::NodeViewEdit edit = nodes::RemoveNodesEdit(view, selected); // The selected transitions not already going with their states. std::vector transitions; for (const ID id : view.state.selectedTransitionIDs) if (std::none_of(edit.transitions.begin(), edit.transitions.end(), - [id](const NodeViewEdit::Transition& t) { return t.transition.stableID == id; })) + [id](const nodes::NodeViewEdit::Transition& t) { return t.transition.stableID == id; })) transitions.push_back(id); // Applied after the states are gone: by then each one's index is as it is without them. - NodeGraph afterGraph = view.graph; - NodeViewState afterView = view.state; - ApplyNodeViewEdit({ afterGraph, afterView }, edit); - const NodeViewEdit removed = RemoveTransitionsEdit({ afterGraph, afterView }, transitions); + nodes::NodeGraph afterGraph = view.graph; + nodes::NodeViewState afterView = view.state; + nodes::ApplyNodeViewEdit({ afterGraph, afterView }, edit); + const nodes::NodeViewEdit removed = nodes::RemoveTransitionsEdit({ afterGraph, afterView }, transitions); edit.transitions.insert(edit.transitions.end(), removed.transitions.begin(), removed.transitions.end()); if (view.state.selectedNodeIDs.contains(view.graph.activeState)) view.graph.activeState = ID::Invalid(); - CommitNodeViewEdit(view, edit); + nodes::CommitNodeViewEdit(view, edit); } } diff --git a/examples/showcase/panel_table.cpp b/examples/showcase/panel_table.cpp index fdf0f265..f76c1c9e 100644 --- a/examples/showcase/panel_table.cpp +++ b/examples/showcase/panel_table.cpp @@ -1,4 +1,6 @@ #include "application.h" +#include +#include #include #include @@ -45,9 +47,9 @@ namespace tachyon } } - void Application::SelectionModeSwitch(TableSelectionMode& mode) + void Application::SelectionModeSwitch(views::TableSelectionMode& mode) { - static constexpr std::string_view kModes[] = { "Row", "Cell" }; // TableSelectionMode's order + static constexpr std::string_view kModes[] = { "Row", "Cell" }; // views::TableSelectionMode's order // A toolbar above the table, padded, with a line under it. BeginHorizontal(idManager.AllocateDynamicID("selectionModeBar"), tableToolbarStyleRef, LayoutOverride::Auto().NoShrink()); Text(idManager.AllocateDynamicID(), "Selection mode", theme.staticTextStyleRef); @@ -58,11 +60,11 @@ namespace tachyon // A Table panel's own: its sort, widths, selection and column order. struct TablePanel { - TableState state; - std::vector columns; + views::TableState state; + 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(); @@ -72,30 +74,30 @@ namespace tachyon // left, and other columns can't be dragged past it. { .column = { .header = "#", .initialWidth = 64, .minWidth = 40, .maxWidth = 160, .locked = true, - .sizing = ColumnSizing::Fixed }, + .sizing = views::ColumnSizing::Fixed }, .generateCell = [this, &rows](int rowIdx) { - char buf[16]; std::snprintf(buf, sizeof(buf), "%d", rows[rowIdx].index); Cell(buf); + char buf[16]; std::snprintf(buf, sizeof(buf), "%d", rows[rowIdx].index); views::Cell(*this, viewsContext, buf); }, .sortAscending = [&rows](int a, int b) { return rows[a].index < rows[b].index; }, }, { .column = { .header = "Name", .initialWidth = 160, .minWidth = 60, .maxWidth = 400 }, .generateCell = [this, &rows](int rowIdx) { - Cell(rows[rowIdx].name.c_str()); + views::Cell(*this, viewsContext, rows[rowIdx].name.c_str()); }, .sortAscending = [&rows](int a, int b) { return rows[a].name < rows[b].name; }, }, { .column = { .header = "Hex", .initialWidth = 120, .minWidth = 60, .maxWidth = 200 }, .generateCell = [this, &rows](int rowIdx) { - char buf[16]; std::snprintf(buf, sizeof(buf), "0x%06X", rows[rowIdx].hex); Cell(buf); + char buf[16]; std::snprintf(buf, sizeof(buf), "0x%06X", rows[rowIdx].hex); views::Cell(*this, viewsContext, buf); }, .sortAscending = [&rows](int a, int b) { return rows[a].hex < rows[b].hex; }, }, { .column = { .header = "Multiple", .initialWidth = 140, .minWidth = 60, .maxWidth = 400 }, .generateCell = [this, &rows](int rowIdx) { - char buf[40]; std::snprintf(buf, sizeof(buf), "%d x 7 = %d", rows[rowIdx].index, rows[rowIdx].multiple); Cell(buf); + char buf[40]; std::snprintf(buf, sizeof(buf), "%d x 7 = %d", rows[rowIdx].index, rows[rowIdx].multiple); views::Cell(*this, viewsContext, buf); }, .sortAscending = [&rows](int a, int b) { return rows[a].multiple < rows[b].multiple; }, }, @@ -111,25 +113,25 @@ 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) { // ---- Virtual-scrolled table (50k rows, click-to-sort, drag-to-reorder) - std::vector& columns = panel.columns; - TableState& state = panel.state; + std::vector& columns = panel.columns; + views::TableState& state = panel.state; // The row number is a count: right-aligned, so its digits line up. Hex codes and the // multiplications read as text, at the start, in the mono font. Set each frame as // styles reload. - for (VirtualTableColumn& c : columns) + for (views::VirtualTableColumn& c : columns) c.column.cellStyle = c.column.header == "#" ? dataTableNumberStyleRef : c.column.header == "Name" ? StyleRef::Invalid() : dataTableCodeStyleRef; const int kTotalRows = int(GetDemoRows().size()); - std::span columnSpan(columns.data(), columns.size()); + std::span columnSpan(columns.data(), columns.size()); // ---- Mode switcher ------------------------------------------------- @@ -140,9 +142,9 @@ namespace tachyon // Fills the panel and scrolls: sized to its 50k rows it would be past the // 16-bit layout range and not show at all. state.cellStyle = dataTableCellStyleRef; - VirtualTable(idManager.AllocateDynamicID("tablePanelVirtual"), + views::VirtualTable(*this, viewsContext, idManager.AllocateDynamicID("tablePanelVirtual"), state, - columnSpan, kTotalRows, 0, theme.tableFillStyleRef, + columnSpan, kTotalRows, 0, views::GetStyles(*this, viewsContext).tableFillStyleRef, LayoutOverride::Auto().FlexGrow(1).MinHeight(0)); } diff --git a/examples/showcase/panel_timeline.cpp b/examples/showcase/panel_timeline.cpp index e0b6f89b..4d1c6cc7 100644 --- a/examples/showcase/panel_timeline.cpp +++ b/examples/showcase/panel_timeline.cpp @@ -1,4 +1,5 @@ #include "application.h" +#include #include #include @@ -16,18 +17,18 @@ namespace tachyon void Application::SeedAnimation() { animationSeeded = true; - TimelineData& view = animation; + app_controls::TimelineData& view = animation; view.duration = 8.0f; view.fps = 30.0f; view.loopRange = { 1.0f, 6.0f }; view.playback.loop = true; auto group = [this](const char* name, color4f color, bool expanded = true) { - return TimelineTrack{ .stableID = idManager.CreateStaticID(), .name = name, .kind = TimelineTrackKind::Group, + return app_controls::TimelineTrack{ .stableID = idManager.CreateStaticID(), .name = name, .kind = app_controls::TimelineTrackKind::Group, .expanded = expanded, .color = color }; }; auto property = [this](const char* name, std::initializer_list times) { - TimelineTrack track{ .stableID = idManager.CreateStaticID(), .name = name, .kind = TimelineTrackKind::Property, .depth = 1 }; + app_controls::TimelineTrack track{ .stableID = idManager.CreateStaticID(), .name = name, .kind = app_controls::TimelineTrackKind::Property, .depth = 1 }; for (const float t : times) track.keys.push_back({ idManager.CreateStaticID(), t }); return track; @@ -43,53 +44,53 @@ namespace tachyon view.tracks.push_back(property("Intensity", { 0.5f, 3.5f, 7.0f })); // A sound with a made-up waveform: louder and quieter stretches, and some noise. - TimelineClip clip{ .start = 0.4f, .length = 7.0f }; + app_controls::TimelineClip clip{ .start = 0.4f, .length = 7.0f }; for (int i = 0; i < 400; ++i) { const float swell = 0.35f + 0.65f * std::fabs(std::sin(float(i) * 0.018f)); const float noise = std::fmod(std::fabs(std::sin(float(i) * 12.9898f) * 43758.5453f), 1.0f); clip.peaks.push_back(std::min(0.95f, (0.25f + 0.75f * noise) * swell)); } - view.tracks.push_back(TimelineTrack{ .stableID = idManager.CreateStaticID(), .name = "music.wav", - .kind = TimelineTrackKind::Audio, .clip = std::move(clip) }); + view.tracks.push_back(app_controls::TimelineTrack{ .stableID = idManager.CreateStaticID(), .name = "music.wav", + .kind = app_controls::TimelineTrackKind::Audio, .clip = std::move(clip) }); - TimelineTrack events{ .stableID = idManager.CreateStaticID(), .name = "Events", .kind = TimelineTrackKind::Events }; + app_controls::TimelineTrack events{ .stableID = idManager.CreateStaticID(), .name = "Events", .kind = app_controls::TimelineTrackKind::Events }; events.events.push_back({ idManager.CreateStaticID(), 1.5f, "Spawn" }); events.events.push_back({ idManager.CreateStaticID(), 5.2f, "Explode" }); view.tracks.push_back(std::move(events)); // Each change goes on the app's undo history, which gives back the IDs of what it took // away once it can no longer be undone. - view.onEdit = [this](const TimelineEdit& edit) + view.onEdit = [this](const app_controls::TimelineEdit& edit) { - const auto shared = std::make_shared(edit); + const auto shared = std::make_shared(edit); commandManager.History().Push({ .description = "Edit animation", - .undo = [this, shared] { ApplyTimelineEdit(animation, *shared, /*undo*/ true); }, - .redo = [this, shared] { ApplyTimelineEdit(animation, *shared, /*undo*/ false); }, - .drop = [this, shared](bool undone) { ReleaseTimelineEditIDs(idManager, *shared, undone); } }); + .undo = [this, shared] { app_controls::ApplyTimelineEdit(animation, *shared, /*undo*/ true); }, + .redo = [this, shared] { app_controls::ApplyTimelineEdit(animation, *shared, /*undo*/ false); }, + .drop = [this, shared](bool undone) { app_controls::ReleaseTimelineEditIDs(idManager, *shared, undone); } }); commandManager.History().EndMerge(); }; SeedAnimationCurves(); } - void Application::SetUpTimelineView(TimelineViewState& view) + void Application::SetUpTimelineView(app_controls::TimelineViewState& view) { if (!animationSeeded) SeedAnimation(); view.selectedTrack = animation.tracks[1].stableID; // "+": a property in the selected track's group (or at the end). - TimelineViewState* shown = &view; + app_controls::TimelineViewState* shown = &view; view.onAddTrack = [this, shown] { int at = (int)animation.tracks.size(), depth = 0; for (int t = 0; t < (int)animation.tracks.size(); ++t) if (animation.tracks[size_t(t)].stableID == shown->selectedTrack) { - const TimelineTrack& selected = animation.tracks[size_t(t)]; - const int group = selected.kind == TimelineTrackKind::Group ? t : -1; + const app_controls::TimelineTrack& selected = animation.tracks[size_t(t)]; + const int group = selected.kind == app_controls::TimelineTrackKind::Group ? t : -1; if (group >= 0) { - at = group + 1 + (int)TracksInGroup(animation, group).size(); + at = group + 1 + (int)app_controls::TracksInGroup(animation, group).size(); depth = selected.depth + 1; } else @@ -98,74 +99,74 @@ namespace tachyon depth = selected.depth; } } - TimelineTrack track{ .stableID = idManager.CreateStaticID(), .name = "New property", - .kind = TimelineTrackKind::Property, .depth = depth }; + app_controls::TimelineTrack track{ .stableID = idManager.CreateStaticID(), .name = "New property", + .kind = app_controls::TimelineTrackKind::Property, .depth = depth }; shown->selectedTrack = track.stableID; - CommitTimelineEdit(animation, AddTrackEdit(animation, std::move(track), at)); + app_controls::CommitTimelineEdit(animation, app_controls::AddTrackEdit(animation, std::move(track), at)); }; view.onTrackContextMenu = [this, shown](int track) { MenuItem("Key at the playhead", [this, track] { - CommitTimelineEdit(animation, AddKeyEdit(animation, track, animation.playback.time, idManager.CreateStaticID())); + app_controls::CommitTimelineEdit(animation, app_controls::AddKeyEdit(animation, track, animation.playback.time, idManager.CreateStaticID())); }); - MenuItem("Delete the selected keys", [this, shown] { CommitTimelineEdit(animation, DeleteSelectedKeysEdit({ animation, *shown })); }); + MenuItem("Delete the selected keys", [this, shown] { app_controls::CommitTimelineEdit(animation, app_controls::DeleteSelectedKeysEdit({ animation, *shown })); }); MenuSeparator(); - MenuItem("Delete track", [this, track] { CommitTimelineEdit(animation, RemoveTrackEdit(animation, track)); }); + MenuItem("Delete track", [this, track] { app_controls::CommitTimelineEdit(animation, app_controls::RemoveTrackEdit(animation, track)); }); }; } void Application::SeedAnimationCurves() { - CurveData& view = animationCurves; + curves::CurveData& view = animationCurves; view.fps = animation.fps; view.range = { 0.0f, animation.duration, -2.0f, 4.0f }; - auto channel = [this](const char* path, const char* name, CurveChannelColor color, std::initializer_list points) { - CurveChannel c{ .name = name, .path = path, .color = color, - .curve = MakeCurve(std::span(points.begin(), points.size())) }; - for (CurveKey& k : c.curve.keys) + auto channel = [this](const char* path, const char* name, curves::CurveChannelColor color, std::initializer_list points) { + curves::CurveChannel c{ .name = name, .path = path, .color = color, + .curve = curves::MakeCurve(std::span(points.begin(), points.size())) }; + for (curves::CurveKey& k : c.curve.keys) k.stableID = idManager.CreateStaticID(); return c; }; // The keys on the Timeline's Position, Rotation and Scale tracks, with values. view.channels = { - channel("Sphere/Position", "X", CurveChannelColor::Red, { { 0.0f, 0.0f }, { 1.0f, 1.5f }, { 2.5f, -1.0f }, { 4.0f, 0.5f }, { 6.0f, 0.0f } }), - channel("Sphere/Position", "Y", CurveChannelColor::Green, { { 0.0f, 0.0f }, { 1.0f, 2.0f }, { 2.5f, 0.0f }, { 4.0f, 1.2f }, { 6.0f, 0.0f } }), - channel("Sphere/Position", "Z", CurveChannelColor::Blue, { { 0.0f, -1.0f }, { 2.5f, 0.5f }, { 6.0f, -1.0f } }), - channel("Sphere/Rotation", "Y", CurveChannelColor::Green, { { 0.0f, 0.0f }, { 3.0f, 1.8f }, { 6.0f, 3.6f } }), - channel("Sphere/Scale", "Uniform", CurveChannelColor::Value, { { 2.0f, 1.0f }, { 5.0f, 1.6f } }) }; + channel("Sphere/Position", "X", curves::CurveChannelColor::Red, { { 0.0f, 0.0f }, { 1.0f, 1.5f }, { 2.5f, -1.0f }, { 4.0f, 0.5f }, { 6.0f, 0.0f } }), + channel("Sphere/Position", "Y", curves::CurveChannelColor::Green, { { 0.0f, 0.0f }, { 1.0f, 2.0f }, { 2.5f, 0.0f }, { 4.0f, 1.2f }, { 6.0f, 0.0f } }), + channel("Sphere/Position", "Z", curves::CurveChannelColor::Blue, { { 0.0f, -1.0f }, { 2.5f, 0.5f }, { 6.0f, -1.0f } }), + channel("Sphere/Rotation", "Y", curves::CurveChannelColor::Green, { { 0.0f, 0.0f }, { 3.0f, 1.8f }, { 6.0f, 3.6f } }), + channel("Sphere/Scale", "Uniform", curves::CurveChannelColor::Value, { { 2.0f, 1.0f }, { 5.0f, 1.6f } }) }; // The rotation turns at an even rate; the scale pops. - for (CurveKey& k : view.channels[3].curve.keys) - k.interpolation = CurveInterpolation::Linear; - view.channels[4].curve.keys[0].interpolation = CurveInterpolation::Constant; - for (CurveChannel& c : view.channels) - UpdateCurveTangents(c.curve); + for (curves::CurveKey& k : view.channels[3].curve.keys) + k.interpolation = curves::CurveInterpolation::Linear; + view.channels[4].curve.keys[0].interpolation = curves::CurveInterpolation::Constant; + for (curves::CurveChannel& c : view.channels) + curves::UpdateCurveTangents(c.curve); - view.onEdit = [this](const CurveEdit& edit) + view.onEdit = [this](const curves::CurveEdit& edit) { - const auto shared = std::make_shared(edit); + const auto shared = std::make_shared(edit); commandManager.History().Push({ .description = "Edit curves", - .undo = [this, shared] { ApplyCurveEdit(animationCurves, *shared, /*undo*/ true); }, - .redo = [this, shared] { ApplyCurveEdit(animationCurves, *shared, /*undo*/ false); }, - .drop = [this, shared](bool undone) { ReleaseCurveEditIDs(idManager, *shared, undone); } }); + .undo = [this, shared] { curves::ApplyCurveEdit(animationCurves, *shared, /*undo*/ true); }, + .redo = [this, shared] { curves::ApplyCurveEdit(animationCurves, *shared, /*undo*/ false); }, + .drop = [this, shared](bool undone) { curves::ReleaseCurveEditIDs(idManager, *shared, undone); } }); commandManager.History().EndMerge(); }; // Scrubbing the ruler moves the timeline's playhead, as scrubbing the timeline's does. view.onPlayheadChanged = [this](float time) { animation.playback.time = time; }; } - void Application::RenderTimelinePanel(TimelineViewState& view) + void Application::RenderTimelinePanel(app_controls::TimelineViewState& view) { // The editor, the whole panel: tracks of keys, a sound and events, played round the // loop range (in OnGUI). - TimelineEditor(idManager.AllocateDynamicID("editor"), { animation, view }, LayoutOverride{}.FlexGrow(1)); + app_controls::TimelineEditor(*this, controlsContext, idManager.AllocateDynamicID("editor"), { animation, view }, LayoutOverride{}.FlexGrow(1)); } - void Application::RenderCurvesPanel(CurveViewState& view) + void Application::RenderCurvesPanel(curves::CurveViewState& view) { // The curve editor, the whole panel, its playhead the timeline's. if (!animationSeeded) SeedAnimation(); animationCurves.playhead = animation.playback.time; - CurveEditor(idManager.AllocateDynamicID("curves"), { animationCurves, view }, LayoutOverride{}.FlexGrow(1)); + curves::CurveEditor(*this, curvesContext, idManager.AllocateDynamicID("curves"), { animationCurves, view }, LayoutOverride{}.FlexGrow(1)); } } diff --git a/examples/showcase/panel_tree_table.cpp b/examples/showcase/panel_tree_table.cpp index eb8c5631..6dcb2bed 100644 --- a/examples/showcase/panel_tree_table.cpp +++ b/examples/showcase/panel_tree_table.cpp @@ -1,5 +1,7 @@ #include "application.h" -#include +#include +#include +#include #include #include @@ -17,7 +19,7 @@ // `visibleIdx` maps visible row -> flat row and its size is the row count. // // `skipCount` / `ancestorLineMask` / `isLastSibling` are derived from `depth` -// by TreeUtils::RebuildTreeIndex after adding or removing rows; toggling +// by views::TreeUtils::RebuildTreeIndex after adding or removing rows; toggling // `isOpen` needs no rebuild. // @@ -39,11 +41,11 @@ namespace tachyon { IDManager* ids = nullptr; // the rows' static IDs come from it, and go back to it std::vector rows; - TableState state; + views::TableState state; MultiSelectState multiSelect; ItemDragDropConfig dragDrop; // payload: the flat row index std::vector visibleIdx; // visible row -> flat row, rebuilt each frame - std::vector columns; + std::vector columns; // A moved row's new flat index, selected after the next VirtualTable call (which // allocates the row IDs). int pendingSelectFlatIdx = -1; @@ -56,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(); @@ -104,7 +106,7 @@ namespace tachyon add("README.md", 1, false, false, "8 KB", "Text", showcase.heartIcon); add("CHANGELOG.md", 1, false, false, "3 KB", "Text", showcase.heartIcon); - TreeUtils::RebuildTreeIndex(self->rows); + views::TreeUtils::RebuildTreeIndex(self->rows); self->state.multiSelect = &self->multiSelect; @@ -127,9 +129,9 @@ namespace tachyon if (targetVis < 0 || targetVis >= int(v.size())) return; const int srcDs = static_cast(srcPayload); const int dstDs = v[targetVis]; - const int newFlatIdx = TreeUtils::ReorderTreeRow(self->rows, srcDs, dstDs, pos); + const int newFlatIdx = views::TreeUtils::ReorderTreeRow(self->rows, srcDs, dstDs, pos); if (newFlatIdx < 0) return; - TreeUtils::RebuildTreeIndex(self->rows); + views::TreeUtils::RebuildTreeIndex(self->rows); // Deferred: the matching sub-range rowID needs the // row IDs VirtualTable allocates next frame. self->pendingSelectFlatIdx = newFlatIdx; @@ -153,7 +155,7 @@ namespace tachyon TreeRow& r = self->rows[size_t(v[size_t(rowIdx)])]; // Arrow follows actual descendants, not `hasChildren`. const bool branch = (r.skipCount > 0); - TreeCell(r.name, r.depth, + views::TreeCell(*this, viewsContext, r.name, r.depth, branch ? &r.isOpen : nullptr, r.icon, r.ancestorLineMask, @@ -166,7 +168,7 @@ namespace tachyon [this, self](int rowIdx) { auto& v = self->visibleIdx; if (rowIdx < 0 || rowIdx >= int(v.size())) return; - Cell(self->rows[size_t(v[size_t(rowIdx)])].size); + views::Cell(*this, viewsContext, self->rows[size_t(v[size_t(rowIdx)])].size); } }, { @@ -174,11 +176,11 @@ namespace tachyon [this, self](int rowIdx) { auto& v = self->visibleIdx; if (rowIdx < 0 || rowIdx >= int(v.size())) return; - Cell(self->rows[size_t(v[size_t(rowIdx)])].type); + views::Cell(*this, viewsContext, self->rows[size_t(v[size_t(rowIdx)])].type); } } }; - 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) @@ -200,10 +202,10 @@ namespace tachyon // Left/Right arrow navigation. SelectionModeSwitch(panel.state.selectionMode); - std::span columnSpan(panel.columns.data(), panel.columns.size()); - VirtualTable(idManager.AllocateDynamicID("treeTable"), + std::span columnSpan(panel.columns.data(), panel.columns.size()); + views::VirtualTable(*this, viewsContext, idManager.AllocateDynamicID("treeTable"), panel.state, columnSpan, - int(visibleIdx.size()), 0, theme.tableStyleRef, + int(visibleIdx.size()), 0, views::GetStyles(*this, viewsContext).tableStyleRef, LayoutOverride{}.Width(520).Height(400).BreakBefore()); // Apply a pending post-drop selection now that VirtualTable has set diff --git a/examples/showcase/panel_view.cpp b/examples/showcase/panel_view.cpp index 0db5c036..988dcf2d 100644 --- a/examples/showcase/panel_view.cpp +++ b/examples/showcase/panel_view.cpp @@ -1,7 +1,6 @@ #include "application.h" #include -#include #include #include @@ -17,6 +16,7 @@ #endif #if TACHYON_METAL #include +#include #endif // @@ -32,8 +32,8 @@ namespace tachyon struct ViewportPanel { Application* app = nullptr; // its IDs come from it, and go back to it - ViewportView view; - ViewportTransform shownSelection; // the picked shape's transform as this view last had it + app_controls::ViewportView view; + app_controls::ViewportTransform shownSelection; // the picked shape's transform as this view last had it ViewMode viewMode = ViewMode::Default; bool showGrid = true; @@ -76,7 +76,7 @@ namespace tachyon if (!sceneObjects.empty()) return; auto place = [](float3 at, float scale = 1.0f) { - return ViewportTransform{ .position = at, .scale = { scale, scale, scale } }; + return app_controls::ViewportTransform{ .position = at, .scale = { scale, scale, scale } }; }; sceneObjects = { { "Cube", SceneMesh::Cube, place({ -1.8f, 0.5f, 0.0f }), { 0.42f, 0.61f, 1.00f, 1 } }, @@ -98,7 +98,7 @@ namespace tachyon // another view, by undo, or another shape picked). void SyncSelection(ViewportPanel& panel, std::vector& objects, int selected) { - ViewportView& view = panel.view; + app_controls::ViewportView& view = panel.view; view.hasSelection = selected >= 0 && selected < int(objects.size()); if (!view.hasSelection) return; @@ -112,19 +112,19 @@ 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(); panel->app = this; - ViewportView& view = panel->view; + app_controls::ViewportView& view = panel->view; view.camera.target = { 0.0f, 0.6f, 0.0f }; view.camera.distance = 7.0f; view.showTools = false; // the toolbar dock's Tools set view.tool ViewportPanel* const self = panel.get(); // The app draws its scene: the viewport hands it a command buffer, ready to draw into. - view.onRender = [this, self](const ViewportRenderContext& ctx) { + view.onRender = [this, self](const app_controls::ViewportRenderContext& ctx) { // The picked shape where this view's gizmo has it now, this frame's drag included. SyncSelection(*self, sceneObjects, sceneSelected); #if TACHYON_VULKAN @@ -149,10 +149,10 @@ namespace tachyon // A click picks the shape under it; on nothing it lets go of the selection. view.onClick = [this](const Ray& ray, KeyModifier) { SelectSceneObject(PickSceneObject(sceneObjects, ray)); }; // A gizmo's drag moves the shape, on the undo history. - view.onEdit = [this, self](const ViewportEdit& edit) { + view.onEdit = [this, self](const app_controls::ViewportEdit& edit) { SyncSelection(*self, sceneObjects, sceneSelected); const int index = sceneSelected; - auto apply = [this, index](const ViewportTransform& t) { + auto apply = [this, index](const app_controls::ViewportTransform& t) { if (index >= 0 && index < (int)sceneObjects.size()) sceneObjects[size_t(index)].transform = t; }; @@ -166,13 +166,13 @@ 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)); for (const SceneObject& object : sceneObjects) { - const ViewportTransform& t = object.transform; + const app_controls::ViewportTransform& t = object.transform; for (const float f : { t.position.x, t.position.y, t.position.z, t.rotation.x, t.rotation.y, t.rotation.z, t.rotation.w, t.scale.x, t.scale.y, t.scale.z }) signature = Hash::Combine(signature, uint64_t(std::bit_cast(f))); @@ -291,14 +291,14 @@ namespace tachyon .renderBody = [this, self]() { // The view's tool; Q, W, E and R over the view set it too. - ViewportTool& tool = self->view.tool; - Toggle(tool == ViewportTool::Select, showcase.toolSelectIcon, [&tool](bool value) { if (value) tool = ViewportTool::Select; }); + app_controls::ViewportTool& tool = self->view.tool; + Toggle(tool == app_controls::ViewportTool::Select, showcase.toolSelectIcon, [&tool](bool value) { if (value) tool = app_controls::ViewportTool::Select; }); SetTooltip("Select mode (Q)"); - Toggle(tool == ViewportTool::Move, showcase.toolMoveIcon, [&tool](bool value) { if (value) tool = ViewportTool::Move; }); + Toggle(tool == app_controls::ViewportTool::Move, showcase.toolMoveIcon, [&tool](bool value) { if (value) tool = app_controls::ViewportTool::Move; }); SetTooltip("Move mode (W)"); - Toggle(tool == ViewportTool::Rotate, showcase.toolRotateIcon, [&tool](bool value) { if (value) tool = ViewportTool::Rotate; }); + Toggle(tool == app_controls::ViewportTool::Rotate, showcase.toolRotateIcon, [&tool](bool value) { if (value) tool = app_controls::ViewportTool::Rotate; }); SetTooltip("Rotate mode (E)"); - Toggle(tool == ViewportTool::Scale, showcase.toolScaleIcon, [&tool](bool value) { if (value) tool = ViewportTool::Scale; }); + Toggle(tool == app_controls::ViewportTool::Scale, showcase.toolScaleIcon, [&tool](bool value) { if (value) tool = app_controls::ViewportTool::Scale; }); SetTooltip("Scale mode (R)"); } }); @@ -368,7 +368,7 @@ namespace tachyon { SyncSelection(panel, sceneObjects, sceneSelected); const ID viewportID = idManager.AllocateDynamicID("scene"); - Viewport(viewportID, panel.view, LayoutOverride{}.FlexGrow(1)); + app_controls::Viewport(*this, controlsContext, viewportID, panel.view, LayoutOverride{}.FlexGrow(1)); // Its width, for the busy bar along its top next frame. if (const ElementRef ref = elementStorage.FindElementRefByID(viewportID); ref.IsValid()) VERIFY(elementStorage.AddPostLayout(ref, [&panel](PostLayoutContext& ctx) { panel.width = ctx.ElementRect().w; })); 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/scene.h b/examples/showcase/scene.h index 87851d08..51325c7e 100644 --- a/examples/showcase/scene.h +++ b/examples/showcase/scene.h @@ -3,7 +3,7 @@ // The showcase's 3D scene: a few shapes on a ground grid, in the Viewport panel. What they are // and which one a click picks; scene_renderer.h draws them. -#include +#include #include #include @@ -18,7 +18,7 @@ namespace tachyon { std::string name; SceneMesh mesh = SceneMesh::Cube; - ViewportTransform transform; + app_controls::ViewportTransform transform; color4f color { 0.8f, 0.8f, 0.8f, 1.0f }; }; diff --git a/examples/showcase/scene_renderer.cpp b/examples/showcase/scene_renderer.cpp index d5810668..bdd2fcc3 100644 --- a/examples/showcase/scene_renderer.cpp +++ b/examples/showcase/scene_renderer.cpp @@ -161,7 +161,7 @@ namespace tachyon } template - void SceneRenderer::Walk(const ViewportRenderContext& ctx, std::span objects, int selected, + void SceneRenderer::Walk(const app_controls::ViewportRenderContext& ctx, std::span objects, int selected, Use&& use, Draw&& draw) const { const float4x4 viewProjection = ctx.projection * ctx.view; @@ -252,7 +252,7 @@ namespace tachyon } void SceneRenderer::Render(vulkan::VulkanGraphicsContext& vk, const vulkan::VulkanSceneRender& target, - const ViewportRenderContext& ctx, std::span objects, int selected) + const app_controls::ViewportRenderContext& ctx, std::span objects, int selected) { if (m_failed) return; @@ -379,7 +379,7 @@ namespace tachyon return SUCCEEDED(device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&m_d3dLines))); } - void SceneRenderer::Render(const d3d12::D3D12SceneRender& target, const ViewportRenderContext& ctx, + void SceneRenderer::Render(const d3d12::D3D12SceneRender& target, const app_controls::ViewportRenderContext& ctx, std::span objects, int selected) { if (m_failed) @@ -521,7 +521,7 @@ namespace tachyon return m_sdlShapes != nullptr && m_sdlLines != nullptr; } - void SceneRenderer::Render(const sdlgpu::SDLGPUSceneRender& target, const ViewportRenderContext& ctx, + void SceneRenderer::Render(const sdlgpu::SDLGPUSceneRender& target, const app_controls::ViewportRenderContext& ctx, std::span objects, int selected) { if (m_failed) @@ -649,7 +649,7 @@ namespace tachyon return true; } - void SceneRenderer::Render(const metal::MetalSceneRender& target, const ViewportRenderContext& ctx, + void SceneRenderer::Render(const metal::MetalSceneRender& target, const app_controls::ViewportRenderContext& ctx, std::span objects, int selected) { if (m_failed) diff --git a/examples/showcase/scene_renderer.h b/examples/showcase/scene_renderer.h index 3d7c1448..e626b1fa 100644 --- a/examples/showcase/scene_renderer.h +++ b/examples/showcase/scene_renderer.h @@ -40,24 +40,24 @@ namespace tachyon /// Draws the grid and `objects` into the viewport's image; `selected` lighter. Makes /// its pipelines and meshes the first time, on `vk`'s device; they go when it's cleaned up. void Render(vulkan::VulkanGraphicsContext& vk, const vulkan::VulkanSceneRender& target, - const ViewportRenderContext& ctx, std::span objects, int selected); + const app_controls::ViewportRenderContext& ctx, std::span objects, int selected); #endif #if TACHYON_D3D12 /// As above on Direct3D 12, on the device of the scene's command list. Its objects /// stay until ReleaseD3D12. - void Render(const d3d12::D3D12SceneRender& target, const ViewportRenderContext& ctx, + void Render(const d3d12::D3D12SceneRender& target, const app_controls::ViewportRenderContext& ctx, std::span objects, int selected); #endif #if TACHYON_SDLGPU /// As above on SDL GPU, on the scene's device: its upload in a copy pass of the scene's /// command buffer the first time, then a render pass. Its objects stay until ReleaseSDLGPU. - void Render(const sdlgpu::SDLGPUSceneRender& target, const ViewportRenderContext& ctx, + void Render(const sdlgpu::SDLGPUSceneRender& target, const app_controls::ViewportRenderContext& ctx, std::span objects, int selected); #endif #if TACHYON_METAL /// As above on Metal, with the scene's encoder, on its command buffer's device. Its /// objects stay until ReleaseMetal. - void Render(const metal::MetalSceneRender& target, const ViewportRenderContext& ctx, + void Render(const metal::MetalSceneRender& target, const app_controls::ViewportRenderContext& ctx, std::span objects, int selected); #endif /// Lets go of the Direct3D 12 objects. Call once the GPU is done with them, before the @@ -84,7 +84,7 @@ namespace tachyon /// The scene's draws in order, for either API: `use(lines)` picks the lines' pipeline or /// the shapes', `draw(range, mvp, color, light)` draws a range of vertices. template - void Walk(const ViewportRenderContext& ctx, std::span objects, int selected, Use&& use, Draw&& draw) const; + void Walk(const app_controls::ViewportRenderContext& ctx, std::span objects, int selected, Use&& use, Draw&& draw) const; bool m_created = false; bool m_failed = false; diff --git a/examples/showcase/settings_theme.cpp b/examples/showcase/settings_theme.cpp index 01dc92a8..609a55c7 100644 --- a/examples/showcase/settings_theme.cpp +++ b/examples/showcase/settings_theme.cpp @@ -1,5 +1,6 @@ #include "application.h" #include +#include // The Appearance page's theme: Dark or Light, and below it the theme's colors and sizes by // category, as their @property rules describe them. A change is the theme's own: Dark keeps @@ -99,14 +100,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(); @@ -197,7 +198,7 @@ namespace tachyon else if (info.type == CustomPropertyType::Color && value->hasColor) { color4b color = value->color; - if (ColorField(idManager.AllocateDynamicID("settingsThemeColor"), color, LayoutOverride(fill))) + if (color::ColorField(*this, colorContext, idManager.AllocateDynamicID("settingsThemeColor"), color, LayoutOverride(fill))) set(Hex(color)); } else if (info.type == CustomPropertyType::Number && value->hasNumber) @@ -233,7 +234,7 @@ namespace tachyon BoxShadow shadow = value->shadows[0]; if (shadow.IsNone()) shadow.color = color4b{ 0, 0, 0, 0 }; - if (ShadowField(idManager.AllocateDynamicID("settingsThemeShadow"), shadow, LayoutOverride(fill))) + if (color::ShadowField(*this, colorContext, idManager.AllocateDynamicID("settingsThemeShadow"), shadow, LayoutOverride(fill))) set(ShadowText(shadow)); } else 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..6396715d 100644 --- a/examples/tutorial/my_app.h +++ b/examples/tutorial/my_app.h @@ -4,7 +4,7 @@ #pragma once #include -#include +#include #include @@ -38,6 +38,7 @@ namespace my_app public: tachyon::Result Initialize(const InitializeOptions& options = {}) override; void OnGUI() override; + void Cleanup() override; CounterPanel counter; GreetingPanel greeting; @@ -45,7 +46,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 d88e8ea4..f7073b93 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -474,13 +474,8 @@ 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 - gui_controls/gui_table_types.h - gui_controls/gui_tree_grid_types.h - gui_controls/gui_docking_types.h gui_controls/gui_menu_manager.h gui_controls/gui_menu_manager.cpp @@ -492,12 +487,8 @@ list(APPEND GUI_CONTROLS_FILES gui_controls/subsystems/gui_button_group_subsystem.h gui_controls/subsystems/gui_button_group_subsystem.cpp - gui_controls/subsystems/gui_color_picker_subsystem.h - gui_controls/subsystems/gui_color_picker_subsystem.cpp gui_controls/subsystems/gui_swatch_styles.h - gui_controls/subsystems/gui_gradient_editor_subsystem.h - gui_controls/subsystems/gui_gradient_editor_subsystem.cpp gui_controls/subsystems/gui_reorderable_subsystem.h gui_controls/subsystems/gui_reorderable_subsystem.cpp @@ -505,11 +496,7 @@ 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_table_helpers.h - gui_controls/gui_table_helpers.cpp gui_controls/gui_theme.h gui_controls/gui_theme.cpp @@ -530,53 +517,18 @@ list(APPEND GUI_CONTROLS_FILES gui_controls/gui_transition_manager.h gui_controls/gui_transition_manager.cpp - gui_controls/gui_node_view_helpers.h - gui_controls/gui_node_view_helpers.cpp - gui_controls/gui_tree_utils.h gui_controls/controls.cpp gui_controls/controls_box_fields.cpp - gui_controls/controls_curve.cpp - gui_controls/gui_curve_helpers.cpp - gui_controls/gui_curve_types.h - gui_controls/controls_plot.cpp - gui_controls/gui_plot_helpers.cpp - gui_controls/gui_plot_types.h - gui_controls/gui_plot_grid_internal.h - gui_controls/gui_viewport_types.h - gui_controls/gui_viewport_helpers.cpp - gui_controls/controls_viewport.cpp - gui_controls/controls_color_internal.h - gui_controls/controls_color.cpp - gui_controls/controls_gradient.cpp gui_controls/controls_menus.cpp - gui_controls/controls_node_view.cpp gui_controls/controls_tooltips_menus.cpp gui_controls/controls_reorderable.cpp gui_controls/controls_scrollbar.cpp - gui_controls/controls_tree_list.cpp - gui_controls/controls_grid_view.cpp - gui_controls/controls_table.cpp - gui_controls/controls_table_cells.cpp - gui_controls/controls_table_handlers.cpp - gui_controls/controls_table_virtual.cpp - gui_controls/controls_table_internal.h gui_controls/controls_tabs.cpp - gui_controls/controls_documents.cpp - gui_controls/controls_timeline.cpp - gui_controls/controls_timeline_editor.cpp - gui_controls/gui_timeline_helpers.cpp - gui_controls/gui_timeline_types.h - gui_controls/gui_timeline_internal.h - gui_controls/controls_docking.cpp - gui_controls/controls_settings.cpp gui_controls/gui_ui_state.cpp - gui_controls/gui_view_state.cpp - gui_controls/gui_view_state.h - 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 ) @@ -591,7 +543,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 @@ -603,6 +555,90 @@ add_library(TachyonUI::gui_dialogs ALIAS gui_dialogs) source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR}/.. FILES ${GUI_DIALOGS_FILES}) target_link_libraries(gui_dialogs PUBLIC gui_controls) +# Curves: the curve field and its editor, and plots. An extension on gui_controls. +set(GUI_CURVES_FILES + gui_curves/gui_curves.h + gui_curves/gui_curves.cpp + gui_curves/gui_curve_types.h + gui_curves/gui_curve_helpers.cpp + gui_curves/controls_curve.cpp + gui_curves/gui_plot_types.h + gui_curves/gui_plot_grid_internal.h + gui_curves/gui_plot_helpers.cpp + gui_curves/controls_plot.cpp) +add_library(gui_curves STATIC ${GUI_CURVES_FILES}) +add_library(TachyonUI::gui_curves ALIAS gui_curves) +source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR}/.. FILES ${GUI_CURVES_FILES}) +target_link_libraries(gui_curves PUBLIC gui_controls) + +# Color: the color field and picker, the gradient field and editor, the shadow field. An +# extension on gui_controls. +set(GUI_COLOR_FILES + gui_color/gui_color.h + gui_color/gui_color.cpp + gui_color/gui_color_state.h + gui_color/controls_color_internal.h + gui_color/controls_color.cpp + gui_color/controls_gradient.cpp) +add_library(gui_color STATIC ${GUI_COLOR_FILES}) +add_library(TachyonUI::gui_color ALIAS gui_color) +source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR}/.. FILES ${GUI_COLOR_FILES}) +target_link_libraries(gui_color PUBLIC gui_controls) + +# Views: list, tree and grid views, tables, the settings panel. An extension on gui_controls. +set(GUI_VIEWS_FILES + gui_views/gui_views.h + gui_views/gui_views.cpp + gui_views/gui_table_types.h + gui_views/gui_tree_grid_types.h + gui_views/gui_tree_utils.h + gui_views/gui_table_helpers.h + gui_views/gui_table_helpers.cpp + gui_views/controls_table_internal.h + gui_views/controls_table.cpp + gui_views/controls_table_cells.cpp + gui_views/controls_table_handlers.cpp + gui_views/controls_table_virtual.cpp + gui_views/controls_tree_list.cpp + gui_views/controls_grid_view.cpp + gui_views/controls_settings.cpp) +add_library(gui_views STATIC ${GUI_VIEWS_FILES}) +add_library(TachyonUI::gui_views ALIAS gui_views) +source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR}/.. FILES ${GUI_VIEWS_FILES}) +target_link_libraries(gui_views PUBLIC gui_controls) + +# Nodes: the node view and state machines. An extension on gui_controls. +set(GUI_NODES_FILES + gui_nodes/gui_nodes.h + gui_nodes/gui_nodes.cpp + gui_nodes/gui_node_view_types.h + gui_nodes/gui_node_view_helpers.h + gui_nodes/gui_node_view_helpers.cpp + gui_nodes/controls_node_view.cpp) +add_library(gui_nodes STATIC ${GUI_NODES_FILES}) +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 @@ -619,9 +655,14 @@ target_link_libraries(gui_controls PUBLIC gui_core) tachyon_apply_compile_options(gui_core) tachyon_apply_compile_options(gui_controls) tachyon_apply_compile_options(gui_dialogs) +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 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_color.cpp b/src/gui_color/controls_color.cpp similarity index 64% rename from src/gui_controls/controls_color.cpp rename to src/gui_color/controls_color.cpp index 02fc05a5..240c4063 100644 --- a/src/gui_controls/controls_color.cpp +++ b/src/gui_color/controls_color.cpp @@ -1,5 +1,5 @@ -#include -#include // SetColorStyle (shared with controls_gradient.cpp) +#include +#include // SetColorStyle (shared with controls_gradient.cpp) #include #include @@ -110,7 +110,7 @@ namespace } -namespace tachyon +namespace tachyon::color { // --------------------------------------------------------------------------- @@ -269,9 +269,10 @@ namespace tachyon return SampledGradient([space](float t) { return SpaceHueColor(space, t); }, Gradient::kMaxStops); } - void GUIApplication::EmitColorPicker(color4f& outColor, bool allowHDR) + void EmitColorPicker(GUIApplication& app, Context& context, color4f& outColor, bool allowHDR) { - auto& cp = m_colorPickerSub->State(); + const Styles& styles = GetStyles(app, context); + auto& cp = context.picker; // ---- Resolve slider edits from last frame's input first ---- // Channel handlers edit cp.comp[]; convert back to HSV before rebuilding the styles. @@ -376,45 +377,45 @@ namespace tachyon } } }; - SetQuadColorStyle(styleManager, cp.svQuadColor, corner(0, 0), corner(1, 0), corner(1, 1), corner(0, 1)); + SetQuadColorStyle(app.styleManager, cp.svQuadColor, corner(0, 0), corner(1, 0), corner(1, 1), corner(0, 1)); } const ColorSpace space = cp.activeSpace; - SetVerticalGradient(styleManager, cp.hueStrip, HueStripGradient(space)); - SetVerticalGradient(styleManager, cp.alphaStrip, [&](float t) { return color4f{ curR, curG, curB, 1.0f - t }; }, 2); - SetColorStyle(styleManager, cp.hueColor, SpaceHueColor(space, stripHue)); - SetColorStyle(styleManager, cp.whiteColor, { 1.0f, 1.0f, 1.0f, 1.0f }); - SetColorStyle(styleManager, cp.outlineColor, { 0.0f, 0.0f, 0.0f, 0.5f }); - SetColorStyle(styleManager, cp.newColor, { curR, curG, curB, cp.a }); - SetColorStyle(styleManager, cp.originalStyle, { std::clamp(cp.originalColor.r, 0.f, 1.f), std::clamp(cp.originalColor.g, 0.f, 1.f), + SetVerticalGradient(app.styleManager, cp.hueStrip, HueStripGradient(space)); + SetVerticalGradient(app.styleManager, cp.alphaStrip, [&](float t) { return color4f{ curR, curG, curB, 1.0f - t }; }, 2); + SetColorStyle(app.styleManager, cp.hueColor, SpaceHueColor(space, stripHue)); + SetColorStyle(app.styleManager, cp.whiteColor, { 1.0f, 1.0f, 1.0f, 1.0f }); + SetColorStyle(app.styleManager, cp.outlineColor, { 0.0f, 0.0f, 0.0f, 0.5f }); + SetColorStyle(app.styleManager, cp.newColor, { curR, curG, curB, cp.a }); + SetColorStyle(app.styleManager, cp.originalStyle, { std::clamp(cp.originalColor.r, 0.f, 1.f), std::clamp(cp.originalColor.g, 0.f, 1.f), std::clamp(cp.originalColor.b, 0.f, 1.f), cp.originalColor.a }); - const ColorSwatchLook look = SwatchLook(); - const auto requestClose = [this](ColorPickerState::CloseRequest request) { - return [this, request]() { m_colorPickerSub->State().closeRequest = request; }; + const ColorSwatchLook look = SwatchLook(app, context); + const auto requestClose = [&context, &app](ColorPickerState::CloseRequest request) { + return [&app, request, &context]() { context.picker.closeRequest = request; }; }; // ---- Header: title and close ---- // The header is the dialog's title bar: it drags the window. - BeginTitleBar(idManager.AllocateDynamicID("cp_header"), theme.dialogHeaderStyleRef, LayoutOverride{}.NoShrink()); - Text(idManager.AllocateDynamicID("cp_title"), "Color", theme.dialogTitleStyleRef); - Text(idManager.AllocateDynamicID("cp_context"), DialogContext(cp.context, "Color"), theme.dialogContextStyleRef, LayoutOverride{}.FlexGrow(1)); - Button(idManager.AllocateDynamicID("cp_close"), theme.tabCloseIcon, requestClose(ColorPickerState::CloseRequest::Cancel), - theme.dialogCloseStyleRef); - SetTooltip("Close without changing the color"); - EndTitleBar(); + app.BeginTitleBar(app.idManager.AllocateDynamicID("cp_header"), app.theme.dialogHeaderStyleRef, LayoutOverride{}.NoShrink()); + app.Text(app.idManager.AllocateDynamicID("cp_title"), "Color", app.theme.dialogTitleStyleRef); + app.Text(app.idManager.AllocateDynamicID("cp_context"), DialogContext(cp.context, "Color"), app.theme.dialogContextStyleRef, LayoutOverride{}.FlexGrow(1)); + app.Button(app.idManager.AllocateDynamicID("cp_close"), app.theme.tabCloseIcon, requestClose(ColorPickerState::CloseRequest::Cancel), + app.theme.dialogCloseStyleRef); + app.SetTooltip("Close without changing the color"); + app.EndTitleBar(); - BeginHorizontal(idManager.AllocateDynamicID("cp_body"), theme.colorPickerBodyStyleRef, LayoutOverride{}.NoShrink()); + app.BeginHorizontal(app.idManager.AllocateDynamicID("cp_body"), styles.colorPickerBodyStyleRef, LayoutOverride{}.NoShrink()); // ---- Left: the square and the strips ---- - BeginHorizontal(idManager.AllocateDynamicID("cp_planes"), theme.colorPickerPlanesStyleRef, LayoutOverride{}.NoShrink()); + app.BeginHorizontal(app.idManager.AllocateDynamicID("cp_planes"), styles.colorPickerPlanesStyleRef, LayoutOverride{}.NoShrink()); { // One handler for the three: a press picks the target, the drag follows it and // Escape puts the color back. With the focus, the arrows move the point (1%, with // Shift 10%), Page Up / Down a strip's by 10% and Home / End to its ends. `at` is // where the point is now, as fractions of the width and height. - auto planeHandler = [this](ColorPickerState::DragTarget target, ID id, float2 at) { - return [this, target, id, at](ElementEvent&& event) -> bool { - auto& cp = m_colorPickerSub->State(); + auto planeHandler = [&context, &app](ColorPickerState::DragTarget target, ID id, float2 at) { + return [&context, &app, target, id, at](ElementEvent&& event) -> bool { + auto& cp = context.picker; auto applyAt = [&](float fx, float fy) { fy = std::clamp(fy, 0.0f, 1.0f); switch (target) @@ -428,25 +429,25 @@ namespace tachyon auto apply = [&]() { if (!event.rect || event.rect->rect.w <= 0 || event.rect->rect.h <= 0) return; const IntRect& r = event.rect->rect; - const int2 c = event.LocalCursor(elementStorage); + const int2 c = event.LocalCursor(app.elementStorage); applyAt(float(c.x - r.x) / float(r.w), float(c.y - r.y) / float(r.h)); }; switch (event.type) { case EventType::MouseDown: - if (!cp.press.Press(event, elementStorage, guiStateManager, { cp.h, cp.s, cp.v, cp.a }, + if (!cp.press.Press(event, app.elementStorage, app.guiStateManager, { cp.h, cp.s, cp.v, cp.a }, { .atOnce = true, .focusID = id })) break; apply(); return true; case EventType::KeyDown: { - if (cp.press.Cancel(event, guiStateManager)) + if (cp.press.Cancel(event, app.guiStateManager)) { const ColorPickerState::HSVA& before = cp.press.before; cp.h = before.h; cp.s = before.s; cp.v = before.v; cp.a = before.a; return true; } - if (guiStateManager.Interaction().GetFocusedID() != id || cp.press.IsHeld()) + if (app.guiStateManager.Interaction().GetFocusedID() != id || cp.press.IsHeld()) break; const bool square = target == ColorPickerState::DragTarget::Square; const float step = (event.state.modifiers & KeyModifier::Shift) != KeyModifier::None ? 0.1f : 0.01f; @@ -472,7 +473,7 @@ namespace tachyon return true; case EventType::MouseUp: if (cp.press.Release(event) == PointerDrag::Ended::No) break; - guiStateManager.Interaction().ReleaseCaptureID(); + app.guiStateManager.Interaction().ReleaseCaptureID(); return true; default: break; } @@ -481,14 +482,14 @@ namespace tachyon }; // Saturation/value (per space) square with its cursor ring. - const ID squareID = idManager.AllocateDynamicID("cp_square"); - const ElementRef squareRef = RegisterControl(Element{ .id = squareID, + const ID squareID = app.idManager.AllocateDynamicID("cp_square"); + const ElementRef squareRef = app.RegisterControl(Element{ .id = squareID, .eventHandler = planeHandler(ColorPickerState::DragTarget::Square, squareID, float2{ squareX, 1.0f - squareY }), - .styleRef = theme.colorPickerSquareStyleRef }, + .styleRef = styles.colorPickerSquareStyleRef }, LayoutOverride{}); - VERIFY(elementStorage.AddCustomDraw(squareRef, - [quad = cp.svQuadColor, white = cp.whiteColor, outline = cp.outlineColor, squareX, squareY, - radius = float(styleManager.Px(6)), ring = float(styleManager.Px(6)), width = float(styleManager.Px(2)), edge = float(styleManager.Px(1))] + VERIFY(app.elementStorage.AddCustomDraw(squareRef, + [&app, quad = cp.svQuadColor, white = cp.whiteColor, outline = cp.outlineColor, squareX, squareY, + radius = float(app.styleManager.Px(6)), ring = float(app.styleManager.Px(6)), width = float(app.styleManager.Px(2)), edge = float(app.styleManager.Px(1))] (CustomDrawContext& ctx) { const IntRect r = ctx.ElementRect(); @@ -501,14 +502,14 @@ namespace tachyon auto strip = [&](const char* name, ColorPickerState::DragTarget target, VisualColorStyleIndex fill, bool checker, float position, VisualColorStyleIndex handleFill) { - const ID stripID = idManager.AllocateDynamicID(name); - const ElementRef stripRef = RegisterControl(Element{ .id = stripID, - .eventHandler = planeHandler(target, stripID, float2{ 0.5f, position }), .styleRef = theme.colorPickerStripStyleRef }, + const ID stripID = app.idManager.AllocateDynamicID(name); + const ElementRef stripRef = app.RegisterControl(Element{ .id = stripID, + .eventHandler = planeHandler(target, stripID, float2{ 0.5f, position }), .styleRef = styles.colorPickerStripStyleRef }, LayoutOverride{}); - VERIFY(elementStorage.AddCustomDraw(stripRef, + VERIFY(app.elementStorage.AddCustomDraw(stripRef, [fill, checker, position, handleFill, look, white = cp.whiteColor, outline = cp.outlineColor, - radius = float(styleManager.Px(4)), overhang = styleManager.Px(3), handleH = styleManager.Px(6), - border = styleManager.Px(2), edge = styleManager.Px(1)](CustomDrawContext& ctx) + radius = float(app.styleManager.Px(4)), overhang = app.styleManager.Px(3), handleH = app.styleManager.Px(6), + border = app.styleManager.Px(2), edge = app.styleManager.Px(1)](CustomDrawContext& ctx) { const IntRect r = ctx.ElementRect(); if (checker) @@ -531,19 +532,19 @@ namespace tachyon strip("cp_hue", ColorPickerState::DragTarget::Hue, cp.hueStrip, false, stripHue, cp.hueColor); strip("cp_alpha", ColorPickerState::DragTarget::Alpha, cp.alphaStrip, true, 1.0f - cp.a, cp.newColor); } - EndHorizontal(); + app.EndHorizontal(); // ---- Right: preview, space, channels, hex, HDR ---- - BeginVertical(idManager.AllocateDynamicID("cp_controls"), theme.colorPickerControlsStyleRef, LayoutOverride{}.FlexGrow(1)); + app.BeginVertical(app.idManager.AllocateDynamicID("cp_controls"), styles.colorPickerControlsStyleRef, LayoutOverride{}.FlexGrow(1)); { // New over Original, each at its alpha on the checkerboard, named beside its half. - BeginHorizontal(idManager.AllocateDynamicID("cp_preview_group"), theme.colorPickerPreviewGroupStyleRef, LayoutOverride{}.NoShrink()); + app.BeginHorizontal(app.idManager.AllocateDynamicID("cp_preview_group"), styles.colorPickerPreviewGroupStyleRef, LayoutOverride{}.NoShrink()); { - const ID previewID = idManager.AllocateDynamicID("cp_preview"); - Element preview{ .id = previewID, .styleRef = theme.colorPickerPreviewStyleRef, .flags = ElementFlags::NoInput }; - const ElementRef previewRef = RegisterElement(std::move(preview), LayoutOverride{}.FlexGrow(1)); - VERIFY(elementStorage.AddCustomDraw(previewRef, - [look, newColor = cp.newColor, original = cp.originalStyle, radius = float(styleManager.Px(5))](CustomDrawContext& ctx) + const ID previewID = app.idManager.AllocateDynamicID("cp_preview"); + Element preview{ .id = previewID, .styleRef = styles.colorPickerPreviewStyleRef, .flags = ElementFlags::NoInput }; + const ElementRef previewRef = app.RegisterElement(std::move(preview), LayoutOverride{}.FlexGrow(1)); + VERIFY(app.elementStorage.AddCustomDraw(previewRef, + [&app, look, newColor = cp.newColor, original = cp.originalStyle, radius = float(app.styleManager.Px(5))](CustomDrawContext& ctx) { const IntRect r = ctx.ElementInnerRect(); ColorSwatchLook preview = look; @@ -553,15 +554,15 @@ namespace tachyon ctx.RenderQuad(r, IntRect{ .position = { r.x, r.y }, .size = { r.w, top } }, newColor, radius); ctx.RenderQuad(r, IntRect{ .position = { r.x, r.y + top }, .size = { r.w, r.h - top } }, original, radius); })); - BeginVertical(idManager.AllocateDynamicID("cp_preview_captions"), theme.colorPickerCaptionsStyleRef, LayoutOverride{}); - Text(idManager.AllocateDynamicID("cp_new"), "New", theme.colorPickerCaptionStyleRef, LayoutOverride{}.FlexGrow(1)); - Text(idManager.AllocateDynamicID("cp_original"), "Original", theme.colorPickerCaptionStyleRef, LayoutOverride{}.FlexGrow(1)); - EndVertical(); + app.BeginVertical(app.idManager.AllocateDynamicID("cp_preview_captions"), styles.colorPickerCaptionsStyleRef, LayoutOverride{}); + app.Text(app.idManager.AllocateDynamicID("cp_new"), "New", styles.colorPickerCaptionStyleRef, LayoutOverride{}.FlexGrow(1)); + app.Text(app.idManager.AllocateDynamicID("cp_original"), "Original", styles.colorPickerCaptionStyleRef, LayoutOverride{}.FlexGrow(1)); + app.EndVertical(); } - EndHorizontal(); + app.EndHorizontal(); // Color space, Linear (for RGB) and the value range. - BeginHorizontal(idManager.AllocateDynamicID("cp_mode_row"), theme.colorPickerModeRowStyleRef, LayoutOverride{}.NoShrink()); + app.BeginHorizontal(app.idManager.AllocateDynamicID("cp_mode_row"), styles.colorPickerModeRowStyleRef, LayoutOverride{}.NoShrink()); { const bool rgb = (cp.activeSpace == ColorSpace::sRGB || cp.activeSpace == ColorSpace::LinearRGB); struct SpaceTab { ColorSpace space; std::string_view label; }; @@ -569,22 +570,22 @@ namespace tachyon { ColorSpace::sRGB, "RGB" }, { ColorSpace::HSV, "HSV" }, { ColorSpace::HSL, "HSL" }, { ColorSpace::Lab, "Lab" }, { ColorSpace::Oklab, "Oklab" }, }; - BeginButtonGroup(LayoutOverride{}.NoGrow().NoShrink()); + app.BeginButtonGroup(LayoutOverride{}.NoGrow().NoShrink()); for (const SpaceTab& tab : tabs) { const bool active = (tab.space == ColorSpace::sRGB) ? rgb : (cp.activeSpace == tab.space); - if (active) guiStateManager.Construction().PushSelected(); + if (active) app.guiStateManager.Construction().PushSelected(); const ColorSpace target = tab.space; - Button(tab.label, [this, target, rgb]() { - auto& cp = m_colorPickerSub->State(); + app.Button(tab.label, [&context, &app, target, rgb]() { + auto& cp = context.picker; if (target != ColorSpace::sRGB || !rgb) // RGB keeps its Linear choice cp.activeSpace = target; }); - if (active) guiStateManager.Construction().PopSelected(); + if (active) app.guiStateManager.Construction().PopSelected(); } - EndButtonGroup(); + app.EndButtonGroup(); } - EndHorizontal(); + app.EndHorizontal(); // Channel sliders: label, gradient track with a round thumb, value. auto& gs = cp.gradientStyles; @@ -600,12 +601,12 @@ namespace tachyon cp.comp[0] = cp.h; cp.comp[1] = cp.s; cp.comp[2] = cp.v; labels[0] = "H"; labels[1] = "S"; labels[2] = "V"; scales[0] = cp.byteRange ? 360.0f : 1.0f; scales[1] = scales[2] = percent; - SetHueGradientStyleHorizontal(styleManager, gs[0]); + SetHueGradientStyleHorizontal(app.styleManager, gs[0]); auto [s0r, s0g, s0b] = ColorConvert::HSVtoRGB(cp.h, 0.0f, cp.v); auto [s1r, s1g, s1b] = ColorConvert::HSVtoRGB(cp.h, 1.0f, cp.v); - SetGradientStyle2(styleManager, gs[1], { s0r, s0g, s0b, 1 }, { s1r, s1g, s1b, 1 }); + SetGradientStyle2(app.styleManager, gs[1], { s0r, s0g, s0b, 1 }, { s1r, s1g, s1b, 1 }); auto [v1r, v1g, v1b] = ColorConvert::HSVtoRGB(cp.h, cp.s, 1.0f); - SetGradientStyle2(styleManager, gs[2], { 0, 0, 0, 1 }, { v1r, v1g, v1b, 1 }); + SetGradientStyle2(app.styleManager, gs[2], { 0, 0, 0, 1 }, { v1r, v1g, v1b, 1 }); break; } case ColorSpace::HSL: @@ -616,11 +617,11 @@ namespace tachyon cp.comp[0] = hh; cp.comp[1] = ss; cp.comp[2] = ll; labels[0] = "H"; labels[1] = "S"; labels[2] = "L"; scales[0] = cp.byteRange ? 360.0f : 1.0f; scales[1] = scales[2] = percent; - SetHueGradientStyleHorizontal(styleManager, gs[0]); + SetHueGradientStyleHorizontal(app.styleManager, gs[0]); auto [s0r, s0g, s0b] = ColorConvert::HSLtoRGB(hh, 0.0f, ll); auto [s1r, s1g, s1b] = ColorConvert::HSLtoRGB(hh, 1.0f, ll); - SetGradientStyle2(styleManager, gs[1], { s0r, s0g, s0b, 1 }, { s1r, s1g, s1b, 1 }); - SetSampledGradient(styleManager, gs[2], [hh, ss](float t) -> color4f { + SetGradientStyle2(app.styleManager, gs[1], { s0r, s0g, s0b, 1 }, { s1r, s1g, s1b, 1 }); + SetSampledGradient(app.styleManager, gs[2], [hh, ss](float t) -> color4f { auto [r, g, b] = ColorConvert::HSLtoRGB(hh, ss, t); return { r, g, b, 1.0f }; }); @@ -630,9 +631,9 @@ namespace tachyon cp.comp[0] = curR; cp.comp[1] = curG; cp.comp[2] = curB; labels[0] = "R"; labels[1] = "G"; labels[2] = "B"; scales[0] = scales[1] = scales[2] = byte; - SetGradientStyle2(styleManager, gs[0], { 0, curG, curB, 1 }, { 1, curG, curB, 1 }); - SetGradientStyle2(styleManager, gs[1], { curR, 0, curB, 1 }, { curR, 1, curB, 1 }); - SetGradientStyle2(styleManager, gs[2], { curR, curG, 0, 1 }, { curR, curG, 1, 1 }); + SetGradientStyle2(app.styleManager, gs[0], { 0, curG, curB, 1 }, { 1, curG, curB, 1 }); + SetGradientStyle2(app.styleManager, gs[1], { curR, 0, curB, 1 }, { curR, 1, curB, 1 }); + SetGradientStyle2(app.styleManager, gs[2], { curR, curG, 0, 1 }, { curR, curG, 1, 1 }); break; case ColorSpace::LinearRGB: { @@ -641,9 +642,9 @@ namespace tachyon labels[0] = "R"; labels[1] = "G"; labels[2] = "B"; scales[0] = scales[1] = scales[2] = byte; auto toS = [](float x) { return ColorConvert::LinearToSRGB(x); }; - SetGradientStyle2(styleManager, gs[0], { toS(0), toS(lg), toS(lb), 1 }, { toS(1), toS(lg), toS(lb), 1 }); - SetGradientStyle2(styleManager, gs[1], { toS(lr), toS(0), toS(lb), 1 }, { toS(lr), toS(1), toS(lb), 1 }); - SetGradientStyle2(styleManager, gs[2], { toS(lr), toS(lg), toS(0), 1 }, { toS(lr), toS(lg), toS(1), 1 }); + SetGradientStyle2(app.styleManager, gs[0], { toS(0), toS(lg), toS(lb), 1 }, { toS(1), toS(lg), toS(lb), 1 }); + SetGradientStyle2(app.styleManager, gs[1], { toS(lr), toS(0), toS(lb), 1 }, { toS(lr), toS(1), toS(lb), 1 }); + SetGradientStyle2(app.styleManager, gs[2], { toS(lr), toS(lg), toS(0), 1 }, { toS(lr), toS(lg), toS(1), 1 }); break; } case ColorSpace::Lab: @@ -653,9 +654,9 @@ namespace tachyon cp.comp[0] = L; cp.comp[1] = a; cp.comp[2] = b; labels[0] = "L"; labels[1] = "a"; labels[2] = "b"; mins[0] = 0; maxs[0] = 100; mins[1] = -128; maxs[1] = 128; mins[2] = -128; maxs[2] = 128; - SetSampledGradient(styleManager, gs[0], [a, b](float t) -> color4f { auto [r, g, bb] = ColorConvert::LabToRGB(t * 100.0f, a, b); return { r, g, bb, 1.0f }; }); - SetSampledGradient(styleManager, gs[1], [L, b](float t) -> color4f { auto [r, g, bb] = ColorConvert::LabToRGB(L, -128.0f + t * 256.0f, b); return { r, g, bb, 1.0f }; }); - SetSampledGradient(styleManager, gs[2], [L, a](float t) -> color4f { auto [r, g, bb] = ColorConvert::LabToRGB(L, a, -128.0f + t * 256.0f); return { r, g, bb, 1.0f }; }); + SetSampledGradient(app.styleManager, gs[0], [a, b](float t) -> color4f { auto [r, g, bb] = ColorConvert::LabToRGB(t * 100.0f, a, b); return { r, g, bb, 1.0f }; }); + SetSampledGradient(app.styleManager, gs[1], [L, b](float t) -> color4f { auto [r, g, bb] = ColorConvert::LabToRGB(L, -128.0f + t * 256.0f, b); return { r, g, bb, 1.0f }; }); + SetSampledGradient(app.styleManager, gs[2], [L, a](float t) -> color4f { auto [r, g, bb] = ColorConvert::LabToRGB(L, a, -128.0f + t * 256.0f); return { r, g, bb, 1.0f }; }); break; } case ColorSpace::Oklab: @@ -665,29 +666,29 @@ namespace tachyon cp.comp[0] = L; cp.comp[1] = a; cp.comp[2] = b; labels[0] = "L"; labels[1] = "a"; labels[2] = "b"; mins[0] = 0; maxs[0] = 1; mins[1] = -0.5f; maxs[1] = 0.5f; mins[2] = -0.5f; maxs[2] = 0.5f; - SetSampledGradient(styleManager, gs[0], [a, b](float t) -> color4f { auto [r, g, bb] = ColorConvert::OklabToRGB(t, a, b); return { r, g, bb, 1.0f }; }); - SetSampledGradient(styleManager, gs[1], [L, b](float t) -> color4f { auto [r, g, bb] = ColorConvert::OklabToRGB(L, -0.5f + t, b); return { r, g, bb, 1.0f }; }); - SetSampledGradient(styleManager, gs[2], [L, a](float t) -> color4f { auto [r, g, bb] = ColorConvert::OklabToRGB(L, a, -0.5f + t); return { r, g, bb, 1.0f }; }); + SetSampledGradient(app.styleManager, gs[0], [a, b](float t) -> color4f { auto [r, g, bb] = ColorConvert::OklabToRGB(t, a, b); return { r, g, bb, 1.0f }; }); + SetSampledGradient(app.styleManager, gs[1], [L, b](float t) -> color4f { auto [r, g, bb] = ColorConvert::OklabToRGB(L, -0.5f + t, b); return { r, g, bb, 1.0f }; }); + SetSampledGradient(app.styleManager, gs[2], [L, a](float t) -> color4f { auto [r, g, bb] = ColorConvert::OklabToRGB(L, a, -0.5f + t); return { r, g, bb, 1.0f }; }); break; } } - SetGradientStyle2(styleManager, gs[3], { curR, curG, curB, 0 }, { curR, curG, curB, 1 }); + SetGradientStyle2(app.styleManager, gs[3], { curR, curG, curB, 0 }, { curR, curG, curB, 1 }); - BeginVertical(idManager.AllocateDynamicID("cp_channels"), theme.colorPickerChannelsStyleRef, LayoutOverride{}.NoShrink()); + app.BeginVertical(app.idManager.AllocateDynamicID("cp_channels"), styles.colorPickerChannelsStyleRef, LayoutOverride{}.NoShrink()); auto channel = [&](std::string_view label, float& value, float minVal, float maxVal, float scale, VisualColorStyleIndex fill, bool checker) { - BeginHorizontal(idManager.AllocateDynamicID("cp_channel"), theme.colorPickerChannelStyleRef, LayoutOverride{}.NoShrink()); - Text(idManager.AllocateDynamicID("cp_channel_label"), label, theme.colorPickerChannelLabelStyleRef); + app.BeginHorizontal(app.idManager.AllocateDynamicID("cp_channel"), styles.colorPickerChannelStyleRef, LayoutOverride{}.NoShrink()); + app.Text(app.idManager.AllocateDynamicID("cp_channel_label"), label, styles.colorPickerChannelLabelStyleRef); - const ID trackID = idManager.AllocateDynamicID("cp_channel_track"); - const ElementRef trackRef = RegisterControl(Element{ .id = trackID, - .eventHandler = MakeSliderHandler(guiStateManager, elementStorage, &value, styleManager.Px(200), nullptr, minVal, maxVal, SliderPress::Jump), - .styleRef = theme.colorPickerTrackStyleRef }, LayoutOverride{}.FlexGrow(1)); + const ID trackID = app.idManager.AllocateDynamicID("cp_channel_track"); + const ElementRef trackRef = app.RegisterControl(Element{ .id = trackID, + .eventHandler = MakeSliderHandler(app.guiStateManager, app.elementStorage, &value, app.styleManager.Px(200), nullptr, minVal, maxVal, SliderPress::Jump), + .styleRef = styles.colorPickerTrackStyleRef }, LayoutOverride{}.FlexGrow(1)); const float t = (maxVal > minVal) ? std::clamp((value - minVal) / (maxVal - minVal), 0.0f, 1.0f) : 0.0f; - VERIFY(elementStorage.AddCustomDraw(trackRef, - [fill, checker, t, look, white = cp.whiteColor, outline = cp.outlineColor, trackH = styleManager.Px(8), - thumb = float(styleManager.Px(6)), edge = float(styleManager.Px(1))](CustomDrawContext& ctx) + VERIFY(app.elementStorage.AddCustomDraw(trackRef, + [fill, checker, t, look, white = cp.whiteColor, outline = cp.outlineColor, trackH = app.styleManager.Px(8), + thumb = float(app.styleManager.Px(6)), edge = float(app.styleManager.Px(1))](CustomDrawContext& ctx) { const IntRect r = ctx.ElementInnerRect(); const IntRect track{ .position = { r.x, r.y + (r.h - trackH) / 2 }, .size = { r.w, trackH } }; @@ -708,15 +709,15 @@ namespace tachyon // The value, rounded to what the range shows. float shown = value * scale; shown = (scale > 1.0f) ? std::round(shown) : std::round(shown * 1000.0f) / 1000.0f; - if (Field(idManager.AllocateDynamicID("cp_channel_value"), shown, TextEditBehavior::None, theme.colorPickerChannelValueStyleRef, + if (app.Field(app.idManager.AllocateDynamicID("cp_channel_value"), shown, TextEditBehavior::None, styles.colorPickerChannelValueStyleRef, NumericFieldConfig{ .minVal = minVal * scale, .maxVal = maxVal * scale }, LayoutOverride{})) value = shown / scale; - EndHorizontal(); + app.EndHorizontal(); }; for (int i = 0; i < 3; ++i) channel(labels[i], cp.comp[i], mins[i], maxs[i], scales[i], gs[i], false); channel("A", cp.a, 0.0f, 1.0f, byte, gs[3], true); - EndVertical(); + app.EndVertical(); cp.snapComp[0] = cp.comp[0]; cp.snapComp[1] = cp.comp[1]; @@ -724,13 +725,13 @@ namespace tachyon cp.slidersInitialized = true; // Hex. - BeginHorizontal(idManager.AllocateDynamicID("cp_hex_row"), theme.colorPickerFieldRowStyleRef, LayoutOverride{}.NoShrink()); + app.BeginHorizontal(app.idManager.AllocateDynamicID("cp_hex_row"), styles.colorPickerFieldRowStyleRef, LayoutOverride{}.NoShrink()); { - Text(idManager.AllocateDynamicID("cp_hex_label"), "Hex", theme.colorPickerRowLabelStyleRef); - const ID hexID = idManager.AllocateDynamicID("color_picker_hex"); - if (guiStateManager.Interaction().GetFocusedID() != hexID) + app.Text(app.idManager.AllocateDynamicID("cp_hex_label"), "Hex", styles.colorPickerRowLabelStyleRef); + const ID hexID = app.idManager.AllocateDynamicID("color_picker_hex"); + if (app.guiStateManager.Interaction().GetFocusedID() != hexID) cp.hexText = ColorToHex(curR, curG, curB); - if (Field(hexID, cp.hexText, TextEditBehavior::None, theme.colorHexStyleRef, LayoutOverride{}.FlexGrow(1))) + if (app.Field(hexID, cp.hexText, TextEditBehavior::None, styles.colorHexStyleRef, LayoutOverride{}.FlexGrow(1))) { float nr, ng, nb; if (HexToColor(cp.hexText, nr, ng, nb)) @@ -740,22 +741,22 @@ namespace tachyon // Eyedropper: press it and drag anywhere on screen; the color follows the // pixel under the cursor, opaque, and stays when released. Only where the screen can be read. if (!cp.canPick) - cp.canPick = windowManager->ReadScreenPixel(windowManager->GetScreenMousePos()).has_value(); + cp.canPick = app.windowManager->ReadScreenPixel(app.windowManager->GetScreenMousePos()).has_value(); if (*cp.canPick) { - auto pick = [this] + auto pick = [&context, &app] { - auto& state = m_colorPickerSub->State(); - if (const auto c = windowManager->ReadScreenPixel(windowManager->GetScreenMousePos())) + auto& state = context.picker; + if (const auto c = app.windowManager->ReadScreenPixel(app.windowManager->GetScreenMousePos())) { ColorConvert::RGBtoHSV(c->r / 255.0f, c->g / 255.0f, c->b / 255.0f, state.h, state.s, state.v); state.a = 1.0f; // the screen is opaque } }; - RegisterControl(Element{ .id = idManager.AllocateDynamicID("cp_eyedropper"), - .eventHandler = [this, pick](ElementEvent&& event) -> bool + app.RegisterControl(Element{ .id = app.idManager.AllocateDynamicID("cp_eyedropper"), + .eventHandler = [&context, &app, pick](ElementEvent&& event) -> bool { - auto& state = m_colorPickerSub->State(); + auto& state = context.picker; switch (event.type) { case EventType::MouseDown: @@ -776,44 +777,44 @@ namespace tachyon return false; } }, - .styleRef = theme.dialogSquareButtonStyleRef }, - [this](Element& e) { return textSystem->RegisterText(e.id, theme.eyedropperIcon, std::string_view{}, e.styleRef, e.state); }, + .styleRef = app.theme.dialogSquareButtonStyleRef }, + [&app](Element& e) { return app.textSystem->RegisterText(e.id, app.theme.eyedropperIcon, std::string_view{}, e.styleRef, e.state); }, LayoutOverride{}); - SetTooltip("Pick a color from the screen: press and drag"); + app.SetTooltip("Pick a color from the screen: press and drag"); } } - EndHorizontal(); + app.EndHorizontal(); // HDR: the brightness multiplier over 1 (disabled for a field without HDR), and // whether the RGB channels are edited in linear light. { - BeginHorizontal(idManager.AllocateDynamicID("cp_hdr_row"), theme.colorPickerFieldRowStyleRef, LayoutOverride{}.NoShrink()); - Text(idManager.AllocateDynamicID("cp_hdr_label"), "HDR", theme.colorPickerRowLabelStyleRef); - if (!allowHDR) guiStateManager.Construction().PushDisabled(); - BeginFieldBox(idManager.AllocateDynamicID("cp_hdr_box"), theme.colorPickerHdrStyleRef, LayoutOverride{}.FlexGrow(1)); - Text(idManager.AllocateDynamicID("cp_hdr_caption"), "Intensity", theme.colorPickerCaptionStyleRef); - Field(idManager.AllocateDynamicID("cp_hdr_value"), cp.hdrBrightness, TextEditBehavior::None, theme.colorPickerHdrValueStyleRef, + app.BeginHorizontal(app.idManager.AllocateDynamicID("cp_hdr_row"), styles.colorPickerFieldRowStyleRef, LayoutOverride{}.NoShrink()); + app.Text(app.idManager.AllocateDynamicID("cp_hdr_label"), "HDR", styles.colorPickerRowLabelStyleRef); + if (!allowHDR) app.guiStateManager.Construction().PushDisabled(); + app.BeginFieldBox(app.idManager.AllocateDynamicID("cp_hdr_box"), styles.colorPickerHdrStyleRef, LayoutOverride{}.FlexGrow(1)); + app.Text(app.idManager.AllocateDynamicID("cp_hdr_caption"), "Intensity", styles.colorPickerCaptionStyleRef); + app.Field(app.idManager.AllocateDynamicID("cp_hdr_value"), cp.hdrBrightness, TextEditBehavior::None, styles.colorPickerHdrValueStyleRef, NumericFieldConfig{ .minVal = 1.0f, .maxVal = 1000.0f }, LayoutOverride{}.FlexGrow(1)); - EndFieldBox(); - if (!allowHDR) guiStateManager.Construction().PopDisabled(); - SetTooltip(allowHDR ? "Brightness over 1" : "This color has no HDR range"); + app.EndFieldBox(); + if (!allowHDR) app.guiStateManager.Construction().PopDisabled(); + app.SetTooltip(allowHDR ? "Brightness over 1" : "This color has no HDR range"); const bool linear = (cp.activeSpace == ColorSpace::LinearRGB); - Checkbox(idManager.AllocateDynamicID("cp_linear"), linear, "Linear", [this](bool on) { - m_colorPickerSub->State().activeSpace = on ? ColorSpace::LinearRGB : ColorSpace::sRGB; + app.Checkbox(app.idManager.AllocateDynamicID("cp_linear"), linear, "Linear", [&context, &app](bool on) { + context.picker.activeSpace = on ? ColorSpace::LinearRGB : ColorSpace::sRGB; }); - SetTooltip("Edit the RGB channels in linear light"); - EndHorizontal(); + app.SetTooltip("Edit the RGB channels in linear light"); + app.EndHorizontal(); } } - EndVertical(); - EndHorizontal(); // body + app.EndVertical(); + app.EndHorizontal(); // body // ---- Swatches and recent colors ---- - BeginVertical(idManager.AllocateDynamicID("cp_swatches"), theme.colorPickerSwatchesStyleRef, LayoutOverride{}.NoShrink()); + app.BeginVertical(app.idManager.AllocateDynamicID("cp_swatches"), styles.colorPickerSwatchesStyleRef, LayoutOverride{}.NoShrink()); { const color4f current{ curR, curG, curB, cp.a }; - auto pick = [this](const color4f& c) { - auto& cp = m_colorPickerSub->State(); + auto pick = [&context, &app](const color4f& c) { + auto& cp = context.picker; ColorConvert::RGBtoHSV(std::clamp(c.r, 0.f, 1.f), std::clamp(c.g, 0.f, 1.f), std::clamp(c.b, 0.f, 1.f), cp.h, cp.s, cp.v); cp.a = c.a; }; @@ -823,21 +824,21 @@ namespace tachyon // One swatch: the color split opaque | with alpha, an accent ring when it's the current one. auto swatch = [&](ID id, const color4f& c, bool round, EventHandler handler) { - NoteSwatchClaim(id); - auto& alphaStyle = m_colorPickerSub->ClaimSwatchStyle(id); - SetColorStyle(styleManager, alphaStyle, c); - const ID opaqueID = idManager.AllocateDynamicID("cp_swatch_opaque"); - NoteSwatchClaim(opaqueID); - auto& opaqueStyle = m_colorPickerSub->ClaimSwatchStyle(opaqueID); - SetColorStyle(styleManager, opaqueStyle, color4f{ c.r, c.g, c.b, 1.0f }); + app.NoteSwatchClaim(id); + auto& alphaStyle = app.ClaimSwatchStyle(id); + SetColorStyle(app.styleManager, alphaStyle, c); + const ID opaqueID = app.idManager.AllocateDynamicID("cp_swatch_opaque"); + app.NoteSwatchClaim(opaqueID); + auto& opaqueStyle = app.ClaimSwatchStyle(opaqueID); + SetColorStyle(app.styleManager, opaqueStyle, color4f{ c.r, c.g, c.b, 1.0f }); const bool selected = !round && same(c, current); - const ElementRef ref = RegisterControl(Element{ .id = id, .eventHandler = std::move(handler), - .styleRef = round ? theme.colorPickerRecentStyleRef : theme.colorPickerSwatchStyleRef }, LayoutOverride{}); + const ElementRef ref = app.RegisterControl(Element{ .id = id, .eventHandler = std::move(handler), + .styleRef = round ? styles.colorPickerRecentStyleRef : styles.colorPickerSwatchStyleRef }, LayoutOverride{}); ColorSwatchLook swLook = look; - swLook.alphaBar = round ? 0 : styleManager.Px(2); - VERIFY(elementStorage.AddCustomDraw(ref, + swLook.alphaBar = round ? 0 : app.styleManager.Px(2); + VERIFY(app.elementStorage.AddCustomDraw(ref, [swLook, round, selected, opaque = opaqueStyle, withAlpha = alphaStyle, alpha = c.a, - accent = theme.accentColor, panel = theme.panelColor, gap = styleManager.Px(2)](CustomDrawContext& ctx) + accent = app.theme.accentColor, panel = app.theme.panelColor, gap = app.styleManager.Px(2)](CustomDrawContext& ctx) { const IntRect outer = ctx.ElementRect(); IntRect inner = ctx.ElementInnerRect(); @@ -856,72 +857,72 @@ namespace tachyon })); }; - BeginHorizontal(idManager.AllocateDynamicID("cp_swatch_row"), theme.colorPickerSwatchRowStyleRef, LayoutOverride{}.NoShrink()); - Text(idManager.AllocateDynamicID("cp_swatches_label"), "Swatches", theme.colorPickerSectionLabelStyleRef); + app.BeginHorizontal(app.idManager.AllocateDynamicID("cp_swatch_row"), styles.colorPickerSwatchRowStyleRef, LayoutOverride{}.NoShrink()); + app.Text(app.idManager.AllocateDynamicID("cp_swatches_label"), "Swatches", styles.colorPickerSectionLabelStyleRef); auto& palette = cp.palette; const ID swatchRange = palette.empty() ? ID::Invalid() - : idManager.AllocateRangedID(static_cast(palette.size()), "color_picker_swatch"); + : app.idManager.AllocateRangedID(static_cast(palette.size()), "color_picker_swatch"); for (int i = 0; i < int(palette.size()); i++) { // Left-click picks it, right-click removes it. - swatch(idManager.GetSubID(swatchRange, uint32_t(i)), palette[size_t(i)].color, false, - [this, i, pick](ElementEvent&& event) -> bool { + swatch(app.idManager.GetSubID(swatchRange, uint32_t(i)), palette[size_t(i)].color, false, + [&context, &app, i, pick](ElementEvent&& event) -> bool { if (event.type != EventType::MouseDown) return false; - auto& palette = m_colorPickerSub->State().palette; + auto& palette = context.picker.palette; if (i >= int(palette.size())) return false; if (event.state.LeftPressed()) { pick(palette[size_t(i)].color); return true; } if (event.state.RightPressed()) { palette.erase(palette.begin() + i); return true; } return false; }); - SetTooltip("Click to use, right-click to remove"); + app.SetTooltip("Click to use, right-click to remove"); } - Button(idManager.AllocateDynamicID("color_picker_add_swatch"), theme.addIcon, [this]() { - auto& cp = m_colorPickerSub->State(); + app.Button(app.idManager.AllocateDynamicID("color_picker_add_swatch"), app.theme.addIcon, [&context, &app]() { + auto& cp = context.picker; auto [r, g, b] = ColorConvert::HSVtoRGB(cp.h, cp.s, cp.v); const color4f c{ r, g, b, cp.a }; if (cp.palette.empty() || !(cp.palette.back().color == c)) cp.palette.push_back({ c }); - }, theme.colorPickerNewStyleRef); - SetTooltip("Add the color to the swatches"); - EndHorizontal(); + }, styles.colorPickerNewStyleRef); + app.SetTooltip("Add the color to the swatches"); + app.EndHorizontal(); { - BeginHorizontal(idManager.AllocateDynamicID("cp_recent_row"), theme.colorPickerSwatchRowStyleRef, LayoutOverride{}.NoShrink()); - Text(idManager.AllocateDynamicID("cp_recent_label"), "Recent", theme.colorPickerSectionLabelStyleRef); - const ID recentRange = idManager.AllocateRangedID(static_cast(std::max(1, cp.recent.size())), "color_picker_recent"); + app.BeginHorizontal(app.idManager.AllocateDynamicID("cp_recent_row"), styles.colorPickerSwatchRowStyleRef, LayoutOverride{}.NoShrink()); + app.Text(app.idManager.AllocateDynamicID("cp_recent_label"), "Recent", styles.colorPickerSectionLabelStyleRef); + const ID recentRange = app.idManager.AllocateRangedID(static_cast(std::max(1, cp.recent.size())), "color_picker_recent"); for (int i = 0; i < int(cp.recent.size()); i++) { const color4f c = cp.recent[size_t(i)]; - swatch(idManager.GetSubID(recentRange, uint32_t(i)), c, true, MakeButtonHandler([pick, c]() { pick(c); })); + swatch(app.idManager.GetSubID(recentRange, uint32_t(i)), c, true, app.MakeButtonHandler([pick, c]() { pick(c); })); } - EndHorizontal(); + app.EndHorizontal(); } } - EndVertical(); + app.EndVertical(); // ---- Footer: status, Cancel, OK ---- - BeginHorizontal(idManager.AllocateDynamicID("cp_footer"), theme.dialogFooterStyleRef, LayoutOverride{}.NoShrink()); + app.BeginHorizontal(app.idManager.AllocateDynamicID("cp_footer"), app.theme.dialogFooterStyleRef, LayoutOverride{}.NoShrink()); { - Element dot{ .id = idManager.AllocateDynamicID("cp_status_dot"), .styleRef = theme.dialogStatusDotStyleRef, .flags = ElementFlags::NoInput }; - RegisterElement(std::move(dot), LayoutOverride{}); + Element dot{ .id = app.idManager.AllocateDynamicID("cp_status_dot"), .styleRef = app.theme.dialogStatusDotStyleRef, .flags = ElementFlags::NoInput }; + app.RegisterElement(std::move(dot), LayoutOverride{}); // The format, then the range the values show in, as one line: a click on the range // switches it. - BeginHorizontal(idManager.AllocateDynamicID("cp_status_line"), theme.emptyHorzStyleRef, LayoutOverride{}.NoShrink()); - Text(idManager.AllocateDynamicID("cp_status"), allowHDR ? "HDR \xC2\xB7 float \xC2\xB7" : "sRGB \xC2\xB7 8-bit \xC2\xB7", - theme.dialogStatusStyleRef); - Button(idManager.AllocateDynamicID("cp_range"), cp.byteRange ? "0\xE2\x80\x93" "255" : "0\xE2\x80\x93" "1", - [this]() { auto& cp = m_colorPickerSub->State(); cp.byteRange = !cp.byteRange; }, - theme.colorPickerRangeStyleRef); - SetTooltip("Show the values 0-255 or 0-1"); - EndHorizontal(); - Element footerSpacer{ .id = idManager.AllocateDynamicID("cp_footer_spacer"), .styleRef = theme.emptyHorzStyleRef, .flags = ElementFlags::NoInput }; - RegisterElement(std::move(footerSpacer), LayoutOverride{}.FlexGrow(1)); - Button(idManager.AllocateDynamicID("cp_cancel"), "Cancel", requestClose(ColorPickerState::CloseRequest::Cancel), - theme.dialogButtonStyleRef); - Button(idManager.AllocateDynamicID("cp_ok"), "OK", requestClose(ColorPickerState::CloseRequest::Ok), - theme.dialogPrimaryButtonStyleRef); + app.BeginHorizontal(app.idManager.AllocateDynamicID("cp_status_line"), app.theme.emptyHorzStyleRef, LayoutOverride{}.NoShrink()); + app.Text(app.idManager.AllocateDynamicID("cp_status"), allowHDR ? "HDR \xC2\xB7 float \xC2\xB7" : "sRGB \xC2\xB7 8-bit \xC2\xB7", + app.theme.dialogStatusStyleRef); + app.Button(app.idManager.AllocateDynamicID("cp_range"), cp.byteRange ? "0\xE2\x80\x93" "255" : "0\xE2\x80\x93" "1", + [&app, &context]() { auto& cp = context.picker; cp.byteRange = !cp.byteRange; }, + styles.colorPickerRangeStyleRef); + app.SetTooltip("Show the values 0-255 or 0-1"); + app.EndHorizontal(); + Element footerSpacer{ .id = app.idManager.AllocateDynamicID("cp_footer_spacer"), .styleRef = app.theme.emptyHorzStyleRef, .flags = ElementFlags::NoInput }; + app.RegisterElement(std::move(footerSpacer), LayoutOverride{}.FlexGrow(1)); + app.Button(app.idManager.AllocateDynamicID("cp_cancel"), "Cancel", requestClose(ColorPickerState::CloseRequest::Cancel), + app.theme.dialogButtonStyleRef); + app.Button(app.idManager.AllocateDynamicID("cp_ok"), "OK", requestClose(ColorPickerState::CloseRequest::Ok), + app.theme.dialogPrimaryButtonStyleRef); } - EndHorizontal(); + app.EndHorizontal(); // Write the working color back every frame while the picker is open. const float mult = (allowHDR && cp.hdrBrightness > 1.0f) ? cp.hdrBrightness : 1.0f; @@ -932,26 +933,26 @@ namespace tachyon // The picker's swatches and recent colors // --------------------------------------------------------------------------- - void GUIApplication::SetColorSwatches(std::span colors) + void SetColorSwatches(GUIApplication& /*app*/, Context& context, std::span colors) { - auto& palette = m_colorPickerSub->State().palette; + auto& palette = context.picker.palette; palette.clear(); for (const color4f& color : colors) palette.push_back({ color }); } - std::vector GUIApplication::ColorSwatches() const + std::vector ColorSwatches(GUIApplication& /*app*/, Context& context) { std::vector colors; - for (const auto& swatch : m_colorPickerSub->State().palette) + for (const auto& swatch : context.picker.palette) colors.push_back(swatch.color); return colors; } - void GUIApplication::AddRecentColor(color4f color) + void AddRecentColor(GUIApplication& /*app*/, Context& context, color4f color) { constexpr size_t kRecentColors = 8; - auto& recent = m_colorPickerSub->State().recent; + auto& recent = context.picker.recent; recent.erase(std::remove(recent.begin(), recent.end(), color), recent.end()); recent.insert(recent.begin(), color); if (recent.size() > kRecentColors) @@ -994,37 +995,38 @@ namespace tachyon } } - ColorSwatchLook GUIApplication::SwatchLook() const + ColorSwatchLook SwatchLook(GUIApplication& app, Context& /*context*/) { return ColorSwatchLook{ - .checkerA = theme.checkerAColor, .checkerB = theme.checkerBColor, - .alphaTrack = theme.alphaTrackColor, .alphaFill = theme.alphaFillColor, - .checkerSize = styleManager.Px(8), - .alphaBar = styleManager.Px(3), - .radius = float(styleManager.Px(3)), // --radius-md inside the 1 px border + .checkerA = app.theme.checkerAColor, .checkerB = app.theme.checkerBColor, + .alphaTrack = app.theme.alphaTrackColor, .alphaFill = app.theme.alphaFillColor, + .checkerSize = app.styleManager.Px(8), + .alphaBar = app.styleManager.Px(3), + .radius = float(app.styleManager.Px(3)), // --radius-md inside the 1 px border }; } - bool GUIApplication::ColorField(ID id, color4f& value, bool allowHDR, StyleRef style, LayoutOverride&& constraints) + bool ColorField(GUIApplication& app, Context& context, ID id, color4f& value, bool allowHDR, StyleRef style, LayoutOverride&& constraints) { + const Styles& styles = GetStyles(app, context); const color4f before = value; // A swatch (opens the picker), the color as hex, and its alpha in percent. The row // takes their states, so a tooltip or context menu on the field covers all three. - BeginFieldBox(id, style, std::move(constraints)); + app.BeginFieldBox(id, style, std::move(constraints)); // ---- Swatch button ---- // The parts' IDs go under the field's own, so they don't depend on what came before. - [[maybe_unused]] const bool pushed = idManager.PushParent(id); - const ID swatchID = idManager.AllocateDynamicID("color_swatch"); - const std::string context = PendingLabelText(); - auto& cp = m_colorPickerSub->State(); + [[maybe_unused]] const bool pushed = app.idManager.PushParent(id); + const ID swatchID = app.idManager.AllocateDynamicID("color_swatch"); + const std::string fieldLabel = app.PendingLabelText(); + auto& cp = context.picker; // Escape is Cancel, and the keyboard goes back to the swatch. - if (cp.triggerID == swatchID && cp.closeRequest == ColorPickerState::CloseRequest::None && TakeEscapeFor(cp.windowID, swatchID)) + if (cp.triggerID == swatchID && cp.closeRequest == ColorPickerState::CloseRequest::None && app.TakeEscapeFor(cp.windowID, swatchID)) { cp.closeRequest = ColorPickerState::CloseRequest::Cancel; - guiStateManager.Interaction().SetFocusID(swatchID); + app.guiStateManager.Interaction().SetFocusID(swatchID); } // OK keeps the color and remembers it; Cancel and the close button restore the original. if (cp.triggerID == swatchID && cp.closeRequest != ColorPickerState::CloseRequest::None) @@ -1032,26 +1034,26 @@ namespace tachyon if (cp.closeRequest == ColorPickerState::CloseRequest::Cancel) value = cp.originalColor; else - AddRecentColor(value); + AddRecentColor(app, context, value); cp.closeRequest = ColorPickerState::CloseRequest::None; cp.triggerID = ID::Invalid(); } const bool pickerIsOpen = (cp.triggerID == swatchID); // this field's picker, not just any - NoteSwatchClaim(swatchID); - auto& swatchStyle = m_colorPickerSub->ClaimSwatchStyle(swatchID); - SetColorStyle(styleManager, swatchStyle, value); - const ID opaqueID = idManager.AllocateDynamicID("color_swatch_opaque"); - NoteSwatchClaim(opaqueID); - auto& opaqueStyle = m_colorPickerSub->ClaimSwatchStyle(opaqueID); - SetColorStyle(styleManager, opaqueStyle, color4f{ value.r, value.g, value.b, 1.0f }); - const ElementRef swatchRef = RegisterControl( + app.NoteSwatchClaim(swatchID); + auto& swatchStyle = app.ClaimSwatchStyle(swatchID); + SetColorStyle(app.styleManager, swatchStyle, value); + const ID opaqueID = app.idManager.AllocateDynamicID("color_swatch_opaque"); + app.NoteSwatchClaim(opaqueID); + auto& opaqueStyle = app.ClaimSwatchStyle(opaqueID); + SetColorStyle(app.styleManager, opaqueStyle, color4f{ value.r, value.g, value.b, 1.0f }); + const ElementRef swatchRef = app.RegisterControl( tachyon::Element { .id = swatchID, // Captures a copy: handlers run after this returns, and `value` may be a temporary. - .eventHandler = MakeButtonHandler([this, value, swatchID, allowHDR, pickerIsOpen, context]() + .eventHandler = app.MakeButtonHandler([&app, state = &context, value, swatchID, allowHDR, pickerIsOpen, fieldLabel]() { - auto& cp = m_colorPickerSub->State(); + auto& cp = state->picker; if (pickerIsOpen) { cp.triggerID = ID::Invalid(); @@ -1059,7 +1061,7 @@ namespace tachyon { cp.triggerID = swatchID; if (cp.windowID == ID::Invalid()) - cp.windowID = idManager.CreateStaticID(); + cp.windowID = app.idManager.CreateStaticID(); // HDR: the over-range part becomes the brightness multiplier, so // HSV (of the colour divided by it) times brightness gives it back. cp.hdrBrightness = allowHDR ? std::max({value.r, value.g, value.b, 1.0f}) : 1.0f; @@ -1070,63 +1072,63 @@ namespace tachyon cp.a = value.a; cp.originalColor = value; cp.allowHDR = allowHDR; - cp.context = context; + cp.context = fieldLabel; // The color it had counts as a recent one. - AddRecentColor(value); + AddRecentColor(app, *state, value); } }), - .styleRef = theme.colorSwatchStyleRef + .styleRef = styles.colorSwatchStyleRef }, LayoutOverride{}); - VERIFY(elementStorage.AddCustomDraw(swatchRef, - [look = SwatchLook(), opaque = opaqueStyle, withAlpha = swatchStyle, alpha = value.a](CustomDrawContext& ctx) + VERIFY(app.elementStorage.AddCustomDraw(swatchRef, + [look = SwatchLook(app, context), opaque = opaqueStyle, withAlpha = swatchStyle, alpha = value.a](CustomDrawContext& ctx) { DrawColorSwatch(ctx, ctx.ElementInnerRect(), look, opaque, withAlpha, alpha); })); std::string hex = ColorHex(value); - if (Field(idManager.AllocateDynamicID("color_hex"), hex, TextEditBehavior::None, theme.colorHexStyleRef, + if (app.Field(app.idManager.AllocateDynamicID("color_hex"), hex, TextEditBehavior::None, styles.colorHexStyleRef, LayoutOverride{}.FlexGrow(1))) ParseColorHex(hex, value); - BeginFieldBox(idManager.AllocateDynamicID("color_alpha"), theme.colorAlphaStyleRef, LayoutOverride{}); - Text(idManager.AllocateDynamicID("color_alpha_caption"), "A", theme.colorAlphaCaptionStyleRef); + app.BeginFieldBox(app.idManager.AllocateDynamicID("color_alpha"), styles.colorAlphaStyleRef, LayoutOverride{}); + app.Text(app.idManager.AllocateDynamicID("color_alpha_caption"), "A", styles.colorAlphaCaptionStyleRef); int alphaPercent = int(std::lround(std::clamp(value.a, 0.0f, 1.0f) * 100.0f)); - if (Field(idManager.AllocateDynamicID("color_alpha_value"), alphaPercent, TextEditBehavior::ContinuousUpdate, - theme.colorAlphaInputStyleRef, NumericFieldConfig{ .minVal = 0, .maxVal = 100 }, + if (app.Field(app.idManager.AllocateDynamicID("color_alpha_value"), alphaPercent, TextEditBehavior::ContinuousUpdate, + styles.colorAlphaInputStyleRef, NumericFieldConfig{ .minVal = 0, .maxVal = 100 }, LayoutOverride{}.FlexGrow(1))) value.a = float(alphaPercent) / 100.0f; - Text(idManager.AllocateDynamicID("color_alpha_unit"), "%", theme.colorAlphaUnitStyleRef); - EndFieldBox(); + app.Text(app.idManager.AllocateDynamicID("color_alpha_unit"), "%", styles.colorAlphaUnitStyleRef); + app.EndFieldBox(); - if (pushed) (void)idManager.PopParent(); - EndFieldBox(); // the row + if (pushed) (void)app.idManager.PopParent(); + app.EndFieldBox(); // the row // ---- Picker popup ---- if (pickerIsOpen && cp.windowID != ID::Invalid()) { LayoutOverride popupPos = LayoutOverride{}.Anchored(swatchID, AnchorPlacement::OutsideBottom | AnchorPlacement::InsideLeft, - {0, int16_t(styleManager.Px(4))}, AutoFlipMode::FlipAvoidTarget); + {0, int16_t(app.styleManager.Px(4))}, AutoFlipMode::FlipAvoidTarget); - if (BeginWindow(cp.windowID, "Color Picker", theme.colorPickerStyleRef, std::move(popupPos), + if (app.BeginWindow(cp.windowID, "Color Picker", styles.colorPickerStyleRef, std::move(popupPos), ElementFlags::WindowCanMove | ElementFlags::WindowNoCaption | ElementFlags::Shadows)) { - EmitColorPicker(value, allowHDR); + EmitColorPicker(app, context, value, allowHDR); } else { // Window was closed (click outside / focus lost) cp.triggerID = ID::Invalid(); } - EndWindow(); + app.EndWindow(); } const bool changed = value != before; - guiStateManager.SetModified(changed); + app.guiStateManager.SetModified(changed); return changed; } - bool GUIApplication::ColorField(ID id, color4b& value, StyleRef style, LayoutOverride&& constraints) + bool ColorField(GUIApplication& app, Context& context, ID id, color4b& value, StyleRef style, LayoutOverride&& constraints) { color4f f { value.r / 255.0f, @@ -1134,7 +1136,7 @@ namespace tachyon value.b / 255.0f, value.a / 255.0f }; - bool changed = ColorField(id, f, false, style, std::move(constraints)); + bool changed = ColorField(app, context, id, f, false, style, std::move(constraints)); if (changed) { value.r = static_cast(std::clamp(int(f.r * 255.0f + 0.5f), 0, 255)); @@ -1145,4 +1147,45 @@ namespace tachyon return changed; } -} \ No newline at end of file + // A shadow: its color over its offsets, blur and spread (BoxShadow). + bool ShadowField(GUIApplication& app, Context& context, ID id, BoxShadow& value, LayoutOverride&& constraints) + { + bool modified = false; + app.BeginVertical(id, app.theme.emptyVertStyleRef, std::move(constraints)); + const bool pushed = app.idManager.PushParent(id); + + modified = ColorField(app, context, app.idManager.AllocateDynamicID("shadow_color"), value.color) || modified; + + // The offsets may be negative; the blur may not. + struct Part { std::string_view caption, name; int32_t value; int32_t min; }; + Part parts[] = { + { "X", "Horizontal offset", value.x, -256 }, + { "Y", "Vertical offset", value.y, -256 }, + { "Blur", "Blur radius", value.blur, 0 }, + { "Spread", "How far it grows past the box", value.spread, -256 }, + }; + app.RegisterElement(Element{ .id = app.idManager.AllocateDynamicID("shadow_sizes"), .styleRef = app.theme.fieldElementGroupStyleRef, + .flags = ElementFlags::PropagatesDescendantState }, LayoutOverride::Auto()); + VERIFY(app.elementStorage.BeginChildren()); + for (Part& part : parts) + { + app.DragLabel(app.idManager.AllocateDynamicID("shadow_caption"), part.caption, app.theme.axisLabelStyleRefs[3], + LayoutOverride::Auto().MinWidth(Pixels{ app.theme.axisLabelWidth }).NoGrow().KeepWithNext()); + app.SetTooltip(part.name); + modified = app.Field(app.idManager.AllocateDynamicID("shadow_size"), part.value, TextEditBehavior::ContinuousUpdate, + app.theme.vectorComponentStyleRef, + NumericFieldConfig{ .stepPerPixel = 0.25, .minVal = part.min, .maxVal = 256 }, + LayoutOverride::Auto().MinWidth(40)) || modified; + } + VERIFY(app.elementStorage.EndChildren()); + value.x = int16_t(std::clamp(parts[0].value, -256, 256)); + value.y = int16_t(std::clamp(parts[1].value, -256, 256)); + value.blur = uint16_t(std::clamp(parts[2].value, 0, 256)); + value.spread = int16_t(std::clamp(parts[3].value, -256, 256)); + + if (pushed) (void)app.idManager.PopParent(); + app.EndVertical(); + app.guiStateManager.SetModified(modified); + return modified; + } +} diff --git a/src/gui_controls/controls_color_internal.h b/src/gui_color/controls_color_internal.h similarity index 76% rename from src/gui_controls/controls_color_internal.h rename to src/gui_color/controls_color_internal.h index 06910fe3..6688eb7d 100644 --- a/src/gui_controls/controls_color_internal.h +++ b/src/gui_color/controls_color_internal.h @@ -1,5 +1,7 @@ #pragma once +#include + #include // color4f #include // ColorStyle #include // StyleManager @@ -11,7 +13,7 @@ // Helpers shared by the color picker (controls_color.cpp) and gradient editor (controls_gradient.cpp). -namespace tachyon +namespace tachyon::color { // How a color shows in a swatch: the left half opaque, the right half at its alpha over // a checkerboard, and an alpha bar along the bottom (alphaBar 0 leaves it out). @@ -75,12 +77,21 @@ namespace tachyon } // Create or update a VisualColorStyleIndex with a solid color. - inline void SetColorStyle(tachyon::StyleManager& sm, tachyon::VisualColorStyleIndex& idx, tachyon::color4f c) - { - tachyon::ColorStyle cs = tachyon::ColorStyle::Create(c); - if (idx == tachyon::VisualColorStyleIndex::Invalid) - idx = sm.CreateColorStyle(cs); - else - sm.UpdateColorStyle(idx, cs); - } + + struct Context; + + /// `context`, with its styles looked up again (and its color styles dropped) when the + /// app's styles loaded since: what each color control does first. + Context& Prepare(GUIApplication& app, Context& context); + /// How color swatches draw a color (the theme's checkerboard and alpha bar). + ColorSwatchLook SwatchLook(GUIApplication& app, Context& context); + /// Popup content for ColorField / GradientField. + void EmitColorPicker(GUIApplication& app, Context& context, color4f& outColor, bool allowHDR); + /// The editor's body, on its working copy, which it writes to `outGradient`. + void EmitGradientEditor(GUIApplication& app, Context& context, GradientF& outGradient); + /// GradientField on a GradientF; `gradient8` is the Gradient it stands for, which limits + /// the editor to its stops and colors (null for a GradientF field). `cancelled` when the + /// editor's Cancel put the gradient back this frame. + bool GradientFieldCore(GUIApplication& app, Context& context, ID id, GradientF& value, const Gradient* gradient8, + bool& cancelled, StyleRef style, LayoutOverride&& constraints); } diff --git a/src/gui_controls/controls_gradient.cpp b/src/gui_color/controls_gradient.cpp similarity index 62% rename from src/gui_controls/controls_gradient.cpp rename to src/gui_color/controls_gradient.cpp index 849e3680..1a391161 100644 --- a/src/gui_controls/controls_gradient.cpp +++ b/src/gui_color/controls_gradient.cpp @@ -1,8 +1,8 @@ -#include +#include #include #include #include -#include // SetColorStyle (shared with controls_color.cpp) +#include // SetColorStyle (shared with controls_color.cpp) #include #include @@ -77,30 +77,30 @@ namespace } -namespace tachyon +namespace tachyon::color { // --------------------------------------------------------------------------- // GradientField - gradient swatch + editor popup // --------------------------------------------------------------------------- - bool GUIApplication::GradientField(ID id, Gradient& value, StyleRef style, LayoutOverride&& constraints) + bool GradientField(GUIApplication& app, Context& context, ID id, Gradient& value, StyleRef style, LayoutOverride&& constraints) { if (value.stopCount > Gradient::kMaxStops) { - ReportMisuse("GUIApplication: a gradient with more stops than Gradient::kMaxStops (clamped)"); + app.ReportMisuse("GUIApplication: a gradient with more stops than Gradient::kMaxStops (clamped)"); value.stopCount = Gradient::kMaxStops; } const Gradient before = value; // The core edits a copy, not `value`: both in the application's buffers, which keep // their storage from field to field. - GradientF& given = m_gradientFieldGiven; - GradientF& edited = m_gradientFieldEdited; + GradientF& given = context.gradientFieldGiven; + GradientF& edited = context.gradientFieldEdited; given.Assign(value); edited = given; bool cancelled = false; - (void)GradientFieldCore(id, edited, &value, cancelled, style, std::move(constraints)); + (void)GradientFieldCore(app, context, id, edited, &value, cancelled, style, std::move(constraints)); if (cancelled) - value = m_gradientEditorSub->State().originalGradient8; // exactly as it was + value = context.gradientEditor.originalGradient8; // exactly as it was else if (!(edited == given)) { // Only an edit writes back: the stops and the blend space, the rest kept. @@ -110,40 +110,41 @@ namespace tachyon value = out; } const bool changed = !(value == before); - guiStateManager.SetModified(changed); + app.guiStateManager.SetModified(changed); return changed; } - bool GUIApplication::GradientField(ID id, GradientF& value, StyleRef style, LayoutOverride&& constraints) + bool GradientField(GUIApplication& app, Context& context, ID id, GradientF& value, StyleRef style, LayoutOverride&& constraints) { if (value.stops.size() > size_t(GradientF::kMaxStops)) { - ReportMisuse("GUIApplication: a gradient with more stops than GradientF::kMaxStops (clamped)"); + app.ReportMisuse("GUIApplication: a gradient with more stops than GradientF::kMaxStops (clamped)"); value.stops.resize(size_t(GradientF::kMaxStops)); } const GradientF before = value; bool cancelled = false; - (void)GradientFieldCore(id, value, nullptr, cancelled, style, std::move(constraints)); + (void)GradientFieldCore(app, context, id, value, nullptr, cancelled, style, std::move(constraints)); const bool changed = !(value == before); - guiStateManager.SetModified(changed); + app.guiStateManager.SetModified(changed); return changed; } - bool GUIApplication::GradientFieldCore(ID id, GradientF& value, const Gradient* gradient8, bool& cancelled, + bool GradientFieldCore(GUIApplication& app, Context& context, ID id, GradientF& value, const Gradient* gradient8, bool& cancelled, StyleRef style, LayoutOverride&& constraints) { + const Styles& styles = GetStyles(app, context); cancelled = false; const GradientEditLimits limits = gradient8 ? GradientEditLimits{ Gradient::kMaxStops, false, false } : GradientEditLimits{ GradientF::kMaxStops, true, true }; // ---- Gradient swatch (inline preview bar) ---- const ID swatchID = id; - auto& ge = m_gradientEditorSub->State(); + auto& ge = context.gradientEditor; // Escape is Cancel, and the keyboard goes back to the swatch. - if (ge.triggerID == swatchID && ge.closeRequest == GradientEditorState::CloseRequest::None && TakeEscapeFor(ge.windowID, swatchID)) + if (ge.triggerID == swatchID && ge.closeRequest == GradientEditorState::CloseRequest::None && app.TakeEscapeFor(ge.windowID, swatchID)) { ge.closeRequest = GradientEditorState::CloseRequest::Cancel; - guiStateManager.Interaction().SetFocusID(swatchID); + app.guiStateManager.Interaction().SetFocusID(swatchID); } // OK keeps the gradient; Cancel and the close button restore the original. if (ge.triggerID == swatchID && ge.closeRequest != GradientEditorState::CloseRequest::None) @@ -161,17 +162,17 @@ namespace tachyon // Persistent style indices for this swatch: the gradient as it is, and opaque. The bar // is sampled again only when the gradient changed. Copied out, as a later claim can // add entries. - NoteSwatchClaim(swatchID); - GradientEditorSubsystem::Swatch& field = m_gradientEditorSub->ClaimSwatch(swatchID); - const ID opaqueID = idManager.AllocateDynamicID("gradient_opaque"); - NoteSwatchClaim(opaqueID); - auto& opaqueStyle = m_gradientEditorSub->ClaimSwatchStyle(opaqueID); + app.NoteSwatchClaim(swatchID); + GradientSwatch& field = context.gradientSwatches.Claim(swatchID); + const ID opaqueID = app.idManager.AllocateDynamicID("gradient_opaque"); + app.NoteSwatchClaim(opaqueID); + auto& opaqueStyle = context.gradientSwatches.Claim(opaqueID).index; const bool redraw = field.index == VisualColorStyleIndex::Invalid || opaqueStyle == VisualColorStyleIndex::Invalid || !field.data.drawnSet || !(field.data.drawn == value); if (redraw) { - SetGradientPreviewStyle(styleManager, field.index, value); - SetGradientPreviewStyle(styleManager, opaqueStyle, value, /*opaque*/ true); + SetGradientPreviewStyle(app.styleManager, field.index, value); + SetGradientPreviewStyle(app.styleManager, opaqueStyle, value, /*opaque*/ true); field.data.drawn = value; // into the storage it has field.data.drawnSet = true; } @@ -181,26 +182,26 @@ namespace tachyon // caller's, kept in the swatch rather than copied into the handler each frame. field.data.original8 = gradient8 ? *gradient8 : Gradient{}; field.data.limits = limits; - field.data.context.assign(PendingLabelTextView()); + field.data.context.assign(app.PendingLabelTextView()); Element swatch {}; swatch.id = swatchID; swatch.styleRef = style; - swatch.state = guiStateManager.GetCurrentState(swatchID); - swatch.eventHandler = MakeButtonHandler([this, swatchID, editorIsOpen]() + swatch.state = app.guiStateManager.GetCurrentState(swatchID); + swatch.eventHandler = app.MakeButtonHandler([&context, &app, swatchID, editorIsOpen]() { - auto& ge = m_gradientEditorSub->State(); + auto& ge = context.gradientEditor; if (editorIsOpen) { ge.triggerID = ID::Invalid(); return; } - const GradientEditorSubsystem::Swatch* drawn = m_gradientEditorSub->FindSwatch(swatchID); + const GradientSwatch* drawn = context.gradientSwatches.Find(swatchID); if (drawn == nullptr || !drawn->data.drawnSet) return; ge.triggerID = swatchID; if (ge.windowID == ID::Invalid()) - ge.windowID = idManager.CreateStaticID(); + ge.windowID = app.idManager.CreateStaticID(); ge.workingCopy = drawn->data.drawn; ge.originalGradient = drawn->data.drawn; ge.originalGradient8 = drawn->data.original8; @@ -215,34 +216,34 @@ namespace tachyon for (const GradientStop& stop : value.stops) brightest = std::max(brightest, Brightest(stop.color)); const bool hdr = brightest > 1.0f; - const ElementRef swatchRef = RegisterControl(std::move(swatch), std::move(constraints)); + const ElementRef swatchRef = app.RegisterControl(std::move(swatch), std::move(constraints)); // How bright a gradient brighter than 1 gets, which the bar can't show. if (hdr) { char tip[48]; std::snprintf(tip, sizeof(tip), "Up to %.1f \xC3\x97 white", double(brightest)); - SetTooltip(tip); + app.SetTooltip(tip); } // A band over the bar where the gradient is brighter than 1. VisualColorStyleIndex band = VisualColorStyleIndex::Invalid; if (hdr) { - const ID bandID = idManager.AllocateDynamicID("gradient_hdr_band"); - NoteSwatchClaim(bandID); - auto& bandStyle = m_gradientEditorSub->ClaimSwatchStyle(bandID); + const ID bandID = app.idManager.AllocateDynamicID("gradient_hdr_band"); + app.NoteSwatchClaim(bandID); + auto& bandStyle = context.gradientSwatches.Claim(bandID).index; if (redraw || bandStyle == VisualColorStyleIndex::Invalid) - SetHdrBandStyle(styleManager, bandStyle, value); + SetHdrBandStyle(app.styleManager, bandStyle, value); band = bandStyle; } // The gradient's colors opaque in the top half, and in the bottom half as they are over a // checkerboard, as a color swatch shows its alpha. The stops are the editor's to show. { - ColorSwatchLook look = SwatchLook(); - look.radius = float(styleManager.Px(2)); - VERIFY(elementStorage.AddCustomDraw(swatchRef, - [look, withAlpha, opaque, band, bandH = styleManager.Px(3), bandGap = styleManager.Px(2)](CustomDrawContext& ctx) + ColorSwatchLook look = SwatchLook(app, context); + look.radius = float(app.styleManager.Px(2)); + VERIFY(app.elementStorage.AddCustomDraw(swatchRef, + [look, withAlpha, opaque, band, bandH = app.styleManager.Px(3), bandGap = app.styleManager.Px(2)](CustomDrawContext& ctx) { const IntRect outer = ctx.ElementRect(); const IntRect inner = ctx.ElementInnerRect(); @@ -265,18 +266,18 @@ namespace tachyon { auto popupPos = LayoutOverride{}.Anchored(swatchID, AnchorPlacement::OutsideBottom | AnchorPlacement::InsideLeft, - {0, int16_t(styleManager.Px(4))}, AutoFlipMode::FlipAvoidTarget); + {0, int16_t(app.styleManager.Px(4))}, AutoFlipMode::FlipAvoidTarget); - if (BeginWindow(ge.windowID, "Gradient Editor", theme.gradientEditorStyleRef, std::move(popupPos), + if (app.BeginWindow(ge.windowID, "Gradient Editor", styles.gradientEditorStyleRef, std::move(popupPos), ElementFlags::WindowCanMove | ElementFlags::WindowNoCaption | ElementFlags::Shadows)) { - EmitGradientEditor(value); + EmitGradientEditor(app, context, value); } else { ge.triggerID = ID::Invalid(); } - EndWindow(); + app.EndWindow(); } return editorIsOpen; } @@ -388,53 +389,54 @@ namespace tachyon constexpr std::string_view kInterpolationNames[] = { "Linear", "Smooth", "Constant" }; } - void GUIApplication::EmitGradientEditor(GradientF& outGradient) + void EmitGradientEditor(GUIApplication& app, Context& context, GradientF& outGradient) { - auto& ge = m_gradientEditorSub->State(); + const Styles& styles = GetStyles(app, context); + auto& ge = context.gradientEditor; auto& g = ge.workingCopy; if (int(g.stops.size()) > ge.limits.maxStops) { - ReportMisuse("GUIApplication: a gradient with more stops than its field takes (clamped)"); + app.ReportMisuse("GUIApplication: a gradient with more stops than its field takes (clamped)"); g.stops.resize(size_t(ge.limits.maxStops)); } const int stopCount = int(g.stops.size()); if (ge.selectedStop >= stopCount) ge.selectedStop = stopCount > 0 ? stopCount - 1 : 0; - SetGradientPreviewStyle(styleManager, ge.previewGradientStyle, g); - SetColorStyle(styleManager, ge.stopEdgeColor, theme.GetColor("--text-1", color4f{ 0.91f, 0.92f, 0.94f, 1.0f })); - SetColorStyle(styleManager, ge.stopOutlineColor, color4f{ 0.0f, 0.0f, 0.0f, 0.5f }); - SetColorStyle(styleManager, ge.stopHaloColor, theme.GetColor("--accent-soft", color4f{ 0.42f, 0.61f, 1.0f, 0.16f })); + SetGradientPreviewStyle(app.styleManager, ge.previewGradientStyle, g); + SetColorStyle(app.styleManager, ge.stopEdgeColor, app.theme.GetColor("--text-1", color4f{ 0.91f, 0.92f, 0.94f, 1.0f })); + SetColorStyle(app.styleManager, ge.stopOutlineColor, color4f{ 0.0f, 0.0f, 0.0f, 0.5f }); + SetColorStyle(app.styleManager, ge.stopHaloColor, app.theme.GetColor("--accent-soft", color4f{ 0.42f, 0.61f, 1.0f, 0.16f })); - const ColorSwatchLook look = SwatchLook(); - const auto requestClose = [this](GradientEditorState::CloseRequest request) { - return [this, request]() { m_gradientEditorSub->State().closeRequest = request; }; + const ColorSwatchLook look = SwatchLook(app, context); + const auto requestClose = [&context, &app](GradientEditorState::CloseRequest request) { + return [&app, request, &context]() { context.gradientEditor.closeRequest = request; }; }; // ---- Header ---- // The header is the dialog's title bar: it drags the window. - BeginTitleBar(idManager.AllocateDynamicID("ge_header"), theme.dialogHeaderStyleRef, LayoutOverride{}.NoShrink()); - Text(idManager.AllocateDynamicID("ge_title"), "Gradient", theme.dialogTitleStyleRef); - Text(idManager.AllocateDynamicID("ge_context"), DialogContext(ge.context, "Gradient"), theme.dialogContextStyleRef, LayoutOverride{}.FlexGrow(1)); - Button(idManager.AllocateDynamicID("ge_close"), theme.tabCloseIcon, requestClose(GradientEditorState::CloseRequest::Cancel), - theme.dialogCloseStyleRef); - SetTooltip("Close without changing the gradient"); - EndTitleBar(); + app.BeginTitleBar(app.idManager.AllocateDynamicID("ge_header"), app.theme.dialogHeaderStyleRef, LayoutOverride{}.NoShrink()); + app.Text(app.idManager.AllocateDynamicID("ge_title"), "Gradient", app.theme.dialogTitleStyleRef); + app.Text(app.idManager.AllocateDynamicID("ge_context"), DialogContext(ge.context, "Gradient"), app.theme.dialogContextStyleRef, LayoutOverride{}.FlexGrow(1)); + app.Button(app.idManager.AllocateDynamicID("ge_close"), app.theme.tabCloseIcon, requestClose(GradientEditorState::CloseRequest::Cancel), + app.theme.dialogCloseStyleRef); + app.SetTooltip("Close without changing the gradient"); + app.EndTitleBar(); // ---- Presets ---- - BeginHorizontal(idManager.AllocateDynamicID("ge_presets"), theme.gradientEditorPresetsStyleRef, LayoutOverride{}.NoShrink()); + app.BeginHorizontal(app.idManager.AllocateDynamicID("ge_presets"), styles.gradientEditorPresetsStyleRef, LayoutOverride{}.NoShrink()); { - Text(idManager.AllocateDynamicID("ge_presets_label"), "Presets", theme.gradientEditorSectionLabelStyleRef); + app.Text(app.idManager.AllocateDynamicID("ge_presets_label"), "Presets", styles.gradientEditorSectionLabelStyleRef); // A chip draws its gradient over the checkerboard; the one matching the gradient is ringed. auto chip = [&](ID id, const GradientF& preset, std::string_view name) { - NoteSwatchClaim(id); - auto& style = m_gradientEditorSub->ClaimSwatchStyle(id); - SetGradientPreviewStyle(styleManager, style, preset); + app.NoteSwatchClaim(id); + auto& style = context.gradientSwatches.Claim(id).index; + SetGradientPreviewStyle(app.styleManager, style, preset); const bool current = SameAsPreset(g, preset); - const ElementRef ref = RegisterControl(Element{ .id = id, - .eventHandler = MakeButtonHandler([this, preset]() { - auto& ge = m_gradientEditorSub->State(); + const ElementRef ref = app.RegisterControl(Element{ .id = id, + .eventHandler = app.MakeButtonHandler([&context, &app, preset]() { + auto& ge = context.gradientEditor; const ColorSpace space = ge.workingCopy.colorSpace; ge.workingCopy = preset; ge.workingCopy.colorSpace = space; @@ -442,11 +444,11 @@ namespace tachyon ge.workingCopy.stops.resize(size_t(ge.limits.maxStops)); ge.selectedStop = 0; }), - .styleRef = theme.gradientEditorPresetStyleRef }, LayoutOverride{}); - SetTooltip(name); - VERIFY(elementStorage.AddCustomDraw(ref, - [look, style, current, accent = theme.accentColor, panel = theme.panelColor, - radius = float(styleManager.Px(4)), gap = styleManager.Px(2)](CustomDrawContext& ctx) + .styleRef = styles.gradientEditorPresetStyleRef }, LayoutOverride{}); + app.SetTooltip(name); + VERIFY(app.elementStorage.AddCustomDraw(ref, + [look, style, current, accent = app.theme.accentColor, panel = app.theme.panelColor, + radius = float(app.styleManager.Px(4)), gap = app.styleManager.Px(2)](CustomDrawContext& ctx) { const IntRect r = ctx.ElementRect(); if (current) @@ -462,48 +464,48 @@ namespace tachyon ctx.RenderQuad(r, style, radius); })); }; - const ID builtInRange = idManager.AllocateRangedID(uint32_t(std::size(kGradientPresets)), "ge_preset"); + const ID builtInRange = app.idManager.AllocateRangedID(uint32_t(std::size(kGradientPresets)), "ge_preset"); for (uint32_t i = 0; i < uint32_t(std::size(kGradientPresets)); ++i) - chip(idManager.GetSubID(builtInRange, i), MakePreset(kGradientPresets[i], g.colorSpace), kGradientPresets[i].name); + chip(app.idManager.GetSubID(builtInRange, i), MakePreset(kGradientPresets[i], g.colorSpace), kGradientPresets[i].name); if (!ge.savedPresets.empty()) { - const ID savedRange = idManager.AllocateRangedID(uint32_t(ge.savedPresets.size()), "ge_saved_preset"); + const ID savedRange = app.idManager.AllocateRangedID(uint32_t(ge.savedPresets.size()), "ge_saved_preset"); for (uint32_t i = 0; i < uint32_t(ge.savedPresets.size()); ++i) - chip(idManager.GetSubID(savedRange, i), ge.savedPresets[i], "Saved preset"); + chip(app.idManager.GetSubID(savedRange, i), ge.savedPresets[i], "Saved preset"); } - Element spacer{ .id = idManager.AllocateDynamicID("ge_presets_spacer"), .styleRef = theme.emptyHorzStyleRef, .flags = ElementFlags::NoInput }; - RegisterElement(std::move(spacer), LayoutOverride{}.FlexGrow(1)); - Button(idManager.AllocateDynamicID("ge_save_preset"), { theme.addIcon, "Save preset" }, [this]() { - auto& ge = m_gradientEditorSub->State(); + Element spacer{ .id = app.idManager.AllocateDynamicID("ge_presets_spacer"), .styleRef = app.theme.emptyHorzStyleRef, .flags = ElementFlags::NoInput }; + app.RegisterElement(std::move(spacer), LayoutOverride{}.FlexGrow(1)); + app.Button(app.idManager.AllocateDynamicID("ge_save_preset"), { app.theme.addIcon, "Save preset" }, [&context, &app]() { + auto& ge = context.gradientEditor; ge.savedPresets.push_back(ge.workingCopy); - }, theme.dialogSmallButtonStyleRef); - SetTooltip("Keep this gradient as a preset"); + }, app.theme.dialogSmallButtonStyleRef); + app.SetTooltip("Keep this gradient as a preset"); } - EndHorizontal(); + app.EndHorizontal(); // ---- The bar and its stops ---- { - const ID barID = idManager.AllocateDynamicID("ge_bar"); - const int barH = styleManager.Px(44); - const int stopBox = styleManager.Px(18); - const int pointer = styleManager.Px(6); - const int inset = styleManager.Px(24); // the bar's side inset, so the end stops fit - const int removeDistance = styleManager.Px(40); + const ID barID = app.idManager.AllocateDynamicID("ge_bar"); + const int barH = app.styleManager.Px(44); + const int stopBox = app.styleManager.Px(18); + const int pointer = app.styleManager.Px(6); + const int inset = app.styleManager.Px(24); // the bar's side inset, so the end stops fit + const int removeDistance = app.styleManager.Px(40); Element bar{}; bar.id = barID; - bar.styleRef = theme.gradientEditorBarStyleRef; - bar.state = guiStateManager.GetCurrentState(barID); - bar.eventHandler = [this, barID, barH, stopBox, pointer, inset, removeDistance](ElementEvent&& event) -> bool + bar.styleRef = styles.gradientEditorBarStyleRef; + bar.state = app.guiStateManager.GetCurrentState(barID); + bar.eventHandler = [&context, &app, barID, barH, stopBox, pointer, inset, removeDistance](ElementEvent&& event) -> bool { - auto& ge = m_gradientEditorSub->State(); + auto& ge = context.gradientEditor; auto& g = ge.workingCopy; if (!event.rect) return false; const IntRect& r = event.rect->rect; const int barW = r.w - 2 * inset; if (barW <= 0) return false; - const int2 c = event.LocalCursor(elementStorage); + const int2 c = event.LocalCursor(app.elementStorage); const float t = std::clamp(float(c.x - r.x - inset) / float(barW), 0.0f, 1.0f); const int top = r.y + (r.h - (barH + pointer + stopBox)) / 2; const bool belowBar = c.y >= top + barH; @@ -524,12 +526,12 @@ namespace tachyon case EventType::MouseDown: { if (!event.state.LeftPressed()) break; - guiStateManager.Interaction().SetFocusID(barID); + app.guiStateManager.Interaction().SetFocusID(barID); const int hit = hitStop(); if (hit >= 0) { // Focused above already; the text editor keeps its own focus. - ge.press.Press(event, elementStorage, guiStateManager, { g, ge.selectedStop }, + ge.press.Press(event, app.elementStorage, app.guiStateManager, { g, ge.selectedStop }, { .atOnce = true, .focus = false }); ge.selectedStop = hit; ge.dragStopIndex = hit; @@ -572,13 +574,13 @@ namespace tachyon } ge.dragStopIndex = -1; ge.dragOff = false; - guiStateManager.Interaction().ReleaseCaptureID(); + app.guiStateManager.Interaction().ReleaseCaptureID(); return true; } break; case EventType::KeyDown: // Escape during a drag puts the gradient back. - if (ge.press.Cancel(event, guiStateManager)) + if (ge.press.Cancel(event, app.guiStateManager)) { g = ge.press.before.gradient; ge.selectedStop = ge.press.before.selectedStop; @@ -597,30 +599,30 @@ namespace tachyon } return false; }; - const ElementRef barRef = RegisterControl(std::move(bar), LayoutOverride{}); + const ElementRef barRef = app.RegisterControl(std::move(bar), LayoutOverride{}); struct StopDraw { float t; VisualColorStyleIndex color; }; std::vector stops; for (int i = 0; i < stopCount; i++) { - const ID stopStyleID = idManager.AllocateDynamicID("ge_stop_color"); - NoteSwatchClaim(stopStyleID); - auto& stopStyle = m_gradientEditorSub->ClaimSwatchStyle(stopStyleID); - SetColorStyle(styleManager, stopStyle, Clamp01(g.stops[size_t(i)].color)); + const ID stopStyleID = app.idManager.AllocateDynamicID("ge_stop_color"); + app.NoteSwatchClaim(stopStyleID); + auto& stopStyle = context.gradientSwatches.Claim(stopStyleID).index; + SetColorStyle(app.styleManager, stopStyle, Clamp01(g.stops[size_t(i)].color)); stops.push_back({ std::clamp(g.stops[size_t(i)].offset, 0.0f, 1.0f), stopStyle }); } const int selected = ge.selectedStop; const bool hideSelected = ge.dragOff; - const TextID badgeText = textSystem->RegisterText(idManager.AllocateDynamicID("ge_badge_text"), - Percent(selected < stopCount ? stops[size_t(selected)].t : 0.0f), theme.gradientEditorBadgeStyleRef, ElementState::None); - const auto badgeSize = textSystem->GetTextMeasurement(badgeText); - VERIFY(elementStorage.AddCustomDraw(barRef, + const TextID badgeText = app.textSystem->RegisterText(app.idManager.AllocateDynamicID("ge_badge_text"), + Percent(selected < stopCount ? stops[size_t(selected)].t : 0.0f), styles.gradientEditorBadgeStyleRef, ElementState::None); + const auto badgeSize = app.textSystem->GetTextMeasurement(badgeText); + VERIFY(app.elementStorage.AddCustomDraw(barRef, [look, preview = ge.previewGradientStyle, stops = std::move(stops), selected, hideSelected, badgeText, badgeW = badgeSize.maxWidth, badgeH = badgeSize.minHeight, edgeColor = ge.stopEdgeColor, outline = ge.stopOutlineColor, halo = ge.stopHaloColor, - accent = theme.accentColor, barH, stopBox, pointer, inset, - radius = float(styleManager.Px(4)), border = styleManager.Px(2), haloW = styleManager.Px(3), - badgePadX = styleManager.Px(6), badgePadY = styleManager.Px(1), badgeGap = styleManager.Px(2)](CustomDrawContext& ctx) + accent = app.theme.accentColor, barH, stopBox, pointer, inset, + radius = float(app.styleManager.Px(4)), border = app.styleManager.Px(2), haloW = app.styleManager.Px(3), + badgePadX = app.styleManager.Px(6), badgePadY = app.styleManager.Px(1), badgeGap = app.styleManager.Px(2)](CustomDrawContext& ctx) { const IntRect r = ctx.ElementRect(); const int top = r.y + (r.h - (barH + pointer + stopBox)) / 2; @@ -666,51 +668,51 @@ namespace tachyon } // ---- Below: the selected stop and options at the left, the stops at the right ---- - BeginHorizontal(idManager.AllocateDynamicID("ge_columns"), theme.gradientEditorColumnsStyleRef, LayoutOverride{}.NoShrink()); + app.BeginHorizontal(app.idManager.AllocateDynamicID("ge_columns"), styles.gradientEditorColumnsStyleRef, LayoutOverride{}.NoShrink()); - BeginVertical(idManager.AllocateDynamicID("ge_left"), theme.gradientEditorColumnStyleRef, LayoutOverride{}.FlexGrow(3)); // room for the six blend spaces + app.BeginVertical(app.idManager.AllocateDynamicID("ge_left"), styles.gradientEditorColumnStyleRef, LayoutOverride{}.FlexGrow(3)); // room for the six blend spaces if (ge.selectedStop >= 0 && ge.selectedStop < int(g.stops.size())) { // "Color stop 2 / 3", previous, next. - BeginHorizontal(idManager.AllocateDynamicID("ge_stop_head"), theme.gradientEditorRowStyleRef, LayoutOverride{}.NoShrink()); - Text(idManager.AllocateDynamicID("ge_stop_title"), "Color stop", theme.gradientEditorHeadingStyleRef); + app.BeginHorizontal(app.idManager.AllocateDynamicID("ge_stop_head"), styles.gradientEditorRowStyleRef, LayoutOverride{}.NoShrink()); + app.Text(app.idManager.AllocateDynamicID("ge_stop_title"), "Color stop", styles.gradientEditorHeadingStyleRef); char count[32]; std::snprintf(count, sizeof(count), "%d / %d", ge.selectedStop + 1, int(g.stops.size())); - Text(idManager.AllocateDynamicID("ge_stop_count"), count, theme.gradientEditorCountStyleRef, LayoutOverride{}.FlexGrow(1)); - Button(idManager.AllocateDynamicID("ge_prev"), theme.chevronLeftIcon, [this]() { - auto& ge = m_gradientEditorSub->State(); + app.Text(app.idManager.AllocateDynamicID("ge_stop_count"), count, styles.gradientEditorCountStyleRef, LayoutOverride{}.FlexGrow(1)); + app.Button(app.idManager.AllocateDynamicID("ge_prev"), app.theme.chevronLeftIcon, [&context, &app]() { + auto& ge = context.gradientEditor; ge.selectedStop = std::max(0, ge.selectedStop - 1); - }, theme.dialogIconButtonStyleRef); - SetTooltip("Previous stop"); - Button(idManager.AllocateDynamicID("ge_next"), theme.treeArrowRight, [this]() { - auto& ge = m_gradientEditorSub->State(); + }, app.theme.dialogIconButtonStyleRef); + app.SetTooltip("Previous stop"); + app.Button(app.idManager.AllocateDynamicID("ge_next"), app.theme.treeArrowRight, [&context, &app]() { + auto& ge = context.gradientEditor; ge.selectedStop = std::min(int(ge.workingCopy.stops.size()) - 1, ge.selectedStop + 1); - }, theme.dialogIconButtonStyleRef); - SetTooltip("Next stop"); - EndHorizontal(); + }, app.theme.dialogIconButtonStyleRef); + app.SetTooltip("Next stop"); + app.EndHorizontal(); // Color, then location with duplicate and delete. - BeginHorizontal(idManager.AllocateDynamicID("ge_color_row"), theme.gradientEditorRowStyleRef, LayoutOverride{}.NoShrink()); - Text(idManager.AllocateDynamicID("ge_color_label"), "Color", theme.gradientEditorLabelStyleRef); + app.BeginHorizontal(app.idManager.AllocateDynamicID("ge_color_row"), styles.gradientEditorRowStyleRef, LayoutOverride{}.NoShrink()); + app.Text(app.idManager.AllocateDynamicID("ge_color_label"), "Color", styles.gradientEditorLabelStyleRef); ge.selectedStopColor = g.stops[size_t(ge.selectedStop)].color; - if (ColorField(ge.selectedStopColor, ge.limits.hdr, LayoutOverride{}.FlexGrow(1))) + if (ColorField(app, context, ge.selectedStopColor, ge.limits.hdr, LayoutOverride{}.FlexGrow(1))) g.stops[size_t(ge.selectedStop)].color = ge.limits.hdr ? ge.selectedStopColor : Clamp01(ge.selectedStopColor); - EndHorizontal(); + app.EndHorizontal(); - BeginHorizontal(idManager.AllocateDynamicID("ge_location_row"), theme.gradientEditorRowStyleRef, LayoutOverride{}.NoShrink()); - Text(idManager.AllocateDynamicID("ge_location_label"), "Location", theme.gradientEditorLabelStyleRef); - BeginFieldBox(idManager.AllocateDynamicID("ge_location_box"), theme.gradientEditorLocationStyleRef, LayoutOverride{}.FlexGrow(1)); + app.BeginHorizontal(app.idManager.AllocateDynamicID("ge_location_row"), styles.gradientEditorRowStyleRef, LayoutOverride{}.NoShrink()); + app.Text(app.idManager.AllocateDynamicID("ge_location_label"), "Location", styles.gradientEditorLabelStyleRef); + app.BeginFieldBox(app.idManager.AllocateDynamicID("ge_location_box"), styles.gradientEditorLocationStyleRef, LayoutOverride{}.FlexGrow(1)); float percent = std::round(g.stops[size_t(ge.selectedStop)].offset * 1000.0f) / 10.0f; - if (Field(idManager.AllocateDynamicID("ge_location_value"), percent, TextEditBehavior::None, theme.gradientEditorLocationInputStyleRef, + if (app.Field(app.idManager.AllocateDynamicID("ge_location_value"), percent, TextEditBehavior::None, styles.gradientEditorLocationInputStyleRef, NumericFieldConfig{ .stepPerPixel = 0.1, .minVal = 0.0f, .maxVal = 100.0f }, LayoutOverride{}.FlexGrow(1))) { g.stops[size_t(ge.selectedStop)].offset = std::clamp(percent / 100.0f, 0.0f, 1.0f); ge.selectedStop = SortStops(g, ge.selectedStop); } - Text(idManager.AllocateDynamicID("ge_location_unit"), "%", theme.gradientEditorLocationUnitStyleRef); - EndFieldBox(); - Button(idManager.AllocateDynamicID("ge_duplicate"), theme.duplicateIcon, [this]() { - auto& ge = m_gradientEditorSub->State(); + app.Text(app.idManager.AllocateDynamicID("ge_location_unit"), "%", styles.gradientEditorLocationUnitStyleRef); + app.EndFieldBox(); + app.Button(app.idManager.AllocateDynamicID("ge_duplicate"), app.theme.duplicateIcon, [&context, &app]() { + auto& ge = context.gradientEditor; auto& g = ge.workingCopy; const int count = int(g.stops.size()); if (count >= ge.limits.maxStops || ge.selectedStop >= count) return; @@ -720,62 +722,62 @@ namespace tachyon : (ge.selectedStop > 0 ? g.stops[size_t(ge.selectedStop - 1)].offset : 1.0f); g.AddStop(stop.color, (stop.offset + there) * 0.5f, stop.interpolation); ge.selectedStop = SortStops(g, int(g.stops.size()) - 1); - }, theme.dialogSquareButtonStyleRef); - SetTooltip("Duplicate the stop"); - Button(idManager.AllocateDynamicID("ge_delete"), theme.deleteIcon, [this]() { - auto& ge = m_gradientEditorSub->State(); + }, app.theme.dialogSquareButtonStyleRef); + app.SetTooltip("Duplicate the stop"); + app.Button(app.idManager.AllocateDynamicID("ge_delete"), app.theme.deleteIcon, [&context, &app]() { + auto& ge = context.gradientEditor; RemoveStop(ge.workingCopy, ge.selectedStop); ge.selectedStop = std::min(ge.selectedStop, int(ge.workingCopy.stops.size()) - 1); - }, theme.dialogDeleteButtonStyleRef); - SetTooltip("Delete the stop"); - EndHorizontal(); + }, app.theme.dialogDeleteButtonStyleRef); + app.SetTooltip("Delete the stop"); + app.EndHorizontal(); // How it blends to the next stop (a GradientF's; the last stop has no next). if (ge.limits.perStopInterpolation) { - BeginHorizontal(idManager.AllocateDynamicID("ge_blend_row"), theme.gradientEditorRowStyleRef, LayoutOverride{}.NoShrink()); - Text(idManager.AllocateDynamicID("ge_blend_label"), "To next", theme.gradientEditorLabelStyleRef); + app.BeginHorizontal(app.idManager.AllocateDynamicID("ge_blend_row"), styles.gradientEditorRowStyleRef, LayoutOverride{}.NoShrink()); + app.Text(app.idManager.AllocateDynamicID("ge_blend_label"), "To next", styles.gradientEditorLabelStyleRef); const bool last = ge.selectedStop == int(g.stops.size()) - 1; int blend = int(g.stops[size_t(ge.selectedStop)].interpolation); - if (last) BeginDisabled(); - if (Dropdown(idManager.AllocateDynamicID("ge_blend"), blend, std::span(kInterpolationNames), + if (last) app.BeginDisabled(); + if (app.Dropdown(app.idManager.AllocateDynamicID("ge_blend"), blend, std::span(kInterpolationNames), LayoutOverride{}.FlexGrow(1))) g.stops[size_t(ge.selectedStop)].interpolation = StopInterpolation(std::clamp(blend, 0, 2)); - if (last) EndDisabled(); - SetTooltip(last ? "The last stop has no next stop to blend to" : "How the color goes from this stop to the next"); - EndHorizontal(); + if (last) app.EndDisabled(); + app.SetTooltip(last ? "The last stop has no next stop to blend to" : "How the color goes from this stop to the next"); + app.EndHorizontal(); } } - Element divider{ .id = idManager.AllocateDynamicID("ge_divider"), .styleRef = theme.gradientEditorDividerStyleRef, .flags = ElementFlags::NoInput }; - RegisterElement(std::move(divider), LayoutOverride{}); + Element divider{ .id = app.idManager.AllocateDynamicID("ge_divider"), .styleRef = styles.gradientEditorDividerStyleRef, .flags = ElementFlags::NoInput }; + app.RegisterElement(std::move(divider), LayoutOverride{}); // Blend space. - BeginHorizontal(idManager.AllocateDynamicID("ge_space_row"), theme.gradientEditorRowStyleRef, LayoutOverride{}.NoShrink()); - Text(idManager.AllocateDynamicID("ge_space_label"), "Blend space", theme.gradientEditorLabelStyleRef); + app.BeginHorizontal(app.idManager.AllocateDynamicID("ge_space_row"), styles.gradientEditorRowStyleRef, LayoutOverride{}.NoShrink()); + app.Text(app.idManager.AllocateDynamicID("ge_space_label"), "Blend space", styles.gradientEditorLabelStyleRef); { struct SpaceTab { ColorSpace space; std::string_view label; }; constexpr SpaceTab tabs[] = { { ColorSpace::sRGB, "sRGB" }, { ColorSpace::LinearRGB, "Linear" }, { ColorSpace::HSL, "HSL" }, { ColorSpace::HSV, "HSV" }, { ColorSpace::Lab, "Lab" }, { ColorSpace::Oklab, "Oklab" }, }; - BeginButtonGroup(LayoutOverride{}.NoGrow().NoShrink()); + app.BeginButtonGroup(LayoutOverride{}.NoGrow().NoShrink()); for (const SpaceTab& tab : tabs) { const bool active = (g.colorSpace == tab.space); - if (active) guiStateManager.Construction().PushSelected(); + if (active) app.guiStateManager.Construction().PushSelected(); const ColorSpace target = tab.space; - Button(tab.label, [this, target]() { m_gradientEditorSub->State().workingCopy.colorSpace = target; }); - if (active) guiStateManager.Construction().PopSelected(); + app.Button(tab.label, [&app, target, &context]() { context.gradientEditor.workingCopy.colorSpace = target; }); + if (active) app.guiStateManager.Construction().PopSelected(); } - EndButtonGroup(); + app.EndButtonGroup(); } - EndHorizontal(); + app.EndHorizontal(); // Reverse, distribute evenly. - BeginHorizontal(idManager.AllocateDynamicID("ge_actions"), theme.gradientEditorActionsStyleRef, LayoutOverride{}.NoShrink()); - Button(idManager.AllocateDynamicID("ge_reverse"), { theme.reverseIcon, "Reverse" }, [this]() { - auto& ge = m_gradientEditorSub->State(); + app.BeginHorizontal(app.idManager.AllocateDynamicID("ge_actions"), styles.gradientEditorActionsStyleRef, LayoutOverride{}.NoShrink()); + app.Button(app.idManager.AllocateDynamicID("ge_reverse"), { app.theme.reverseIcon, "Reverse" }, [&context, &app]() { + auto& ge = context.gradientEditor; auto& g = ge.workingCopy; const int count = int(g.stops.size()); // Each stretch keeps its blend: it's now the other stop's to give. @@ -788,50 +790,50 @@ namespace tachyon for (int i = 0; i < count; i++) g.stops[size_t(i)].interpolation = i + 1 < count ? blends[size_t(count - 2 - i)] : StopInterpolation::Linear; ge.selectedStop = count - 1 - ge.selectedStop; - }, theme.dialogSmallButtonStyleRef); - Button(idManager.AllocateDynamicID("ge_distribute"), { theme.distributeIcon, "Distribute evenly" }, [this]() { - auto& g = m_gradientEditorSub->State().workingCopy; + }, app.theme.dialogSmallButtonStyleRef); + app.Button(app.idManager.AllocateDynamicID("ge_distribute"), { app.theme.distributeIcon, "Distribute evenly" }, [&context, &app]() { + auto& g = context.gradientEditor.workingCopy; const int count = int(g.stops.size()); for (int i = 0; i < count; i++) g.stops[size_t(i)].offset = count > 1 ? float(i) / float(count - 1) : 0.0f; - }, theme.dialogSmallButtonStyleRef); - EndHorizontal(); - EndVertical(); // left + }, app.theme.dialogSmallButtonStyleRef); + app.EndHorizontal(); + app.EndVertical(); // left // The stops table: swatch and color, alpha, (each stop's blend to the next,) location; // a click selects. const bool blendColumn = ge.limits.perStopInterpolation; - BeginVertical(idManager.AllocateDynamicID("ge_table"), theme.gradientEditorTableStyleRef, LayoutOverride{}.FlexGrow(2)); + app.BeginVertical(app.idManager.AllocateDynamicID("ge_table"), styles.gradientEditorTableStyleRef, LayoutOverride{}.FlexGrow(2)); { - BeginHorizontal(idManager.AllocateDynamicID("ge_table_head"), theme.gradientEditorTableHeadStyleRef, LayoutOverride{}.NoShrink()); - Element blank{ .id = idManager.AllocateDynamicID("ge_th_swatch"), .styleRef = theme.gradientEditorSwatchCellStyleRef, .flags = ElementFlags::NoInput }; - RegisterElement(std::move(blank), LayoutOverride{}); - Text(idManager.AllocateDynamicID("ge_th_color"), "Color", theme.gradientEditorHeadCellStyleRef, LayoutOverride{}.FlexGrow(1)); - Text(idManager.AllocateDynamicID("ge_th_alpha"), "Alpha", theme.gradientEditorHeadLocationStyleRef); + app.BeginHorizontal(app.idManager.AllocateDynamicID("ge_table_head"), styles.gradientEditorTableHeadStyleRef, LayoutOverride{}.NoShrink()); + Element blank{ .id = app.idManager.AllocateDynamicID("ge_th_swatch"), .styleRef = styles.gradientEditorSwatchCellStyleRef, .flags = ElementFlags::NoInput }; + app.RegisterElement(std::move(blank), LayoutOverride{}); + app.Text(app.idManager.AllocateDynamicID("ge_th_color"), "Color", styles.gradientEditorHeadCellStyleRef, LayoutOverride{}.FlexGrow(1)); + app.Text(app.idManager.AllocateDynamicID("ge_th_alpha"), "Alpha", styles.gradientEditorHeadLocationStyleRef); if (blendColumn) - Text(idManager.AllocateDynamicID("ge_th_blend"), "Blend", theme.gradientEditorTypeCellStyleRef); - Text(idManager.AllocateDynamicID("ge_th_location"), "Location", theme.gradientEditorHeadLocationStyleRef); - EndHorizontal(); + app.Text(app.idManager.AllocateDynamicID("ge_th_blend"), "Blend", styles.gradientEditorTypeCellStyleRef); + app.Text(app.idManager.AllocateDynamicID("ge_th_location"), "Location", styles.gradientEditorHeadLocationStyleRef); + app.EndHorizontal(); const int rows = int(g.stops.size()); - const ID rowRange = idManager.AllocateRangedID(uint32_t(std::max(1, rows)), "ge_table_row"); + const ID rowRange = app.idManager.AllocateRangedID(uint32_t(std::max(1, rows)), "ge_table_row"); for (int i = 0; i < rows; i++) { - const ID rowID = idManager.GetSubID(rowRange, uint32_t(i)); + const ID rowID = app.idManager.GetSubID(rowRange, uint32_t(i)); const bool sel = (i == ge.selectedStop); - if (sel) guiStateManager.Construction().PushSelected(); - RegisterElement(Element{ .id = rowID, - .eventHandler = MakeButtonHandler([this, i]() { m_gradientEditorSub->State().selectedStop = i; }), - .styleRef = theme.gradientEditorTableRowStyleRef, .state = guiStateManager.GetCurrentState(rowID) }, + if (sel) app.guiStateManager.Construction().PushSelected(); + app.RegisterElement(Element{ .id = rowID, + .eventHandler = app.MakeButtonHandler([&app, i, &context]() { context.gradientEditor.selectedStop = i; }), + .styleRef = styles.gradientEditorTableRowStyleRef, .state = app.guiStateManager.GetCurrentState(rowID) }, LayoutOverride{}.NoShrink()); - VERIFY(elementStorage.BeginChildren()); - const ID swID = idManager.AllocateDynamicID("ge_td_swatch"); - NoteSwatchClaim(swID); - auto& swStyle = m_gradientEditorSub->ClaimSwatchStyle(swID); - SetColorStyle(styleManager, swStyle, Clamp01(g.stops[size_t(i)].color)); - Element sw{ .id = swID, .styleRef = theme.gradientEditorSwatchCellStyleRef, .flags = ElementFlags::NoInput }; - const ElementRef swRef = RegisterElement(std::move(sw), LayoutOverride{}); - VERIFY(elementStorage.AddCustomDraw(swRef, [look, swStyle, radius = float(styleManager.Px(3))](CustomDrawContext& ctx) { + VERIFY(app.elementStorage.BeginChildren()); + const ID swID = app.idManager.AllocateDynamicID("ge_td_swatch"); + app.NoteSwatchClaim(swID); + auto& swStyle = context.gradientSwatches.Claim(swID).index; + SetColorStyle(app.styleManager, swStyle, Clamp01(g.stops[size_t(i)].color)); + Element sw{ .id = swID, .styleRef = styles.gradientEditorSwatchCellStyleRef, .flags = ElementFlags::NoInput }; + const ElementRef swRef = app.RegisterElement(std::move(sw), LayoutOverride{}); + VERIFY(app.elementStorage.AddCustomDraw(swRef, [look, swStyle, radius = float(app.styleManager.Px(3))](CustomDrawContext& ctx) { const IntRect r = ctx.ElementInnerRect(); ColorSwatchLook l = look; l.radius = radius; @@ -839,32 +841,32 @@ namespace tachyon DrawCheckerboard(ctx, r, r, l); ctx.RenderQuad(r, swStyle, radius); })); - Text(idManager.AllocateDynamicID("ge_td_color"), StopColorText(g.stops[size_t(i)]), theme.gradientEditorValueCellStyleRef, LayoutOverride{}.FlexGrow(1)); - Text(idManager.AllocateDynamicID("ge_td_alpha"), StopAlphaText(g.stops[size_t(i)]), theme.gradientEditorLocationCellStyleRef); + app.Text(app.idManager.AllocateDynamicID("ge_td_color"), StopColorText(g.stops[size_t(i)]), styles.gradientEditorValueCellStyleRef, LayoutOverride{}.FlexGrow(1)); + app.Text(app.idManager.AllocateDynamicID("ge_td_alpha"), StopAlphaText(g.stops[size_t(i)]), styles.gradientEditorLocationCellStyleRef); // How it goes on to the next stop; the last goes on to none. if (blendColumn) - Text(idManager.AllocateDynamicID("ge_td_blend"), i + 1 < rows + app.Text(app.idManager.AllocateDynamicID("ge_td_blend"), i + 1 < rows ? kInterpolationNames[std::min(size_t(g.stops[size_t(i)].interpolation), std::size(kInterpolationNames) - 1)] - : std::string_view{}, theme.gradientEditorTypeCellStyleRef); - Text(idManager.AllocateDynamicID("ge_td_location"), Percent(g.stops[size_t(i)].offset), theme.gradientEditorLocationCellStyleRef); - VERIFY(elementStorage.EndChildren()); - if (sel) guiStateManager.Construction().PopSelected(); + : std::string_view{}, styles.gradientEditorTypeCellStyleRef); + app.Text(app.idManager.AllocateDynamicID("ge_td_location"), Percent(g.stops[size_t(i)].offset), styles.gradientEditorLocationCellStyleRef); + VERIFY(app.elementStorage.EndChildren()); + if (sel) app.guiStateManager.Construction().PopSelected(); } } - EndVertical(); - EndHorizontal(); // columns + app.EndVertical(); + app.EndHorizontal(); // columns // ---- Footer ---- - BeginHorizontal(idManager.AllocateDynamicID("ge_footer"), theme.dialogFooterStyleRef, LayoutOverride{}.NoShrink()); + app.BeginHorizontal(app.idManager.AllocateDynamicID("ge_footer"), app.theme.dialogFooterStyleRef, LayoutOverride{}.NoShrink()); { - Element footerSpacer{ .id = idManager.AllocateDynamicID("ge_footer_spacer"), .styleRef = theme.emptyHorzStyleRef, .flags = ElementFlags::NoInput }; - RegisterElement(std::move(footerSpacer), LayoutOverride{}.FlexGrow(1)); - Button(idManager.AllocateDynamicID("ge_cancel"), "Cancel", requestClose(GradientEditorState::CloseRequest::Cancel), - theme.dialogButtonStyleRef); - Button(idManager.AllocateDynamicID("ge_ok"), "OK", requestClose(GradientEditorState::CloseRequest::Ok), - theme.dialogPrimaryButtonStyleRef); + Element footerSpacer{ .id = app.idManager.AllocateDynamicID("ge_footer_spacer"), .styleRef = app.theme.emptyHorzStyleRef, .flags = ElementFlags::NoInput }; + app.RegisterElement(std::move(footerSpacer), LayoutOverride{}.FlexGrow(1)); + app.Button(app.idManager.AllocateDynamicID("ge_cancel"), "Cancel", requestClose(GradientEditorState::CloseRequest::Cancel), + app.theme.dialogButtonStyleRef); + app.Button(app.idManager.AllocateDynamicID("ge_ok"), "OK", requestClose(GradientEditorState::CloseRequest::Ok), + app.theme.dialogPrimaryButtonStyleRef); } - EndHorizontal(); + app.EndHorizontal(); outGradient = g; } diff --git a/src/gui_color/gui_color.cpp b/src/gui_color/gui_color.cpp new file mode 100644 index 00000000..70ac71ac --- /dev/null +++ b/src/gui_color/gui_color.cpp @@ -0,0 +1,115 @@ +#include +#include + +#include + +namespace tachyon::color +{ + void Styles::Load(GUIApplication& app) + { + GUITheme& theme = app.theme; + colorSwatchStyleRef = theme.GetStyle("color-swatch"); + colorFieldStyleRef = theme.GetStyle("color-field"); + colorHexStyleRef = theme.GetStyle("color-hex"); + colorAlphaStyleRef = theme.GetStyle("color-alpha"); + colorAlphaInputStyleRef = theme.GetStyle("color-alpha-input"); + colorAlphaUnitStyleRef = theme.GetStyle("color-alpha-unit"); + colorAlphaCaptionStyleRef = theme.GetStyle("color-alpha-caption"); + colorPickerStyleRef = theme.GetStyle("color-picker"); + colorPickerHdrValueStyleRef = theme.GetStyle("color-picker-hdr-value"); + colorPickerBodyStyleRef = theme.GetStyle("color-picker-body"); + colorPickerPlanesStyleRef = theme.GetStyle("color-picker-planes"); + colorPickerSquareStyleRef = theme.GetStyle("color-picker-square"); + colorPickerStripStyleRef = theme.GetStyle("color-picker-strip"); + colorPickerControlsStyleRef = theme.GetStyle("color-picker-controls"); + colorPickerPreviewGroupStyleRef = theme.GetStyle("color-picker-preview-group"); + colorPickerCaptionsStyleRef = theme.GetStyle("color-picker-captions"); + colorPickerCaptionStyleRef = theme.GetStyle("color-picker-caption"); + colorPickerModeRowStyleRef = theme.GetStyle("color-picker-mode-row"); + colorPickerRangeStyleRef = theme.GetStyle("color-picker-range"); + colorPickerChannelsStyleRef = theme.GetStyle("color-picker-channels"); + colorPickerChannelStyleRef = theme.GetStyle("color-picker-channel"); + colorPickerChannelLabelStyleRef = theme.GetStyle("color-picker-channel-label"); + colorPickerTrackStyleRef = theme.GetStyle("color-picker-track"); + colorPickerChannelValueStyleRef = theme.GetStyle("color-picker-channel-value"); + colorPickerFieldRowStyleRef = theme.GetStyle("color-picker-field-row"); + colorPickerRowLabelStyleRef = theme.GetStyle("color-picker-row-label"); + colorPickerHdrStyleRef = theme.GetStyle("color-picker-hdr"); + colorPickerSwatchesStyleRef = theme.GetStyle("color-picker-swatches"); + colorPickerSwatchRowStyleRef = theme.GetStyle("color-picker-swatch-row"); + colorPickerSectionLabelStyleRef = theme.GetStyle("color-picker-section-label"); + colorPickerSwatchStyleRef = theme.GetStyle("color-picker-swatch"); + colorPickerRecentStyleRef = theme.GetStyle("color-picker-recent"); + colorPickerPreviewStyleRef = theme.GetStyle("color-picker-preview"); + colorPickerNewStyleRef = theme.GetStyle("color-picker-new"); + gradientSwatchStyleRef = theme.GetStyle("gradient-swatch"); + gradientEditorStyleRef = theme.GetStyle("gradient-editor"); + gradientEditorBarStyleRef = theme.GetStyle("gradient-editor-bar"); + gradientEditorPresetsStyleRef = theme.GetStyle("gradient-editor-presets"); + gradientEditorSectionLabelStyleRef = theme.GetStyle("gradient-editor-section-label"); + gradientEditorPresetStyleRef = theme.GetStyle("gradient-editor-preset"); + gradientEditorBadgeStyleRef = theme.GetStyle("gradient-editor-badge"); + gradientEditorColumnsStyleRef = theme.GetStyle("gradient-editor-columns"); + gradientEditorColumnStyleRef = theme.GetStyle("gradient-editor-column"); + gradientEditorRowStyleRef = theme.GetStyle("gradient-editor-row"); + gradientEditorHeadingStyleRef = theme.GetStyle("gradient-editor-heading"); + gradientEditorCountStyleRef = theme.GetStyle("gradient-editor-count"); + gradientEditorLabelStyleRef = theme.GetStyle("gradient-editor-label"); + gradientEditorLocationStyleRef = theme.GetStyle("gradient-editor-location"); + gradientEditorLocationInputStyleRef = theme.GetStyle("gradient-editor-location-input"); + gradientEditorLocationUnitStyleRef = theme.GetStyle("gradient-editor-location-unit"); + gradientEditorDividerStyleRef = theme.GetStyle("gradient-editor-divider"); + gradientEditorActionsStyleRef = theme.GetStyle("gradient-editor-actions"); + gradientEditorTableStyleRef = theme.GetStyle("gradient-editor-table"); + gradientEditorTableHeadStyleRef = theme.GetStyle("gradient-editor-table-head"); + gradientEditorTableRowStyleRef = theme.GetStyle("gradient-editor-table-row"); + gradientEditorTypeCellStyleRef = theme.GetStyle("gradient-editor-type-cell"); + gradientEditorSwatchCellStyleRef = theme.GetStyle("gradient-editor-swatch-cell"); + gradientEditorHeadCellStyleRef = theme.GetStyle("gradient-editor-head-cell"); + gradientEditorHeadLocationStyleRef = theme.GetStyle("gradient-editor-head-location"); + gradientEditorValueCellStyleRef = theme.GetStyle("gradient-editor-value-cell"); + gradientEditorLocationCellStyleRef = theme.GetStyle("gradient-editor-location-cell"); + } + + Context& Prepare(GUIApplication& app, Context& context) + { + if (context.stylesGeneration == app.StylesGeneration()) + return context; + context.styles.Load(app); + context.stylesGeneration = app.StylesGeneration(); + // The load cleared every color style: drop the indices (without destroying them) so + // they're made anew. + context.gradientSwatches.Forget(); + ColorPickerState& p = context.picker; + for (auto* index : { &p.svQuadColor, &p.hueStrip, &p.alphaStrip, &p.hueColor, &p.whiteColor, + &p.outlineColor, &p.newColor, &p.originalStyle }) + *index = VisualColorStyleIndex::Invalid; + for (auto& index : p.gradientStyles) + index = VisualColorStyleIndex::Invalid; + GradientEditorState& e = context.gradientEditor; + for (auto* index : { &e.previewGradientStyle, &e.stopEdgeColor, &e.stopOutlineColor, &e.stopHaloColor }) + *index = VisualColorStyleIndex::Invalid; + return context; + } + + const Styles& GetStyles(GUIApplication& app, Context& context) { return Prepare(app, context).styles; } + + void EndGUI(GUIApplication& app, Context& context) + { + Prepare(app, context); + // A cached scope drawn from its capture didn't claim its swatches, but draws with them. + for (const ID id : app.ReplayedSwatches()) + context.gradientSwatches.KeepAlive(id); + context.gradientSwatches.NextFrame(app.styleManager); + } + + void Cleanup(GUIApplication& app, Context& context) + { + for (ID* id : { &context.picker.windowID, &context.gradientEditor.windowID }) + { + if (*id != ID::Invalid() && id->GetMode() == IDMode::Static) + app.idManager.ReleaseStaticID(*id); + *id = ID::Invalid(); + } + } +} diff --git a/src/gui_color/gui_color.h b/src/gui_color/gui_color.h new file mode 100644 index 00000000..2d92379a --- /dev/null +++ b/src/gui_color/gui_color.h @@ -0,0 +1,176 @@ +#pragma once + +// Color: the color field and its picker, the gradient field and its editor, and the shadow +// field. A library of its own on gui_controls, in namespace tachyon::color: each control is a +// free function that takes the application and a color::Context, which the app owns. +// +// color::Context colorContext; // a member of the app class +// +// color::ColorField(*this, colorContext, tint); +// color::EndGUI(*this, colorContext); // last in OnGUI +// color::Cleanup(*this, colorContext); // before GUIApplication::Cleanup + +#include +#include + +#include +#include +#include +#include + +namespace tachyon::color +{ + /// @addtogroup controls + /// @{ + + /// The color controls' styles, looked up in the theme after each load. + struct Styles + { + StyleRef colorSwatchStyleRef {}; ///< ColorField: the swatch + StyleRef colorFieldStyleRef {}; ///< ColorField: swatch, hex and alpha in a row + StyleRef colorHexStyleRef {}; ///< ColorField: the hex field + StyleRef colorAlphaStyleRef {}; ///< ColorField: the alpha box (value and %) + StyleRef colorAlphaInputStyleRef {}; ///< ColorField: the alpha value in its box + StyleRef colorAlphaUnitStyleRef {}; ///< ColorField: the % after it + StyleRef colorAlphaCaptionStyleRef {}; ///< ColorField: the "A" before it + StyleRef colorPickerStyleRef {}; ///< color picker: the window + StyleRef colorPickerHdrValueStyleRef {}; ///< color picker: the intensity value + StyleRef colorPickerBodyStyleRef {}; ///< color picker: planes and controls + StyleRef colorPickerPlanesStyleRef {}; ///< color picker: square and strips + StyleRef colorPickerSquareStyleRef {}; ///< color picker: the saturation/value square + StyleRef colorPickerStripStyleRef {}; ///< color picker: the hue and alpha strips + StyleRef colorPickerControlsStyleRef {}; ///< color picker: the right column + StyleRef colorPickerPreviewGroupStyleRef {}; ///< color picker: preview and captions + StyleRef colorPickerCaptionsStyleRef {}; ///< color picker: New / Original + StyleRef colorPickerCaptionStyleRef {}; ///< color picker: a small caption + StyleRef colorPickerModeRowStyleRef {}; ///< color picker: space, Linear, range + StyleRef colorPickerRangeStyleRef {}; ///< color picker: the 0-255 / 0-1 toggle + StyleRef colorPickerChannelsStyleRef {}; ///< color picker: the channel rows + StyleRef colorPickerChannelStyleRef {}; ///< color picker: one channel row + StyleRef colorPickerChannelLabelStyleRef {}; ///< color picker: R, G, B, A ... + StyleRef colorPickerTrackStyleRef {}; ///< color picker: a channel's track + StyleRef colorPickerChannelValueStyleRef {}; ///< color picker: a channel's value + StyleRef colorPickerFieldRowStyleRef {}; ///< color picker: Hex / HDR rows + StyleRef colorPickerRowLabelStyleRef {}; ///< color picker: Hex, HDR + StyleRef colorPickerHdrStyleRef {}; ///< color picker: the intensity box + StyleRef colorPickerSwatchesStyleRef {}; ///< color picker: swatches and recent + StyleRef colorPickerSwatchRowStyleRef {}; ///< color picker: one swatch row + StyleRef colorPickerSectionLabelStyleRef {}; ///< color picker: Swatches, Recent + StyleRef colorPickerSwatchStyleRef {}; ///< color picker: a swatch + StyleRef colorPickerRecentStyleRef {}; ///< color picker: a recent color + StyleRef colorPickerPreviewStyleRef {}; ///< color picker: the color preview + StyleRef colorPickerNewStyleRef {}; ///< color picker: the add-swatch button + StyleRef gradientSwatchStyleRef {}; ///< GradientField: the swatch + StyleRef gradientEditorStyleRef {}; ///< gradient editor: the window + StyleRef gradientEditorBarStyleRef {}; ///< gradient editor: the gradient bar with its stops + StyleRef gradientEditorPresetsStyleRef {}; ///< gradient editor: the presets row + StyleRef gradientEditorSectionLabelStyleRef {}; ///< gradient editor: Presets + StyleRef gradientEditorPresetStyleRef {}; ///< gradient editor: a preset chip + StyleRef gradientEditorBadgeStyleRef {}; ///< gradient editor: the selected stop's location + StyleRef gradientEditorColumnsStyleRef {}; ///< gradient editor: the two columns + StyleRef gradientEditorColumnStyleRef {}; ///< gradient editor: the left column + StyleRef gradientEditorRowStyleRef {}; ///< gradient editor: a labeled row + StyleRef gradientEditorHeadingStyleRef {}; ///< gradient editor: Color stop + StyleRef gradientEditorCountStyleRef {}; ///< gradient editor: 2 / 3 + StyleRef gradientEditorLabelStyleRef {}; ///< gradient editor: a row's label + StyleRef gradientEditorLocationStyleRef {}; ///< gradient editor: the location box + StyleRef gradientEditorLocationInputStyleRef {}; ///< gradient editor: its value + StyleRef gradientEditorLocationUnitStyleRef {}; ///< gradient editor: its % + StyleRef gradientEditorDividerStyleRef {}; ///< gradient editor: a divider line + StyleRef gradientEditorActionsStyleRef {}; ///< gradient editor: Reverse, Distribute + StyleRef gradientEditorTableStyleRef {}; ///< gradient editor: the stops table + StyleRef gradientEditorTableHeadStyleRef {}; ///< gradient editor: its header row + StyleRef gradientEditorTableRowStyleRef {}; ///< gradient editor: a stop's row + StyleRef gradientEditorTypeCellStyleRef {}; ///< gradient editor: Type + StyleRef gradientEditorSwatchCellStyleRef {}; ///< gradient editor: the stop's color + StyleRef gradientEditorHeadCellStyleRef {}; ///< gradient editor: a header caption + StyleRef gradientEditorHeadLocationStyleRef {}; ///< gradient editor: Location + StyleRef gradientEditorValueCellStyleRef {}; ///< gradient editor: the stop's hex + StyleRef gradientEditorLocationCellStyleRef {}; ///< gradient editor: the stop's location + + /// Looks them all up in `app`'s theme, after it loads. + void Load(GUIApplication& app); + }; + + /// What the color controls keep from frame to frame, the app's to own 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 + ColorPickerState picker; ///< the color picker, while a ColorField has it open + GradientEditorState gradientEditor; ///< the gradient editor, while a GradientField has it open + SwatchStyles gradientSwatches; ///< each GradientField's swatch + /// GradientField(Gradient&)'s gradient as given and as edited, kept for their storage. + GradientF gradientFieldGiven, gradientFieldEdited; + }; + + /// The color controls' styles in `app`'s theme, looked up again after each theme load. + const Styles& GetStyles(GUIApplication& app, Context& context); + + /// After everything the frame builds: lets the gradient fields' swatches no longer built + /// go. Call it last in OnGUI, every frame. + void EndGUI(GUIApplication& app, Context& context); + + /// Gives back what the color controls hold (their popup windows' IDs). Call it before + /// GUIApplication::Cleanup. + void Cleanup(GUIApplication& app, Context& context); + + /// A shadow: its color over its offsets (X, Y), blur and spread. A transparent color + /// is no shadow. True when the value changed. + /// BoxShadow shadow{ .y = 4, .blur = 12, .color = { 0, 0, 0, 90 } }; + /// ShadowField(app, context, app.idManager.AllocateDynamicID("shadow"), shadow); + bool ShadowField(GUIApplication& app, Context& context, ID id, BoxShadow& value, LayoutOverride&& constraints = {}); + + /// @name Color and gradient fields + ///@{ + + // ---- ColorField: swatch + color picker popup ---- + /// A color swatch that opens a color picker; true when the color changed. allowHDR lets + /// the picker take brightness over 1. + bool ColorField(GUIApplication& app, Context& context, ID id, tachyon::color4f& value, bool allowHDR, StyleRef style, LayoutOverride&& constraints = {}); + /// As above, in the theme's color field style. + inline bool ColorField(GUIApplication& app, Context& context, ID id, tachyon::color4f& value, bool allowHDR = false, LayoutOverride&& constraints = {}) { return ColorField(app, context, id, value, allowHDR, GetStyles(app, context).colorFieldStyleRef, std::move(constraints)); } + /// As above, with the call site as the ID. + inline bool ColorField(GUIApplication& app, Context& context, tachyon::color4f& value, bool allowHDR, StyleRef style, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return ColorField(app, context, app.idManager.AllocateDynamicID(site), value, allowHDR, style, std::move(constraints)); } + /// As above, with the call site as the ID, in the theme's color field style. + inline bool ColorField(GUIApplication& app, Context& context, tachyon::color4f& value, bool allowHDR = false, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return ColorField(app, context, app.idManager.AllocateDynamicID(site), value, allowHDR, GetStyles(app, context).colorFieldStyleRef, std::move(constraints)); } + /// As above, for an 8-bit color. + bool ColorField(GUIApplication& app, Context& context, ID id, tachyon::color4b& value, StyleRef style, LayoutOverride&& constraints = {}); + /// As above, in the theme's color field style. + inline bool ColorField(GUIApplication& app, Context& context, ID id, tachyon::color4b& value, LayoutOverride&& constraints = {}) { return ColorField(app, context, id, value, GetStyles(app, context).colorFieldStyleRef, std::move(constraints)); } + /// As above, with the call site as the ID. + inline bool ColorField(GUIApplication& app, Context& context, tachyon::color4b& value, StyleRef style, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return ColorField(app, context, app.idManager.AllocateDynamicID(site), value, style, std::move(constraints)); } + /// As above, with the call site as the ID, in the theme's color field style. + inline bool ColorField(GUIApplication& app, Context& context, tachyon::color4b& value, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return ColorField(app, context, app.idManager.AllocateDynamicID(site), value, GetStyles(app, context).colorFieldStyleRef, std::move(constraints)); } + /// The color picker's swatches, which the user adds to and removes from; set them to + /// start from the app's palette, read them to keep it. A palette of twelve to begin with. + void SetColorSwatches(GUIApplication& app, Context& context, std::span colors); + std::vector ColorSwatches(GUIApplication& app, Context& context); + /// Adds a color to the picker's recent ones, as OK does: newest first, each once, at + /// most 8. For colors the app restores from a previous run. + void AddRecentColor(GUIApplication& app, Context& context, tachyon::color4f color); + + // ---- GradientField: gradient swatch + editor popup ---- + /// A gradient swatch that opens a gradient editor; true when the gradient changed. + bool GradientField(GUIApplication& app, Context& context, ID id, tachyon::Gradient& value, StyleRef style, LayoutOverride&& constraints = {}); + /// As above, in the theme's gradient swatch style. + inline bool GradientField(GUIApplication& app, Context& context, ID id, tachyon::Gradient& value, LayoutOverride&& constraints = {}) { return GradientField(app, context, id, value, GetStyles(app, context).gradientSwatchStyleRef, std::move(constraints)); } + /// As above, with the call site as the ID. + inline bool GradientField(GUIApplication& app, Context& context, tachyon::Gradient& value, StyleRef style, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return GradientField(app, context, app.idManager.AllocateDynamicID(site), value, style, std::move(constraints)); } + /// As above, with the call site as the ID, in the theme's gradient swatch style. + inline bool GradientField(GUIApplication& app, Context& context, tachyon::Gradient& value, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return GradientField(app, context, app.idManager.AllocateDynamicID(site), value, GetStyles(app, context).gradientSwatchStyleRef, std::move(constraints)); } + /// As above, for a GradientF: up to GradientF::kMaxStops stops, colors over 1 (HDR), + /// and each stop's interpolation to the next. The swatch shows it clamped to 0..1. + bool GradientField(GUIApplication& app, Context& context, ID id, tachyon::GradientF& value, StyleRef style, LayoutOverride&& constraints = {}); + /// As above, in the theme's gradient swatch style. + inline bool GradientField(GUIApplication& app, Context& context, ID id, tachyon::GradientF& value, LayoutOverride&& constraints = {}) { return GradientField(app, context, id, value, GetStyles(app, context).gradientSwatchStyleRef, std::move(constraints)); } + /// As above, with the call site as the ID. + inline bool GradientField(GUIApplication& app, Context& context, tachyon::GradientF& value, StyleRef style, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return GradientField(app, context, app.idManager.AllocateDynamicID(site), value, style, std::move(constraints)); } + /// As above, with the call site as the ID, in the theme's gradient swatch style. + inline bool GradientField(GUIApplication& app, Context& context, tachyon::GradientF& value, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return GradientField(app, context, app.idManager.AllocateDynamicID(site), value, GetStyles(app, context).gradientSwatchStyleRef, std::move(constraints)); } + + ///@} + + /// @} +} diff --git a/src/gui_controls/subsystems/gui_color_picker_subsystem.h b/src/gui_color/gui_color_state.h similarity index 56% rename from src/gui_controls/subsystems/gui_color_picker_subsystem.h rename to src/gui_color/gui_color_state.h index bd41a55e..60323408 100644 --- a/src/gui_controls/subsystems/gui_color_picker_subsystem.h +++ b/src/gui_color/gui_color_state.h @@ -1,23 +1,23 @@ #pragma once -#include -#include -#include -#include +// What the color picker and the gradient editor keep while they're open, and what a gradient +// field's swatch keeps: part of color::Context. #include #include #include +#include #include -namespace tachyon +#include +#include +#include + +namespace tachyon::color { /// @addtogroup controls /// @{ - class FramePipeline; - struct FrameContext; - /// Persistent state of the color picker popup. The picker opens off a ColorField /// swatch (triggerID), edits a working copy, and writes the result back to the /// caller's color. It lives across frames so the popup keeps its tab, palette and @@ -90,33 +90,65 @@ namespace tachyon }; }; - /// The color picker popup's state plus swatch ColorStyles keyed by swatch ID. - /// Claimed styles are updated in place across frames; unclaimed ones belong to - /// vanished swatches and are destroyed next frame. The popup body is - /// GUIApplication::EmitColorPicker. - class ColorPickerSubsystem + /// What the gradient editor lets a field's gradient have: a Gradient's 8 stops of 8-bit + /// colors, or a GradientF's 64 of HDR ones, each blending to the next its own way. + struct GradientEditLimits { - public: - explicit ColorPickerSubsystem(FramePipeline& frame); + int maxStops = Gradient::kMaxStops; + bool hdr = false; ///< colors over 1 + bool perStopInterpolation = false; ///< each stop's StopInterpolation + }; - /// The picker popup's state. - ColorPickerState& State() { return m_state; } + /// Gradient editor popup state: edits a working copy, written back each frame it's open. + struct GradientEditorState + { + tachyon::ID triggerID = tachyon::ID::Invalid(); ///< swatch that opened the editor + tachyon::ID windowID = tachyon::ID::Invalid(); ///< popup window ID + tachyon::GradientF workingCopy {}; ///< the gradient being edited + GradientEditLimits limits {}; ///< what the field's gradient can have + int selectedStop = 0; ///< index into workingCopy.stops + tachyon::color4f selectedStopColor {}; ///< selected stop's color, for its ColorField + float selectedStopPosition = 0.0f; ///< selected stop's position, for its Field + + tachyon::GradientF originalGradient {}; ///< to restore on Cancel + tachyon::Gradient originalGradient8 {}; ///< a Gradient field's own, restored exactly + std::string context; ///< the field's label, shown after the title + + /// OK keeps the gradient, Cancel and the close button restore the original one. + /// Handled by the GradientField on its next frame. + enum class CloseRequest { None, Ok, Cancel } closeRequest = CloseRequest::None; + std::vector savedPresets; ///< "Save preset", for the session - /// The color style slot of swatch `swatchID`, kept alive this frame. Invalid for a new - /// swatch: the caller creates the style and stores it there, reused from then on. - tachyon::VisualColorStyleIndex& ClaimSwatchStyle(tachyon::ID swatchID); + /// What a stop's drag changes, as it was at the press; put back by Escape. + struct DragSnapshot + { + tachyon::GradientF gradient {}; + int selectedStop = 0; + }; + tachyon::Gesture press; ///< the press on a stop, a drag from the start + int dragStopIndex = -1; ///< the dragged stop, or -1 + float dragGrab = 0.0f; ///< cursor minus the stop's offset at the press, so it doesn't jump + bool dragOff = false; ///< dragged well below the bar: removed on release + + tachyon::VisualColorStyleIndex previewGradientStyle = tachyon::VisualColorStyleIndex::Invalid; + tachyon::VisualColorStyleIndex stopEdgeColor = tachyon::VisualColorStyleIndex::Invalid; + tachyon::VisualColorStyleIndex stopOutlineColor = tachyon::VisualColorStyleIndex::Invalid; + tachyon::VisualColorStyleIndex stopHaloColor = tachyon::VisualColorStyleIndex::Invalid; + }; - /// Carries `swatchID`'s style over without rebuilding it: a cache-hit scope - /// doesn't re-claim its swatches, but its blitted primitives still use them. - void KeepSwatchAlive(tachyon::ID swatchID); + /// What a GradientField's swatch keeps besides its style: the gradient it was drawn from, + /// so an unchanged one isn't sampled again, and what a click opens the editor with. + struct GradientFieldSwatch + { + tachyon::GradientF drawn {}; ///< the gradient as last drawn + bool drawnSet = false; + tachyon::Gradient original8 {}; ///< a Gradient field's own, restored exactly on Cancel + GradientEditLimits limits {}; + std::string context; ///< the field's label + }; - /// Drops every held style index without destroying it; call after a theme reload - /// (StyleManager::ClearAll), which already freed them. - void ForgetStyles(); + /// A gradient field's swatch: its style and what it keeps besides. + using GradientSwatch = SwatchStyles::Entry; - private: - ColorPickerState m_state{}; - SwatchStyles<> m_swatchStyles; - }; /// @} } diff --git a/src/gui_controls/controls.cpp b/src/gui_controls/controls.cpp index bf46c6d7..6fc42aad 100644 --- a/src/gui_controls/controls.cpp +++ b/src/gui_controls/controls.cpp @@ -124,9 +124,9 @@ namespace tachyon bool GUIApplication::Field(ID id, std::string& value, TextEditBehavior textEditBehavior, StyleRef style, LayoutOverride&& constraints) { - // Inside a node row, fill the body after the label so the node stays grid-aligned. - if (nodeRowFieldMinWidth > 0 && !constraints.HasFixedWidth()) - constraints.FlexGrow(1).MinWidth(Pixels{ nodeRowFieldMinWidth }); + // In a row that fills (SetFieldRowFill), fill the body after the label. + if (m_fieldRowFill > 0 && !constraints.HasFixedWidth()) + constraints.FlexGrow(1).MinWidth(Pixels{ m_fieldRowFill }); if (guiStateManager.Construction().IsIndeterminate()) { @@ -961,8 +961,8 @@ namespace tachyon // Its parts' IDs go under the switch's own, so they don't depend on what came before. [[maybe_unused]] const bool pushed = idManager.PushParent(id); - // Inside a node row it sits at the right, by its socket, where fields end. - if (nodeRowFieldMinWidth > 0) + // In a row that fills (SetFieldRowFill) it sits at the row's end, where fields end. + if (m_fieldRowFill > 0) { tachyon::Element spacer{}; spacer.id = idManager.AllocateDynamicID("switchSpacer"); @@ -1230,8 +1230,8 @@ namespace tachyon { for (ID swatchID : scope.claimedSwatches) { - m_colorPickerSub->KeepSwatchAlive(swatchID); - m_gradientEditorSub->KeepSwatchAlive(swatchID); + m_swatchSlots.KeepAlive(swatchID); + m_replayedSwatches.push_back(swatchID); } // Hit: leave the container empty; OnRender blits the cached primitives in its place. @@ -1257,16 +1257,17 @@ namespace tachyon VisualColorStyleIndex GUIApplication::AppColorStyle(ID owner, color4f color) { - NoteSwatchClaim(owner); - VisualColorStyleIndex& slot = m_colorPickerSub->ClaimSwatchStyle(owner); - const ColorStyle style = ColorStyle::Create(color); - if (slot == VisualColorStyleIndex::Invalid) - slot = styleManager.CreateColorStyle(style); - else - styleManager.UpdateColorStyle(slot, style); + VisualColorStyleIndex& slot = ClaimSwatchStyle(owner); + SetColorStyle(styleManager, slot, color); return slot; } + VisualColorStyleIndex& GUIApplication::ClaimSwatchStyle(ID owner) + { + NoteSwatchClaim(owner); + return m_swatchSlots.Claim(owner).index; + } + // Called for every BeginCached, hit or miss. void GUIApplication::EndCached() { @@ -1357,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_box_fields.cpp b/src/gui_controls/controls_box_fields.cpp index 0c0d54d5..091cd0ec 100644 --- a/src/gui_controls/controls_box_fields.cpp +++ b/src/gui_controls/controls_box_fields.cpp @@ -4,7 +4,7 @@ #include // Fields for a box's looks: EdgesField and CornersField, four numbers (one a side or a -// corner) with a link toggle that makes them one; ShadowField, a shadow's color and sizes. +// corner) with a link toggle that makes them one. namespace tachyon { @@ -98,45 +98,5 @@ namespace tachyon return BoxSidesField(id, sides, kCaptions, kNames, config, std::move(constraints)); } - bool GUIApplication::ShadowField(ID id, BoxShadow& value, LayoutOverride&& constraints) - { - bool modified = false; - BeginVertical(id, theme.emptyVertStyleRef, std::move(constraints)); - const bool pushed = idManager.PushParent(id); - - modified = ColorField(idManager.AllocateDynamicID("shadow_color"), value.color) || modified; - - // The offsets may be negative; the blur may not. - struct Part { std::string_view caption, name; int32_t value; int32_t min; }; - Part parts[] = { - { "X", "Horizontal offset", value.x, -256 }, - { "Y", "Vertical offset", value.y, -256 }, - { "Blur", "Blur radius", value.blur, 0 }, - { "Spread", "How far it grows past the box", value.spread, -256 }, - }; - RegisterElement(Element{ .id = idManager.AllocateDynamicID("shadow_sizes"), .styleRef = theme.fieldElementGroupStyleRef, - .flags = ElementFlags::PropagatesDescendantState }, LayoutOverride::Auto()); - VERIFY(elementStorage.BeginChildren()); - for (Part& part : parts) - { - DragLabel(idManager.AllocateDynamicID("shadow_caption"), part.caption, theme.axisLabelStyleRefs[3], - LayoutOverride::Auto().MinWidth(Pixels{ theme.axisLabelWidth }).NoGrow().KeepWithNext()); - SetTooltip(part.name); - modified = Field(idManager.AllocateDynamicID("shadow_size"), part.value, TextEditBehavior::ContinuousUpdate, - theme.vectorComponentStyleRef, - NumericFieldConfig{ .stepPerPixel = 0.25, .minVal = part.min, .maxVal = 256 }, - LayoutOverride::Auto().MinWidth(40)) || modified; - } - VERIFY(elementStorage.EndChildren()); - value.x = int16_t(std::clamp(parts[0].value, -256, 256)); - value.y = int16_t(std::clamp(parts[1].value, -256, 256)); - value.blur = uint16_t(std::clamp(parts[2].value, 0, 256)); - value.spread = int16_t(std::clamp(parts[3].value, -256, 256)); - - if (pushed) (void)idManager.PopParent(); - EndVertical(); - guiStateManager.SetModified(modified); - return modified; - } } diff --git a/src/gui_controls/controls_table.cpp b/src/gui_controls/controls_table.cpp deleted file mode 100644 index afed358b..00000000 --- a/src/gui_controls/controls_table.cpp +++ /dev/null @@ -1,124 +0,0 @@ -// Public table API: BeginTable/EndTable + BeginRow/EndRow. Thin recording -// shell - the real work happens when EndTable hands the recorded cells to -// VirtualTable (controls_table_virtual.cpp). -// -// Cell record-builders live in controls_table_cells.cpp; event-handler -// builders in controls_table_handlers.cpp; shared helpers in -// controls_table_internal.h. - -#include "controls_table_internal.h" - -#include -#include - -namespace tachyon -{ - using namespace tachyon::TableInternal; - - // BeginTable opens a recording. Cell()/TreeCell() push records onto - // m_tableEmit->columnCells; EndTable hands the populated optional to - // VirtualTable, which drains them per row. - bool GUIApplication::BeginTable(ID id, VirtualTableColumn* columns, size_t columnCount, - TableState& state, StyleRef style, - LayoutOverride&& constraints) - { - m_outerTableEmits.push_back(std::move(m_tableEmit)); - m_tableEmit.emplace(); - m_tableEmit->containerID = id; - m_tableEmit->columns = columns; - m_tableEmit->columnCount = columnCount; - m_tableEmit->userState = &state; - m_tableEmit->style = style; - m_tableEmit->constraints = std::move(constraints); - m_tableEmit->isRecording = true; - m_tableEmit->columnCells.assign(columnCount, {}); - - // Lazy-init persisted widths. - if (state.columnWidths.size() != columnCount) - { - state.columnWidths.assign(columnCount, 0); - for (size_t c = 0; c < columnCount; c++) - state.columnWidths[c] = columns[c].column.initialWidth.value; - } - - // Clamp persisted selectedColumn. - if (columnCount == 0) - state.selectedColumn = 0; - else if (state.selectedColumn < 0 || state.selectedColumn >= int(columnCount)) - state.selectedColumn = std::clamp(state.selectedColumn, 0, int(columnCount) - 1); - - // Reset per-column scratch on the user-owned VirtualTableColumn array. - // Cell()/TreeCell() grow internal.maxContentWidth during replay. - for (size_t c = 0; c < columnCount; c++) - { - columns[c].internal.maxContentWidth = 0; - columns[c].internal.headerRef = tachyon::ElementRef::Invalid(); - columns[c].internal.dragOffsetX = 0; - } - - // Reset per-frame maps for TreeCell; clear() keeps the buckets allocated. - if (state.internal.treeRowInfo) state.internal.treeRowInfo->clear(); - - return true; - } - - - void GUIApplication::EndTable() - { - if (!m_tableEmit.has_value() || !m_tableEmit->isRecording) - { - ReportMisuse("GUIApplication: EndTable without BeginTable (ignored)"); - return; - } - TableState& state = *m_tableEmit->userState; - VirtualTableColumn* columns = m_tableEmit->columns; - const size_t columnCount = m_tableEmit->columnCount; - const tachyon::ID containerID = m_tableEmit->containerID; - const StyleRef style = m_tableEmit->style; - tachyon::LayoutOverride constraints = std::move(m_tableEmit->constraints); - const int rowCount = m_tableEmit->rowCount; - const auto recorded = std::move(m_tableEmit->columnCells); - - // Replay the recorded cells through the same per-column path a - // direct VirtualTable caller drives with its own generateCell. - // The lambdas point into `recorded`, which outlives the call. - for (size_t c = 0; c < columnCount; c++) - { - columns[c].generateCell = [cells = &recorded[c]](int row) - { - if (row < 0 || size_t(row) >= cells->size()) return; - if (const auto& replay = (*cells)[size_t(row)]) replay(); - }; - } - - VirtualTable(containerID, state, std::span(columns, columnCount), - rowCount, /*rowHeight*/0, style, std::move(constraints)); - - for (size_t c = 0; c < columnCount; c++) - columns[c].generateCell = nullptr; - } - - - bool GUIApplication::BeginRow() - { - if (!m_tableEmit.has_value()) - { - ReportMisuse("GUIApplication: BeginRow outside a table (ignored)"); - return true; - } - m_tableEmit->currentCol = 0; - m_tableEmit->rowCount++; - return true; - } - - - void GUIApplication::EndRow() - { - if (!m_tableEmit.has_value()) - { - ReportMisuse("GUIApplication: EndRow outside a table (ignored)"); - return; - } - m_tableEmit->currentCol = 0; - } -} diff --git a/src/gui_controls/controls_table_internal.h b/src/gui_controls/controls_table_internal.h deleted file mode 100644 index fd4bc7c5..00000000 --- a/src/gui_controls/controls_table_internal.h +++ /dev/null @@ -1,90 +0,0 @@ -#pragma once - -// Helpers shared between controls_table.cpp, controls_table_cells.cpp and -// controls_table_handlers.cpp. Internal - not in gui_application.h. - -#include - -#include - -namespace tachyon::TableInternal -{ - // Hit-strip width of an active (draggable) sizer overlay (CSS pixels). - constexpr int32_t kActiveSizerWidth = 4; - // Cross-axis size for full-height sizers/separators (clipped by parent). - constexpr int32_t kStretchHeight = 32768; - - - // Double-click / slow-re-click tracker; each TableState holds its own. - using DoubleClickTracker = tachyon::DoubleClickTracker; - - - // Column GridTrack: 1fr when stretchy, else Fixed. The table's last column - // turns Fixed during a column drag so cells don't paint under the V scrollbar. - // columnWidths are CSS pixels (laid out at the UI scale); lastColDragFixedWidth is pixels. - inline GridTrack ComputeColumnTrack(const StyleManager& sm, - int c, - int globalColumnCount, - const tachyon::VirtualTableColumn* /*columns*/, - const std::vector& columnWidths, - bool dragActive, - int32_t lastColDragFixedWidth, - bool isStretch) - { - const bool isLastGlobal = (c + 1 == globalColumnCount); - const float width = static_cast(sm.Px(columnWidths[c])); - if (isStretch) - { - if (isLastGlobal && dragActive) - return GridTrack::Fixed(static_cast(lastColDragFixedWidth)); - return GridTrack::Fractional(1.0f, width); - } - return GridTrack::Fixed(width); - } - - // Overload with implicit stretch on the table's last column. Frozen mode passes - // `isStretch` explicitly (only the middle section's last column stretches). - inline GridTrack ComputeColumnTrack(const StyleManager& sm, int c, int globalColumnCount, - const tachyon::VirtualTableColumn* columns, - const std::vector& columnWidths, - bool dragActive, int32_t lastColDragFixedWidth) - { - const bool isLastGlobal = (c + 1 == globalColumnCount); - const bool isStretch = isLastGlobal - || columns[c].column.sizing == tachyon::ColumnSizing::Stretch; - return ComputeColumnTrack(sm, c, globalColumnCount, columns, columnWidths, - dragActive, lastColDragFixedWidth, isStretch); - } - - // Persistent hover/focus state for the cell ID + cell-mode Selected. - // Callers add NoInput themselves when needed (Cell does in row mode; - // TreeCell stays hittable so its arrow/text can be clicked). - struct CellStateBits - { - tachyon::ElementState state; - bool selected; - }; - - inline CellStateBits ComputeCellSelectionBits(GUIStateManager& sm, - const tachyon::TableState* userState, - tachyon::ID cellID, tachyon::ID currentRowID, - int c, bool cellMode) - { - tachyon::ElementState st = sm.GetCurrentState(cellID); - const bool selected = cellMode - && userState->selectedRowID == currentRowID - && userState->selectedColumn == c; - if (selected) st |= tachyon::ElementState::Selected; - return { st, selected }; - } -} - -namespace tachyon -{ - // Tree-cell flex-row children - emitted at drain time by EndTable's - // body-section drain. Defined in controls_table_cells.cpp. - void EmitTreeCellIndent(GUIApplication& app, int depth); - void EmitTreeCellArrowOrLeafSpacer(GUIApplication& app, TreeOpenRef isOpen); - void EmitTreeCellIcon(GUIApplication& app, IconID icon, TreeOpenRef isOpen, - tachyon::DoubleClickTracker* tracker); -} 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/controls_tooltips_menus.cpp b/src/gui_controls/controls_tooltips_menus.cpp index c3f8b489..6bac218b 100644 --- a/src/gui_controls/controls_tooltips_menus.cpp +++ b/src/gui_controls/controls_tooltips_menus.cpp @@ -155,40 +155,11 @@ namespace tachyon CloseTooltip(); } - void GUIApplication::ShowPinTooltip(const NodeGraph& view, ID socketID, PropertyEndpoint pin, bool isOutput) - { - const NodeProperty& prop = view.nodes[size_t(pin.nodeIdx)].properties[size_t(pin.propIdx)]; - if ((prop.name.empty() && prop.type.empty() && !prop.value) || !OpenTooltip(socketID, TooltipBox::Lines)) - return; - auto line = [this](std::string_view text, StyleRef style) { - if (!text.empty()) - RegisterElement(tachyon::Element{ .id = idManager.AllocateDynamicID(), .styleRef = style, - .flags = ElementFlags::NoInput }, text, LayoutOverride{}); - }; - // "Strength float 0.75" - RegisterElement(tachyon::Element{ .id = idManager.AllocateDynamicID(), .styleRef = theme.tooltipPinRowStyleRef, - .flags = ElementFlags::NoInput }, LayoutOverride{}); - VERIFY(elementStorage.BeginChildren()); - line(prop.name, theme.tooltipTextStyleRef); - line(prop.type, theme.tooltipPinTypeStyleRef); - if (prop.value) - line(prop.value(), theme.tooltipPinValueStyleRef); - VERIFY(elementStorage.EndChildren()); - // "from Source.Value" - if (!isOutput && prop.input && prop.input->valid() && size_t(prop.input->nodeIdx) < view.nodes.size()) - { - const NodeModel& source = view.nodes[size_t(prop.input->nodeIdx)]; - std::string from = "from " + source.title; - if (size_t(prop.input->propIdx) < source.properties.size() && !source.properties[size_t(prop.input->propIdx)].name.empty()) - from += "." + source.properties[size_t(prop.input->propIdx)].name; - line(from, theme.tooltipNoteStyleRef); - } - CloseTooltip(); - } + bool GUIApplication::BeginTooltip(ID targetID) { return BeginTooltip(targetID, TooltipBox::Plain); } - bool GUIApplication::BeginTooltip(ID targetID) + bool GUIApplication::BeginTooltip(ID targetID, TooltipBox box) { - const bool open = OpenTooltip(targetID); + const bool open = OpenTooltip(targetID, box); m_tooltipOpen.push_back(open); return open; } 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..5dfd8283 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 @@ -245,11 +244,7 @@ namespace tachyon m_menuRects = std::make_unique(); m_labelGroup = std::make_unique(m_frame, elementStorage, guiStateManager, theme); m_buttonGroup = std::make_unique(m_frame, elementStorage, styleManager); - m_colorPickerSub = std::make_unique(m_frame); - m_gradientEditorSub = std::make_unique(m_frame); - m_renameSub = std::make_unique(); m_reorderable = std::make_unique(m_frame); - m_dockTabDragSub = std::make_unique(); m_uiCache = std::make_unique(m_frame, elementStorage, guiStateManager); RegisterFrameBalanceChecks(); @@ -284,47 +279,13 @@ namespace tachyon void GUIApplication::RegisterFrameHooks() { - // Keyed by item ID, so every list/grid view in a frame shares them; end-of-frame - // handlers read them, so they're only reset when the next frame's construction starts. - m_frame.OnPreConstruct([this](FrameContext&) + // The swatches not claimed last frame go, and so does the list of those replayed. + m_frame.OnPreFrame([this](FrameContext& ctx) { - m_listItemIndexByID.clear(); - m_gridItemRenameByID.clear(); + m_swatchSlots.NextFrame(ctx.styleManager); + m_replayedSwatches.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) @@ -339,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 @@ -354,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 @@ -371,12 +338,6 @@ namespace tachyon m_tooltipOpen.clear(); m_cachedOpen.clear(); } - if (m_tableEmit.has_value() || !m_outerTableEmits.empty()) - { - ReportMisuse("GUIApplication: unbalanced BeginTable/EndTable at end of frame (closed)"); - m_tableEmit.reset(); - m_outerTableEmits.clear(); - } if (!m_cacheRecordStack.empty()) { ReportMisuse("GUIApplication: unbalanced BeginCached/EndCached at end of frame (closed)"); @@ -397,26 +358,11 @@ namespace tachyon Diagnostics::ReportMisuse(kLogApp, "GUIApplication: unbalanced BeginWindow/EndWindow at end of frame (closed)"); m_windowIdScopeStack.clear(); } - if (m_treeState.containerID != ID::Invalid()) - { - Diagnostics::ReportMisuse(kLogApp, "GUIApplication: unbalanced BeginListView/BeginTreeView/EndListView at end of frame (closed)"); - m_treeState = {}; - } - if (m_gridViewState.containerID != ID::Invalid()) - { - Diagnostics::ReportMisuse(kLogApp, "GUIApplication: unbalanced BeginGridView/EndGridView at end of frame (closed)"); - m_gridViewState = {}; - } if (m_tabBarState.barID != ID::Invalid()) { 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)"); @@ -425,12 +371,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,13 +380,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()) - CloseFloatingDockWindow(m_floatingDockWindows.size() - 1); - auto release = [this](ID& id) { if (id != ID::Invalid() && id.GetMode() == IDMode::Static) idManager.ReleaseStaticID(id); @@ -455,15 +388,12 @@ namespace tachyon release(tooltipWindowID); release(contextMenuWindowID); release(tabDragGhostWindowID); - release(m_colorPickerSub->State().windowID); - release(m_gradientEditorSub->State().windowID); m_autocomplete.ForEach([&](ID, AutocompleteState& state) { release(state.listWindowID); }); m_autocomplete.Clear(); for (RetiredWindow& retired : m_retiredWindows) 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() @@ -471,8 +401,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,33 +443,13 @@ 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 }; } - 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 @@ -763,14 +671,12 @@ 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_colorPickerSub->ForgetStyles(); - m_gradientEditorSub->ForgetStyles(); + m_swatchSlots.Forget(); // ClearAll freed their styles if (textSystem) textSystem->ClearCache(); m_themeReload = InitializeStyles(); bool loaded = m_themeReload.HasValue(); @@ -1816,7 +1722,7 @@ namespace tachyon .elapsedTimeSecs = elapsedTimeSecs, }; - m_frame.RunStage(FrameStage::PreFrame, ctx); + RunStage(FrameStage::PreFrame, ctx); ApplyPendingStyleReload(); @@ -1857,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); @@ -1892,7 +1798,7 @@ namespace tachyon windowRegistry.Clear(); guiStateManager.Cursor().Clear(); - m_frame.RunStage(FrameStage::PreConstruct, ctx); + RunStage(FrameStage::PreConstruct, ctx); } // *** @@ -1904,7 +1810,7 @@ namespace tachyon { TACHYON_PROFILE_SCOPE("EndFrame"); - m_frame.RunStage(FrameStage::PostConstruct, ctx); + RunStage(FrameStage::PostConstruct, ctx); ShowCutShortText(); tooltipManager.EndFrame(); @@ -1935,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); @@ -1949,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); @@ -2012,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(); @@ -2223,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 242d3689..e36278b2 100644 --- a/src/gui_controls/gui_application.h +++ b/src/gui_controls/gui_application.h @@ -1,11 +1,11 @@ #pragma once #include +#include #include #include #include #include -#include #include #include #include @@ -63,31 +63,21 @@ #include #include #include -#include +#include #include #include -#include -#include -#include -#include #include #include +#include #include -#include -#include -#include -#include -#include #include #include #include -#include -#include +#include #include #include -#include namespace tachyon { @@ -209,11 +199,7 @@ namespace tachyon std::unique_ptr m_menuRects; std::unique_ptr m_labelGroup; std::unique_ptr m_buttonGroup; - std::unique_ptr m_colorPickerSub; - std::unique_ptr m_gradientEditorSub; - std::unique_ptr m_renameSub; std::unique_ptr m_reorderable; - std::unique_ptr m_dockTabDragSub; ToolbarWindowDragSubsystem m_toolbarWindowDrag{}; std::unique_ptr m_uiCache; @@ -262,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 ///@{ @@ -703,101 +588,6 @@ namespace tachyon inline bool Toggle( bool& value, const GUIContent& content, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return Toggle(idManager.AllocateDynamicID(site), value, content, [&value](bool newValue){ value = newValue; }, theme.controls->toggle, std::move(constraints)); } - ///@} - - /// @name Timeline - ///@{ - - /// Playback on one row: go to the start, step back a frame, play or pause, step on a - /// frame, go to the end and loop; the time and frame; and a scrubber with ticks (every - /// second when there's room), the `progress` fill, a line per marker and the playhead. - /// A press or drag on the scrubber moves the playhead there, onto a frame. Keys on the - /// focused scrubber: Space plays or pauses, Left / Right step a frame, Page Down / - /// Page Up go to the previous / next marker, Home / End to the ends; Escape during a - /// drag puts the playhead back. A step is a frame, or a hundredth of the length - /// without frames; stepping pauses. - /// Edits `state`; the app moves it on while it plays (AdvanceTimeline). Returns true - /// on the frame the user changed it. - bool Timeline(ID id, TimelineState& state, const TimelineOptions& options, LayoutOverride&& constraints = {}); - /// As above, with the call site as the ID. - inline bool Timeline( TimelineState& state, const TimelineOptions& options, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return Timeline(idManager.AllocateDynamicID(site), state, options, std::move(constraints)); } - - /// A timeline editor over `view`: a toolbar (the transport, with the previous and next - /// key in place of the frame steps; the time; the frame rate; Snap; zoom), the track - /// list beside the ruler and the lanes, and a scroll bar under them. - /// - The track list: groups (a chevron, a color chip, eye and lock), properties (a - /// button to key them at the playhead), audio (mute, solo) and events; a filter and - /// an add button (`onAddTrack`) over it; a right click opens `onTrackContextMenu`. - /// - The ruler: a press or drag moves the playhead; Shift + drag sets the loop range, - /// its ends drag, Ctrl + click clears it. - /// - The lanes: keys (a group's summed up), audio clips with their waveform, events. - /// A click selects a key (Shift adds, Ctrl toggles), a drag on the empty lanes - /// selects those in a box, and a drag on a selected key moves them all, onto frames - /// while Snap is on; Escape puts them back. - /// - Over the ruler and the lanes, the wheel zooms round the pointer and Shift + the - /// wheel pans; a drag with the right button pans along the time and scrolls the - /// rows. - /// - Keys on the focused lanes: Delete removes the selected keys, Left / Right move - /// them a frame, Ctrl+A selects them all, K keys the selected track at the playhead, - /// Space plays or pauses, Home / End go to the ends, Escape clears the selection. - /// Every change to the tracks or the loop range is a TimelineEdit, handed to the data's - /// `onEdit` for undo; the playhead and selection change directly. `view` is a - /// TimelineView, or `{ data, state }` for one of several editors of the same tracks. - void TimelineEditor(ID id, TimelineViewRef view, LayoutOverride&& constraints = {}); - /// As above, with the call site as the ID. - inline void TimelineEditor( TimelineViewRef view, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { TimelineEditor(idManager.AllocateDynamicID(site), view, std::move(constraints)); } - - ///@} - - /// @name Curves - ///@{ - - /// A curve in a box, over the curves' range: a click opens the curve editor (CurveEditor) - /// in a window under it. Every change comes to the curves' `onEdit`, already applied. - /// True on the frame after a change made in it, as a field's is. `view` is a CurveView, - /// or `{ data, state }` for one of several views of the same curves. - /// CurveView falloff; // a member: one channel, keys over 0 to 1 - /// Label("Falloff"); - /// CurveField(idManager.AllocateDynamicID("falloff"), falloff); - bool CurveField(ID id, CurveViewRef view, LayoutOverride&& constraints = {}); - /// As above, with the call site as the ID. - inline bool CurveField( CurveViewRef view, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return CurveField(idManager.AllocateDynamicID(site), view, std::move(constraints)); } - - /// The curve editor a CurveField opens, as a control of its own: the channels and the - /// selected key's time and value over the plot; the keys, their tangent handles and the - /// grid on it; the presets and the wrap modes under it. - void CurveEditor(ID id, CurveViewRef view, LayoutOverride&& constraints = {}); - /// As above, with the call site as the ID. - inline void CurveEditor( CurveViewRef view, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { CurveEditor(idManager.AllocateDynamicID(site), view, std::move(constraints)); } - - /// Series of values as lines, bars or areas over the x range (a histogram's channels), - /// with a chip per series to show one on its own, the values under the pointer, and - /// handles dragged along x under the plot. True on the frame after a handle moved in - /// it. `view` is a PlotView, or `{ data, state }` for one of several views of a plot. - /// - /// PlotView levels; // a member - /// levels.series = { PlotSeries{ .name = "Luma", .values = HistogramBins(lumas, 256) } }; - /// levels.handles = { { "Black", 0.0f }, { "White", 1.0f } }; - /// if (Plot(idManager.AllocateDynamicID("levels"), levels)) - /// ApplyLevels(levels.handles[0].x, levels.handles[1].x); - bool Plot(ID id, PlotViewRef view, LayoutOverride&& constraints = {}); - /// As above, with the call site as the ID. - inline bool Plot( PlotViewRef view, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return Plot(idManager.AllocateDynamicID(site), view, std::move(constraints)); } - - /// A 3D view: the app's scene, drawn by `view.onRender` into an image the library keeps - /// at the view's size, a camera the mouse moves round it, the move, rotate and scale - /// gizmos over the selection, the tools down the left and the axes at the top right. - /// True on the frame after a gizmo's drag changed the selection. - /// - /// ViewportView scene; // a member - /// scene.onRender = [this](const ViewportRenderContext& ctx) { DrawScene(ctx); }; - /// scene.onClick = [this](const Ray& ray, KeyModifier) { Pick(ray); }; - /// if (Viewport(idManager.AllocateDynamicID("scene"), scene, LayoutOverride{}.FlexGrow(1))) - /// MoveSelected(scene.selection); - bool Viewport(ID id, ViewportView& view, LayoutOverride&& constraints = {}); - /// As above, with the call site as the ID. - inline bool Viewport( ViewportView& view, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return Viewport(idManager.AllocateDynamicID(site), view, std::move(constraints)); } - ///@} /// @name Menus and message dialogs @@ -961,6 +751,11 @@ namespace tachyon /// A tooltip with any content on targetID: build it while this returns true. /// EndTooltip is called either way. bool BeginTooltip(ID targetID); + /// A tooltip's box: the plain one; a few lines; property help's, on the popup surface; an + /// error's, on the popup surface with an error border. + enum class TooltipBox : uint8_t { Plain, Lines, Help, Error }; + /// As above, in the `box` look (a few lines, say). + bool BeginTooltip(ID targetID, TooltipBox box); /// As above, on the control just drawn. inline bool BeginTooltip() { return BeginTooltip(elementStorage.GetLastItemID()); } /// Closes BeginTooltip; called whether or not it returned true. @@ -1059,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 = {}); @@ -1111,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); ///@} @@ -1200,84 +996,9 @@ namespace tachyon ///@} - /// @name List and tree views + /// @name Drag and drop, and the states controls are built in ///@{ - // ---- ListView: scrollable list with selectable items ---- - /// Opens a list view of ListItems. selectedIndex (optional) holds the selection, which a - /// click or Up / Down changes; itemCount bounds the keys. dragDrop (optional) lets items be dragged. - bool BeginListView(ID id, int* selectedIndex, int itemCount, ItemDragDropConfig* dragDrop, StyleRef style, LayoutOverride&& constraints = {}); - /// As above, without drag and drop. - inline bool BeginListView(ID id, int* selectedIndex, int itemCount, StyleRef style, LayoutOverride&& constraints = {}) { return BeginListView(id, selectedIndex, itemCount, nullptr, style, std::move(constraints)); } - /// As above, without drag and drop, in the theme's list style. - inline bool BeginListView(ID id, int* selectedIndex, int itemCount, LayoutOverride&& constraints = {}) { return BeginListView(id, selectedIndex, itemCount, nullptr, theme.listViewStyleRef, std::move(constraints)); } - /// As above, with the call site as the ID. - inline bool BeginListView( int* selectedIndex, int itemCount, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return BeginListView(idManager.AllocateDynamicID(site), selectedIndex, itemCount, nullptr, theme.listViewStyleRef, std::move(constraints)); } - /// As above, with drag and drop, in the theme's list style. - inline bool BeginListView(ID id, int* selectedIndex, int itemCount, ItemDragDropConfig* dragDrop, LayoutOverride&& constraints = {}) { return BeginListView(id, selectedIndex, itemCount, dragDrop, theme.listViewStyleRef, std::move(constraints)); } - /// As above, with the call site as the ID. - inline bool BeginListView( int* selectedIndex, int itemCount, ItemDragDropConfig* dragDrop, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return BeginListView(idManager.AllocateDynamicID(site), selectedIndex, itemCount, dragDrop, theme.listViewStyleRef, std::move(constraints)); } - /// As above, with the call site as the ID, in `style`. - inline bool BeginListView( int* selectedIndex, int itemCount, ItemDragDropConfig* dragDrop, StyleRef style, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return BeginListView(idManager.AllocateDynamicID(site), selectedIndex, itemCount, dragDrop, style, std::move(constraints)); } - /// As above, without drag and drop, with the call site as the ID, in `style`. - inline bool BeginListView( int* selectedIndex, int itemCount, StyleRef style, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return BeginListView(idManager.AllocateDynamicID(site), selectedIndex, itemCount, nullptr, style, std::move(constraints)); } - /// Closes BeginListView. - void EndListView(); - - /// A list item's index by ID, for end-of-frame handlers; -1 if unknown. Filled only for - /// lists with drag and drop. - int FindListItemIndex(tachyon::ID id) const; - - /// One item of a list view, drawn selected when it is the selected index. True when clicked. - bool ListItem(ID id, const GUIContent& content, StyleRef style, LayoutOverride&& constraints = {}); - /// As above, in the theme's item style. - inline bool ListItem(ID id, const GUIContent& content, LayoutOverride&& constraints = {}) { return ListItem(id, content, theme.listItemStyleRef, std::move(constraints)); } - /// As above, with the call site as the ID. - inline bool ListItem( const GUIContent& content, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return ListItem(idManager.AllocateDynamicID(site), content, theme.listItemStyleRef, std::move(constraints)); } - /// As above, with the call site as the ID, in `style`. - inline bool ListItem( const GUIContent& content, StyleRef style, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return ListItem(idManager.AllocateDynamicID(site), content, style, std::move(constraints)); } - - - /// Recomputes skipCount / ancestorLineMask / isLastSibling from row depths. - /// Call after any structural change. O(n^2) worst case. - static void RebuildTreeViewIndex(std::vector& rows); - - /// Writes the flat indices of the rows shown to visibleIdx: those under no closed - /// branch, the open ones being in `openRows` (by TreeViewRowKey). - static void WalkTreeViewVisibility(const std::vector& rows, - const std::unordered_set& openRows, - std::vector& visibleIdx); - /// As above, for a tree drawn by a table with `state`, open as its openRows says: when - /// rows were opened or closed, its selection stays on the same rows (row IDs are - /// visible positions). For a tree built on VirtualTable directly; VirtualTreeView does - /// this itself. - static void WalkTreeViewVisibility(const std::vector& rows, - std::vector& visibleIdx, TableState& state); - /// The TreeCell open state of flat row `flat` in the view with `state`: its key in - /// state.openRows, or nothing for a row without children. - static TreeOpenRef TreeViewOpenRef(const std::vector& rows, size_t flat, TableState& state) - { - const TreeViewRow& row = rows[flat]; - return row.HasChildren() ? TreeOpenRef{ .set = &state.openRows, .key = TreeViewRowKey(row, flat) } : TreeOpenRef{}; - } - - /// Single-column virtualized tree view (a VirtualTable with one TreeCell column). - /// A non-empty header shows the header row. - void VirtualTreeView(ID id, - std::vector& rows, - std::vector& visibleIdx, - TableState& state, - StyleRef style = {}, - LayoutOverride&& constraints = {}, - std::string_view header = {}); - /// As above, with the call site as the ID. - inline void VirtualTreeView(std::vector& rows, std::vector& visibleIdx, TableState& state, - StyleRef style = {}, LayoutOverride&& constraints = {}, std::string_view header = {}, - std::source_location site = std::source_location::current()) - { VirtualTreeView(idManager.AllocateDynamicID(site), rows, visibleIdx, state, style, std::move(constraints), header); } - - /// The tree row a drag is over (drives the drop indicator), or Invalid. - ID TreeDropTargetRow() const { return m_treeDropState.targetRowID; } /// Whether files or text from another application are dragged over one of the app's /// windows. What's dragged is known only once it's dropped. @@ -1337,179 +1058,6 @@ namespace tachyon ///@} - /// @name Grid views - ///@{ - - // ---- GridView: 2D icon grid (like file explorer) ---- - /// Opens a grid view of GridViewItems. selectedIndex (optional) holds a single selection, - /// multiSelect (optional) a multi-selection; dragDrop (optional) lets items be dragged. - /// Arrow keys move the selection. - bool BeginGridView(ID id, int* selectedIndex, StyleRef style, MultiSelectState* multiSelect = nullptr, ItemDragDropConfig* dragDrop = nullptr, LayoutOverride&& constraints = {}); - /// As above, in the theme's grid style. - inline bool BeginGridView(ID id, int* selectedIndex = nullptr, MultiSelectState* multiSelect = nullptr, ItemDragDropConfig* dragDrop = nullptr, LayoutOverride&& constraints = {}) { return BeginGridView(id, selectedIndex, theme.gridViewStyleRef, multiSelect, dragDrop, std::move(constraints)); } - /// As above, with the call site as the ID, in `style`. - inline bool BeginGridView(int* selectedIndex, StyleRef style, MultiSelectState* multiSelect = nullptr, ItemDragDropConfig* dragDrop = nullptr, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return BeginGridView(idManager.AllocateDynamicID(site), selectedIndex, style, multiSelect, dragDrop, std::move(constraints)); } - /// As above, with the call site as the ID, in the theme's grid style. - inline bool BeginGridView(int* selectedIndex, MultiSelectState* multiSelect = nullptr, ItemDragDropConfig* dragDrop = nullptr, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return BeginGridView(idManager.AllocateDynamicID(site), selectedIndex, theme.gridViewStyleRef, multiSelect, dragDrop, std::move(constraints)); } - /// Closes BeginGridView. - void EndGridView(); - - /// renameBuffer (optional) enables in-place rename: F2, Ctrl+Shift+Click or a slow - /// re-click opens an editor. Enter commits; Escape or focus loss cancels. - bool GridViewItem(ID id, const GUIContent& content, - tachyon::ElementState extraState = tachyon::ElementState::None, - std::string* renameBuffer = nullptr, - StyleRef itemStyle = {}, - LayoutOverride&& constraints = {}); - /// As above, without rename. - inline bool GridViewItem(ID id, const GUIContent& content, LayoutOverride&& constraints) - { return GridViewItem(id, content, tachyon::ElementState::None, nullptr, {}, std::move(constraints)); } - /// As above, with the call site as the ID. - inline bool GridViewItem(const GUIContent& content, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) - { return GridViewItem(idManager.AllocateDynamicID(site), content, tachyon::ElementState::None, nullptr, {}, std::move(constraints)); } - /// Without rename, in `style`. - inline bool GridViewItem(ID id, const GUIContent& content, StyleRef style, LayoutOverride&& constraints = {}) - { return GridViewItem(id, content, tachyon::ElementState::None, nullptr, style, std::move(constraints)); } - /// Without rename, with the call site as the ID, in `style`. - inline bool GridViewItem(const GUIContent& content, StyleRef style, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) - { return GridViewItem(idManager.AllocateDynamicID(site), content, tachyon::ElementState::None, nullptr, style, std::move(constraints)); } - - /// Whether an inline rename editor (a grid item's, a tree row's) is open; an app that - /// sorts by name re-sorts once it closes. - bool IsRenaming() const { return m_renameSub && m_renameSub->isActive; } - - - /// generateItem(index, itemID) must emit exactly one cell, typically GridViewItem(itemID, ...). - /// itemID is a stable ranged sub-ID (index = id.value.subRangeParts.index), used for - /// selection and drag payloads. Cells are cellSize, with a 4px gap between columns. - void VirtualGridView(ID id, GridViewVirtualState& vstate, - int itemCount, int2 cellSize, - const std::function& generateItem, - int* selectedIndex = nullptr, - MultiSelectState* multiSelect = nullptr, - ItemDragDropConfig* dragDrop = nullptr, - StyleRef scrollStyle = {}, - StyleRef rowStyle = {}, - LayoutOverride&& constraints = {}); - /// As above, with the call site as the ID. - inline void VirtualGridView(GridViewVirtualState& vstate, int itemCount, int2 cellSize, - const std::function& generateItem, - int* selectedIndex = nullptr, MultiSelectState* multiSelect = nullptr, - ItemDragDropConfig* dragDrop = nullptr, StyleRef scrollStyle = {}, StyleRef rowStyle = {}, - LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) - { VirtualGridView(idManager.AllocateDynamicID(site), vstate, itemCount, cellSize, generateItem, selectedIndex, multiSelect, dragDrop, scrollStyle, rowStyle, std::move(constraints)); } - - ///@} - - /// @name Tables - ///@{ - - // ---- Table: row x column data grid ---- - /// Opens a table. Columns are described each frame; widths, selection and sort state - /// live in the caller's TableState. Rows are BeginRow / EndRow with Cell(text) or - /// Cell(emit); EndTable builds them as a VirtualTable. `columns` must stay valid until - /// EndTable. - bool BeginTable(ID id, VirtualTableColumn* columns, size_t columnCount, - TableState& state, StyleRef style, - LayoutOverride&& constraints = {}); - /// As above, in the theme's table style. - inline bool BeginTable(ID id, VirtualTableColumn* columns, size_t columnCount, - TableState& state, LayoutOverride&& constraints = {}) - { return BeginTable(id, columns, columnCount, state, theme.tableStyleRef, std::move(constraints)); } - /// As above, for a C array of columns. - template - inline bool BeginTable(ID id, VirtualTableColumn (&columns)[N], TableState& state, - StyleRef style, LayoutOverride&& constraints = {}) - { return BeginTable(id, columns, N, state, style, std::move(constraints)); } - /// As above, for a C array of columns, in the theme's table style. - template - inline bool BeginTable(ID id, VirtualTableColumn (&columns)[N], TableState& state, - LayoutOverride&& constraints = {}) - { return BeginTable(id, columns, N, state, theme.tableStyleRef, std::move(constraints)); } - /// As above, with the call site as the ID. - inline bool BeginTable(VirtualTableColumn* columns, size_t columnCount, TableState& state, StyleRef style, - LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) - { return BeginTable(idManager.AllocateDynamicID(site), columns, columnCount, state, style, std::move(constraints)); } - /// As above, with the call site as the ID, in the theme's table style. - inline bool BeginTable(VirtualTableColumn* columns, size_t columnCount, TableState& state, - LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) - { return BeginTable(idManager.AllocateDynamicID(site), columns, columnCount, state, theme.tableStyleRef, std::move(constraints)); } - /// As above, for a C array of columns, with the call site as the ID. - template - inline bool BeginTable(VirtualTableColumn (&columns)[N], TableState& state, StyleRef style, - LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) - { return BeginTable(idManager.AllocateDynamicID(site), columns, N, state, style, std::move(constraints)); } - /// As above, for a C array of columns, with the call site as the ID, in the theme's table style. - template - inline bool BeginTable(VirtualTableColumn (&columns)[N], TableState& state, - LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) - { return BeginTable(idManager.AllocateDynamicID(site), columns, N, state, theme.tableStyleRef, std::move(constraints)); } - /// Builds the recorded rows as a VirtualTable. - void EndTable(); - - /// Starts a row; its Cells fill the columns in order. - bool BeginRow(); - /// Ends the row. - void EndRow(); - - /// Cells auto-advance to the next column. - void Cell(std::string_view text); - - /// Custom-content cell: `emit` runs inside the cell during EndTable, so its - /// captures must live until then. - void Cell(std::function emit); - - /// Tree-style first column: [indent][arrow or spacer][optional icon][text]. - /// - /// depth horizontal indent (pixels = depth * theme.treeTableIndent). - /// isOpen where the row's open state lives: empty for leaves (no - /// arrow), else a bool of yours or a view's open rows (see - /// TreeViewOpenRef). Clicks toggle it. - /// icon optional leading icon rendered between arrow and text. - /// ancestorLineMask bit d set iff the ancestor at depth d+1 has a next sibling - /// (its guide line passes through this row at column d). - /// isLastSibling true -> own-depth L-tick stops at row center. - /// renameBuffer optional; enables in-place rename (F2 / Ctrl+Shift+Click / slow re-click). - /// reserveExpander false drops the arrow slot for leaves (for flat trees). - /// - /// Arrow clicks toggle without selecting; other clicks select the row. - void TreeCell(std::string_view text, int depth, TreeOpenRef isOpen, - IconID icon = IconID::Invalid, - uint32_t ancestorLineMask = 0, - bool isLastSibling = true, - std::string* renameBuffer = nullptr, - bool reserveExpander = true); - /// As above, the open state a bool of yours; null for leaves. - inline void TreeCell(std::string_view text, int depth, bool* isOpen, - IconID icon = IconID::Invalid, - uint32_t ancestorLineMask = 0, - bool isLastSibling = true, - std::string* renameBuffer = nullptr, - bool reserveExpander = true) - { TreeCell(text, depth, TreeOpenRef{ .flag = isOpen }, icon, ancestorLineMask, isLastSibling, renameBuffer, reserveExpander); } - - /// Virtual-scrolled table: emits only the visible rows, under one ranged ID. - /// Frozen columns get their own body section (left / mid / right), scroll-synced. - /// - /// columns : each carries its own generateCell(rowIndex), so reordering - /// the array reorders headers and cells together. A C array - /// converts to the span. - /// rowHeight : row-height floor; 0 uses the style's natural row height. - /// Headers, cell style and separators are TableState options. - void VirtualTable(ID id, TableState& state, - std::span columns, - int totalRowCount, - CssPx rowHeight = 0, - StyleRef style = {}, - LayoutOverride&& constraints = {}); - /// As above, with the call site as the ID. - inline void VirtualTable(TableState& state, std::span columns, int totalRowCount, - CssPx rowHeight = 0, StyleRef style = {}, LayoutOverride&& constraints = {}, - std::source_location site = std::source_location::current()) - { VirtualTable(idManager.AllocateDynamicID(site), state, columns, totalRowCount, rowHeight, style, std::move(constraints)); } - - ///@} - /// @name Breadcrumb ///@{ @@ -1571,22 +1119,6 @@ namespace tachyon ///@} - /// @name Node view - ///@{ - - // ---- Node view: self-contained graph editor ---- - // All state lives in the graph and its view state, so several views can coexist, - // of one graph too (a NodeViewState each). - /// Builds `view` (canvas, nodes, wires and overlays) in the current container: a NodeView, - /// or `{ graph, state }` for one of several views of a graph. - void RenderNodeView(NodeViewRef view); - - /// Text property body aligned by the row's sockets: left => left, right => right, - /// both => centre. Call inside NodeProperty::renderBody. - void NodeText(std::string_view text); - - ///@} - /// @name Tabs ///@{ @@ -1637,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 ///@{ @@ -1751,9 +1243,9 @@ namespace tachyon if constexpr (TypeDimensions::dimensions == 1) { - // Inside a node row, fill the body after the label so the node stays grid-aligned. - if (nodeRowFieldMinWidth > 0 && !constraints.HasFixedWidth()) - constraints.FlexGrow(1).MinWidth(Pixels{ nodeRowFieldMinWidth }); + // In a row that fills (SetFieldRowFill), fill the body after the label. + if (m_fieldRowFill > 0 && !constraints.HasFixedWidth()) + constraints.FlexGrow(1).MinWidth(Pixels{ m_fieldRowFill }); bool modified = false; RegisterControl(tachyon::Element { .id = id, .eventHandler = ReportingChanges(guiStateManager, &value, MakeNumericalBoxHandler(guiStateManager, value, config)), .styleRef = style, .flags = ElementFlags::DoNotMeasureText }, @@ -2049,65 +1541,10 @@ namespace tachyon /// As EdgesField, for corner radii: top left, top right, bottom right and bottom left. bool CornersField(ID id, BoxCorners& value, NumericFieldConfig config = { .stepPerPixel = 0.25, .minVal = 0, .maxVal = 64 }, LayoutOverride&& constraints = {}); - /// A shadow: its color over its offsets (X, Y), blur and spread. A transparent color - /// is no shadow. True when the value changed. - /// BoxShadow shadow{ .y = 4, .blur = 12, .color = { 0, 0, 0, 90 } }; - /// ShadowField(idManager.AllocateDynamicID("shadow"), shadow); - bool ShadowField(ID id, BoxShadow& value, LayoutOverride&& constraints = {}); ///@} - /// @name Color and gradient fields - ///@{ - - // ---- ColorField: swatch + color picker popup ---- - /// A color swatch that opens a color picker; true when the color changed. allowHDR lets - /// the picker take brightness over 1. - bool ColorField(ID id, tachyon::color4f& value, bool allowHDR, StyleRef style, LayoutOverride&& constraints = {}); - /// As above, in the theme's color field style. - inline bool ColorField(ID id, tachyon::color4f& value, bool allowHDR = false, LayoutOverride&& constraints = {}) { return ColorField(id, value, allowHDR, theme.colorFieldStyleRef, std::move(constraints)); } - /// As above, with the call site as the ID. - inline bool ColorField( tachyon::color4f& value, bool allowHDR, StyleRef style, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return ColorField(idManager.AllocateDynamicID(site), value, allowHDR, style, std::move(constraints)); } - /// As above, with the call site as the ID, in the theme's color field style. - inline bool ColorField( tachyon::color4f& value, bool allowHDR = false, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return ColorField(idManager.AllocateDynamicID(site), value, allowHDR, theme.colorFieldStyleRef, std::move(constraints)); } - /// As above, for an 8-bit color. - bool ColorField(ID id, tachyon::color4b& value, StyleRef style, LayoutOverride&& constraints = {}); - /// As above, in the theme's color field style. - inline bool ColorField(ID id, tachyon::color4b& value, LayoutOverride&& constraints = {}) { return ColorField(id, value, theme.colorFieldStyleRef, std::move(constraints)); } - /// As above, with the call site as the ID. - inline bool ColorField( tachyon::color4b& value, StyleRef style, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return ColorField(idManager.AllocateDynamicID(site), value, style, std::move(constraints)); } - /// As above, with the call site as the ID, in the theme's color field style. - inline bool ColorField( tachyon::color4b& value, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return ColorField(idManager.AllocateDynamicID(site), value, theme.colorFieldStyleRef, std::move(constraints)); } - /// The color picker's swatches, which the user adds to and removes from; set them to - /// start from the app's palette, read them to keep it. A palette of twelve to begin with. - void SetColorSwatches(std::span colors); - std::vector ColorSwatches() const; - /// Adds a color to the picker's recent ones, as OK does: newest first, each once, at - /// most 8. For colors the app restores from a previous run. - void AddRecentColor(tachyon::color4f color); - - // ---- GradientField: gradient swatch + editor popup ---- - /// A gradient swatch that opens a gradient editor; true when the gradient changed. - bool GradientField(ID id, tachyon::Gradient& value, StyleRef style, LayoutOverride&& constraints = {}); - /// As above, in the theme's gradient swatch style. - inline bool GradientField(ID id, tachyon::Gradient& value, LayoutOverride&& constraints = {}) { return GradientField(id, value, theme.gradientSwatchStyleRef, std::move(constraints)); } - /// As above, with the call site as the ID. - inline bool GradientField( tachyon::Gradient& value, StyleRef style, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return GradientField(idManager.AllocateDynamicID(site), value, style, std::move(constraints)); } - /// As above, with the call site as the ID, in the theme's gradient swatch style. - inline bool GradientField( tachyon::Gradient& value, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return GradientField(idManager.AllocateDynamicID(site), value, theme.gradientSwatchStyleRef, std::move(constraints)); } - /// As above, for a GradientF: up to GradientF::kMaxStops stops, colors over 1 (HDR), - /// and each stop's interpolation to the next. The swatch shows it clamped to 0..1. - bool GradientField(ID id, tachyon::GradientF& value, StyleRef style, LayoutOverride&& constraints = {}); - /// As above, in the theme's gradient swatch style. - inline bool GradientField(ID id, tachyon::GradientF& value, LayoutOverride&& constraints = {}) { return GradientField(id, value, theme.gradientSwatchStyleRef, std::move(constraints)); } - /// As above, with the call site as the ID. - inline bool GradientField( tachyon::GradientF& value, StyleRef style, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return GradientField(idManager.AllocateDynamicID(site), value, style, std::move(constraints)); } - /// As above, with the call site as the ID, in the theme's gradient swatch style. - inline bool GradientField( tachyon::GradientF& value, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return GradientField(idManager.AllocateDynamicID(site), value, theme.gradientSwatchStyleRef, std::move(constraints)); } - - ///@} - /// @name Sliders ///@{ @@ -2572,10 +2009,6 @@ namespace tachyon template auto LabelGroup(A&&... a) { return Scope<&GUIApplication::EndLabelGroup>(*this, BeginLabelGroup(std::forward(a)...)); } template auto ButtonGroup(A&&... a) { return Scope<&GUIApplication::EndButtonGroup>(*this, BeginButtonGroup(std::forward(a)...)); } template auto ToggleGroup(A&&... a) { return Scope<&GUIApplication::EndToggleGroup>(*this, BeginToggleGroup(std::forward(a)...)); } - template auto Table(A&&... a) { return Scope<&GUIApplication::EndTable>(*this, BeginTable(std::forward(a)...)); } - template auto Row(A&&... a) { return Scope<&GUIApplication::EndRow>(*this, BeginRow(std::forward(a)...)); } - template auto ListView(A&&... a) { return Scope<&GUIApplication::EndListView>(*this, BeginListView(std::forward(a)...)); } - template auto GridView(A&&... a) { return Scope<&GUIApplication::EndGridView>(*this, BeginGridView(std::forward(a)...)); } template auto TabBar(A&&... a) { return Scope<&GUIApplication::EndTabBar>(*this, BeginTabBar(std::forward(a)...)); } template auto Toolbar(A&&... a) { return Scope<&GUIApplication::EndToolbar>(*this, BeginToolbar(std::forward(a)...)); } template auto StatusBar(A&&... a) { return Scope<&GUIApplication::EndStatusBar>(*this, BeginStatusBar(std::forward(a)...)); } @@ -2586,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 @@ -2692,81 +2123,15 @@ namespace tachyon ///@} - /// @name Settings panel - ///@{ - - // ------------------------------------------------------------------ - // Settings panel - // ------------------------------------------------------------------ - // Two-pane settings panel: a page tree, a sizer, and the selected page's content. - // Owns only selection and tree width; page state belongs to the application. - /// What RenderSettingsPanel shows: its pages, the selected one and the tree width. - struct SettingsPanelState - { - /// A page: a stable ID, its name in the tree, and render, which builds its content. - struct Page - { - /// Stable across frames. - tachyon::ID id; - /// Shown in the page tree. - std::string name; - /// Builds the page's content while it is selected. - std::function render; - /// Before its name in the page list; optional. - IconID icon = IconID::Invalid; - }; - - /// Added with AddPage. - std::vector pages; - /// Above the page list, as a small caption ("Preferences"); none when empty. - std::string header; - /// The page shown; a click in the tree changes it. - tachyon::ID selectedID = tachyon::ID::Invalid(); - /// The page tree's width; its sizer changes it. - CssPx treeWidth = 200; - - /// Tree-view backing state, rebuilt per frame; not part of the API. - struct Internal - { - std::vector rows; - std::vector visibleIdx; - TableState tableState; - } internal; - - /// `id` must be stable. The first page added is selected initially. - tachyon::ID AddPage(tachyon::ID id, std::string_view name, - std::function render) - { - return AddPage(id, name, IconID::Invalid, std::move(render)); - } - /// As above, with an icon before its name in the page list. - tachyon::ID AddPage(tachyon::ID id, std::string_view name, IconID icon, - std::function render) - { - pages.push_back({ id, std::string(name), std::move(render), icon }); - if (selectedID == tachyon::ID::Invalid()) selectedID = id; - return id; - } - }; - - /// Renders into the current container; the caller provides the outer panel. - void RenderSettingsPanel(SettingsPanelState& state); - - ///@} - /// @name Saved UI state /// The UI's state as JSON text, which the host stores where and when it likes. Name /// what to keep once, by keys that stay the same between runs; the named objects /// must outlive the naming: /// /// PersistWindow("main", mainWindowID); // position, size, mode - /// PersistDocking("dock", dockingLayout); // panels by type, else title - /// PersistTable("assets", tableState, columns); // column widths and order, by header /// 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. @@ -2774,10 +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 the table's column widths and order, matching columns by header. - void PersistTable(std::string key, TableState& state, std::span columns); /// Keeps each side's toolbar items, by debugName. void PersistToolbars(std::string key, std::span, kToolbarSideCount> sides); /// Keeps an app value. @@ -2788,51 +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 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 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 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 @@ -2841,24 +2182,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 @@ -2878,6 +2210,74 @@ namespace tachyon StyleRef ButtonGroupItemStyle(StyleRef style); /// The element of the button styled with ButtonGroupItemStyle: the group keeps its first. void NoteButtonGroupItem(ElementRef ref); + /// Rebuilds the cached scopes (BeginCached) around `id` next frame: for a control whose + /// look changes outside its build, such as a scene drawn into an image. + void RebuildCachedScopesAbove(ID id) { m_cacheRebuildRequests.push_back(id); } + /// Where the context menu opening now was asked for: the right click, or the point + /// OpenContextMenu was given; empty when it opens below its target. + std::optional ContextMenuScreenPos() const { return contextMenuScreenPos; } + /// The color style slot of swatch `owner`: kept while `owner` asks for it every frame + /// (or a cached scope holding it is drawn from its capture), destroyed the frame after + /// it isn't. Invalid for a new swatch: make the style and store it there + /// (SetColorStyle), changed in place from then on. + VisualColorStyleIndex& ClaimSwatchStyle(ID owner); + /// Records that the cached scopes being built (BeginCached) use swatch `id`'s style, so + /// it's kept while they're drawn from their capture; ClaimSwatchStyle does it. For a + /// control that keeps swatch styles of its own (SwatchStyles), with ReplayedSwatches. + void NoteSwatchClaim(ID id); + /// The swatches of the cached scopes drawn from their capture this frame, as recorded + /// by NoteSwatchClaim: a control with swatch styles of its own keeps them alive + /// (SwatchStyles::KeepAlive) before it lets the unclaimed ones go. + std::span ReplayedSwatches() const { return m_replayedSwatches; } + /// The text of the label just before the current control (empty without one): what a + /// popup it opens names in its title. + std::string PendingLabelText() const; + /// As PendingLabelText, the text system's own, valid until the text changes. + std::string_view PendingLabelTextView() const; + /// A box that draws the border of the field inside it (a field with a caption or a + /// unit): it takes the field's hover and focus, so its :hover / :focus rules show them. + void BeginFieldBox(ID id, StyleRef style, LayoutOverride&& constraints); + /// Closes BeginFieldBox. + void EndFieldBox(); + /// Adds `id` to the Tab order, unless it's disabled. + void RegisterTabStop(ID id); + /// The PropagatesDescendantState ancestors of `leafID`'s element, innermost first. + static std::vector CollectPropagatedAncestors(const ElementStorage& storage, ID leafID); + /// The same into `out`, reusing its room. + static void CollectPropagatedAncestors(const ElementStorage& storage, ID leafID, std::vector& out); + /// 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 /// later, once the window is gone (an ID handed out again meanwhile would find it). void RetireWindow(ID windowID); @@ -2897,14 +2297,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, @@ -2919,17 +2312,7 @@ namespace tachyon uint64_t m_inputFlagsFrame = 0; void RefreshCachedInputFlags(); - /// Registers a swatch claim with the enclosing cached scopes so hit frames can keep it alive. - void NoteSwatchClaim(ID swatchID); - /// The text of the label just before the current control (empty without one). - std::string PendingLabelText() const; - /// As PendingLabelText, the text system's own, valid until the text changes. - std::string_view PendingLabelTextView() const; - /// How color swatches draw a color (the theme's checkerboard and alpha bar). - struct ColorSwatchLook SwatchLook() const; - /// Panel id -> its dock content (cached scope) id, for InvalidatePanel. - RecentIDMap m_panelContentIDs; /// Save-stack for nested BeginToolbar/EndToolbar. std::vector controlStylesStack; @@ -2945,54 +2328,11 @@ namespace tachyon FrameTimingSample frameTimingHistory[kFrameHistoryCount] = {}; int frameTimingHead = 0; ///< next write slot - /// Table drag state that persists across frames (defs in gui_table_types.h). - ColumnDragState m_columnDrag{}; - TreeDropState m_treeDropState{}; - - // ---- ListView ID->index map (shared by every list view; cleared once per frame) ---- - // Filled by ListItem when dragDrop is on; valid in end-of-frame handlers via FindListItemIndex(). - std::unordered_map m_listItemIndexByID; - /// A BackgroundTasks pill's popover: its window, and whether it's open. - /// A task's bar: the fill by its state, sliding while running with no value known. - /// A step's 16px glyph for `state`. - - - /// Transient construction state (defs in gui_tree_grid_types.h), valid only between - /// Begin*/End*. Handlers run later, so they must capture pointers, never read these. - TreeViewState m_treeState{}; - GridViewState m_gridViewState; - - /// GridView rename lookup, shared by every grid view; cleared before construction. - std::unordered_map m_gridItemRenameByID; - - - /// Transient state of the VirtualTable being emitted (def in gui_table_types.h). - std::optional m_tableEmit; - /// Emit states of outer tables while a table is built inside a cell, innermost last. - std::vector> m_outerTableEmits; - - int CurrentCellCol() const - { - const int c = m_tableEmit->currentCol; - assert(c < int(m_tableEmit->columnCount)); - return c; - } - 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; }; @@ -3004,51 +2344,23 @@ 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 void RegisterFrameBalanceChecks(); - /// API misuse (e.g. an End without its Begin): logged once, and the caller carries on. - static void ReportMisuse(const char* message); /// The bodies of the conditional Begin / End pairs (the public ones keep the open stacks). bool OpenMenu(ID menuID, const GUIContent& content, StyleRef buttonStyle, StyleRef menuStyle, StyleRef itemStyle, LayoutOverride&& constraints); void CloseMenu(); - /// A tooltip's box: the plain one; a few lines; property help's, on the popup surface; an - /// error's, on the popup surface with an error border. - enum class TooltipBox : uint8_t { Plain, Lines, Help, Error }; bool OpenTooltip(ID targetID, TooltipBox box = TooltipBox::Plain); - /// A node socket's tooltip: its pin's name, type and value, and a wired input's source. - void ShowPinTooltip(const NodeGraph& view, ID socketID, PropertyEndpoint pin, bool isOutput); /// Closes what OpenTooltip opened: the box and the window. void CloseTooltip(); /// Text cut short, as last frame laid it out. @@ -3074,18 +2386,13 @@ namespace tachyon /// FindCutShortText's walk of the target's elements, kept for its storage. mutable std::vector m_cutShortWalk; /// GradientField(Gradient&)'s gradient as given and as edited, kept for their storage. - GradientF m_gradientFieldGiven, m_gradientFieldEdited; + SwatchStyles<> m_swatchSlots; ///< ClaimSwatchStyle's + std::vector m_replayedSwatches; ///< ReplayedSwatches, this frame's bool OpenContextMenuWindow(ID targetID); bool OpenCached(ID id, StyleRef style, uint64_t signature, LayoutOverride&& constraints); static void ReportInvalidControlID(ID id); - /// Adds `id` to the Tab order, unless it's disabled. - void RegisterTabStop(ID id); /// SearchField, also giving the inner text field's ID. bool SearchField(ID id, std::string& value, const GUIContent& content, TextEditBehavior textEditBehavior, StyleRef style, LayoutOverride&& constraints, ID* outFieldID); - /// A box that draws the border of the field inside it (a field with a caption or a - /// unit): it takes the field's hover and focus, so its :hover / :focus rules show them. - void BeginFieldBox(ID id, StyleRef style, LayoutOverride&& constraints); - void EndFieldBox(); /// Rebuilds the styles when a reload is pending or the main window's /// display scale changed. Runs before the managers begin their frame. @@ -3149,13 +2456,10 @@ 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 PersistedTable { struct Target { TableState* state; std::span columns; }; std::string key; Target 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 { IntRect rect {}; @@ -3166,16 +2470,11 @@ namespace tachyon bool rectDone = false; }; std::vector m_persistWindows; - std::vector m_persistDocks; - std::vector m_persistTables; + 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. @@ -3201,8 +2500,6 @@ namespace tachyon /// The theme loaded's, made when there are none. ThemeVariableOverrides& ThemeVariables(); /// CurveEditor's channel tree and frame ruler, for views with paths and fps. - void CurveTree(CurveViewRef view); - void CurveRuler(CurveViewRef view); /// A theme's path as m_themeVariables keys it: backslashes as forward slashes, then /// lexically normal, so one theme written two ways is one key on every platform. static std::string ThemePathKey(std::string_view themePath); @@ -3261,10 +2558,6 @@ namespace tachyon /// Invalidates the scopes under the cursor and, on key input, the focused one. /// Call after hit-testing, before dispatch. void InvalidateCachedScopesForInput(ID overID); - /// The PropagatesDescendantState ancestors of `leafID`'s element, innermost first. - static std::vector CollectPropagatedAncestors(const ElementStorage& storage, ID leafID); - /// The same into `out`, reusing its room. - static void CollectPropagatedAncestors(const ElementStorage& storage, ID leafID, std::vector& out); /// Before construction: a tooltip or context menu on an element that takes its parts' /// states (PropagatesDescendantState) is for those parts too. Also notes the target's /// text cut short (FindCutShortText), with the pointer at `mousePos`. @@ -3282,44 +2575,34 @@ namespace tachyon void InvalidateCachedScopesAbove(ID id); /// As InvalidateCachedScopesAbove, from layout: this frame's capture would clear it, so /// it applies after the frame is drawn. - void RebuildCachedScopesAbove(ID id) { m_cacheRebuildRequests.push_back(id); } 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); - - /// Set by RenderNodeView around each renderBody; Start elsewhere. - TextAlign nodeRowTextAlign = TextAlign::Start; - /// When > 0, a Field() in a node row grows to fill the body with this minimum width. - /// Set by RenderNodeView around each renderBody; 0 elsewhere. - int32_t nodeRowFieldMinWidth = 0; + 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; - /// The node view's breadcrumb, zoom controls and minimap, over its canvas. - void EmitNodeViewOverlays(NodeViewRef view, ID canvasID); /// Each window's title bar, from its last BeginTitleBar / EndTitleBar. struct TitleBarInfo { ID barID = ID::Invalid(); ID maximizeID = ID::Invalid(); std::vector captions; }; @@ -3370,134 +2653,8 @@ 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); - - /// Popup content for ColorField / GradientField. - void EmitColorPicker(tachyon::color4f& outColor, bool allowHDR); - /// The editor's body, on its working copy, which it writes to `outGradient`. - void EmitGradientEditor(tachyon::GradientF& outGradient); - /// GradientField on a GradientF; `gradient8` is the Gradient it stands for, which limits - /// the editor to its stops and colors (null for a GradientF field). `cancelled` when the - /// editor's Cancel put the gradient back this frame. - bool GradientFieldCore(ID id, tachyon::GradientF& value, const tachyon::Gradient* gradient8, - bool& cancelled, StyleRef style, LayoutOverride&& constraints); - - /// Column-boundary sizers for [colStart, colEnd), anchored to each header cell's right edge. - /// skipDragged leaves out the dragged column's sizer; EmitDraggedColumnOnTop emits it last. - void EmitColumnSizers(TableEmit& emit, int colStart, int colEnd, - bool skipDragged = false); - /// 1px column dividers for headerless tables, which have no sizers. - void EmitColumnSeparators(TableEmit& emit, int colStart, int colEnd); - /// Full-height strips for columns with columnBackground: above the row backdrops, below the cells. - void EmitColumnBackgrounds(TableEmit& emit, int colStart, int colEnd); - - /// followTail, run from the body section's post-layout hook (final viewport/content height). - void UpdateTableFollowTail(TableState& state, int32_t viewportH, int32_t contentH); - void ScrollTableSectionsToBottom(TableState& state); - /// 1px separator between adjacent frozen sections. - void EmitTableSectionSeparator(); - - /// Adds column c's reorder-drag X offset while a drag is live. - tachyon::LayoutOverride ApplyColumnDragOffsetX(tachyon::LayoutOverride lo, - const TableEmit& emit, int c) const - { - if (emit.dragActive) - lo = std::move(lo).PositionX(tachyon::PositionConstraintAxis::Relative(emit.columns[c].internal.dragOffsetX)); - return lo; - } - /// Mirrors Y across the left/mid/right bodies and X to the mid header; absent sections have invalid IDs. - void MirrorTableScroll(TableState* state); - /// `gridCol` is section-local. `sectionMin/Max` are the inclusive global columns - /// the reorder drag may move this header within. - void EmitTableHeaderCell(TableEmit& emit, tachyon::ID tableID, int c, int16_t gridCol, - bool isStretchTrack, int sectionMin, int sectionMax, - int effectiveSortCol, IconID sortIcon); - /// Header cells go into row 0 of the section's body grid, StickyY-pinned to the top. - void EmitTableHeaderSection(TableEmit& emit, tachyon::ID tableID, - int colStart, int colEnd, bool lastColIsStretch, - int effectiveSortCol, IconID sortIcon); - /// Stretch for Stretch columns and the middle section's last column; fitContent - /// forces Fixed (fit-content sections have no leftover space to absorb). - GridTrack ComputeSectionColumnTrack(const TableEmit& emit, int c, int colEnd, - bool isMiddle, bool fitContent = false) const; - /// Follow with the row loop and CloseTableBodySection. `sampleViewport` records the - /// viewport size for next frame (primary section only). - void OpenTableBodySection(TableEmit& emit, tachyon::ID sectionID, tachyon::StyleRef sectionStyle, - tachyon::LayoutOverride&& layout, bool sampleViewport); - /// Emits sizers and the section's H scrollbar (the rightmost section also gets the - /// shared V scrollbar). suppressHorzScrollbar is for fit-content sections. - void CloseTableBodySection(TableEmit& emit, - tachyon::ID sectionBodyID, bool emitVerticalScrollbar, - bool suppressHorzScrollbar = false); - /// Row loop for an open body section: spacers for off-screen rows, backdrop + cells for visible ones. - void EmitVirtualBodyRows(TableEmit& emit, - int colStart, int colEnd, - int totalRowCount, int32_t actualRowHeight, - int firstVisible, int lastVisible, - tachyon::ID rowsRangeID, - bool isLastSection); - - /// Emits the dragged column (cells, header, sizer) last so it paints on top. - /// Only when emit.dragActive and draggedCol is in [colStart, colEnd). - void EmitDraggedColumnOnTop(TableEmit& emit, tachyon::ID tableID, - int colStart, int colEnd, - int firstVisible, int lastVisible, - tachyon::ID rowsRangeID, - bool lastColIsStretch, - int effectiveSortCol, IconID sortIcon); - /// Cell emitters for Cell() / TreeCell(), into the open body section. - void EmitDirectCellText(const VirtualTableColumn& column, TableEmit& emit, - tachyon::ID cellID, tachyon::ElementState cellState, tachyon::ElementFlags cellFlags, - tachyon::StyleRef cellStyleRef, tachyon::EventHandler cellHandler, - tachyon::TextID textID, - int colIdx, int colStart, int16_t gridRow); - void EmitDirectCellCustom(const VirtualTableColumn& column, TableEmit& emit, - tachyon::ID cellID, tachyon::ElementState cellState, tachyon::ElementFlags cellFlags, - tachyon::StyleRef cellStyleRef, tachyon::EventHandler cellHandler, - bool cellSelected, - std::function emit_fn, - int colIdx, int colStart, int16_t gridRow); - /// Returns the cell's element. - tachyon::ElementRef EmitDirectCellTree(const VirtualTableColumn& column, TableEmit& emit, - tachyon::ID cellID, tachyon::ElementState cellState, tachyon::ElementFlags cellFlags, - tachyon::StyleRef cellStyleRef, tachyon::EventHandler cellHandler, - bool cellSelected, - tachyon::TextID textID, - int treeDepth, TreeOpenRef treeIsOpen, IconID treeIcon, - uint32_t treeAncestorMask, bool treeIsLastSibling, - std::string* treeRenameBuffer, bool treeRenameActive, - tachyon::ID treeBodyID, bool reserveExpander, - int colIdx, int colStart, int16_t gridRow); - /// One element spanning [colStart, colEnd) at gridRow. - void EmitDirectRowBackdrop(tachyon::ID rowID, int16_t gridRow, - int colStart, int colEnd, - tachyon::ElementState backdropState, - tachyon::ElementFlags backdropFlags, - tachyon::StyleRef rowStyle, - tachyon::EventHandler backdropHandler, - TableState* tableState, - bool isLastSection); - /// Invisible row of `height` pixels at gridRow. - void EmitDirectRowSpacer(int16_t gridRow, - int colStart, int colEnd, int32_t height); - /// Row-mode backdrop MouseDown handler, shared by all rows (the row comes from the event id): - /// selection, double-click toggle, rename start. - tachyon::EventHandler BuildRowBackdropHandler(TableState* state, - tachyon::ID containerID); - /// Focus on click, scroll routing to the middle body, keyboard navigation. - tachyon::EventHandler BuildTableContainerHandler(TableState* state, - tachyon::ID containerID); - - /// Tree/list item construction helpers (OnGUI only, not from handlers). - bool IsTreeItemSelected(tachyon::ID id, int itemIndex) const; - tachyon::TextID TreeItemRegisterText(tachyon::ID id, std::string_view text, IconID icon, StyleRef style, tachyon::ElementState state); - void TreeItemRowCustomDraw(const tachyon::ElementRef& rowRef, bool hasArrow, tachyon::ID rowID); - tachyon::EventHandler MakeTreeRowDragDropHandler(tachyon::ID rowID, bool rowHasChildren, ItemDragDropConfig* dd, bool* isOpen = nullptr); - bool TreeItemRenameCheck(tachyon::ID bodyID, std::string* renameBuffer, StyleRef textStyle); - - struct TreeClickState { tachyon::ID lastClickID = tachyon::ID::Invalid(); int64_t lastClickTimeNanos = 0; }; + + }; diff --git a/src/gui_controls/gui_application_internal.h b/src/gui_controls/gui_application_internal.h index 4e8d0a28..f889370d 100644 --- a/src/gui_controls/gui_application_internal.h +++ b/src/gui_controls/gui_application_internal.h @@ -15,11 +15,7 @@ namespace tachyon using GUIApplication::m_menuRects; using GUIApplication::m_labelGroup; using GUIApplication::m_buttonGroup; - using GUIApplication::m_colorPickerSub; - using GUIApplication::m_gradientEditorSub; - using GUIApplication::m_renameSub; using GUIApplication::m_reorderable; - using GUIApplication::m_dockTabDragSub; using GUIApplication::m_toolbarWindowDrag; using GUIApplication::m_uiCache; using GUIApplication::FireStateTransitions; @@ -33,11 +29,6 @@ namespace tachyon using GUIApplication::contextMenuTargetID; using GUIApplication::tabDragGhostWindowID; - using GUIApplication::m_columnDrag; - using GUIApplication::m_treeDropState; - using GUIApplication::m_tableEmit; - using GUIApplication::m_dockingState; - using GUIApplication::m_floatingDockWindows; using GUIApplication::activeWindowID; using GUIApplication::m_windowIdScopeStack; @@ -46,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; @@ -58,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; @@ -67,15 +59,9 @@ 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 ColorPickerSubsystem& ColorPicker(GUIApplication& app) { return *app.m_colorPickerSub; } - static GradientEditorSubsystem& GradientEditor(GUIApplication& app) { return *app.m_gradientEditorSub; } 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. static void TickFrameClock(GUIApplication& app, int64_t nowNanos) { app.m_frameClock.Tick(nowNanos, 0.0f); } 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 f7a4b534..1e92464a 100644 --- a/src/gui_controls/gui_theme.cpp +++ b/src/gui_controls/gui_theme.cpp @@ -129,8 +129,6 @@ namespace tachyon }; treeArrowRight = registerIcon("tree-arrow-right", R"()"); treeArrowDown = registerIcon("tree-arrow-down", R"()"); - sortArrowUpIcon = registerIcon("sort-arrow-up", R"()"); - sortArrowDownIcon = registerIcon("sort-arrow-down", R"()"); tabCloseIcon = registerIcon("tab-close", R"()"); menuCheckIcon = registerIcon("menu-check", R"()"); boldCheckIcon = registerIcon("bold-check", R"()"); @@ -153,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"()"); @@ -163,39 +160,12 @@ namespace tachyon windowRestoreIcon = registerIcon("window-restore", R"()"); // Playback, as the Graphite timeline draws it; play and pause are filled. - timelineStartIcon = registerIcon("timeline-start", R"()"); - timelineStepBackIcon = registerIcon("timeline-step-back", R"()"); timelinePlayIcon = registerIcon("timeline-play", R"()"); timelinePauseIcon = registerIcon("timeline-pause", R"()"); - timelineStepIcon = registerIcon("timeline-step", R"()"); - timelineEndIcon = registerIcon("timeline-end", R"()"); - timelineLoopIcon = registerIcon("timeline-loop", - R"()"); - timelinePrevKeyIcon = registerIcon("timeline-prev-key", R"()"); - timelineNextKeyIcon = registerIcon("timeline-next-key", R"()"); - timelineSnapIcon = registerIcon("timeline-snap", - R"()"); - timelineZoomOutIcon = registerIcon("timeline-zoom-out", R"()"); - timelineZoomInIcon = registerIcon("timeline-zoom-in", R"()"); timelineEyeIcon = registerIcon("timeline-eye", R"()"); timelineEyeOffIcon = registerIcon("timeline-eye-off", R"()"); - timelineLockIcon = registerIcon("timeline-lock", R"()"); - timelineUnlockIcon = registerIcon("timeline-unlock", R"()"); - timelineKeyIcon = registerIcon("timeline-key", R"()"); - timelineAudioIcon = registerIcon("timeline-audio", R"()"); - timelineEventsIcon = registerIcon("timeline-events", R"()"); - curveConstantIcon = registerIcon("curve-constant", R"()"); - curveLinearIcon = registerIcon("curve-linear", R"()"); - curveBezierIcon = registerIcon("curve-bezier", R"()"); - curveFrameAllIcon = registerIcon("curve-frame-all", R"()"); - viewportSelectIcon = registerIcon("viewport-select", - R"()"); - viewportMoveIcon = registerIcon("viewport-move", R"()"); - viewportRotateIcon = registerIcon("viewport-rotate", R"()"); - viewportScaleIcon = registerIcon("viewport-scale", - R"()"); linkIcon = registerIcon("link", R"()"); unlinkIcon = registerIcon("unlink", @@ -286,6 +256,12 @@ namespace tachyon return it != m_variableValues.end() ? &it->second : nullptr; } + void GUITheme::RegisterDropdownParts(StyleRef trigger, std::string_view cssClass) + { + const std::string name(cssClass); + m_dropdownParts.push_back({ trigger, DropdownParts{ GetStyle(name + "-text"), GetStyle(name + "-arrow") } }); + } + GUITheme::DropdownParts GUITheme::DropdownPartsFor(StyleRef button) const { for (const auto& [trigger, parts] : m_dropdownParts) @@ -455,10 +431,7 @@ namespace tachyon }; lineGrayStyle = lineColorFromCSS("--text-3", color4f{ 0.4f, 0.4f, 0.4f, 1.0f }); - lineYellowStyle = lineColorFromCSS("--warn", color4f{ 1.0f, 0.8f, 0.2f, 1.0f }); - lineWhiteStyle = lineColorFromCSS("--text-1", color4f{ 1.0f, 1.0f, 1.0f, 1.0f }); lineDarkStyle = lineColorFromCSS("--bg-app", color4f{ 0.1f, 0.1f, 0.1f, 1.0f }); - treeGuideLineStyle = lineColorFromCSS("--tree-guide", color4f{ 0.5f, 0.5f, 0.5f, 1.0f }); dividerHoverLineStyle = lineColorFromCSS("--divider-hover", color4f{ 0.42f, 0.61f, 1.0f, 1.0f }); tooltipArrowFill = lineColorFromCSS("--tooltip-bg", color4f{ 0.16f, 0.18f, 0.22f, 1.0f }); tooltipArrowLine = lineColorFromCSS("--tooltip-border", color4f{ 0.21f, 0.24f, 0.28f, 1.0f }); @@ -468,36 +441,6 @@ namespace tachyon if (textSystem) textSystem->SetCaretColor(lineColorFromCSS("--caret", color4f{ 0.42f, 0.61f, 1.0f, 1.0f })); nanTextColor = lineColorFromCSS("--warn-text", color4f{ 0.9f, 0.7f, 0.33f, 1.0f }); - timelineKeyColor = lineColorFromCSS("--timeline-key", color4f{ 0.79f, 0.81f, 0.85f, 1.0f }); - timelineKeyEdgeColor = lineColorFromCSS("--bg-panel", color4f{ 0.07f, 0.08f, 0.09f, 1.0f }); - timelineKeySelectedColor = lineColorFromCSS("--accent", color4f{ 0.42f, 0.61f, 1.0f, 1.0f }); - timelineKeySelectedEdgeColor = lineColorFromCSS("--text-1", color4f{ 0.91f, 0.92f, 0.94f, 1.0f }); - timelineSummaryKeyColor = lineColorFromCSS("--timeline-summary", color4f{ 0.42f, 0.45f, 0.5f, 1.0f }); - timelineWaveColor = lineColorFromCSS("--timeline-wave", color4f{ 0.2f, 0.82f, 0.75f, 0.65f }); - curveGridColor = lineColorFromCSS("--curve-grid", color4f{ 0.08f, 0.09f, 0.11f, 1.0f }); - curveGridMajorColor = lineColorFromCSS("--curve-grid-major", color4f{ 0.12f, 0.14f, 0.16f, 1.0f }); - curveZeroColor = lineColorFromCSS("--curve-zero", color4f{ 0.2f, 0.23f, 0.27f, 1.0f }); - curveKeyEdgeColor = lineColorFromCSS("--curve-plot", color4f{ 0.05f, 0.06f, 0.07f, 1.0f }); - curveSelectedKeyColor = lineColorFromCSS("--text-1", color4f{ 0.91f, 0.92f, 0.94f, 1.0f }); - curveHandleColor = lineColorFromCSS("--accent", color4f{ 0.42f, 0.61f, 1.0f, 1.0f }); - nodeTransitionColor = lineColorFromCSS("--text-3", color4f{ 0.56f, 0.59f, 0.65f, 1.0f }); - nodeTransitionHoverColor = lineColorFromCSS("--text-1", color4f{ 0.91f, 0.92f, 0.94f, 1.0f }); - nodeTransitionSelectedColor = lineColorFromCSS("--accent", color4f{ 0.42f, 0.61f, 1.0f, 1.0f }); - nodeInitialStateColor = lineColorFromCSS("--text-1", color4f{ 0.91f, 0.92f, 0.94f, 1.0f }); - { - // Value, red, green, blue, alpha: the design's axis colors, and the warning color for one value. - static constexpr const char* kChannelVars[5] = { "--warn", "--axis-x", "--axis-y", "--axis-z", "--text-1" }; - static constexpr color4f kFallbacks[5] = { { 0.9f, 0.7f, 0.33f, 1.0f }, { 0.94f, 0.42f, 0.42f, 1.0f }, - { 0.31f, 0.77f, 0.54f, 1.0f }, { 0.42f, 0.61f, 1.0f, 1.0f }, - { 0.91f, 0.92f, 0.94f, 1.0f } }; - for (int c = 0; c < 5; ++c) - { - curveChannelColors[c] = lineColorFromCSS(kChannelVars[c], kFallbacks[c]); - color4f faded = GetColor(kChannelVars[c], kFallbacks[c]); - faded.a *= 0.55f; - curveChannelFadedColors[c] = styleManager.RegisterColorStyle(ColorStyle::Create(faded)); - } - } if (const auto* prop = sheet.GetCustomProperty("--scrim"); prop && prop->hasColor) scrim = prop->color; else scrim = color4b{ 0, 0, 0, 140 }; if (const auto* prop = sheet.GetCustomProperty("--error"); prop && prop->hasColor) invalidColor = prop->color; @@ -513,20 +456,6 @@ namespace tachyon disabledOpacity = std::clamp(prop->number, 0.0f, 1.0f); else disabledOpacity = 0.4f; - { - auto tint = [&](const char* name, float& out) { - if (const auto* prop = sheet.GetCustomProperty(name); prop && prop->hasNumber && prop->dimCount == 1) - out = std::clamp(prop->number, 0.0f, 1.0f); - }; - nodeTints = {}; - tint("--node-header-tint", nodeTints.header); - tint("--node-header-line-tint", nodeTints.headerLine); - tint("--state-tint", nodeTints.state); - tint("--state-border-tint", nodeTints.stateBorder); - tint("--frame-fill-tint", nodeTints.frameFill); - tint("--frame-band-tint", nodeTints.frameBand); - tint("--frame-border-tint", nodeTints.frameBorder); - } auto linkFrom = [&sheet](const char* name) { const Style* link = sheet.GetStyle(name); return link ? LinkStyle{ .color = link->states[ElementState::None].textColor.GetFirstColor(), @@ -545,9 +474,6 @@ namespace tachyon panelColor = lineColorFromCSS("--bg-panel", color4f{ 0.07f, 0.08f, 0.09f, 1.0f }); treeDropIndicatorStyle = lineColorFromCSS("--accent", color4f{ 0.0f, 0.478f, 0.8f, 1.0f }); - marqueeFillColorStyle = styleManager.RegisterColorStyle( - ColorStyle::Create(color4f{ 0.3f, 0.6f, 1.0f, 0.15f })); - imageFillColorStyle = styleManager.RegisterColorStyle( ColorStyle::Create(color4b{ 255, 255, 255, 255 }, color4b{ 255, 255, 255, 255 }, ColorType::StretchedTexture)); clearColorStyle = styleManager.RegisterColorStyle(ColorStyle::Create(color4f{ 0.0f, 0.0f, 0.0f, 0.0f })); @@ -598,8 +524,6 @@ namespace tachyon toolbarControls.number = registerCSS("toolbar-number-field"); toolbarControls.menuTrigger = registerCSS("toolbar-menu-trigger"); - nodeControls = regularControls; - nodeControls.number = registerCSS("node-number-field"); labelStyleRef = registerCSS("label"); iconLabelStyleRef = registerCSS("icon-label"); @@ -678,18 +602,9 @@ namespace tachyon if (const LayoutStyle* p = styleManager.GetLayoutStyle(scrollbarVerticalTrackStyleRef.layoutStyleIndex); p && p->layoutData.width > 0) scrollbarThickness = p->layoutData.width; scrollbarHorizontalThumbStyleRef = registerCSS("scrollbar-horizontal-thumb"); - colorSwatchStyleRef = registerCSS("color-swatch"); - colorFieldStyleRef = registerCSS("color-field"); - colorHexStyleRef = registerCSS("color-hex"); - colorAlphaStyleRef = registerCSS("color-alpha"); - colorAlphaInputStyleRef = registerCSS("color-alpha-input"); - colorAlphaUnitStyleRef = registerCSS("color-alpha-unit"); - colorAlphaCaptionStyleRef = registerCSS("color-alpha-caption"); - colorPickerStyleRef = registerCSS("color-picker"); dialogHeaderStyleRef = registerCSS("dialog-header"); dialogTitleStyleRef = registerCSS("dialog-title"); dialogContextStyleRef = registerCSS("dialog-context"); - colorPickerHdrValueStyleRef = registerCSS("color-picker-hdr-value"); dialogCloseStyleRef = registerCSS("dialog-close"); dialogFooterStyleRef = registerCSS("dialog-footer"); dialogStatusStyleRef = registerCSS("dialog-status"); @@ -700,93 +615,13 @@ namespace tachyon checkboxStyleRef = registerCSS("checkbox"); checkboxBoxStyleRef = registerCSS("checkbox-box"); checkboxLabelStyleRef = registerCSS("checkbox-label"); - colorPickerBodyStyleRef = registerCSS("color-picker-body"); - colorPickerPlanesStyleRef = registerCSS("color-picker-planes"); - colorPickerSquareStyleRef = registerCSS("color-picker-square"); - colorPickerStripStyleRef = registerCSS("color-picker-strip"); - colorPickerControlsStyleRef = registerCSS("color-picker-controls"); - colorPickerPreviewGroupStyleRef = registerCSS("color-picker-preview-group"); - colorPickerCaptionsStyleRef = registerCSS("color-picker-captions"); - colorPickerCaptionStyleRef = registerCSS("color-picker-caption"); - colorPickerModeRowStyleRef = registerCSS("color-picker-mode-row"); - colorPickerRangeStyleRef = registerCSS("color-picker-range"); - colorPickerChannelsStyleRef = registerCSS("color-picker-channels"); - colorPickerChannelStyleRef = registerCSS("color-picker-channel"); - colorPickerChannelLabelStyleRef = registerCSS("color-picker-channel-label"); - colorPickerTrackStyleRef = registerCSS("color-picker-track"); - colorPickerChannelValueStyleRef = registerCSS("color-picker-channel-value"); - colorPickerFieldRowStyleRef = registerCSS("color-picker-field-row"); - colorPickerRowLabelStyleRef = registerCSS("color-picker-row-label"); - colorPickerHdrStyleRef = registerCSS("color-picker-hdr"); - colorPickerSwatchesStyleRef = registerCSS("color-picker-swatches"); - colorPickerSwatchRowStyleRef = registerCSS("color-picker-swatch-row"); - colorPickerSectionLabelStyleRef = registerCSS("color-picker-section-label"); - colorPickerSwatchStyleRef = registerCSS("color-picker-swatch"); - colorPickerRecentStyleRef = registerCSS("color-picker-recent"); - colorPickerPreviewStyleRef = registerCSS("color-picker-preview"); - colorPickerNewStyleRef = registerCSS("color-picker-new"); - gradientSwatchStyleRef = registerCSS("gradient-swatch"); - nodeFrameMenuStyleRef = registerCSS("node-frame-menu"); - nodeViewOverlayDividerStyleRef = registerCSS("node-view-overlay-divider"); - nodeStateTimeStyleRef = registerCSS("node-state-time"); - nodeStateNestedMarkStyleRef = registerCSS("node-state-nested-mark"); - gradientEditorStyleRef = registerCSS("gradient-editor"); - gradientEditorBarStyleRef = registerCSS("gradient-editor-bar"); dialogSmallButtonStyleRef = registerCSS("dialog-small-button"); dialogIconButtonStyleRef = registerCSS("dialog-icon-button"); dialogSquareButtonStyleRef = registerCSS("dialog-square-button"); dialogDeleteButtonStyleRef = registerCSS("dialog-delete-button"); - gradientEditorPresetsStyleRef = registerCSS("gradient-editor-presets"); - gradientEditorSectionLabelStyleRef = registerCSS("gradient-editor-section-label"); - gradientEditorPresetStyleRef = registerCSS("gradient-editor-preset"); - gradientEditorBadgeStyleRef = registerCSS("gradient-editor-badge"); - gradientEditorColumnsStyleRef = registerCSS("gradient-editor-columns"); - gradientEditorColumnStyleRef = registerCSS("gradient-editor-column"); - gradientEditorRowStyleRef = registerCSS("gradient-editor-row"); - gradientEditorHeadingStyleRef = registerCSS("gradient-editor-heading"); - gradientEditorCountStyleRef = registerCSS("gradient-editor-count"); - gradientEditorLabelStyleRef = registerCSS("gradient-editor-label"); - gradientEditorLocationStyleRef = registerCSS("gradient-editor-location"); - gradientEditorLocationInputStyleRef = registerCSS("gradient-editor-location-input"); - gradientEditorLocationUnitStyleRef = registerCSS("gradient-editor-location-unit"); - gradientEditorDividerStyleRef = registerCSS("gradient-editor-divider"); - gradientEditorActionsStyleRef = registerCSS("gradient-editor-actions"); - gradientEditorTableStyleRef = registerCSS("gradient-editor-table"); - gradientEditorTableHeadStyleRef = registerCSS("gradient-editor-table-head"); - gradientEditorTableRowStyleRef = registerCSS("gradient-editor-table-row"); - gradientEditorTypeCellStyleRef = registerCSS("gradient-editor-type-cell"); - gradientEditorSwatchCellStyleRef = registerCSS("gradient-editor-swatch-cell"); - gradientEditorHeadCellStyleRef = registerCSS("gradient-editor-head-cell"); - gradientEditorHeadLocationStyleRef = registerCSS("gradient-editor-head-location"); - gradientEditorValueCellStyleRef = registerCSS("gradient-editor-value-cell"); - gradientEditorLocationCellStyleRef = registerCSS("gradient-editor-location-cell"); itemListStyleRef = registerCSS("item-list"); - nodeViewStyleRef = registerCSS("node-view"); viewBackgroundStyleRef = registerCSS("view-background"); - nodeStyleRef = registerCSS("node"); - nodeRerouteStyleRef = registerCSS("node-reroute"); - nodeFrameStyleRef = registerCSS("node-frame"); - nodeFrameBandStyleRef = registerCSS("node-frame-band"); - nodeFrameTitleStyleRef = registerCSS("node-frame-title"); - nodeFrameRenameStyleRef = registerCSS("node-frame-rename"); - nodeTransitionLabelStyleRef = registerCSS("node-transition-label"); - nodeTransitionRenameStyleRef = registerCSS("node-transition-rename"); - nodeStateActiveStyleRef = registerCSS("node-state-active"); - nodeStateEdgeStyleRef = registerCSS("node-state-edge"); - nodeStateNestedStyleRef = registerCSS("node-state-nested"); - nodeFramePortsStyleRef = registerCSS("node-frame-ports"); - nodeFramePortStyleRef = registerCSS("node-frame-port"); - nodeFramePortOutStyleRef = registerCSS("node-frame-port-out"); - nodeHeaderStyleRef = registerCSS("node-header"); - nodeHeaderStateStyleRef = registerCSS("node-header-state"); - nodeStateStyleRef = registerCSS("node-state"); - nodeCategoryStyleRef = registerCSS("node-category"); - nodeTitleStyleRef = registerCSS("node-title"); - nodeCaptionStyleRef = registerCSS("node-caption"); - nodeViewOverlayStyleRef = registerCSS("node-view-overlay"); - nodeViewOverlayButtonStyleRef = registerCSS("node-view-overlay-button"); - nodeViewMinimapStyleRef = registerCSS("node-view-minimap"); breadcrumbStyleRef = registerCSS("breadcrumb"); breadcrumbSegmentStyleRef = registerCSS("breadcrumb-segment"); breadcrumbCurrentStyleRef = registerCSS("breadcrumb-current"); @@ -804,28 +639,7 @@ namespace tachyon commandSearchKeyStyleRef = registerCSS("command-search-key"); commandSearchListStyleRef = registerCSS("command-search-list"); commandSearchCurrentRowStyleRef = registerCSS("command-search-current-row"); - nodeRowStyleRef = registerCSS("node-row"); - nodeBodyCenterStyleRef = registerCSS("node-body-center"); - nodeSocketStyleRef = registerCSS("node-socket"); - if (const LayoutStyle* p = styleManager.GetLayoutStyle(nodeSocketStyleRef.layoutStyleIndex); p && p->layoutData.width > 0) - socketSize = p->layoutData.width; - // Text-only node properties: one CSS rule, registered per alignment (follows the sockets). - { - const Style* base = sheet.GetStyle("node-text"); - auto registerAligned = [&](TextAlign align) -> StyleRef - { - Style s = base ? *base : sheet.baseStyle; - if (fontScale != 1.0f) - for (int i = 0; i < Style::kStateCount; i++) - s.states[i].textStyle.fontSize *= fontScale; - s.textLayoutStyle.horizontalAlignment = align; - return styleManager.Register(s); - }; - nodeTextLeftStyleRef = registerAligned(TextAlign::Start); - nodeTextCenterStyleRef = registerAligned(TextAlign::Center); - nodeTextRightStyleRef = registerAligned(TextAlign::End); - } itemStyleRef = registerCSS("item"); collectionStyleRef = registerCSS("collection"); @@ -857,22 +671,9 @@ namespace tachyon iconButtonStyleRef = registerCSS("icon-button"); iconButtonEndStyleRef = registerCSS("icon-button-end"); - listViewStyleRef = registerCSS("list-view"); - listItemStyleRef = registerCSS("list-item"); - listItemRowStyleRef = registerCSS("list-item-row"); listItemDragKnobHorzStyleRef = registerCSS("list-item-drag-knob-horz"); listItemDragKnobVertStyleRef = registerCSS("list-item-drag-knob-vert"); - listItemBodyStyleRef = registerCSS("list-item-body"); - treeViewStyleRef = registerCSS("tree-view"); - gridViewStyleRef = registerCSS("grid-view"); - gridViewItemStyleRef = registerCSS("grid-view-item"); - gridViewScrollStyleRef = registerCSS("grid-view-scroll"); - gridViewRowStyleRef = registerCSS("grid-view-row"); gridViewListItemStyleRef = registerCSS("grid-view-list-item"); - gridViewRenameItemStyleRef = registerCSS("grid-view-rename-item"); - gridViewRenameListItemStyleRef = registerCSS("grid-view-rename-list-item"); - gridViewRenameIconStyleRef = registerCSS("grid-view-rename-icon"); - gridViewRenameEditStyleRef = registerCSS("grid-view-rename-edit"); flexFillRowStyleRef = registerCSS("flex-fill-row"); flexFillColStyleRef = registerCSS("flex-fill-col"); flatButtonStyleRef = registerCSS("flat-button"); @@ -899,116 +700,12 @@ namespace tachyon tabCloseStyleRef = registerCSS("tab-close"); statusTextMonoStyleRef = registerCSS("status-text-mono"); - timelineStyleRef = registerCSS("timeline"); - timelineTransportStyleRef = registerCSS("timeline-transport"); - timelineButtonStyleRef = registerCSS("timeline-button"); - timelinePlayStyleRef = registerCSS("timeline-play"); - timelineLoopStyleRef = registerCSS("timeline-loop"); - timelineTimeStyleRef = registerCSS("timeline-time"); - timelineTimeCurrentStyleRef = registerCSS("timeline-time-current"); - timelineTimeTotalStyleRef = registerCSS("timeline-time-total"); - timelineFrameStyleRef = registerCSS("timeline-frame"); - timelineScrubberStyleRef = registerCSS("timeline-scrubber"); - timelineReadyStyleRef = registerCSS("timeline-ready"); - timelineTickStyleRef = registerCSS("timeline-tick"); - timelineTickMajorStyleRef = registerCSS("timeline-tick-major"); - timelineMarkerStyleRef = registerCSS("timeline-marker"); - timelinePlayheadStyleRef = registerCSS("timeline-playhead"); - timelineEditorStyleRef = registerCSS("timeline-editor"); - timelineToolbarStyleRef = registerCSS("timeline-toolbar"); - timelineDividerStyleRef = registerCSS("timeline-divider"); - curveFrameAllStyleRef = registerCSS("curve-frame-all"); timelineFpsStyleRef = registerCSS("timeline-fps"); - timelineSnapStyleRef = registerCSS("timeline-snap"); boxSidesLinkStyleRef = registerCSS("box-sides-link"); - curveFieldStyleRef = registerCSS("curve-field"); - curveWindowStyleRef = registerCSS("curve-window"); - curveToolbarStyleRef = registerCSS("curve-toolbar"); - curveChannelStyleRef = registerCSS("curve-channel"); - curvePlotStyleRef = registerCSS("curve-plot"); - curveLabelStyleRef = registerCSS("curve-label"); - curveReadoutStyleRef = registerCSS("curve-readout"); - curveBoxSelectStyleRef = registerCSS("curve-box-select"); - curvePresetStyleRef = registerCSS("curve-preset"); - curvePlotFramesStyleRef = registerCSS("curve-plot-frames"); - curveTreeStyleRef = registerCSS("curve-tree"); - curveTreeHeaderStyleRef = registerCSS("curve-tree-header"); - curveTreeGroupStyleRef = registerCSS("curve-tree-group"); - curveTreeRowStyleRef = registerCSS("curve-tree-row"); - curveTreeRowHiddenStyleRef = registerCSS("curve-tree-row-hidden"); - curveTreeSwatchStyleRef = registerCSS("curve-tree-swatch"); - curveTreeNameStyleRef = registerCSS("curve-tree-name"); - curveTreeValueStyleRef = registerCSS("curve-tree-value"); - curveRulerStyleRef = registerCSS("curve-ruler"); - curveRulerLabelStyleRef = registerCSS("curve-ruler-label"); - curvePlayheadStyleRef = registerCSS("curve-playhead"); - plotToolbarStyleRef = registerCSS("plot-toolbar"); - plotChannelStyleRef = registerCSS("plot-channel"); - plotStyleRef = registerCSS("plot"); - plotLabelStyleRef = registerCSS("plot-label"); - plotReadoutStyleRef = registerCSS("plot-readout"); - viewportStyleRef = registerCSS("viewport"); - viewportToolsStyleRef = registerCSS("viewport-tools"); - viewportToolStyleRef = registerCSS("viewport-tool"); - viewportAxisLabelStyleRef = registerCSS("viewport-axis-label"); - timelineZoomStyleRef = registerCSS("timeline-zoom"); - timelineZoomIconStyleRef = registerCSS("timeline-zoom-icon"); - timelineHeaderStyleRef = registerCSS("timeline-header"); - timelineListHeaderStyleRef = registerCSS("timeline-list-header"); - timelineListTitleStyleRef = registerCSS("timeline-list-title"); - timelineFilterStyleRef = registerCSS("timeline-filter"); - timelineAddTrackStyleRef = registerCSS("timeline-add-track"); - timelineBodyStyleRef = registerCSS("timeline-body"); - timelineListStyleRef = registerCSS("timeline-list"); - timelineRowStyleRef = registerCSS("timeline-row"); - timelineChevronStyleRef = registerCSS("timeline-chevron"); - timelineChipStyleRef = registerCSS("timeline-chip"); - timelineGroupNameStyleRef = registerCSS("timeline-group-name"); - timelineTrackNameStyleRef = registerCSS("timeline-track-name"); timelineRowButtonStyleRef = registerCSS("timeline-row-button"); - timelineMuteStyleRef = registerCSS("timeline-mute"); - timelineSoloStyleRef = registerCSS("timeline-solo"); - timelineRulerStyleRef = registerCSS("timeline-ruler"); - timelineRulerLabelStyleRef = registerCSS("timeline-ruler-label"); - timelinePlayheadLabelStyleRef = registerCSS("timeline-playhead-label"); - timelineLanesStyleRef = registerCSS("timeline-lanes"); - timelineLaneSelectedStyleRef = registerCSS("timeline-lane-selected"); - timelineRowLineStyleRef = registerCSS("timeline-row-line"); - timelineOutsideStyleRef = registerCSS("timeline-outside"); - timelineLoopRangeStyleRef = registerCSS("timeline-loop-range"); - timelineLoopEdgeStyleRef = registerCSS("timeline-loop-edge"); - timelineClipStyleRef = registerCSS("timeline-clip"); - timelineEventStyleRef = registerCSS("timeline-event"); - timelineEventChipStyleRef = registerCSS("timeline-event-chip"); - timelineEventLabelStyleRef = registerCSS("timeline-event-label"); - timelineBoxSelectStyleRef = registerCSS("timeline-box-select"); - timelineScrollStyleRef = registerCSS("timeline-scroll"); - timelineScrollThumbStyleRef = registerCSS("timeline-scroll-thumb"); - - - 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"); @@ -1020,43 +717,12 @@ namespace tachyon // ------------------------------------------------------------------------- // Table styles (row x column data grid) // ------------------------------------------------------------------------- - tableStyleRef = registerCSS("table"); - tableFillStyleRef = registerCSS("table-fill"); - tableHeaderSectionStyleRef = registerCSS("table-header-section"); - tableBodiesRowStyleRef = registerCSS("table-bodies-row"); - tableScrollableBodyStyleRef = registerCSS("table-scrollable-body"); - tableFitContentBodyStyleRef = registerCSS("table-fit-content-body"); - tableRowStyleRef = registerCSS("table-row"); - tableRowAltStyleRef = registerCSS("table-row-alt"); - tableRowBarStyleRef = registerCSS("table-row-bar"); - listRowStyleRef = registerCSS("list-row"); - tableHeaderStyleRef = registerCSS("table-header"); - tableHeaderLockedStyleRef = registerCSS("table-header-locked"); - tableHeaderEndStyleRef = registerCSS("table-header-end"); - tableHeaderLockedEndStyleRef = registerCSS("table-header-locked-end"); - tableSizerStyleRef = registerCSS("table-sizer"); - tableSeparatorStyleRef = registerCSS("table-separator"); - tableCellStyleRef = registerCSS("table-cell"); - tableCellNumberStyleRef = registerCSS("table-cell-number"); - tableCellCompactStyleRef = registerCSS("table-cell-compact"); - treeTableCellStyleRef = registerCSS("tree-table-cell"); - treeTableCellRowModeStyleRef = registerCSS("tree-table-cell-row-mode"); - treeTableArrowGlyphStyleRef = registerCSS("tree-table-arrow-glyph"); - treeTableIndentStyleRef = registerCSS("tree-table-indent"); - treeTableArrowStyleRef = registerCSS("tree-table-arrow"); - treeTableIconStyleRef = registerCSS("tree-table-icon"); - treeTableTextStyleRef = registerCSS("tree-table-text"); - treeTableTextEditStyleRef = registerCSS("tree-table-text-edit"); // ------------------------------------------------------------------------- // Window and menu styles from CSS // ------------------------------------------------------------------------- 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"); @@ -1081,9 +747,7 @@ 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") }, - { timelineFpsStyleRef, partsOf("timeline-fps") }, { iconMenuButtonStyleRef, DropdownParts{ registerCSS("icon-menu-button-text"), StyleRef::Invalid() } }, }; } @@ -1120,9 +784,6 @@ namespace tachyon tooltipPinRowStyleRef = registerCSS("tooltip-pin-row"); tooltipPinTypeStyleRef = registerCSS("tooltip-pin-type"); tooltipPinValueStyleRef = registerCSS("tooltip-pin-value"); - settingsPageSelectionRef = registerCSS("settings-page-selection"); - settingsPageStyleRef = registerCSS("settings-page"); - settingsSizerStyleRef = registerCSS("settings-sizer"); shortcutButtonStyleRef = registerCSS("shortcut-button"); keycapStyleRef = registerCSS("keycap"); shortcutMutedStyleRef = registerCSS("shortcut-muted"); @@ -1132,9 +793,7 @@ namespace tachyon void GUITheme::ComputeRowMetrics(StyleManager& styleManager, ITextSystem& textSystem) { - // Measure "Mg" (ascender + descender) in both cell styles; the max gives mixed tables - // a uniform row height. Must be real metrics: VirtualTable's spacer math uses it - // verbatim, and an estimate makes the max scroll oscillate. + // "Mg" (ascender + descender) in `style`, with its padding and border. auto measure = [&](StyleRef style) -> int32_t { const TextID probeID = textSystem.RegisterText( ID::Invalid(), "Mg", style, ElementState::None); @@ -1144,9 +803,6 @@ namespace tachyon if (ls) h += ls->padding.Vertical() + ls->borderWidths.Vertical(); return std::max(1, h); }; - tableRowHeight = std::max(measure(tableCellStyleRef), - measure(treeTableCellStyleRef)); - // Vector component labels share one width, the widest name with its padding and border. axisLabelWidth = 1; for (const char* name : { "X", "Y", "Z", "W", "R", "G", "B", "A" }) @@ -1159,33 +815,12 @@ namespace tachyon axisLabelWidth = std::max(axisLabelWidth, w); } - // Tree-table cell metrics: the stylesheet owns them; a missing value falls back to the - // text line height so it still follows the font. - { - const TextID probeID = textSystem.RegisterText( - ID::Invalid(), "Mg", treeTableTextStyleRef, ElementState::None); - const int32_t lineHeight = std::max(1, textSystem.GetTextMeasurement(probeID).minHeight); - auto cssWidth = [&](StyleRef s) -> int32_t { - const LayoutStyle* ls = styleManager.GetLayoutStyle(s.layoutStyleIndex); - return (ls && ls->layoutData.width != LayoutData::kAutoSize) ? ls->layoutData.width : lineHeight; - }; - auto cssIconSize = [&](StyleRef s, int32_t fallback) -> int32_t { - const LayoutStyle* ls = styleManager.GetLayoutStyle(s.layoutStyleIndex); - return (ls && ls->iconSize > 0) ? static_cast(ls->iconSize) : fallback; - }; - treeTableIndent = cssWidth(treeTableIndentStyleRef); - treeTableExpanderWidth = cssWidth(treeTableArrowStyleRef); - treeTableIconSize = cssIconSize(treeTableIconStyleRef, lineHeight); - treeTableArrowGlyphSize = cssIconSize(treeTableArrowGlyphStyleRef, treeTableIconSize); - } - - // Same for the files grid (icon-on-top label line, icon-left list row), so names never clip. + // A grid view's list-mode row (icon left of its name), so names never clip. auto measureText = [&](StyleRef style) -> int32_t { const TextID probeID = textSystem.RegisterText( ID::Invalid(), "Mg", style, ElementState::None); return std::max(1, textSystem.GetTextMeasurement(probeID).minHeight); }; - gridViewItemLineHeight = measureText(gridViewItemStyleRef); { const int32_t listText = measureText(gridViewListItemStyleRef); const LayoutStyle* ls = styleManager.GetLayoutStyle(gridViewListItemStyleRef.layoutStyleIndex); @@ -1194,13 +829,5 @@ namespace tachyon gridViewListRowHeight = std::max(listText, iconSize) + pad; } - // The node view's single grid pitch (node/wire snapping and the drawn grid): half a - // property row, so row edges and centers (sockets) land on grid lines. The row lays - // the field out at its margin box, so the margin is included. - float fieldHeight = (float)measure(regularControls.textbox); - if (const LayoutStyle* tb = styleManager.GetLayoutStyle(regularControls.textbox.layoutStyleIndex)) - fieldHeight += tb->margin.Vertical(); - fieldHeight /= 2.0f; // one property row = two grid cells - nodeGridSize = (int)ceil(fieldHeight); } } // namespace tachyon diff --git a/src/gui_controls/gui_theme.h b/src/gui_controls/gui_theme.h index cf04e88b..dc9c6aa1 100644 --- a/src/gui_controls/gui_theme.h +++ b/src/gui_controls/gui_theme.h @@ -68,7 +68,7 @@ namespace tachyon /// The library's styles, icons and theme metrics, the defaults the controls draw with. /// LoadTheme registers every class of the style files; each xxxStyleRef below is the - /// class of the same name in kebab-case (tableRowAltStyleRef -> .table-row-alt) unless + /// class of the same name in kebab-case (menuItemRowStyleRef -> .menu-item-row) unless /// its comment names another. They are reassigned on every theme (re)load. /// /// An app's own classes (from SetStyleFiles) are found by name; look them up in OnGUI, @@ -81,7 +81,6 @@ namespace tachyon public: ControlStyles regularControls {}; ///< .button, .toggle, .textbox, .number-field, .menu-trigger ControlStyles toolbarControls {}; ///< the .toolbar-* variants of those - ControlStyles nodeControls {}; ///< in a node's rows: the regular ones, numbers in .node-number-field const ControlStyles* controls = ®ularControls; ///< the bundle in use StyleRef emptyHorzStyleRef; ///< horizontal flex, no wrap; groups elements without drawing anything @@ -164,18 +163,9 @@ namespace tachyon StyleRef scrollbarHorizontalThumbStyleRef {}; ///@} int scrollbarThickness = 12; ///< .scrollbar-vertical width (read from CSS, at the UI scale) - StyleRef colorSwatchStyleRef {}; ///< ColorField: the swatch - StyleRef colorFieldStyleRef {}; ///< ColorField: swatch, hex and alpha in a row - StyleRef colorHexStyleRef {}; ///< ColorField: the hex field - StyleRef colorAlphaStyleRef {}; ///< ColorField: the alpha box (value and %) - StyleRef colorAlphaInputStyleRef {}; ///< ColorField: the alpha value in its box - StyleRef colorAlphaUnitStyleRef {}; ///< ColorField: the % after it - StyleRef colorAlphaCaptionStyleRef {}; ///< ColorField: the "A" before it - StyleRef colorPickerStyleRef {}; ///< color picker: the window StyleRef dialogHeaderStyleRef {}; ///< dialog: the title row StyleRef dialogTitleStyleRef {}; ///< dialog: its title StyleRef dialogContextStyleRef {}; ///< dialog: what's being edited, after the title - StyleRef colorPickerHdrValueStyleRef {}; ///< color picker: the intensity value StyleRef dialogCloseStyleRef {}; ///< dialog: the close button StyleRef dialogFooterStyleRef {}; ///< dialog: status and buttons StyleRef dialogStatusStyleRef {}; ///< dialog: the footer's status text @@ -186,131 +176,24 @@ namespace tachyon StyleRef checkboxStyleRef {}; ///< Checkbox: the control StyleRef checkboxBoxStyleRef {}; ///< Checkbox: the box StyleRef checkboxLabelStyleRef {}; ///< Checkbox: its label - StyleRef colorPickerBodyStyleRef {}; ///< color picker: planes and controls - StyleRef colorPickerPlanesStyleRef {}; ///< color picker: square and strips - StyleRef colorPickerSquareStyleRef {}; ///< color picker: the saturation/value square - StyleRef colorPickerStripStyleRef {}; ///< color picker: the hue and alpha strips - StyleRef colorPickerControlsStyleRef {}; ///< color picker: the right column - StyleRef colorPickerPreviewGroupStyleRef {}; ///< color picker: preview and captions - StyleRef colorPickerCaptionsStyleRef {}; ///< color picker: New / Original - StyleRef colorPickerCaptionStyleRef {}; ///< color picker: a small caption - StyleRef colorPickerModeRowStyleRef {}; ///< color picker: space, Linear, range - StyleRef colorPickerRangeStyleRef {}; ///< color picker: the 0-255 / 0-1 toggle - StyleRef colorPickerChannelsStyleRef {}; ///< color picker: the channel rows - StyleRef colorPickerChannelStyleRef {}; ///< color picker: one channel row - StyleRef colorPickerChannelLabelStyleRef {}; ///< color picker: R, G, B, A ... - StyleRef colorPickerTrackStyleRef {}; ///< color picker: a channel's track - StyleRef colorPickerChannelValueStyleRef {}; ///< color picker: a channel's value - StyleRef colorPickerFieldRowStyleRef {}; ///< color picker: Hex / HDR rows - StyleRef colorPickerRowLabelStyleRef {}; ///< color picker: Hex, HDR - StyleRef colorPickerHdrStyleRef {}; ///< color picker: the intensity box - StyleRef colorPickerSwatchesStyleRef {}; ///< color picker: swatches and recent - StyleRef colorPickerSwatchRowStyleRef {}; ///< color picker: one swatch row - StyleRef colorPickerSectionLabelStyleRef {}; ///< color picker: Swatches, Recent - StyleRef colorPickerSwatchStyleRef {}; ///< color picker: a swatch - StyleRef colorPickerRecentStyleRef {}; ///< color picker: a recent color - StyleRef colorPickerPreviewStyleRef {}; ///< color picker: the color preview - StyleRef colorPickerNewStyleRef{}; ///< color picker: the add-swatch button - StyleRef gradientSwatchStyleRef {}; ///< GradientField: the swatch - StyleRef nodeFrameMenuStyleRef {}; ///< a node frame's "..." button, at its title bar's end - StyleRef nodeViewOverlayDividerStyleRef {}; ///< the line before Fit in a node view's zoom bar - StyleRef nodeStateTimeStyleRef {}; ///< the pill under a state machine's active state: its time in it - StyleRef nodeStateNestedMarkStyleRef {}; ///< the mark at the end of a state holding a machine (its size) - StyleRef gradientEditorStyleRef {}; ///< gradient editor: the window - StyleRef gradientEditorBarStyleRef {}; ///< gradient editor: the gradient bar with its stops StyleRef dialogSmallButtonStyleRef {}; ///< dialog: a short button (Save preset, Reverse) StyleRef dialogIconButtonStyleRef {}; ///< dialog: a small borderless icon button (previous / next) StyleRef dialogSquareButtonStyleRef {}; ///< dialog: a small bordered icon button (duplicate) StyleRef dialogDeleteButtonStyleRef {}; ///< dialog: the same, in the error color - StyleRef gradientEditorPresetsStyleRef {}; ///< gradient editor: the presets row - StyleRef gradientEditorSectionLabelStyleRef {}; ///< gradient editor: Presets - StyleRef gradientEditorPresetStyleRef {}; ///< gradient editor: a preset chip - StyleRef gradientEditorBadgeStyleRef {}; ///< gradient editor: the selected stop's location - StyleRef gradientEditorColumnsStyleRef {}; ///< gradient editor: the two columns - StyleRef gradientEditorColumnStyleRef {}; ///< gradient editor: the left column - StyleRef gradientEditorRowStyleRef {}; ///< gradient editor: a labeled row - StyleRef gradientEditorHeadingStyleRef {}; ///< gradient editor: Color stop - StyleRef gradientEditorCountStyleRef {}; ///< gradient editor: 2 / 3 - StyleRef gradientEditorLabelStyleRef {}; ///< gradient editor: a row's label - StyleRef gradientEditorLocationStyleRef {}; ///< gradient editor: the location box - StyleRef gradientEditorLocationInputStyleRef {}; ///< gradient editor: its value - StyleRef gradientEditorLocationUnitStyleRef {}; ///< gradient editor: its % - StyleRef gradientEditorDividerStyleRef {}; ///< gradient editor: a divider line - StyleRef gradientEditorActionsStyleRef {}; ///< gradient editor: Reverse, Distribute - StyleRef gradientEditorTableStyleRef {}; ///< gradient editor: the stops table - StyleRef gradientEditorTableHeadStyleRef {}; ///< gradient editor: its header row - StyleRef gradientEditorTableRowStyleRef {}; ///< gradient editor: a stop's row - StyleRef gradientEditorTypeCellStyleRef {}; ///< gradient editor: Type - StyleRef gradientEditorSwatchCellStyleRef {}; ///< gradient editor: the stop's color - StyleRef gradientEditorHeadCellStyleRef {}; ///< gradient editor: a header caption - StyleRef gradientEditorHeadLocationStyleRef {}; ///< gradient editor: Location - StyleRef gradientEditorValueCellStyleRef {}; ///< gradient editor: the stop's hex - StyleRef gradientEditorLocationCellStyleRef {}; ///< gradient editor: the stop's location - StyleRef tableStyleRef {}; ///< Table: the table /// Table bounded to its flex container (flex-basis:0): it doesn't grow, its rows scroll. - StyleRef tableFillStyleRef {}; /// Header grid, a sibling of the body so it doesn't scroll with the rows. - StyleRef tableHeaderSectionStyleRef {}; - StyleRef tableBodiesRowStyleRef {}; ///< row holding the table's body sections, bounded to the table - StyleRef tableScrollableBodyStyleRef {}; ///< a scrolling section body /// SectionSizing::FitContent section body. - StyleRef tableFitContentBodyStyleRef {}; - StyleRef tableRowStyleRef {}; ///< row backdrop (odd rows) - StyleRef tableRowAltStyleRef {}; ///< row backdrop (even rows) - StyleRef tableRowBarStyleRef {}; ///< accent bar on a selected row's left - StyleRef listRowStyleRef {}; ///< rounded row without stripes (tree views, TableState::rowStyle) /// Row-mode tree cell: transparent hover/selected, so the row backdrop shows them. - StyleRef treeTableCellRowModeStyleRef {}; /// The arrow's NoInput glyph, inside a full-row-height hit wrapper /// (treeTableArrowStyleRef) for forgiving clicks. - StyleRef treeTableArrowGlyphStyleRef {}; /// Inline-rename editor. Same box as treeTableTextStyleRef (both have a 1px border), /// so the text doesn't move when a rename starts. - StyleRef treeTableTextEditStyleRef {}; - StyleRef tableHeaderStyleRef {}; ///< a column header /// Locked column headers: default cursor, since they can't be dragged. - StyleRef tableHeaderLockedStyleRef {}; - StyleRef tableHeaderEndStyleRef {}; ///< as tableHeaderStyleRef, over cells aligned to the end (numbers) - StyleRef tableHeaderLockedEndStyleRef {}; ///< as tableHeaderLockedStyleRef, over cells aligned to the end - StyleRef tableSizerStyleRef {}; ///< a column's resize handle - StyleRef tableSeparatorStyleRef {}; ///< the divider between table sections - StyleRef tableCellStyleRef {}; ///< a cell - StyleRef tableCellNumberStyleRef {}; ///< right-aligned number cell (TableColumn::cellStyle) - StyleRef tableCellCompactStyleRef {}; ///< tighter-padded cell for dense tables (opt-in via VirtualTable cellStyle) /// @name Tree table cells /// Tree column: [indent][arrow|spacer][icon?][text], guide lines custom-drawn. ///@{ - StyleRef treeTableCellStyleRef {}; - StyleRef treeTableIndentStyleRef {}; - StyleRef treeTableArrowStyleRef {}; - StyleRef treeTableIconStyleRef {}; - StyleRef treeTableTextStyleRef {}; ///@} - StyleRef nodeViewStyleRef {}; ///< NodeView: the canvas StyleRef viewBackgroundStyleRef {}; ///< solid backdrop (--bg-app) for the View panel's toolbar dock - StyleRef nodeStyleRef {}; ///< single node container (vertical column with border + bg) - StyleRef nodeRerouteStyleRef {}; ///< a reroute node's square (the dot is drawn on it) - StyleRef nodeFrameStyleRef {}; ///< a frame's box (drawn behind the wires) - StyleRef nodeFrameBandStyleRef {}; ///< its title bar's band, over the top of the box - StyleRef nodeFrameTitleStyleRef {}; ///< the title on it - StyleRef nodeFrameRenameStyleRef {}; ///< the field over the title bar while renaming - StyleRef nodeTransitionLabelStyleRef {}; ///< a state machine transition's label: its text and its chip - StyleRef nodeTransitionRenameStyleRef {}; ///< the field over a transition's label while relabelling - StyleRef nodeStateActiveStyleRef {}; ///< the ring round the state a machine is in - StyleRef nodeStateEdgeStyleRef {}; ///< the ring round a state whose edge is hovered (a transition starts there) - StyleRef nodeStateNestedStyleRef {}; ///< the mark on a state that holds a machine of its own - StyleRef nodeFramePortsStyleRef {}; ///< a collapsed frame's row, a wire in and one out - StyleRef nodeFramePortStyleRef {}; ///< the name of the input on it - StyleRef nodeFramePortOutStyleRef {};///< the name of the output on it - StyleRef nodeHeaderStyleRef {}; ///< node title bar (distinct background, sits at top of node) - StyleRef nodeHeaderStateStyleRef {}; ///< a state machine's state: the title bar alone, no line under it - StyleRef nodeStateStyleRef {}; ///< a state machine's state: a node box with nothing under its title bar - StyleRef nodeCategoryStyleRef {}; ///< the category square in a node header - StyleRef nodeTitleStyleRef {}; ///< a node header's title - StyleRef nodeCaptionStyleRef {}; ///< a node header's category name, right-aligned - StyleRef nodeViewOverlayStyleRef {}; ///< panel floating over the node view (breadcrumb, zoom bar) - StyleRef nodeViewOverlayButtonStyleRef {}; ///< flat button in such a panel - StyleRef nodeViewMinimapStyleRef {}; ///< the node view's minimap StyleRef breadcrumbStyleRef {}; ///< the breadcrumb path bar StyleRef breadcrumbSegmentStyleRef {}; ///< a clickable path segment StyleRef breadcrumbCurrentStyleRef {}; ///< the last segment @@ -332,24 +215,11 @@ namespace tachyon StyleRef commandSearchListStyleRef {}; StyleRef commandSearchCurrentRowStyleRef {}; ///@} - StyleRef nodeRowStyleRef {}; ///< node property row (socket | body | socket) - StyleRef nodeBodyCenterStyleRef {}; ///< centered body for full-body content (image previews) /// A socket's hit target; overflow:visible so the dot and its hover halo aren't clipped. - StyleRef nodeSocketStyleRef {}; - /// .node-socket box size in pixels (read from CSS); the custom-drawn dot and the - /// on-border insets derive from it. - int socketSize = 12; - StyleRef nodeTextLeftStyleRef {}; ///< text-only property body, left-aligned (left dot only) - StyleRef nodeTextCenterStyleRef {}; ///< text-only property body, centered (both dots) - StyleRef nodeTextRightStyleRef {}; ///< text-only property body, right-aligned (right dot only) StyleRef itemListStyleRef {}; ///< a bordered scrolling list box 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 @@ -397,6 +267,10 @@ namespace tachyon /// The parts of the trigger in `button`'s style; the plain `dropdown-text` and /// `dropdown-arrow` for a style without parts of its own. DropdownParts DropdownPartsFor(StyleRef button) const; + /// Makes `trigger`, a dropdown style of a control outside the library, draw its parts + /// as the CSS classes `cssClass`-text and `cssClass`-arrow. Call it after each theme + /// load, which forgets it. + void RegisterDropdownParts(StyleRef trigger, std::string_view cssClass); StyleRef titleBarStyleRef {}; ///< a window's own title bar (BeginTitleBar) StyleRef titleBarButtonStyleRef {}; ///< its minimize and maximize buttons StyleRef titleBarCloseButtonStyleRef {}; ///< its close button @@ -447,22 +321,9 @@ namespace tachyon StyleRef horzReorderableGroupWrapStyleRef{}; StyleRef vertReorderableGroupWrapStyleRef{}; ///@} - StyleRef listViewStyleRef {}; ///< BeginListView's default - StyleRef listItemStyleRef {}; ///< ListItem's default - StyleRef listItemRowStyleRef {}; ///< reorderable list item outer container StyleRef listItemDragKnobHorzStyleRef {}; ///< reorderable list item drag handle (horizontal list - drag along x) StyleRef listItemDragKnobVertStyleRef {}; ///< reorderable list item drag handle (vertical list - drag along y) - StyleRef listItemBodyStyleRef {}; ///< reorderable list item text/icon body - StyleRef treeViewStyleRef {}; ///< a tree view - StyleRef gridViewStyleRef {}; ///< BeginGridView's default - StyleRef gridViewItemStyleRef {}; ///< a grid view cell, by default - StyleRef gridViewScrollStyleRef {}; ///< virtualized grid scroll viewport (column) - StyleRef gridViewRowStyleRef {}; ///< one row strip of cells in the virtual grid StyleRef gridViewListItemStyleRef {}; ///< list-mode cell: icon left, name right, one line - StyleRef gridViewRenameItemStyleRef {}; ///< rename-mode cell: icon above inline editor - StyleRef gridViewRenameListItemStyleRef {}; ///< rename-mode list row: icon left of editor - StyleRef gridViewRenameIconStyleRef {}; ///< the icon child of a renaming cell - StyleRef gridViewRenameEditStyleRef {}; ///< grid-mode inline editor (full cell width) StyleRef flexFillRowStyleRef {}; ///< horizontal flex bounded to its parent (flex-basis:0) StyleRef flexFillColStyleRef {}; ///< vertical flex bounded to its parent (flex-basis:0) StyleRef flatButtonStyleRef {}; ///< button that reads as plain left-aligned text (no chrome) @@ -476,9 +337,6 @@ namespace tachyon ///@} /// Parsed .grid-view-item, for cloning with another iconSize (registering is deduped). Style gridViewItemBaseStyle {}; - /// Line height of a grid view cell's name in pixels, measured in ComputeRowMetrics so - /// names never clip. - int32_t gridViewItemLineHeight = 0; int32_t gridViewListRowHeight = 0; ///< a list-mode grid view row, in pixels (ComputeRowMetrics) /// @name Tabs /// A tab bar, a tab, a tab's icon and text, and its close button. @@ -494,91 +352,8 @@ namespace tachyon /// @name Progress and loading ///@{ StyleRef statusTextMonoStyleRef {}; ///< a status bar's count, monospace - StyleRef timelineStyleRef {}; ///< Timeline: the row - StyleRef timelineTransportStyleRef {}; ///< its buttons - StyleRef timelineButtonStyleRef {}; ///< a transport button: start, step, end - StyleRef timelinePlayStyleRef {}; ///< play / pause, in the accent - StyleRef timelineLoopStyleRef {}; ///< the loop toggle; selected while looping - StyleRef timelineTimeStyleRef {}; ///< the time's well - StyleRef timelineTimeCurrentStyleRef {}; ///< the time now, monospace - StyleRef timelineTimeTotalStyleRef {}; ///< "/ " and the length - StyleRef timelineFrameStyleRef {}; ///< the frame chip - StyleRef timelineScrubberStyleRef {}; ///< the scrubber - StyleRef timelineReadyStyleRef {}; ///< drawn: the progress fill - StyleRef timelineTickStyleRef {}; ///< drawn: a tick every quarter second (or the like) - StyleRef timelineTickMajorStyleRef {}; ///< drawn: a tick every second (or the like) - StyleRef timelineMarkerStyleRef {}; ///< drawn: a marker's line - StyleRef timelinePlayheadStyleRef {}; ///< drawn: the playhead's line and its head - StyleRef timelineEditorStyleRef {}; ///< TimelineEditor: the whole - StyleRef timelineToolbarStyleRef {}; ///< its toolbar: transport, time, fps, snap, zoom - StyleRef timelineDividerStyleRef {}; ///< a line between the toolbar's groups - StyleRef curveFrameAllStyleRef {}; ///< CurveEditor: Frame all, a flat button - StyleRef timelineFpsStyleRef {}; ///< the fps dropdown - StyleRef timelineSnapStyleRef {}; ///< the Snap toggle; selected while snapping StyleRef boxSidesLinkStyleRef {}; ///< EdgesField / CornersField: the link toggle; selected while linked - StyleRef curveFieldStyleRef {}; ///< CurveField: the box the curve is drawn in - StyleRef curveWindowStyleRef {}; ///< its editor's window - StyleRef curveToolbarStyleRef {}; ///< the editor's rows over and under the plot - StyleRef curveChannelStyleRef {}; ///< a channel's chip; selected for the active one - StyleRef curvePlotStyleRef {}; ///< the plot; its padding holds the grid's labels - StyleRef curveLabelStyleRef {}; ///< drawn: a grid line's number - StyleRef curveReadoutStyleRef {}; ///< drawn: the selected key's time and value beside it - StyleRef curveBoxSelectStyleRef {}; ///< drawn: the box a drag on the plot selects with - StyleRef curvePresetStyleRef {}; ///< a preset's thumbnail button - StyleRef curvePlotFramesStyleRef {}; ///< the plot with fps set: no time labels under it - StyleRef curveTreeStyleRef {}; ///< the channel list down the left - StyleRef curveTreeHeaderStyleRef {}; ///< its header: Channel, and the playhead's frame - StyleRef curveTreeGroupStyleRef {}; ///< a group's row, its chevron before its name - StyleRef curveTreeRowStyleRef {}; ///< a channel's row; selected for the active one - StyleRef curveTreeRowHiddenStyleRef {}; ///< a hidden channel's row, faded - StyleRef curveTreeSwatchStyleRef {}; ///< a channel's color square - StyleRef curveTreeNameStyleRef {}; ///< a channel's name - StyleRef curveTreeValueStyleRef {}; ///< its value at the playhead - StyleRef curveRulerStyleRef {}; ///< the frame ruler over the plot - StyleRef curveRulerLabelStyleRef {}; ///< drawn: a frame number on it - StyleRef curvePlayheadStyleRef {}; ///< drawn: the playhead's frame, in its pill - StyleRef plotToolbarStyleRef {}; ///< Plot: the row of series chips over it - StyleRef plotChannelStyleRef {}; ///< a series' chip; selected for the one shown - StyleRef plotStyleRef {}; ///< the plot; its padding holds the labels and the handles - StyleRef plotLabelStyleRef {}; ///< drawn: a grid line's number - StyleRef plotReadoutStyleRef {}; ///< drawn: the values under the pointer - StyleRef viewportStyleRef {}; ///< Viewport: the view - StyleRef viewportToolsStyleRef {}; ///< the tools' strip down its left - StyleRef viewportToolStyleRef {}; ///< a tool's button; selected for the one in use - StyleRef viewportAxisLabelStyleRef {}; ///< drawn: an axis's letter at the top right - StyleRef timelineZoomStyleRef {}; ///< the zoom slider and its icons - StyleRef timelineZoomIconStyleRef {}; ///< a magnifier beside the zoom slider - StyleRef timelineHeaderStyleRef {}; ///< the row over the track list and the ruler - StyleRef timelineListHeaderStyleRef {}; ///< "Tracks", the filter and the add button - StyleRef timelineListTitleStyleRef {}; ///< "Tracks" - StyleRef timelineFilterStyleRef {}; ///< the filter field - StyleRef timelineAddTrackStyleRef {}; ///< the add-track button - StyleRef timelineBodyStyleRef {}; ///< the track list and lanes, scrolled together - StyleRef timelineListStyleRef {}; ///< the track list - StyleRef timelineRowStyleRef {}; ///< a track's row; selected while it's the selected track - StyleRef timelineChevronStyleRef {}; ///< a group's expand / collapse - StyleRef timelineChipStyleRef {}; ///< a group's color chip - StyleRef timelineGroupNameStyleRef {}; ///< a group's name - StyleRef timelineTrackNameStyleRef {}; ///< another track's name, with its icon StyleRef timelineRowButtonStyleRef {}; ///< eye, lock and add-key buttons - StyleRef timelineMuteStyleRef {}; ///< an audio track's M; selected while muted - StyleRef timelineSoloStyleRef {}; ///< an audio track's S; selected while solo - StyleRef timelineRulerStyleRef {}; ///< the ruler over the lanes - StyleRef timelineRulerLabelStyleRef {}; ///< drawn: a second's label on the ruler - StyleRef timelinePlayheadLabelStyleRef {}; ///< drawn: the playhead's time on the ruler - StyleRef timelineLanesStyleRef {}; ///< the lanes - StyleRef timelineLaneSelectedStyleRef {}; ///< drawn: the selected track's lane - StyleRef timelineRowLineStyleRef {}; ///< drawn: the line under a row - StyleRef timelineOutsideStyleRef {}; ///< drawn: the lanes outside the loop range - StyleRef timelineLoopRangeStyleRef {}; ///< drawn: the loop range on the ruler - StyleRef timelineLoopEdgeStyleRef {}; ///< drawn: its ends - StyleRef timelineClipStyleRef {}; ///< drawn: an audio clip - StyleRef timelineEventStyleRef {}; ///< drawn: an event's line - StyleRef timelineEventChipStyleRef {}; ///< drawn: the chip under an event's name - StyleRef timelineEventLabelStyleRef {}; ///< drawn: an event's name - StyleRef timelineBoxSelectStyleRef {}; ///< drawn: the box being dragged to select keys - StyleRef timelineScrollStyleRef {}; ///< the scroll bar under the lanes - StyleRef timelineScrollThumbStyleRef {}; ///< drawn: its thumb static constexpr int kSpinnerFrames = 24; /// A 90-degree arc, one frame per 15 degrees round: a spinner that goes where an icon /// goes, in the color of the icon it stands in for (BusyButton). @@ -592,34 +367,9 @@ 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 settingsPageSelectionRef {}; ///< the settings page list (.settings-page-selection) - StyleRef settingsPageStyleRef {}; ///< settings page body - dock-content layout + left padding off the sizer - StyleRef settingsSizerStyleRef {}; ///< between the page list and the page: a 1px line, lit while hovered + StyleRef shortcutButtonStyleRef {}; ///< ShortcutButton: a flat row of keycaps StyleRef keycapStyleRef {}; ///< a key in a ShortcutButton StyleRef shortcutMutedStyleRef {}; ///< a ShortcutButton's "Unassigned" and the comma between a chord's steps @@ -631,8 +381,6 @@ namespace tachyon IconID treeArrowRight = IconID::Invalid; ///< tree expander: collapsed IconID treeArrowDown = IconID::Invalid; ///< tree expander: expanded - IconID sortArrowUpIcon = IconID::Invalid; ///< table header: sorted descending - IconID sortArrowDownIcon = IconID::Invalid; ///< table header: sorted ascending IconID tabCloseIcon = IconID::Invalid; ///< a tab's close button IconID menuCheckIcon = IconID::Invalid; ///< marks the current/checked item in a menu @@ -650,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 @@ -664,76 +411,23 @@ namespace tachyon IconID windowMinimizeIcon = IconID::Invalid; ///< title bar: minimize IconID windowMaximizeIcon = IconID::Invalid; ///< title bar: maximize IconID windowRestoreIcon = IconID::Invalid; ///< title bar: restore - IconID timelineStartIcon = IconID::Invalid; ///< Timeline: go to the start - IconID timelineStepBackIcon = IconID::Invalid; ///< Timeline: a frame back IconID timelinePlayIcon = IconID::Invalid; ///< Timeline: play (filled) IconID timelinePauseIcon = IconID::Invalid; ///< Timeline: pause (filled) - IconID timelineStepIcon = IconID::Invalid; ///< Timeline: a frame on - IconID timelineEndIcon = IconID::Invalid; ///< Timeline: go to the end - IconID timelineLoopIcon = IconID::Invalid; ///< Timeline: loop - IconID timelinePrevKeyIcon = IconID::Invalid; ///< TimelineEditor: the previous key - IconID timelineNextKeyIcon = IconID::Invalid; ///< TimelineEditor: the next key - IconID timelineSnapIcon = IconID::Invalid; ///< TimelineEditor: snap (a magnet) - IconID timelineZoomInIcon = IconID::Invalid; ///< TimelineEditor: zoom in - IconID timelineZoomOutIcon = IconID::Invalid; ///< TimelineEditor: zoom out IconID timelineEyeIcon = IconID::Invalid; ///< TimelineEditor: a group shown IconID timelineEyeOffIcon = IconID::Invalid; ///< TimelineEditor: a group hidden - IconID timelineLockIcon = IconID::Invalid; ///< TimelineEditor: a group locked - IconID timelineUnlockIcon = IconID::Invalid; ///< TimelineEditor: a group unlocked - IconID timelineKeyIcon = IconID::Invalid; ///< TimelineEditor: add a key (a diamond) - IconID timelineAudioIcon = IconID::Invalid; ///< TimelineEditor: an audio track - IconID timelineEventsIcon = IconID::Invalid; ///< TimelineEditor: an events track (a flag) IconID linkIcon = IconID::Invalid; ///< EdgesField / CornersField: the sides are linked (a chain) - IconID curveFrameAllIcon = IconID::Invalid; ///< CurveField's editor: show all the keys (four corners) - IconID curveConstantIcon = IconID::Invalid; ///< its interpolations: a step - IconID curveLinearIcon = IconID::Invalid; ///< straight lines - IconID curveBezierIcon = IconID::Invalid; ///< a smooth curve - IconID viewportSelectIcon = IconID::Invalid; ///< Viewport's tools: select (a pointer) - IconID viewportMoveIcon = IconID::Invalid; ///< move (four arrows) - IconID viewportRotateIcon = IconID::Invalid; ///< rotate (a turning arrow) - IconID viewportScaleIcon = IconID::Invalid; ///< scale (a corner pulled out) IconID unlinkIcon = IconID::Invalid; ///< and each is its own (a broken chain) ///@} // Line colors, from the palette's custom properties. tachyon::VisualColorStyleIndex lineGrayStyle; ///< --text-3 - tachyon::VisualColorStyleIndex lineYellowStyle; ///< --warn - tachyon::VisualColorStyleIndex lineWhiteStyle; ///< --text-1 tachyon::VisualColorStyleIndex lineDarkStyle; ///< --bg-app - tachyon::VisualColorStyleIndex treeGuideLineStyle; ///< --tree-guide: tree guide lines (transparent: none) tachyon::VisualColorStyleIndex dividerHoverLineStyle; ///< a hovered divider drawn as a line (label sizer) tachyon::VisualColorStyleIndex nanTextColor; ///< a number field's NaN - /// TimelineEditor's keys: a key, its edge, a selected key and its edge, a group's - /// summary key, and an audio clip's waveform. - tachyon::VisualColorStyleIndex timelineKeyColor, timelineKeyEdgeColor, timelineKeySelectedColor, - timelineKeySelectedEdgeColor, timelineSummaryKeyColor, timelineWaveColor; - /// A curve editor's: the plot's grid, its major lines and its lines at zero; a key's edge - /// (the plot's color); a selected key and its tangent handles. - tachyon::VisualColorStyleIndex curveGridColor, curveGridMajorColor, curveZeroColor, curveKeyEdgeColor, - curveSelectedKeyColor, curveHandleColor; - /// A state machine's transitions: an arrow, a hovered one, a selected one; and the mark - /// of its initial state. - tachyon::VisualColorStyleIndex nodeTransitionColor, nodeTransitionHoverColor, nodeTransitionSelectedColor, - nodeInitialStateColor; - /// A channel's color by CurveChannelColor, and the same at 55% for the channels not - /// being edited. - tachyon::VisualColorStyleIndex curveChannelColors[5] {}, curveChannelFadedColors[5] {}; tachyon::color4b scrim {}; ///< dims a window under its modal dialog (fading in and out) /// --disabled-opacity: a disabled control, with all its parts, is drawn this opaque, /// unless its style sets an opacity for :disabled. float disabledOpacity = 0.4f; - /// How strongly a node view's colors show, each over what's under it (0 to 1): a node's - /// header and the line under it over --node-bg, a state's fill and border over - /// --node-bg, and a frame's box, title bar and border over the canvas. - /// --node-header-tint, --node-header-line-tint, --state-tint, --state-border-tint, - /// --frame-fill-tint, --frame-band-tint, --frame-border-tint. - struct NodeTints - { - float header = 0.24f, headerLine = 0.38f; - float state = 0.26f, stateBorder = 0.50f; - float frameFill = 0.07f, frameBand = 0.20f, frameBorder = 0.45f; - }; - NodeTints nodeTints {}; /// An invalid control's border color (--error) and the halo around it (--invalid-halo). tachyon::color4b invalidColor {}; tachyon::VisualShadow invalidHalo {}; @@ -747,7 +441,6 @@ namespace tachyon tachyon::VisualColorStyleIndex accentColor, panelColor; ///< a selected swatch's ring and gap tachyon::VisualColorStyleIndex treeDropIndicatorStyle; ///< drop indicator lines + closed-branch outline - tachyon::VisualColorStyleIndex marqueeFillColorStyle; ///< selection-marquee fill (fixed translucent blue) tachyon::VisualColorStyleIndex imageFillColorStyle; ///< a texture stretched over a quad (RenderQuad with an image) tachyon::VisualColorStyleIndex clearColorStyle; ///< fully transparent tachyon::VisualColorStyleIndex tooltipArrowFill; ///< --tooltip-bg: a tooltip's arrow @@ -756,22 +449,6 @@ namespace tachyon tachyon::VisualColorStyleIndex popupArrowLine; ///< --line-strong: its edges tachyon::VisualColorStyleIndex invalidLine; ///< --error: an error tooltip's arrow edges, a field's error icon - /// Table row height in pixels, measured from real font metrics in ComputeRowMetrics. - /// Must match the rendered rows exactly, or the max scroll oscillates. - int32_t tableRowHeight = 0; - - /// @name Tree table metrics - /// Pixels, read from the stylesheet in ComputeRowMetrics; a theme that omits one gets - /// the measured text line height. - ///@{ - int32_t treeTableIndent = 0; ///< per indent level - int32_t treeTableExpanderWidth = 0; ///< the expander column (arrow or leaf spacer) - int32_t treeTableIconSize = 0; ///< a node's icon - int32_t treeTableArrowGlyphSize = 0; ///< the expander arrow - ///@} - - /// Node-view grid pitch: half a property row, measured in ComputeRowMetrics. - int32_t nodeGridSize = 0; public: /// Registers the styles built in code (fieldElementGroupStyleRef, the empty*StyleRefs) diff --git a/src/gui_controls/gui_ui_state.cpp b/src/gui_controls/gui_ui_state.cpp index 89985c5a..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,88 +115,84 @@ 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::PersistTable(std::string key, TableState& state, std::span columns) - { - Upsert(m_persistTables, std::move(key), PersistedTable::Target{ &state, columns }); - } - void GUIApplication::PersistDocuments(std::string key, std::function()> 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) { - Upsert(m_persistDocuments, std::move(key), std::move(windows)); + for (PersistedJson& entry : m_persistJson) + if (entry.section == section && entry.key == key) + { + entry.save = std::move(save); + entry.restore = std::move(restore); + return; + } + m_persistJson.push_back({ std::move(section), std::move(key), std::move(save), std::move(restore) }); } - void GUIApplication::PersistShortcuts(std::string key, CommandManager& commands) { Upsert(m_persistShortcuts, std::move(key), &commands); } - 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 + std::optional GUIApplication::SaveWindowPlace(ID windowID) 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) - { - // 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; + return w; } - std::vector GUIApplication::TakeSavedDocuments(std::string_view key) + std::optional GUIApplication::ReadWindowPlace(const JsonValue* saved) { - 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; - } - - bool GUIApplication::RestoreDocumentLayout(Document& document, const SavedDocument& saved, - const std::function(std::string_view key)>& makePanel) - { - 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; } @@ -368,101 +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 tables = JsonValue::MakeObject(); - for (const auto& [key, table] : m_persistTables) - { - JsonValue columns = JsonValue::MakeArray(); - for (size_t i = 0; i < table.columns.size(); ++i) - { - const TableColumn& column = table.columns[i].column; - const int32_t width = i < table.state->columnWidths.size() ? table.state->columnWidths[i] : column.initialWidth.value; - JsonValue c = JsonValue::MakeObject(); - c.Set("column", std::string(column.header)); - c.Set("width", width); - columns.Push(std::move(c)); - } - tables.Set(key, std::move(columns)); - } - doc.Set("tables", std::move(tables)); - JsonValue toolbars = JsonValue::MakeObject(); for (const auto& [key, sides] : m_persistToolbars) toolbars.Set(key, ToolbarSidesJson(sides)); @@ -500,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,6 +262,20 @@ namespace tachyon } doc.Set("themeVariables", std::move(themeVariables)); + // The libraries' own, each section an object of keys. + for (size_t i = 0; i < m_persistJson.size(); ++i) + { + const std::string& name = m_persistJson[i].section; + if (std::any_of(m_persistJson.begin(), m_persistJson.begin() + i, [&](const PersistedJson& e) { return e.section == name; })) + continue; + JsonValue section = JsonValue::MakeObject(); + for (const PersistedJson& entry : m_persistJson) + if (entry.section == name && 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)); + } + JsonValue values = JsonValue::MakeObject(); for (const auto& [key, target] : m_persistValues) std::visit([&](auto* v) { values.Set(key, JsonValue(*v)); }, target); @@ -548,111 +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); - } - - // Tables: columns in their saved order (new ones after), with their saved widths. - for (const auto& [key, table] : m_persistTables) - { - const JsonValue* saved = section("tables", key); - if (!saved || !saved->IsArray()) - continue; - const size_t count = table.columns.size(); - std::vector order; - std::vector widths; - std::vector taken(count, false); - for (const JsonValue& c : saved->Items()) - { - const std::string& header = c.Find("column") ? c.Find("column")->AsString() : std::string(); - for (size_t i = 0; i < count; ++i) - if (!taken[i] && table.columns[i].column.header == header) - { - taken[i] = true; - order.push_back(i); - const TableColumn& col = table.columns[i].column; - const double w = c.Find("width") ? c.Find("width")->AsNumber(col.initialWidth.value) : col.initialWidth.value; - widths.push_back(std::clamp(int32_t(std::lround(w)), col.minWidth.value, col.maxWidth.value)); - break; - } - } - for (size_t i = 0; i < count; ++i) - if (!taken[i]) { order.push_back(i); widths.push_back(table.columns[i].column.initialWidth.value); } - - std::vector reordered; - reordered.reserve(count); - for (const size_t i : order) reordered.push_back(std::move(table.columns[i])); - std::move(reordered.begin(), reordered.end(), table.columns.begin()); - if (table.state->sortColumn >= 0 && size_t(table.state->sortColumn) < count) - table.state->sortColumn = int(std::find(order.begin(), order.end(), size_t(table.state->sortColumn)) - order.begin()); - table.state->columnWidths = std::move(widths); - } + 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) @@ -702,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) @@ -736,6 +382,11 @@ namespace tachyon } } + // The libraries' own: each gets what's saved under its section and key. + for (const PersistedJson& entry : m_persistJson) + if (const JsonValue* saved = section(entry.section.c_str(), entry.key); saved && entry.restore) + entry.restore(*saved); + // App values, by their own type; a value of another type is skipped. for (const auto& [key, target] : m_persistValues) { diff --git a/src/gui_controls/gui_view_state.cpp b/src/gui_controls/gui_view_state.cpp deleted file mode 100644 index 3411c1e9..00000000 --- a/src/gui_controls/gui_view_state.cpp +++ /dev/null @@ -1,186 +0,0 @@ -#include -#include - -#include -#include -#include -#include - -namespace tachyon -{ - namespace - { - // The state's JSON object; null when it isn't one. - std::optional ObjectOf(std::string_view state) - { - Result parsed = JsonValue::Parse(state); - if (!parsed || !parsed->IsObject()) - return std::nullopt; - return std::move(*parsed); - } - - // `name`'s array of `out.size()` finite numbers, into `out`; false when it isn't one. - bool Numbers(const JsonValue& object, const char* name, std::span out) - { - const JsonValue* v = object.Find(name); - if (!v || !v->IsArray() || v->Items().size() != out.size()) - return false; - for (size_t i = 0; i < out.size(); ++i) - { - const JsonValue& item = v->Items()[i]; - if (!item.IsNumber() || !std::isfinite(item.AsNumber())) - return false; - out[i] = float(item.AsNumber()); - } - return true; - } - - // `name`'s finite number; null when it isn't one. - std::optional Number(const JsonValue& object, const char* name) - { - const JsonValue* v = object.Find(name); - if (!v || !v->IsNumber() || !std::isfinite(v->AsNumber())) - return std::nullopt; - return float(v->AsNumber()); - } - - JsonValue ArrayOf(std::initializer_list values) - { - JsonValue array = JsonValue::MakeArray(); - for (const float v : values) - array.Push(double(v)); - return array; - } - } - - std::string SaveViewState(const NodeViewState& view) - { - const float3x2& t = view.transform; - JsonValue state = JsonValue::MakeObject(); - state.Set("transform", ArrayOf({ t.r0.x, t.r0.y, t.r0.z, t.r1.x, t.r1.y, t.r1.z })); - return state.Write(); - } - - bool RestoreViewState(NodeViewState& view, std::string_view state) - { - const std::optional object = ObjectOf(state); - float m[6]; - if (!object || !Numbers(*object, "transform", m)) - return false; - // A damaged state: a transform that can't be inverted (or isn't a number) would put - // the canvas nowhere. - const float det = m[0] * m[4] - m[1] * m[3]; - if (!std::all_of(std::begin(m), std::end(m), [](float v) { return std::isfinite(v); }) || std::fabs(det) < 1e-12f) - return false; - view.transform.r0 = float3{ m[0], m[1], m[2] }; - view.transform.r1 = float3{ m[3], m[4], m[5] }; - return true; - } - - std::string SaveViewState(const TimelineViewState& view) - { - JsonValue state = JsonValue::MakeObject(); - state.Set("start", double(view.viewStart)); - state.Set("length", double(view.viewLength)); - state.Set("zoom", view.zoom); - return state.Write(); - } - - bool RestoreViewState(TimelineViewState& view, std::string_view state) - { - const std::optional object = ObjectOf(state); - if (!object) - return false; - const std::optional start = Number(*object, "start"), length = Number(*object, "length"), zoom = Number(*object, "zoom"); - if (!start || !length || !zoom) - return false; - // A damaged state: no negative span (0 shows the whole duration), nothing that isn't a number. - if (!std::isfinite(*start) || !std::isfinite(*length) || *length < 0.0f) - return false; - view.viewStart = *start; - view.viewLength = *length; - view.zoom = std::clamp(int(std::lround(*zoom)), 0, 100); - return true; - } - - std::string SaveViewState(const CurveViewState& view) - { - if (!view.shownSet) - return {}; - const CurveRange& r = view.shown; - JsonValue state = JsonValue::MakeObject(); - state.Set("shown", ArrayOf({ r.timeMin, r.timeMax, r.valueMin, r.valueMax })); - return state.Write(); - } - - bool RestoreViewState(CurveViewState& view, std::string_view state) - { - const std::optional object = ObjectOf(state); - float r[4]; - if (!object || !Numbers(*object, "shown", r) || !(r[0] < r[1]) || !(r[2] < r[3])) - return false; - view.shown = CurveRange{ r[0], r[1], r[2], r[3] }; - view.shownSet = true; - return true; - } - - std::string SaveViewState(const ViewportCamera& camera) - { - JsonValue state = JsonValue::MakeObject(); - state.Set("target", ArrayOf({ camera.target.x, camera.target.y, camera.target.z })); - state.Set("distance", double(camera.distance)); - state.Set("yaw", double(camera.yaw)); - state.Set("pitch", double(camera.pitch)); - state.Set("fovY", double(camera.fovY)); - state.Set("orthographic", camera.orthographic); - return state.Write(); - } - - bool RestoreViewState(ViewportCamera& camera, std::string_view state) - { - const std::optional object = ObjectOf(state); - if (!object) - return false; - float target[3]; - const std::optional distance = Number(*object, "distance"), yaw = Number(*object, "yaw"), - pitch = Number(*object, "pitch"), fovY = Number(*object, "fovY"); - const JsonValue* orthographic = object->Find("orthographic"); - if (!Numbers(*object, "target", target) || !distance || !yaw || !pitch || !fovY || !(*distance > 0.0f) - || !(*fovY > 0.0f && *fovY < 3.14f) || !orthographic || !orthographic->IsBool()) - return false; - camera.target = float3{ target[0], target[1], target[2] }; - camera.distance = *distance; - camera.yaw = *yaw; - camera.pitch = *pitch; - camera.fovY = *fovY; - camera.orthographic = orthographic->AsBool(); - return true; - } - - std::string SaveViewState(const GUIApplication::SettingsPanelState& settings) - { - for (const GUIApplication::SettingsPanelState::Page& page : settings.pages) - if (page.id == settings.selectedID) - { - JsonValue state = JsonValue::MakeObject(); - state.Set("page", page.name); - return state.Write(); - } - return {}; - } - - bool RestoreViewState(GUIApplication::SettingsPanelState& settings, std::string_view state) - { - const std::optional object = ObjectOf(state); - const JsonValue* name = object ? object->Find("page") : nullptr; - if (!name || !name->IsString()) - return false; - for (const GUIApplication::SettingsPanelState::Page& page : settings.pages) - if (page.name == name->AsString()) - { - settings.selectedID = page.id; - return true; - } - return false; - } -} diff --git a/src/gui_controls/gui_view_state.h b/src/gui_controls/gui_view_state.h deleted file mode 100644 index 03ba9c6a..00000000 --- a/src/gui_controls/gui_view_state.h +++ /dev/null @@ -1,47 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -#include -#include - -namespace tachyon -{ - /// @addtogroup controls_data - /// @{ - - /// A view's own state as text, for a panel to keep with its layout (Panel::saveState and - /// Panel::restoreState), and back. Restore returns false, and changes nothing, for text it - /// can't read; a value it doesn't know stays as it is. - /// - /// panel.saveState = [this] { return SaveViewState(graph); }; - /// panel.restoreState = [this](std::string_view state) { RestoreViewState(graph, state); }; - - /// A node view's pan and zoom (NodeViewState::transform). - std::string SaveViewState(const NodeViewState& view); - bool RestoreViewState(NodeViewState& view, std::string_view state); - - /// 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); - - /// The part of a curve plot in view in its editor. Empty until the editor has shown it. - std::string SaveViewState(const CurveViewState& view); - bool RestoreViewState(CurveViewState& view, std::string_view state); - - /// A viewport's camera: where it looks, from how far and which way, its field of view and - /// whether it's orthographic. - std::string SaveViewState(const ViewportCamera& camera); - bool RestoreViewState(ViewportCamera& camera, std::string_view state); - - /// The settings page open, by its name. False when no page has that name: the one open - /// stays. - std::string SaveViewState(const GUIApplication::SettingsPanelState& settings); - bool RestoreViewState(GUIApplication::SettingsPanelState& settings, std::string_view state); - - /// @} -} diff --git a/src/gui_controls/subsystems/gui_color_picker_subsystem.cpp b/src/gui_controls/subsystems/gui_color_picker_subsystem.cpp deleted file mode 100644 index ee4cb2e7..00000000 --- a/src/gui_controls/subsystems/gui_color_picker_subsystem.cpp +++ /dev/null @@ -1,36 +0,0 @@ -#include - -#include -#include - -namespace tachyon -{ - ColorPickerSubsystem::ColorPickerSubsystem(FramePipeline& frame) - { - // The swatches not claimed last frame are gone. - frame.OnPreFrame([this](FrameContext& ctx) { m_swatchStyles.NextFrame(ctx.styleManager); }); - } - - VisualColorStyleIndex& ColorPickerSubsystem::ClaimSwatchStyle(tachyon::ID swatchID) - { - return m_swatchStyles.Claim(swatchID).index; - } - - void ColorPickerSubsystem::KeepSwatchAlive(tachyon::ID swatchID) - { - m_swatchStyles.KeepAlive(swatchID); - } - - void ColorPickerSubsystem::ForgetStyles() - { - // ClearAll freed every style: drop the indices (without destroying them) so - // they're created anew. - m_swatchStyles.Forget(); - ColorPickerState& s = m_state; - for (auto* idx : { &s.svQuadColor, &s.hueStrip, &s.alphaStrip, &s.hueColor, &s.whiteColor, - &s.outlineColor, &s.newColor, &s.originalStyle }) - *idx = VisualColorStyleIndex::Invalid; - for (auto& idx : s.gradientStyles) - idx = VisualColorStyleIndex::Invalid; - } -} diff --git a/src/gui_controls/subsystems/gui_gradient_editor_subsystem.cpp b/src/gui_controls/subsystems/gui_gradient_editor_subsystem.cpp deleted file mode 100644 index e319aae0..00000000 --- a/src/gui_controls/subsystems/gui_gradient_editor_subsystem.cpp +++ /dev/null @@ -1,28 +0,0 @@ -#include - -#include -#include - -namespace tachyon -{ - GradientEditorSubsystem::GradientEditorSubsystem(FramePipeline& frame) - { - // The swatches not claimed last frame are gone. - frame.OnPreFrame([this](FrameContext& ctx) { m_swatchStyles.NextFrame(ctx.styleManager); }); - } - - void GradientEditorSubsystem::KeepSwatchAlive(tachyon::ID swatchID) - { - m_swatchStyles.KeepAlive(swatchID); - } - - void GradientEditorSubsystem::ForgetStyles() - { - // ClearAll freed every style: drop the indices (without destroying them) so - // they're created anew. - m_swatchStyles.Forget(); - GradientEditorState& s = m_state; - for (auto* idx : { &s.previewGradientStyle, &s.stopEdgeColor, &s.stopOutlineColor, &s.stopHaloColor }) - *idx = VisualColorStyleIndex::Invalid; - } -} diff --git a/src/gui_controls/subsystems/gui_gradient_editor_subsystem.h b/src/gui_controls/subsystems/gui_gradient_editor_subsystem.h deleted file mode 100644 index 294d6285..00000000 --- a/src/gui_controls/subsystems/gui_gradient_editor_subsystem.h +++ /dev/null @@ -1,111 +0,0 @@ -#pragma once - -#include -#include -#include - -#include -#include -#include -#include -#include - -namespace tachyon -{ - /// @addtogroup controls - /// @{ - - class FramePipeline; - struct FrameContext; - - /// What the gradient editor lets a field's gradient have: a Gradient's 8 stops of 8-bit - /// colors, or a GradientF's 64 of HDR ones, each blending to the next its own way. - struct GradientEditLimits - { - int maxStops = Gradient::kMaxStops; - bool hdr = false; ///< colors over 1 - bool perStopInterpolation = false; ///< each stop's StopInterpolation - }; - - /// Gradient editor popup state: edits a working copy, written back each frame it's open. - struct GradientEditorState - { - tachyon::ID triggerID = tachyon::ID::Invalid(); ///< swatch that opened the editor - tachyon::ID windowID = tachyon::ID::Invalid(); ///< popup window ID - tachyon::GradientF workingCopy {}; ///< the gradient being edited - GradientEditLimits limits {}; ///< what the field's gradient can have - int selectedStop = 0; ///< index into workingCopy.stops - tachyon::color4f selectedStopColor {}; ///< selected stop's color, for its ColorField - float selectedStopPosition = 0.0f; ///< selected stop's position, for its Field - - tachyon::GradientF originalGradient {}; ///< to restore on Cancel - tachyon::Gradient originalGradient8 {}; ///< a Gradient field's own, restored exactly - std::string context; ///< the field's label, shown after the title - - /// OK keeps the gradient, Cancel and the close button restore the original one. - /// Handled by the GradientField on its next frame. - enum class CloseRequest { None, Ok, Cancel } closeRequest = CloseRequest::None; - std::vector savedPresets; ///< "Save preset", for the session - - /// What a stop's drag changes, as it was at the press; put back by Escape. - struct DragSnapshot - { - tachyon::GradientF gradient {}; - int selectedStop = 0; - }; - tachyon::Gesture press; ///< the press on a stop, a drag from the start - int dragStopIndex = -1; ///< the dragged stop, or -1 - float dragGrab = 0.0f; ///< cursor minus the stop's offset at the press, so it doesn't jump - bool dragOff = false; ///< dragged well below the bar: removed on release - - tachyon::VisualColorStyleIndex previewGradientStyle = tachyon::VisualColorStyleIndex::Invalid; - tachyon::VisualColorStyleIndex stopEdgeColor = tachyon::VisualColorStyleIndex::Invalid; - tachyon::VisualColorStyleIndex stopOutlineColor = tachyon::VisualColorStyleIndex::Invalid; - tachyon::VisualColorStyleIndex stopHaloColor = tachyon::VisualColorStyleIndex::Invalid; - }; - - /// What a GradientField's swatch keeps besides its style: the gradient it was drawn from, - /// so an unchanged one isn't sampled again, and what a click opens the editor with. - struct GradientFieldSwatch - { - tachyon::GradientF drawn {}; ///< the gradient as last drawn - bool drawnSet = false; - tachyon::Gradient original8 {}; ///< a Gradient field's own, restored exactly on Cancel - GradientEditLimits limits {}; - std::string context; ///< the field's label - }; - - /// The gradient editor's state plus swatch styles keyed by swatch ID, with the same - /// lifecycle as ColorPickerSubsystem's. The popup body is GUIApplication::EmitGradientEditor. - class GradientEditorSubsystem - { - public: - using Swatch = SwatchStyles::Entry; - - explicit GradientEditorSubsystem(FramePipeline& frame); - - /// The editor popup's state. - GradientEditorState& State() { return m_state; } - - /// The style slot of swatch `swatchID`, kept alive this frame. Invalid for a new - /// swatch: the caller creates the style and stores it there, reused from then on. - tachyon::VisualColorStyleIndex& ClaimSwatchStyle(tachyon::ID swatchID) { return ClaimSwatch(swatchID).index; } - /// As ClaimSwatchStyle, the whole entry. - Swatch& ClaimSwatch(tachyon::ID swatchID) { return m_swatchStyles.Claim(swatchID); } - /// Swatch `swatchID` as last claimed, or null. - Swatch* FindSwatch(tachyon::ID swatchID) { return m_swatchStyles.Find(swatchID); } - - /// Carries `swatchID`'s style over without rebuilding it: a cache-hit scope - /// doesn't re-claim its swatches, but its blitted primitives still use them. - void KeepSwatchAlive(tachyon::ID swatchID); - - /// Drops every held style index without destroying it; call after a theme reload - /// (StyleManager::ClearAll), which already freed them. - void ForgetStyles(); - - private: - GradientEditorState m_state{}; - SwatchStyles m_swatchStyles; - }; - /// @} -} diff --git a/src/gui_controls/subsystems/gui_subsystem_state.h b/src/gui_controls/subsystems/gui_subsystem_state.h index 24ee6e9a..4da9f53f 100644 --- a/src/gui_controls/subsystems/gui_subsystem_state.h +++ b/src/gui_controls/subsystems/gui_subsystem_state.h @@ -18,31 +18,6 @@ namespace tachyon /// @addtogroup controls /// @{ - /// In-place rename of a tree / list / grid row (F2, Ctrl+Shift+Click or a slow re-click); - /// the target row emits a text field instead of its label. One rename at a time. - class RenameSubsystem - { - public: - tachyon::ID targetID = tachyon::ID::Invalid(); ///< the row being renamed - bool isActive = false; - /// Set on the frame the rename starts, when a commit left over from an earlier edit - /// must not end it; cleared once the field is built. - bool firstFrame = false; - std::string* editBuffer = nullptr; ///< the caller's buffer the field edits - - /// Starts renaming row `id`: `buffer` is set to `text` and edited in place. - void Start(tachyon::ID id, std::string* buffer, std::string_view text) - { - targetID = id; isActive = true; firstFrame = true; - editBuffer = buffer; *buffer = text; - } - /// Ends the rename without touching the buffer. - void Cancel() - { - targetID = tachyon::ID::Invalid(); isActive = false; firstFrame = false; editBuffer = nullptr; - } - }; - /// Slider track widths written by the sliders' custom draws and read next frame /// (keyboard step sizes, drag mapping). class SliderFieldTrackSubsystem diff --git a/src/gui_core/gui_json.cpp b/src/gui_core/gui_json.cpp index ed1bfe8a..09858164 100644 --- a/src/gui_core/gui_json.cpp +++ b/src/gui_core/gui_json.cpp @@ -309,4 +309,41 @@ namespace tachyon items.push_back(std::move(value)); return items.back(); } + + std::optional ParseJsonObject(std::string_view text) + { + Result parsed = JsonValue::Parse(text); + if (!parsed || !parsed->IsObject()) + return std::nullopt; + return std::move(*parsed); + } + + std::optional JsonFloat(const JsonValue& object, std::string_view name) + { + const JsonValue* v = object.Find(name); + if (!v || !v->IsNumber() || !std::isfinite(v->AsNumber())) + return std::nullopt; + return float(v->AsNumber()); + } + + bool JsonFloats(const JsonValue& object, std::string_view name, std::span out) + { + const JsonValue* v = object.Find(name); + if (!v || !v->IsArray() || v->Items().size() != out.size()) + return false; + for (const JsonValue& item : v->Items()) + if (!item.IsNumber() || !std::isfinite(item.AsNumber())) + return false; + for (size_t i = 0; i < out.size(); ++i) + out[i] = float(v->Items()[i].AsNumber()); + return true; + } + + JsonValue JsonFloatArray(std::initializer_list values) + { + JsonValue array = JsonValue::MakeArray(); + for (const float v : values) + array.Push(double(v)); + return array; + } } diff --git a/src/gui_core/gui_json.h b/src/gui_core/gui_json.h index ccce08ef..a61c50f3 100644 --- a/src/gui_core/gui_json.h +++ b/src/gui_core/gui_json.h @@ -2,6 +2,9 @@ #include +#include +#include +#include #include #include #include @@ -83,5 +86,15 @@ namespace tachyon std::variant m_value = nullptr; }; + + /// The JSON object in `text`, such as a view's saved state; empty when it isn't one. + std::optional ParseJsonObject(std::string_view text); + /// `object`'s member `name`, a finite number; empty when it isn't one. + std::optional JsonFloat(const JsonValue& object, std::string_view name); + /// `object`'s member `name`, an array of exactly `out.size()` finite numbers, into `out`; + /// false, with `out` as it was, when it isn't one. + bool JsonFloats(const JsonValue& object, std::string_view name, std::span out); + /// An array of `values`, to Set as a member. + JsonValue JsonFloatArray(std::initializer_list values); /// @} } diff --git a/src/gui_core/style/gui_style_manager.h b/src/gui_core/style/gui_style_manager.h index 77305ff7..65967815 100644 --- a/src/gui_core/style/gui_style_manager.h +++ b/src/gui_core/style/gui_style_manager.h @@ -288,4 +288,15 @@ namespace tachyon std::vector m_freeColorStyleSlots; }; /// @} + + /// Makes `index` a color style of `color`: a new one while it's Invalid, else the one it + /// is, changed in place. For a color the app gives and may change any frame. + inline void SetColorStyle(StyleManager& styleManager, VisualColorStyleIndex& index, color4f color) + { + const ColorStyle style = ColorStyle::Create(color); + if (index == VisualColorStyleIndex::Invalid) + index = styleManager.CreateColorStyle(style); + else + styleManager.UpdateColorStyle(index, style); + } } diff --git a/src/gui_controls/controls_curve.cpp b/src/gui_curves/controls_curve.cpp similarity index 79% rename from src/gui_controls/controls_curve.cpp rename to src/gui_curves/controls_curve.cpp index 4c14ccd1..988a2e80 100644 --- a/src/gui_controls/controls_curve.cpp +++ b/src/gui_curves/controls_curve.cpp @@ -1,6 +1,6 @@ -#include -#include -#include +#include +#include +#include #include #include @@ -11,7 +11,7 @@ // plot with its grid, curves, keys and tangent handles; the channels and the selected key over // it, the presets and wrap modes under it. Every change is a CurveEdit, for undo. -namespace tachyon +namespace tachyon::curves { namespace { @@ -364,8 +364,9 @@ namespace tachyon // CurveField // ------------------------------------------------------------------------- - bool GUIApplication::CurveField(ID id, CurveViewRef view, LayoutOverride&& constraints) + bool CurveField(GUIApplication& app, Context& context, ID id, CurveViewRef view, LayoutOverride&& constraints) { + const Styles& styles = GetStyles(app, context); PruneCurveSelection(view); CurveViewRef v = view; // The app may have taken channels away: the active one is one of those left. @@ -373,46 +374,46 @@ namespace tachyon view.state.activeChannel = channelCount > 0 ? std::clamp(view.state.activeChannel, 0, channelCount - 1) : 0; const bool changed = view.state.edits != view.state.editsSeen; view.state.editsSeen = view.state.edits; - const bool disabled = guiStateManager.Construction().IsDisabled(); + const bool disabled = app.guiStateManager.Construction().IsDisabled(); if (disabled) view.state.popupOpen = false; // Escape closes the editor, and the keyboard goes back to the field. - if (view.state.popupOpen && TakeEscapeFor(view.state.popupID, id)) + if (view.state.popupOpen && app.TakeEscapeFor(view.state.popupID, id)) { view.state.popupOpen = false; - guiStateManager.Interaction().SetFocusID(id); + app.guiStateManager.Interaction().SetFocusID(id); } // The click toggles the editor from how it was when the field was built: a click on the // field closes an open one, which a click outside would close too. const bool wasOpen = view.state.popupOpen; - if (wasOpen) BeginSelected(); - const ElementRef fieldRef = RegisterControl( + if (wasOpen) app.BeginSelected(); + const ElementRef fieldRef = app.RegisterControl( Element{ .id = id, - .eventHandler = disabled ? EventHandler{} : MakeButtonHandler([this, v, wasOpen]() { + .eventHandler = disabled ? EventHandler{} : app.MakeButtonHandler([&app, v, wasOpen]() { v.state.popupOpen = !wasOpen; if (v.state.popupOpen && v.state.popupID == ID::Invalid()) - v.state.popupID = idManager.CreateStaticID(); + v.state.popupID = app.idManager.CreateStaticID(); }), - .styleRef = theme.curveFieldStyleRef }, + .styleRef = styles.curveFieldStyleRef }, std::move(constraints)); - if (wasOpen) EndSelected(); + if (wasOpen) app.EndSelected(); // The zero line, the curves over the range with the active channel's on top, and a color's // curves over a dashed identity line. Hovered, an open button in the top-right corner. - const bool hovered = (guiStateManager.GetCurrentState(id) & ElementState::Hover) != ElementState::None; - const VisualColorStyleIndex identityColor = styleManager.RegisterColorStyle(ColorStyle::Create(theme.GetColor("--text-2", color4f{ 0.68f, 0.71f, 0.75f, 1.0f }))); - const VisualColorStyleIndex buttonColor = styleManager.RegisterColorStyle(ColorStyle::Create(theme.GetColor("--bg-control", color4f{ 0.12f, 0.13f, 0.16f, 1.0f }))); - VERIFY(elementStorage.AddCustomDraw(fieldRef, [this, v, hovered, identityColor, buttonColor](CustomDrawContext& ctx) + const bool hovered = (app.guiStateManager.GetCurrentState(id) & ElementState::Hover) != ElementState::None; + const VisualColorStyleIndex identityColor = app.styleManager.RegisterColorStyle(ColorStyle::Create(app.theme.GetColor("--text-2", color4f{ 0.68f, 0.71f, 0.75f, 1.0f }))); + const VisualColorStyleIndex buttonColor = app.styleManager.RegisterColorStyle(ColorStyle::Create(app.theme.GetColor("--bg-control", color4f{ 0.12f, 0.13f, 0.16f, 1.0f }))); + VERIFY(app.elementStorage.AddCustomDraw(fieldRef, [&styles, &app, v, hovered, identityColor, buttonColor](CustomDrawContext& ctx) { const CurvePlot plot{ ctx.ElementInnerRect(), Sane(v.data.range) }; - const float px = float(std::max(1, styleManager.Px(1))); + const float px = float(std::max(1, app.styleManager.Px(1))); const IntRect& r = plot.rect; if (plot.shown.valueMin < 0.0f && plot.shown.valueMax > 0.0f) { const int y = int(std::lround(plot.Y(0.0f))); - ctx.RenderLine({ r.x, y }, { r.x + r.w, y }, LineStyle{ .colorStyleIndex = theme.curveGridMajorColor, .lineWidth = px }); + ctx.RenderLine({ r.x, y }, { r.x + r.w, y }, LineStyle{ .colorStyleIndex = styles.curveGridMajorColor, .lineWidth = px }); } bool colorChannels = false; for (const CurveChannel& channel : v.data.channels) @@ -426,8 +427,8 @@ namespace tachyon // A single value in the accent color; a color's channels in theirs. const CurveChannelColor tint = v.data.channels[size_t(c)].color; const LineStyle style = tint == CurveChannelColor::Value - ? LineStyle{ .colorStyleIndex = theme.accentColor, .lineWidth = px * 1.75f } - : LineStyle{ .colorStyleIndex = theme.curveChannelColors[size_t(tint)], .lineWidth = px * 1.5f }; + ? LineStyle{ .colorStyleIndex = app.theme.accentColor, .lineWidth = px * 1.75f } + : LineStyle{ .colorStyleIndex = styles.curveChannelColors[size_t(tint)], .lineWidth = px * 1.5f }; DrawCurve(ctx, plot, v.data.channels[size_t(c)].curve, style, style); } if (colorChannels) @@ -443,14 +444,14 @@ namespace tachyon if (hovered) { const IntRect outer = ctx.ElementRect(); - const int size = styleManager.Px(18), inset = styleManager.Px(4); + const int size = app.styleManager.Px(18), inset = app.styleManager.Px(4); const IntRect button{ .position = { outer.x + outer.w - inset - size, outer.y + inset }, .size = { size, size } }; if (button.x > outer.x) { - ctx.RenderQuad(button, buttonColor, float(styleManager.Px(4))); + ctx.RenderQuad(button, buttonColor, float(app.styleManager.Px(4))); // A chevron pointing right, 11px across. const float2 c{ float(button.x) + float(size) * 0.5f, float(button.y) + float(size) * 0.5f }; - const float s = float(styleManager.Px(11)) / 24.0f; + const float s = float(app.styleManager.Px(11)) / 24.0f; const int2 chevron[] = { { int(std::lround(c.x - 3.0f * s)), int(std::lround(c.y - 6.0f * s)) }, { int(std::lround(c.x + 3.0f * s)), int(std::lround(c.y)) }, { int(std::lround(c.x - 3.0f * s)), int(std::lround(c.y + 6.0f * s)) } }; @@ -463,17 +464,17 @@ namespace tachyon if (view.state.popupOpen && view.state.popupID != ID::Invalid()) { LayoutOverride at = LayoutOverride{}.Anchored(id, AnchorPlacement::OutsideBottom | AnchorPlacement::InsideLeft, - { 0, int16_t(styleManager.Px(4)) }, AutoFlipMode::FlipAvoidTarget); - if (BeginWindow(view.state.popupID, "Curve", theme.curveWindowStyleRef, std::move(at), + { 0, int16_t(app.styleManager.Px(4)) }, AutoFlipMode::FlipAvoidTarget); + if (app.BeginWindow(view.state.popupID, "Curve", styles.curveWindowStyleRef, std::move(at), ElementFlags::WindowCanMove | ElementFlags::WindowNoCaption | ElementFlags::Shadows)) { - CurveEditor(idManager.AllocateDynamicID("curve_editor"), view, LayoutOverride::Auto().FlexGrow(1)); + CurveEditor(app, context, app.idManager.AllocateDynamicID("curve_editor"), view, LayoutOverride::Auto().FlexGrow(1)); } else view.state.popupOpen = false; // closed: a click outside, or the focus gone - EndWindow(); + app.EndWindow(); } - guiStateManager.SetModified(changed); + app.guiStateManager.SetModified(changed); return changed; } @@ -482,30 +483,31 @@ namespace tachyon // The channel tree and the frame ruler (an animation curve editor's) // ------------------------------------------------------------------------- - void GUIApplication::CurveTree(CurveViewRef view) + static void CurveTree(GUIApplication& app, Context& context, CurveViewRef view) { + const Styles& styles = GetStyles(app, context); CurveViewRef v = view; - BeginVertical(idManager.AllocateDynamicID("curve_tree"), theme.curveTreeStyleRef, LayoutOverride::Auto().NoShrink()); + app.BeginVertical(app.idManager.AllocateDynamicID("curve_tree"), styles.curveTreeStyleRef, LayoutOverride::Auto().NoShrink()); // The header: Channel, and the playhead's frame its values are at. - BeginHorizontal(idManager.AllocateDynamicID("curve_tree_header"), theme.curveTreeHeaderStyleRef, LayoutOverride::Auto().NoShrink()); - Text(idManager.AllocateDynamicID("curve_tree_title"), "Channel", theme.curveTreeNameStyleRef); + app.BeginHorizontal(app.idManager.AllocateDynamicID("curve_tree_header"), styles.curveTreeHeaderStyleRef, LayoutOverride::Auto().NoShrink()); + app.Text(app.idManager.AllocateDynamicID("curve_tree_title"), "Channel", styles.curveTreeNameStyleRef); if (view.data.fps > 0.0f) - Text(idManager.AllocateDynamicID("curve_tree_frame"), std::format("@ f {}", FrameOf(view, view.data.playhead)), theme.curveTreeValueStyleRef); - EndHorizontal(); + app.Text(app.idManager.AllocateDynamicID("curve_tree_frame"), std::format("@ f {}", FrameOf(view, view.data.playhead)), styles.curveTreeValueStyleRef); + app.EndHorizontal(); - const int32_t indent = styleManager.Px(14); + const int32_t indent = app.styleManager.Px(14); auto row = [&](std::string_view key, StyleRef style, int depth, std::function onClick, bool selected) { - if (selected) BeginSelected(); - const ElementRef ref = RegisterControl( + if (selected) app.BeginSelected(); + const ElementRef ref = app.RegisterControl( // Hovered and focused while its name, value or eye is too. - Element{ .id = idManager.AllocateDynamicID(key), .eventHandler = MakeButtonHandler(std::move(onClick)), .styleRef = style, + Element{ .id = app.idManager.AllocateDynamicID(key), .eventHandler = app.MakeButtonHandler(std::move(onClick)), .styleRef = style, .flags = ElementFlags::PropagatesDescendantState }, LayoutOverride::Auto().NoShrink()); - if (selected) EndSelected(); - VERIFY(elementStorage.BeginChildren()); + if (selected) app.EndSelected(); + VERIFY(app.elementStorage.BeginChildren()); if (depth > 0) - RegisterElement(Element{ .id = idManager.AllocateDynamicID(std::string(key) + "/indent"), .styleRef = theme.emptyHorzStyleRef, + app.RegisterElement(Element{ .id = app.idManager.AllocateDynamicID(std::string(key) + "/indent"), .styleRef = app.theme.emptyHorzStyleRef, .flags = ElementFlags::NoInput }, LayoutOverride::FixedSize(Pixels{ indent * depth }, Pixels{ 1 })); return ref; @@ -536,16 +538,16 @@ namespace tachyon if (d >= common && !hidden) { const bool closed = view.state.collapsedGroups.contains(path); - row("curve_group/" + path, theme.curveTreeGroupStyleRef, int(d), + row("curve_group/" + path, styles.curveTreeGroupStyleRef, int(d), [v, path, closed]() { if (closed) v.state.collapsedGroups.erase(path); else v.state.collapsedGroups.insert(path); }, false); - const ID nameID = idManager.AllocateDynamicID("curve_group_name/" + path); - RegisterElement(Element{ .id = nameID, - .textID = textSystem->RegisterText(nameID, closed ? theme.treeArrowRight : theme.treeArrowDown, - segments[d], theme.curveTreeNameStyleRef, ElementState::None), - .styleRef = theme.curveTreeNameStyleRef, .flags = ElementFlags::NoInput }, + const ID nameID = app.idManager.AllocateDynamicID("curve_group_name/" + path); + app.RegisterElement(Element{ .id = nameID, + .textID = app.textSystem->RegisterText(nameID, closed ? app.theme.treeArrowRight : app.theme.treeArrowDown, + segments[d], styles.curveTreeNameStyleRef, ElementState::None), + .styleRef = styles.curveTreeNameStyleRef, .flags = ElementFlags::NoInput }, LayoutOverride{}); - VERIFY(elementStorage.EndChildren()); + VERIFY(app.elementStorage.EndChildren()); } if (d >= common) open.push_back(segments[d]); @@ -556,17 +558,17 @@ namespace tachyon // The channel: its color, name, value at the playhead, and its eye. const std::string key = std::format("curve_channel/{}/{}", channel.path, c); - row(key, channel.visible ? theme.curveTreeRowStyleRef : theme.curveTreeRowHiddenStyleRef, int(segments.size()), + row(key, channel.visible ? styles.curveTreeRowStyleRef : styles.curveTreeRowHiddenStyleRef, int(segments.size()), [v, c]() { v.state.activeChannel = c; }, c == view.state.activeChannel); - Element swatch{ .id = idManager.AllocateDynamicID(key + "/swatch"), .styleRef = theme.curveTreeSwatchStyleRef, + Element swatch{ .id = app.idManager.AllocateDynamicID(key + "/swatch"), .styleRef = styles.curveTreeSwatchStyleRef, .flags = ElementFlags::NoInput }; - swatch.colorStyleIndex = theme.curveChannelColors[size_t(channel.color)]; - RegisterElement(std::move(swatch), LayoutOverride{}); - Text(idManager.AllocateDynamicID(key + "/name"), channel.name, theme.curveTreeNameStyleRef); + swatch.colorStyleIndex = styles.curveChannelColors[size_t(channel.color)]; + app.RegisterElement(std::move(swatch), LayoutOverride{}); + app.Text(app.idManager.AllocateDynamicID(key + "/name"), channel.name, styles.curveTreeNameStyleRef); if (view.data.fps > 0.0f) - Text(idManager.AllocateDynamicID(key + "/value"), Number(EvaluateCurve(channel.curve, view.data.playhead)), theme.curveTreeValueStyleRef); - Button(idManager.AllocateDynamicID(key + "/eye"), - { channel.visible ? theme.timelineEyeIcon : theme.timelineEyeOffIcon, {}, channel.visible ? "Hide" : "Show" }, + app.Text(app.idManager.AllocateDynamicID(key + "/value"), Number(EvaluateCurve(channel.curve, view.data.playhead)), styles.curveTreeValueStyleRef); + app.Button(app.idManager.AllocateDynamicID(key + "/eye"), + { channel.visible ? app.theme.timelineEyeIcon : app.theme.timelineEyeOffIcon, {}, channel.visible ? "Hide" : "Show" }, [v, c]() { if (c >= (int)v.data.channels.size()) return; @@ -575,22 +577,23 @@ namespace tachyon const auto& keys = v.data.channels[size_t(c)].curve.keys; return std::any_of(keys.begin(), keys.end(), [id](const CurveKey& k) { return k.stableID == id; }); }); - }, theme.timelineRowButtonStyleRef); // as the timeline's eyes: dim, bright when hovered - VERIFY(elementStorage.EndChildren()); + }, app.theme.timelineRowButtonStyleRef); // as the timeline's eyes: dim, bright when hovered + VERIFY(app.elementStorage.EndChildren()); } - EndVertical(); + app.EndVertical(); } - void GUIApplication::CurveRuler(CurveViewRef view) + static void CurveRuler(GUIApplication& app, Context& context, CurveViewRef view) { + const Styles& styles = GetStyles(app, context); CurveViewRef v = view; - const ID rulerID = idManager.AllocateDynamicID("curve_ruler"); - const ElementStorage& es = elementStorage; - GUIStateManager& gsm = guiStateManager; + const ID rulerID = app.idManager.AllocateDynamicID("curve_ruler"); + const ElementStorage& es = app.elementStorage; + GUIStateManager& gsm = app.guiStateManager; // A press or drag on it moves the playhead there, onto a frame. EventHandler handler; - if (!guiStateManager.Construction().IsDisabled()) + if (!app.guiStateManager.Construction().IsDisabled()) handler = [&es, &gsm, v](ElementEvent&& event) -> bool { auto moveTo = [&]() { const CurvePlot plot{ v.state.plotRect, ShownOf(v) }; @@ -618,7 +621,7 @@ namespace tachyon return false; } }; - const ElementRef ref = RegisterControl(Element{ .id = rulerID, .eventHandler = std::move(handler), .styleRef = theme.curveRulerStyleRef }, + const ElementRef ref = app.RegisterControl(Element{ .id = rulerID, .eventHandler = std::move(handler), .styleRef = styles.curveRulerStyleRef }, LayoutOverride::Auto().NoShrink()); if (!ref.IsValid()) return; @@ -628,21 +631,21 @@ namespace tachyon std::vector labels; if (last.rect.w > 0) { - const float frameStep = std::max(1.0f, NiceStep(last.TimeSpan() * view.data.fps, float(last.rect.w), float(styleManager.Px(56)))); - PlotGrid::AddLabels(*this, theme.curveRulerLabelStyleRef, labels, last.shown.timeMin * view.data.fps, last.shown.timeMax * view.data.fps, + const float frameStep = std::max(1.0f, NiceStep(last.TimeSpan() * view.data.fps, float(last.rect.w), float(app.styleManager.Px(56)))); + PlotGrid::AddLabels(app, styles.curveRulerLabelStyleRef, labels, last.shown.timeMin * view.data.fps, last.shown.timeMax * view.data.fps, frameStep, /*onYAxis*/ false, "curve_ruler_labels"); } - const TextID pill = textSystem->RegisterText(idManager.AllocateDynamicID("curve_playhead"), std::to_string(FrameOf(view, view.data.playhead)), - theme.curvePlayheadStyleRef, ElementState::None); - const TextMeasurement pillSize = textSystem->MeasureText(pill, TextWrapContext{}); - const VisualBoxStyleIndex pillBox = theme.curvePlayheadStyleRef.visualBoxStyleIndex; - const int2 pillPad{ styleManager.Px(6), styleManager.Px(1) }; - const int32_t px1 = std::max(1, styleManager.Px(1)); + const TextID pill = app.textSystem->RegisterText(app.idManager.AllocateDynamicID("curve_playhead"), std::to_string(FrameOf(view, view.data.playhead)), + styles.curvePlayheadStyleRef, ElementState::None); + const TextMeasurement pillSize = app.textSystem->MeasureText(pill, TextWrapContext{}); + const VisualBoxStyleIndex pillBox = styles.curvePlayheadStyleRef.visualBoxStyleIndex; + const int2 pillPad{ app.styleManager.Px(6), app.styleManager.Px(1) }; + const int32_t px1 = std::max(1, app.styleManager.Px(1)); // A press anywhere on the ruler moves the playhead, so its pill lights up while the // ruler is hovered or dragged. - const ElementState pillState = view.state.playheadDrag.IsHeld() || (guiStateManager.GetCurrentState(rulerID) & ElementState::Hover) != ElementState::None + const ElementState pillState = view.state.playheadDrag.IsHeld() || (app.guiStateManager.GetCurrentState(rulerID) & ElementState::Hover) != ElementState::None ? ElementState::Hover : ElementState::None; - VERIFY(elementStorage.AddCustomDraw(ref, [=, this](CustomDrawContext& ctx) + VERIFY(app.elementStorage.AddCustomDraw(ref, [=, &app, &styles](CustomDrawContext& ctx) { // In screen space, as the plot's place is. ctx.SetSpace(DrawSpace::Screen); @@ -653,8 +656,8 @@ namespace tachyon for (const PlotGrid::Label& label : labels) { const float x = plot.X(label.at / v.data.fps); - ctx.RenderQuad(IntRect{ int32_t(x), r.y + r.h - styleManager.Px(5), px1, styleManager.Px(5) }, r, theme.curveGridMajorColor); - ctx.RenderText(label.text, IntRect{ int32_t(x) - label.size.x / 2, r.y + (r.h - label.size.y) / 2 - styleManager.Px(2), + ctx.RenderQuad(IntRect{ int32_t(x), r.y + r.h - app.styleManager.Px(5), px1, app.styleManager.Px(5) }, r, styles.curveGridMajorColor); + ctx.RenderText(label.text, IntRect{ int32_t(x) - label.size.x / 2, r.y + (r.h - label.size.y) / 2 - app.styleManager.Px(2), label.size.x, label.size.y }); } const float x = plot.X(v.data.playhead); @@ -664,7 +667,7 @@ namespace tachyon // Centered on the playhead, but kept on the ruler at the ends of the plot. const int32_t boxX = std::max(r.x, std::min(int32_t(x) - w / 2, r.x + r.w - w)); const IntRect box{ boxX, r.y + (r.h - h) / 2, w, h }; - ctx.RenderQuad(IntRect{ int32_t(x), r.y, px1, r.h }, r, theme.curveHandleColor); + ctx.RenderQuad(IntRect{ int32_t(x), r.y, px1, r.h }, r, styles.curveHandleColor); ctx.RenderBox(box, pillBox, pillState); ctx.RenderText(pill, IntRect{ box.x + pillPad.x, box.y + pillPad.y, pillSize.maxWidth, pillSize.maxHeight }); })); @@ -674,60 +677,61 @@ namespace tachyon // CurveEditor // ------------------------------------------------------------------------- - void GUIApplication::CurveEditor(ID id, CurveViewRef view, LayoutOverride&& constraints) + void CurveEditor(GUIApplication& app, Context& context, ID id, CurveViewRef view, LayoutOverride&& constraints) { + const Styles& styles = GetStyles(app, context); // The curves changed since this view last built (an edit here, or in another view of // them): let go of what's gone. PruneCurveSelection(view); CurveViewRef v = view; const int channelCount = (int)view.data.channels.size(); view.state.activeChannel = channelCount > 0 ? std::clamp(view.state.activeChannel, 0, channelCount - 1) : 0; - const bool disabled = guiStateManager.Construction().IsDisabled(); - IDManager* const ids = &idManager; // new keys' IDs, given back when an edit adds none + const bool disabled = app.guiStateManager.Construction().IsDisabled(); + IDManager* const ids = &app.idManager; // new keys' IDs, given back when an edit adds none // With fps set, an animation editor: interpolation and tangents over the plot, frames // on a ruler with the playhead. With paths, the channels as a tree down the left. const bool animation = view.data.fps > 0.0f; const bool tree = std::any_of(view.data.channels.begin(), view.data.channels.end(), [](const CurveChannel& c) { return !c.path.empty(); }); - BeginVertical(id, theme.emptyVertStyleRef, std::move(constraints)); - const bool pushed = idManager.PushParent(id); + app.BeginVertical(id, app.theme.emptyVertStyleRef, std::move(constraints)); + const bool pushed = app.idManager.PushParent(id); // ---- Over the plot: the channels, the selected key, frame all -------------- // A key's interpolation and tangents are in its menu (a right click on it). - BeginHorizontal(idManager.AllocateDynamicID("curve_top"), theme.curveToolbarStyleRef, LayoutOverride::Auto().NoShrink()); + app.BeginHorizontal(app.idManager.AllocateDynamicID("curve_top"), styles.curveToolbarStyleRef, LayoutOverride::Auto().NoShrink()); if (animation) { - const ID frameAllID = idManager.AllocateDynamicID("curve_frame_all"); - Button(frameAllID, { theme.curveFrameAllIcon, "Frame all" }, [v]() { FrameAll(v); }, - theme.curveFrameAllStyleRef, LayoutOverride{}.NoGrow()); // its icon and text, no wider - SetTooltip(frameAllID, "Frame all", "A"); + const ID frameAllID = app.idManager.AllocateDynamicID("curve_frame_all"); + app.Button(frameAllID, { styles.curveFrameAllIcon, "Frame all" }, [v]() { FrameAll(v); }, + styles.curveFrameAllStyleRef, LayoutOverride{}.NoGrow()); // its icon and text, no wider + app.SetTooltip(frameAllID, "Frame all", "A"); } else if (channelCount > 1 && !tree) { for (int c = 0; c < channelCount; ++c) { const CurveChannel& channel = view.data.channels[size_t(c)]; - const ID chipID = idManager.AllocateDynamicID("curve_channel"); + const ID chipID = app.idManager.AllocateDynamicID("curve_channel"); const bool active = c == view.state.activeChannel; - if (active) BeginSelected(); - const ElementRef chipRef = RegisterControl( + if (active) app.BeginSelected(); + const ElementRef chipRef = app.RegisterControl( Element{ .id = chipID, - .eventHandler = MakeButtonHandler([v, c]() { v.state.activeChannel = c; }), - .styleRef = theme.curveChannelStyleRef }, + .eventHandler = app.MakeButtonHandler([v, c]() { v.state.activeChannel = c; }), + .styleRef = styles.curveChannelStyleRef }, " " + channel.name, LayoutOverride{}); - if (active) EndSelected(); + if (active) app.EndSelected(); // Its color, as a small square before its name. - const VisualColorStyleIndex color = channel.visible ? theme.curveChannelColors[size_t(channel.color)] - : theme.curveChannelFadedColors[size_t(channel.color)]; - const int32_t square = styleManager.Px(8), pad = styleManager.Px(8); - VERIFY(elementStorage.AddCustomDrawAfter(chipRef, [color, square, pad](CustomDrawContext& ctx) + const VisualColorStyleIndex color = channel.visible ? styles.curveChannelColors[size_t(channel.color)] + : styles.curveChannelFadedColors[size_t(channel.color)]; + const int32_t square = app.styleManager.Px(8), pad = app.styleManager.Px(8); + VERIFY(app.elementStorage.AddCustomDrawAfter(chipRef, [color, square, pad](CustomDrawContext& ctx) { const IntRect r = ctx.ElementRect(); ctx.RenderQuad(IntRect{ r.x + pad, r.y + (r.h - square) / 2, square, square }, color, float(square) / 4.0f); })); - Button(idManager.AllocateDynamicID("curve_channel_eye"), - { channel.visible ? theme.timelineEyeIcon : theme.timelineEyeOffIcon, {}, channel.visible ? "Hide" : "Show" }, + app.Button(app.idManager.AllocateDynamicID("curve_channel_eye"), + { channel.visible ? app.theme.timelineEyeIcon : app.theme.timelineEyeOffIcon, {}, channel.visible ? "Hide" : "Show" }, [v, c]() { if (c < (int)v.data.channels.size()) { @@ -737,11 +741,11 @@ namespace tachyon return std::any_of(keys.begin(), keys.end(), [key](const CurveKey& k) { return k.stableID == key; }); }); } - }, theme.iconButtonStyleRef); + }, app.theme.iconButtonStyleRef); } } - BeginHorizontal(idManager.AllocateDynamicID("curve_top_gap"), theme.emptyHorzStyleRef, LayoutOverride{}.FlexGrow(1)); - EndHorizontal(); + app.BeginHorizontal(app.idManager.AllocateDynamicID("curve_top_gap"), app.theme.emptyHorzStyleRef, LayoutOverride{}.FlexGrow(1)); + app.EndHorizontal(); // The selected key's time and value, when there's one. int selChannel = -1, selKey = -1, selCount = 0; @@ -757,7 +761,7 @@ namespace tachyon { const CurveKey key = view.data.channels[size_t(selChannel)].curve.keys[size_t(selKey)]; const CurveRange shown = ShownOf(view); - auto setKey = [this, v, selChannel, id = key.stableID](float time, float value) { + auto setKey = [&app, v, selChannel, id = key.stableID](float time, float value) { const std::vector before = CurvesOf(v); v.data.channels[size_t(selChannel)].curve = before[size_t(selChannel)]; std::unordered_set only{ id }; @@ -778,54 +782,54 @@ namespace tachyon { // The time as a frame. int64_t frame = FrameOf(view, key.time); - DragLabel(idManager.AllocateDynamicID("curve_time_label"), "Frame", theme.dragLabelStyleRef); - if (Field(idManager.AllocateDynamicID("curve_frame"), frame, TextEditBehavior::None, theme.controls->number, + app.DragLabel(app.idManager.AllocateDynamicID("curve_time_label"), "Frame", app.theme.dragLabelStyleRef); + if (app.Field(app.idManager.AllocateDynamicID("curve_frame"), frame, TextEditBehavior::None, app.theme.controls->number, NumericFieldConfig{ .stepPerPixel = 0.25 }, - LayoutOverride::FixedWidth(Pixels{ styleManager.Px(64) }))) + LayoutOverride::FixedWidth(Pixels{ app.styleManager.Px(64) }))) setKey(float(frame) / view.data.fps, key.value); } else { - DragLabel(idManager.AllocateDynamicID("curve_time_label"), "Time", theme.dragLabelStyleRef); - if (Field(idManager.AllocateDynamicID("curve_time"), time, TextEditBehavior::None, theme.controls->number, + app.DragLabel(app.idManager.AllocateDynamicID("curve_time_label"), "Time", app.theme.dragLabelStyleRef); + if (app.Field(app.idManager.AllocateDynamicID("curve_time"), time, TextEditBehavior::None, app.theme.controls->number, NumericFieldConfig{ .stepPerPixel = double(shown.timeMax - shown.timeMin) / 400.0 }, - LayoutOverride::FixedWidth(Pixels{ styleManager.Px(64) }))) + LayoutOverride::FixedWidth(Pixels{ app.styleManager.Px(64) }))) setKey(time, key.value); } - DragLabel(idManager.AllocateDynamicID("curve_value_label"), "Value", theme.dragLabelStyleRef); - if (Field(idManager.AllocateDynamicID("curve_value"), value, TextEditBehavior::None, theme.controls->number, + app.DragLabel(app.idManager.AllocateDynamicID("curve_value_label"), "Value", app.theme.dragLabelStyleRef); + if (app.Field(app.idManager.AllocateDynamicID("curve_value"), value, TextEditBehavior::None, app.theme.controls->number, NumericFieldConfig{ .stepPerPixel = double(shown.valueMax - shown.valueMin) / 400.0 }, - LayoutOverride::FixedWidth(Pixels{ styleManager.Px(64) }))) + LayoutOverride::FixedWidth(Pixels{ app.styleManager.Px(64) }))) setKey(key.time, value); } if (!animation) - Button(idManager.AllocateDynamicID("curve_frame_all"), { theme.curveFrameAllIcon, {}, "Frame all (A)" }, - [v]() { FrameAll(v); }, theme.iconButtonStyleRef); - EndHorizontal(); + app.Button(app.idManager.AllocateDynamicID("curve_frame_all"), { styles.curveFrameAllIcon, {}, "Frame all (A)" }, + [v]() { FrameAll(v); }, app.theme.iconButtonStyleRef); + app.EndHorizontal(); // ---- The tree, the ruler and the plot -------------------------------------- - BeginHorizontal(idManager.AllocateDynamicID("curve_body"), theme.emptyHorzStyleRef, LayoutOverride{}.FlexGrow(1)); + app.BeginHorizontal(app.idManager.AllocateDynamicID("curve_body"), app.theme.emptyHorzStyleRef, LayoutOverride{}.FlexGrow(1)); if (tree) - CurveTree(view); - BeginVertical(idManager.AllocateDynamicID("curve_main"), theme.emptyVertStyleRef, LayoutOverride{}.FlexGrow(1)); + CurveTree(app, context, view); + app.BeginVertical(app.idManager.AllocateDynamicID("curve_main"), app.theme.emptyVertStyleRef, LayoutOverride{}.FlexGrow(1)); if (animation) - CurveRuler(view); + CurveRuler(app, context, view); - const ID plotID = idManager.AllocateDynamicID("curve_plot"); + const ID plotID = app.idManager.AllocateDynamicID("curve_plot"); const CurvePlot lastPlot{ view.state.plotRect, ShownOf(view) }; // The grid's numbers, from where the plot was last frame. std::vector labels; - const float minGap = float(styleManager.Px(56)), minGapV = float(styleManager.Px(32)); + const float minGap = float(app.styleManager.Px(56)), minGapV = float(app.styleManager.Px(32)); const float timeStep = NiceStep(lastPlot.TimeSpan(), float(lastPlot.rect.w), minGap); const float valueStep = NiceStep(lastPlot.ValueSpan(), float(lastPlot.rect.h), minGapV); if (lastPlot.rect.w > 0 && lastPlot.rect.h > 0) { // With fps set, the times are on the ruler instead. if (!animation) - PlotGrid::AddLabels(*this, theme.curveLabelStyleRef, labels, lastPlot.shown.timeMin, lastPlot.shown.timeMax, timeStep, + PlotGrid::AddLabels(app, styles.curveLabelStyleRef, labels, lastPlot.shown.timeMin, lastPlot.shown.timeMax, timeStep, /*onYAxis*/ false, "curve_time_labels"); - PlotGrid::AddLabels(*this, theme.curveLabelStyleRef, labels, lastPlot.shown.valueMin, lastPlot.shown.valueMax, valueStep, + PlotGrid::AddLabels(app, styles.curveLabelStyleRef, labels, lastPlot.shown.valueMin, lastPlot.shown.valueMax, valueStep, /*onYAxis*/ true, "curve_value_labels"); } @@ -839,20 +843,20 @@ namespace tachyon const std::string text = animation ? std::format("{} \xC2\xB7 f {} \xC2\xB7 {}", channel.name, FrameOf(view, key.time), Number(key.value)) : channelCount > 1 ? std::format("{} \xC2\xB7 {} \xC2\xB7 {}", channel.name, Number(key.time), Number(key.value)) : std::format("{} \xC2\xB7 {}", Number(key.time), Number(key.value)); - readout = textSystem->RegisterText(idManager.AllocateDynamicID("curve_readout"), text, theme.curveReadoutStyleRef, ElementState::None); - const TextMeasurement m = textSystem->MeasureText(readout, TextWrapContext{}); + readout = app.textSystem->RegisterText(app.idManager.AllocateDynamicID("curve_readout"), text, styles.curveReadoutStyleRef, ElementState::None); + const TextMeasurement m = app.textSystem->MeasureText(readout, TextWrapContext{}); readoutSize = { m.maxWidth, m.maxHeight }; } EventHandler plotHandler; if (!disabled) { - GUIStateManager& gsm = guiStateManager; - const ElementStorage& es = elementStorage; - const float reach = float(styleManager.Px(7)); - const float handleLength = float(styleManager.Px(40)); - const int32_t dragDistance = styleManager.Px(kDragStartDistance); - plotHandler = [&gsm, &es, v, reach, handleLength, dragDistance, ids, wheelMode = GetWheelMode()](ElementEvent&& event) -> bool + GUIStateManager& gsm = app.guiStateManager; + const ElementStorage& es = app.elementStorage; + const float reach = float(app.styleManager.Px(7)); + const float handleLength = float(app.styleManager.Px(40)); + const int32_t dragDistance = app.styleManager.Px(kDragStartDistance); + plotHandler = [&gsm, &es, v, reach, handleLength, dragDistance, ids, wheelMode = app.GetWheelMode()](ElementEvent&& event) -> bool { if (event.rect == nullptr) return false; @@ -1139,28 +1143,28 @@ namespace tachyon }; } - const ElementRef plotRef = RegisterControl( - Element{ .id = plotID, .eventHandler = std::move(plotHandler), .styleRef = animation ? theme.curvePlotFramesStyleRef : theme.curvePlotStyleRef }, + const ElementRef plotRef = app.RegisterControl( + Element{ .id = plotID, .eventHandler = std::move(plotHandler), .styleRef = animation ? styles.curvePlotFramesStyleRef : styles.curvePlotStyleRef }, LayoutOverride::Auto().FlexGrow(1)); - VERIFY(elementStorage.AddPostLayout(plotRef, [v](PostLayoutContext& ctx) { v.state.plotRect = ctx.ElementInnerRect(); })); + VERIFY(app.elementStorage.AddPostLayout(plotRef, [v](PostLayoutContext& ctx) { v.state.plotRect = ctx.ElementInnerRect(); })); { - const int32_t px1 = std::max(1, styleManager.Px(1)), px4 = styleManager.Px(4); - const float keySize = float(styleManager.Px(8)), selectedSize = float(styleManager.Px(11)), edge = float(std::max(1, styleManager.Px(1))); - const float handleLength = float(styleManager.Px(40)), handleRadius = float(styleManager.Px(4)); + const int32_t px1 = std::max(1, app.styleManager.Px(1)), px4 = app.styleManager.Px(4); + const float keySize = float(app.styleManager.Px(8)), selectedSize = float(app.styleManager.Px(11)), edge = float(std::max(1, app.styleManager.Px(1))); + const float handleLength = float(app.styleManager.Px(40)), handleRadius = float(app.styleManager.Px(4)); // The key or handle under the pointer, while it's over the plot: drawn lighter and larger. - const bool plotHovered = !disabled && (guiStateManager.GetCurrentState(plotID) & ElementState::Hover) != ElementState::None; + const bool plotHovered = !disabled && (app.guiStateManager.GetCurrentState(plotID) & ElementState::Hover) != ElementState::None; const CurveViewState::HoverTarget hoverTarget = view.state.hover.Shown(plotHovered); const ID hoverKey = hoverTarget.key; const ID hoverHandleKey = hoverTarget.handleKey; const bool hoverHandleOut = hoverTarget.handleOut; const int hoverChannel = view.state.boxSelect.IsHeld() ? -1 : hoverTarget.channel; - const float hoverGrow = float(std::max(1, styleManager.Px(2))); + const float hoverGrow = float(std::max(1, app.styleManager.Px(2))); const float lineWidth = float(px1) * 2.0f, otherWidth = float(px1) * 1.5f, handleWidth = float(px1) * 1.25f; - const float dash = float(styleManager.Px(3)); - const VisualBoxStyleIndex readoutBox = theme.curveReadoutStyleRef.visualBoxStyleIndex; - const VisualBoxStyleIndex boxSelect = theme.curveBoxSelectStyleRef.visualBoxStyleIndex; - const int2 readoutPad{ styleManager.Px(6), styleManager.Px(2) }; - VERIFY(elementStorage.AddCustomDraw(plotRef, [=, this](CustomDrawContext& ctx) + const float dash = float(app.styleManager.Px(3)); + const VisualBoxStyleIndex readoutBox = styles.curveReadoutStyleRef.visualBoxStyleIndex; + const VisualBoxStyleIndex boxSelect = styles.curveBoxSelectStyleRef.visualBoxStyleIndex; + const int2 readoutPad{ app.styleManager.Px(6), app.styleManager.Px(2) }; + VERIFY(app.elementStorage.AddCustomDraw(plotRef, [=, &app, &styles](CustomDrawContext& ctx) { const IntRect outer = ctx.ElementRect(), inner = ctx.ElementInnerRect(); const CurvePlot plot{ inner, ShownOf(v) }; @@ -1168,7 +1172,7 @@ namespace tachyon // The grid and its numbers. const PlotGrid::Frame grid = GridFrame(plot); PlotGrid::DrawLines(ctx, grid, NiceStep(plot.TimeSpan(), float(inner.w), minGap), NiceStep(plot.ValueSpan(), float(inner.h), minGapV), - { theme.curveGridColor, theme.curveGridMajorColor, theme.curveZeroColor }, px1); + { styles.curveGridColor, styles.curveGridMajorColor, styles.curveZeroColor }, px1); PlotGrid::DrawLabels(ctx, grid, labels, px4, px4); // The playhead, through the plot. @@ -1176,7 +1180,7 @@ namespace tachyon { const float x = plot.X(v.data.playhead); if (x >= float(inner.x) && x <= float(inner.x + inner.w)) - ctx.RenderQuad(IntRect{ int32_t(x), inner.y, px1, inner.h }, inner, theme.curveHandleColor); + ctx.RenderQuad(IntRect{ int32_t(x), inner.y, px1, inner.h }, inner, styles.curveHandleColor); } // The curves: the others thinner and faded, the active one on top; before the @@ -1191,8 +1195,8 @@ namespace tachyon const CurveChannel& channel = v.data.channels[size_t(c)]; const bool active = c == v.state.activeChannel || count == 1; const bool curveHovered = c == hoverChannel; - const VisualColorStyleIndex color = active || curveHovered ? theme.curveChannelColors[size_t(channel.color)] - : theme.curveChannelFadedColors[size_t(channel.color)]; + const VisualColorStyleIndex color = active || curveHovered ? styles.curveChannelColors[size_t(channel.color)] + : styles.curveChannelFadedColors[size_t(channel.color)]; const float width = (active ? lineWidth : otherWidth) + (curveHovered ? float(px1) : 0.0f); DrawCurve(ctx, plot, channel.curve, LineStyle{ .colorStyleIndex = color, .lineWidth = width }, LineStyle{ .colorStyleIndex = color, .lineWidth = width, .dashSize = dash }); @@ -1214,20 +1218,20 @@ namespace tachyon continue; const float2 end = HandleEnd(plot, k, out, handleLength); ctx.RenderLine(int2{ int32_t(p.x), int32_t(p.y) }, int2{ int32_t(end.x), int32_t(end.y) }, - LineStyle{ .colorStyleIndex = theme.curveHandleColor, .lineWidth = handleWidth }); + LineStyle{ .colorStyleIndex = styles.curveHandleColor, .lineWidth = handleWidth }); // Hovered: filled, a little larger. if (k.stableID == hoverHandleKey && out == hoverHandleOut) { const float r = handleRadius + hoverGrow / 2.0f; - ctx.RenderQuad(IntRect{ int32_t(end.x - r), int32_t(end.y - r), int32_t(2 * r), int32_t(2 * r) }, outer, theme.curveHandleColor, r); + ctx.RenderQuad(IntRect{ int32_t(end.x - r), int32_t(end.y - r), int32_t(2 * r), int32_t(2 * r) }, outer, styles.curveHandleColor, r); } else - ctx.RenderCircle(end, handleRadius, LineStyle{ .colorStyleIndex = theme.curveHandleColor, .lineWidth = handleWidth }); + ctx.RenderCircle(end, handleRadius, LineStyle{ .colorStyleIndex = styles.curveHandleColor, .lineWidth = handleWidth }); } const float s = selectedSize + (k.stableID == hoverKey ? hoverGrow : 0.0f); - ctx.RenderQuad(IntRect{ int32_t(p.x - s / 2), int32_t(p.y - s / 2), int32_t(s), int32_t(s) }, outer, theme.curveHandleColor, s / 4.0f); + ctx.RenderQuad(IntRect{ int32_t(p.x - s / 2), int32_t(p.y - s / 2), int32_t(s), int32_t(s) }, outer, styles.curveHandleColor, s / 4.0f); const float t = s - 4.0f * edge; - ctx.RenderQuad(IntRect{ int32_t(p.x - t / 2), int32_t(p.y - t / 2), int32_t(t), int32_t(t) }, outer, theme.curveSelectedKeyColor, t / 4.0f); + ctx.RenderQuad(IntRect{ int32_t(p.x - t / 2), int32_t(p.y - t / 2), int32_t(t), int32_t(t) }, outer, styles.curveSelectedKeyColor, t / 4.0f); } else { @@ -1235,9 +1239,9 @@ namespace tachyon const bool hovered = k.stableID == hoverKey; const float s = keySize + 2.0f * edge + (hovered ? hoverGrow : 0.0f); ctx.RenderQuad(IntRect{ int32_t(p.x - s / 2), int32_t(p.y - s / 2), int32_t(s), int32_t(s) }, outer, - hovered ? theme.curveHandleColor : theme.curveKeyEdgeColor, s / 4.0f); + hovered ? styles.curveHandleColor : styles.curveKeyEdgeColor, s / 4.0f); ctx.RenderQuad(IntRect{ int32_t(p.x - keySize / 2), int32_t(p.y - keySize / 2), int32_t(keySize), int32_t(keySize) }, - outer, active ? theme.curveChannelColors[size_t(channel.color)] : theme.curveChannelFadedColors[size_t(channel.color)], + outer, active ? styles.curveChannelColors[size_t(channel.color)] : styles.curveChannelFadedColors[size_t(channel.color)], keySize / 4.0f); } } @@ -1267,18 +1271,18 @@ namespace tachyon } // A right click: on a key, its delete and tangent modes; elsewhere, a key there. - if (!disabled && BeginContextMenu(plotID)) + if (!disabled && app.BeginContextMenu(plotID)) { - if (view.state.menuOpening != ContextMenuOpenings()) + if (view.state.menuOpening != app.ContextMenuOpenings()) { // Just opened, or opened again by another right click: what's under it. - view.state.menuOpening = ContextMenuOpenings(); + view.state.menuOpening = app.ContextMenuOpenings(); view.state.menuKey = ID::Invalid(); const CurvePlot plot{ view.state.plotRect, ShownOf(view) }; - const int2 at = contextMenuScreenPos.value_or(int2{ view.state.plotRect.x + view.state.plotRect.w / 2, view.state.plotRect.y + view.state.plotRect.h / 2 }); + const int2 at = app.ContextMenuScreenPos().value_or(int2{ view.state.plotRect.x + view.state.plotRect.w / 2, view.state.plotRect.y + view.state.plotRect.h / 2 }); const float2 p{ float(at.x), float(at.y) }; view.state.menuAt = { plot.Time(p.x), plot.Value(p.y) }; - if (const KeyHit hit = HitKey(view, plot, p, float(styleManager.Px(7))); hit.key >= 0) + if (const KeyHit hit = HitKey(view, plot, p, float(app.styleManager.Px(7))); hit.key >= 0) { view.state.menuKey = hit.id; view.state.activeChannel = hit.channel; @@ -1286,7 +1290,7 @@ namespace tachyon view.state.selectedKeys = { hit.id }; } // On a curve: it becomes the active one and a key added lands on it. - else if (const int curveHit = HitCurve(view, plot, p, float(styleManager.Px(7))); curveHit >= 0) + else if (const int curveHit = HitCurve(view, plot, p, float(app.styleManager.Px(7))); curveHit >= 0) { view.state.activeChannel = curveHit; view.state.menuAt.y = EvaluateCurve(view.data.channels[size_t(curveHit)].curve, view.state.menuAt.x); @@ -1294,8 +1298,8 @@ namespace tachyon } if (view.state.menuKey != ID::Invalid()) { - MenuItem("Delete key", [v]() { CommitCurveEdit(v, DeleteSelectedCurveKeysEdit(v)); }); - MenuSeparator(); + app.MenuItem("Delete key", [v]() { CommitCurveEdit(v, DeleteSelectedCurveKeysEdit(v)); }); + app.MenuSeparator(); // The interpolation and tangents of the key right-clicked, checked. CurveTangentMode mode = CurveTangentMode::Auto; CurveInterpolation interpolation = CurveInterpolation::Bezier; @@ -1303,31 +1307,31 @@ namespace tachyon for (const CurveKey& k : channel.curve.keys) if (k.stableID == view.state.menuKey) { mode = k.tangents; interpolation = k.interpolation; } const std::tuple interpolations[] = { - { CurveInterpolation::Constant, theme.curveConstantIcon, "Constant" }, - { CurveInterpolation::Linear, theme.curveLinearIcon, "Linear" }, - { CurveInterpolation::Bezier, theme.curveBezierIcon, "Bezier" } }; - MenuHeader("Interpolation"); + { CurveInterpolation::Constant, styles.curveConstantIcon, "Constant" }, + { CurveInterpolation::Linear, styles.curveLinearIcon, "Linear" }, + { CurveInterpolation::Bezier, styles.curveBezierIcon, "Bezier" } }; + app.MenuHeader("Interpolation"); for (const auto& [i, icon, name] : interpolations) { - if (i == interpolation) BeginSelected(); - MenuItem({ icon, name }, [v, i = i]() { CommitCurveEdit(v, SetCurveInterpolationEdit(v, i)); }); - if (i == interpolation) EndSelected(); + if (i == interpolation) app.BeginSelected(); + app.MenuItem({ icon, name }, [v, i = i]() { CommitCurveEdit(v, SetCurveInterpolationEdit(v, i)); }); + if (i == interpolation) app.EndSelected(); } - MenuSeparator(); + app.MenuSeparator(); static constexpr std::pair kModes[] = { { CurveTangentMode::Auto, "Auto" }, { CurveTangentMode::Aligned, "Aligned" }, { CurveTangentMode::Free, "Free" }, { CurveTangentMode::Flat, "Flat" } }; - MenuHeader("Tangents"); + app.MenuHeader("Tangents"); for (const auto& [m, name] : kModes) { - if (m == mode) BeginSelected(); - MenuItem(name, [v, m]() { CommitCurveEdit(v, SetCurveTangentModeEdit(v, m)); }); - if (m == mode) EndSelected(); + if (m == mode) app.BeginSelected(); + app.MenuItem(name, [v, m]() { CommitCurveEdit(v, SetCurveTangentModeEdit(v, m)); }); + if (m == mode) app.EndSelected(); } } else { - MenuItem("Add key", [v, ids]() { + app.MenuItem("Add key", [v, ids]() { const ID keyID = ids->CreateStaticID(); const CurveEdit edit = AddCurveKeyEdit(v.data, v.state.activeChannel, v.state.menuAt.x, v.state.menuAt.y, keyID); if (!edit.empty()) @@ -1338,34 +1342,34 @@ namespace tachyon else ids->ReleaseStaticID(keyID); }); - MenuItem("Frame all", [v]() { FrameAll(v); }); + app.MenuItem("Frame all", [v]() { FrameAll(v); }); } } if (!disabled) - EndContextMenu(); + app.EndContextMenu(); - EndVertical(); // the ruler and the plot - EndHorizontal(); // the tree beside them + app.EndVertical(); // the ruler and the plot + app.EndHorizontal(); // the tree beside them // ---- Under the plot: the presets, and what the curve does past its ends ---- if (!animation) { - BeginHorizontal(idManager.AllocateDynamicID("curve_bottom"), theme.curveToolbarStyleRef, LayoutOverride::Auto().NoShrink()); + app.BeginHorizontal(app.idManager.AllocateDynamicID("curve_bottom"), styles.curveToolbarStyleRef, LayoutOverride::Auto().NoShrink()); const std::span presets = view.data.presets.empty() ? DefaultCurvePresets() : std::span(view.data.presets); const int active = view.state.activeChannel; - const VisualColorStyleIndex presetColor = channelCount > 0 ? theme.curveChannelColors[size_t(view.data.channels[size_t(active)].color)] - : theme.curveChannelColors[0]; + const VisualColorStyleIndex presetColor = channelCount > 0 ? styles.curveChannelColors[size_t(view.data.channels[size_t(active)].color)] + : styles.curveChannelColors[0]; // A preset is looked up where it's used, in the curves' list or the built-in ones, not // copied (its name and keys) into its handler and its drawing each frame. The handler // takes the channel active when it's clicked, which is the one shown: what it keeps // stays in std::function's small buffer. const CurveData* data = &view.data; - const float width = float(std::max(1, styleManager.Px(1))) * 1.25f; + const float width = float(std::max(1, app.styleManager.Px(1))) * 1.25f; for (size_t p = 0; p < presets.size(); ++p) { - const ElementRef presetRef = RegisterControl( - Element{ .id = idManager.AllocateDynamicID("curve_preset"), - .eventHandler = disabled ? EventHandler{} : MakeButtonHandler([v, p, ids]() { + const ElementRef presetRef = app.RegisterControl( + Element{ .id = app.idManager.AllocateDynamicID("curve_preset"), + .eventHandler = disabled ? EventHandler{} : app.MakeButtonHandler([v, p, ids]() { const CurvePreset* preset = PresetAt(v.data, p); if (preset == nullptr) return; @@ -1378,10 +1382,10 @@ namespace tachyon else CommitCurveEdit(v, edit); }), - .styleRef = theme.curvePresetStyleRef }, + .styleRef = styles.curvePresetStyleRef }, LayoutOverride{}); - SetTooltip(presets[p].name); - VERIFY(elementStorage.AddCustomDraw(presetRef, [data, p, presetColor, width](CustomDrawContext& ctx) + app.SetTooltip(presets[p].name); + VERIFY(app.elementStorage.AddCustomDraw(presetRef, [data, p, presetColor, width](CustomDrawContext& ctx) { const CurvePreset* preset = PresetAt(*data, p); if (preset == nullptr) @@ -1400,24 +1404,24 @@ namespace tachyon } })); } - BeginHorizontal(idManager.AllocateDynamicID("curve_bottom_gap"), theme.emptyHorzStyleRef, LayoutOverride{}.FlexGrow(1)); - EndHorizontal(); + app.BeginHorizontal(app.idManager.AllocateDynamicID("curve_bottom_gap"), app.theme.emptyHorzStyleRef, LayoutOverride{}.FlexGrow(1)); + app.EndHorizontal(); if (channelCount > 0) { static constexpr std::string_view kWraps[] = { "Clamp", "Loop", "Ping-pong" }; const Curve& curve = view.data.channels[size_t(active)].curve; int pre = int(curve.preWrap), post = int(curve.postWrap); - if (Dropdown(idManager.AllocateDynamicID("curve_pre_wrap"), pre, kWraps, LayoutOverride::FixedWidth(Pixels{ styleManager.Px(96) }))) + if (app.Dropdown(app.idManager.AllocateDynamicID("curve_pre_wrap"), pre, kWraps, LayoutOverride::FixedWidth(Pixels{ app.styleManager.Px(96) }))) CommitCurveEdit(view, SetCurveWrapEdit(view.data, active, CurveWrapMode(pre), curve.postWrap)); - SetTooltip("Before the first key"); - if (Dropdown(idManager.AllocateDynamicID("curve_post_wrap"), post, kWraps, LayoutOverride::FixedWidth(Pixels{ styleManager.Px(96) }))) + app.SetTooltip("Before the first key"); + if (app.Dropdown(app.idManager.AllocateDynamicID("curve_post_wrap"), post, kWraps, LayoutOverride::FixedWidth(Pixels{ app.styleManager.Px(96) }))) CommitCurveEdit(view, SetCurveWrapEdit(view.data, active, view.data.channels[size_t(active)].curve.preWrap, CurveWrapMode(post))); - SetTooltip("After the last key"); + app.SetTooltip("After the last key"); } - EndHorizontal(); + app.EndHorizontal(); } - if (pushed) (void)idManager.PopParent(); - EndVertical(); + if (pushed) (void)app.idManager.PopParent(); + app.EndVertical(); } } diff --git a/src/gui_controls/controls_plot.cpp b/src/gui_curves/controls_plot.cpp similarity index 83% rename from src/gui_controls/controls_plot.cpp rename to src/gui_curves/controls_plot.cpp index 90a0e6da..485b1efe 100644 --- a/src/gui_controls/controls_plot.cpp +++ b/src/gui_curves/controls_plot.cpp @@ -1,6 +1,6 @@ -#include -#include -#include +#include +#include +#include #include #include @@ -10,7 +10,7 @@ // on its own, the value under the pointer, and handles dragged along the x axis under it. It // zooms and scrolls along x as the other canvases do (gui_navigation.h). -namespace tachyon +namespace tachyon::curves { namespace { @@ -114,13 +114,14 @@ namespace tachyon } } - bool GUIApplication::Plot(ID id, PlotViewRef view, LayoutOverride&& constraints) + bool Plot(GUIApplication& app, Context& context, ID id, PlotViewRef view, LayoutOverride&& constraints) { + const Styles& styles = GetStyles(app, context); PlotViewRef v = view; const int count = (int)view.data.series.size(); if (view.state.shownSeries >= count) view.state.shownSeries = -1; view.state.activeHandle = view.data.handles.empty() ? 0 : std::clamp(view.state.activeHandle, 0, (int)view.data.handles.size() - 1); - const bool disabled = guiStateManager.Construction().IsDisabled(); + const bool disabled = app.guiStateManager.Construction().IsDisabled(); if (disabled && v.state.handleDrag.IsHeld()) { ApplyPlotEdit(view.data, PlotEdit{ v.state.handleDrag.before, v.state.handleDrag.before }); @@ -130,27 +131,27 @@ namespace tachyon const bool changed = view.state.edits != view.state.editsSeen; view.state.editsSeen = view.state.edits; - BeginVertical(id, theme.emptyVertStyleRef, std::move(constraints)); - const bool pushed = idManager.PushParent(id); + app.BeginVertical(id, app.theme.emptyVertStyleRef, std::move(constraints)); + const bool pushed = app.idManager.PushParent(id); // ---- The chips: all the series, or one ------------------------------------------ if (count > 1) { - BeginHorizontal(idManager.AllocateDynamicID("plot_chips"), theme.plotToolbarStyleRef, LayoutOverride::Auto().NoShrink()); + app.BeginHorizontal(app.idManager.AllocateDynamicID("plot_chips"), styles.plotToolbarStyleRef, LayoutOverride::Auto().NoShrink()); auto chip = [&](int s, std::string_view text, VisualColorStyleIndex color) { const bool picked = view.state.shownSeries == s; - if (picked) BeginSelected(); - const ElementRef ref = RegisterControl( - Element{ .id = idManager.AllocateDynamicID(s < 0 ? std::string("plot_all") : std::format("plot_series_{}", s)), - .eventHandler = MakeButtonHandler([v, s]() { v.state.shownSeries = s; }), - .styleRef = theme.plotChannelStyleRef }, + if (picked) app.BeginSelected(); + const ElementRef ref = app.RegisterControl( + Element{ .id = app.idManager.AllocateDynamicID(s < 0 ? std::string("plot_all") : std::format("plot_series_{}", s)), + .eventHandler = app.MakeButtonHandler([v, s]() { v.state.shownSeries = s; }), + .styleRef = styles.plotChannelStyleRef }, color == VisualColorStyleIndex{} ? std::string(text) : " " + std::string(text), LayoutOverride{}); - if (picked) EndSelected(); + if (picked) app.EndSelected(); if (color == VisualColorStyleIndex{}) return; // Its color, as a small square before its name. - const int32_t square = styleManager.Px(8), pad = styleManager.Px(8); - VERIFY(elementStorage.AddCustomDrawAfter(ref, [color, square, pad](CustomDrawContext& ctx) + const int32_t square = app.styleManager.Px(8), pad = app.styleManager.Px(8); + VERIFY(app.elementStorage.AddCustomDrawAfter(ref, [color, square, pad](CustomDrawContext& ctx) { const IntRect r = ctx.ElementRect(); ctx.RenderQuad(IntRect{ r.x + pad, r.y + (r.h - square) / 2, square, square }, color, float(square) / 4.0f); @@ -158,30 +159,30 @@ namespace tachyon }; chip(-1, "All", VisualColorStyleIndex{}); for (int s = 0; s < count; ++s) - chip(s, view.data.series[size_t(s)].name, theme.curveChannelColors[size_t(view.data.series[size_t(s)].color)]); - EndHorizontal(); + chip(s, view.data.series[size_t(s)].name, styles.curveChannelColors[size_t(view.data.series[size_t(s)].color)]); + app.EndHorizontal(); } // ---- The plot ------------------------------------------------------------------ - const WheelMode wheelMode = GetWheelMode(); - const ID plotID = idManager.AllocateDynamicID("plot_area"); - const ElementState plotState = guiStateManager.GetCurrentState(plotID); + const WheelMode wheelMode = app.GetWheelMode(); + const ID plotID = app.idManager.AllocateDynamicID("plot_area"); + const ElementState plotState = app.guiStateManager.GetCurrentState(plotID); if ((plotState & ElementState::Hover) == ElementState::None) view.state.hovered = false; const PlotGrid::Frame last = FrameOf(view, view.state.plotRect); - const int32_t px1 = std::max(1, styleManager.Px(1)), px4 = styleManager.Px(4); - const float band = float(styleManager.Px(12)); // the handles' strip under the plot + const int32_t px1 = std::max(1, app.styleManager.Px(1)), px4 = app.styleManager.Px(4); + const float band = float(app.styleManager.Px(12)); // the handles' strip under the plot // The grid's numbers, from where the plot was last frame; the y axis's on a linear scale. std::vector labels; - const float minGap = float(styleManager.Px(56)), minGapV = float(styleManager.Px(28)); + const float minGap = float(app.styleManager.Px(56)), minGapV = float(app.styleManager.Px(28)); const float xStep = PlotGrid::NiceStep(last.XSpan(), float(last.rect.w), minGap); const float yStep = PlotGrid::NiceStep(last.YSpan(), float(last.rect.h), minGapV); if (view.data.labels && last.rect.w > 0 && last.rect.h > 0) { - PlotGrid::AddLabels(*this, theme.plotLabelStyleRef, labels, last.xMin, last.xMax, xStep, /*onYAxis*/ false, "plot_x_labels"); + PlotGrid::AddLabels(app, styles.plotLabelStyleRef, labels, last.xMin, last.xMax, xStep, /*onYAxis*/ false, "plot_x_labels"); if (view.data.yScale == PlotScale::Linear) - PlotGrid::AddLabels(*this, theme.plotLabelStyleRef, labels, last.yMin, last.yMax, yStep, /*onYAxis*/ true, "plot_y_labels"); + PlotGrid::AddLabels(app, styles.plotLabelStyleRef, labels, last.yMin, last.yMax, yStep, /*onYAxis*/ true, "plot_y_labels"); } // What's under the pointer: x, and each shown series' value there. @@ -201,17 +202,17 @@ namespace tachyon text += series.name.empty() ? std::format(" \xC2\xB7 {}", Number(value)) : std::format(" \xC2\xB7 {} {}", series.name, Number(value)); } - readout = textSystem->RegisterText(idManager.AllocateDynamicID("plot_readout"), text, theme.plotReadoutStyleRef, ElementState::None); - const TextMeasurement m = textSystem->MeasureText(readout, TextWrapContext{}); + readout = app.textSystem->RegisterText(app.idManager.AllocateDynamicID("plot_readout"), text, styles.plotReadoutStyleRef, ElementState::None); + const TextMeasurement m = app.textSystem->MeasureText(readout, TextWrapContext{}); readoutSize = { m.maxWidth, m.maxHeight }; } EventHandler plotHandler; if (!disabled) { - GUIStateManager& gsm = guiStateManager; - const ElementStorage& es = elementStorage; - const float reach = float(styleManager.Px(7)); + GUIStateManager& gsm = app.guiStateManager; + const ElementStorage& es = app.elementStorage; + const float reach = float(app.styleManager.Px(7)); plotHandler = [&gsm, &es, v, reach, band, wheelMode](ElementEvent&& event) -> bool { if (event.rect == nullptr) @@ -338,33 +339,33 @@ namespace tachyon }; } - const ElementRef plotRef = RegisterControl( - Element{ .id = plotID, .eventHandler = std::move(plotHandler), .styleRef = theme.plotStyleRef, .state = plotState }, + const ElementRef plotRef = app.RegisterControl( + Element{ .id = plotID, .eventHandler = std::move(plotHandler), .styleRef = styles.plotStyleRef, .state = plotState }, LayoutOverride::Auto().FlexGrow(1)); - VERIFY(elementStorage.AddPostLayout(plotRef, [v](PostLayoutContext& ctx) { v.state.plotRect = ctx.ElementInnerRect(); })); + VERIFY(app.elementStorage.AddPostLayout(plotRef, [v](PostLayoutContext& ctx) { v.state.plotRect = ctx.ElementInnerRect(); })); const float lineWidth = float(px1) * 1.5f, shownWidth = float(px1) * 2.0f; - const float handleSize = float(styleManager.Px(5)); - const VisualBoxStyleIndex readoutBox = theme.plotReadoutStyleRef.visualBoxStyleIndex; - const int2 readoutPad{ styleManager.Px(6), styleManager.Px(2) }; + const float handleSize = float(app.styleManager.Px(5)); + const VisualBoxStyleIndex readoutBox = styles.plotReadoutStyleRef.visualBoxStyleIndex; + const int2 readoutPad{ app.styleManager.Px(6), app.styleManager.Px(2) }; const int32_t labelBelow = int32_t(band) + px4; // Each handle's fill: its own color's style, kept while it's shown (alpha 0: the theme's). - std::vector handleFills(view.data.handles.size(), theme.curveSelectedKeyColor); + std::vector handleFills(view.data.handles.size(), styles.curveSelectedKeyColor); if (!view.data.handles.empty()) { - const ID fillsID = idManager.AllocateRangedID(uint32_t(view.data.handles.size()), "plot-handle-fills"); + const ID fillsID = app.idManager.AllocateRangedID(uint32_t(view.data.handles.size()), "plot-handle-fills"); for (size_t h = 0; h < view.data.handles.size(); ++h) if (view.data.handles[h].color.a > 0.0f) - handleFills[h] = AppColorStyle(idManager.GetSubID(fillsID, uint32_t(h)), view.data.handles[h].color); + handleFills[h] = app.AppColorStyle(app.idManager.GetSubID(fillsID, uint32_t(h)), view.data.handles[h].color); } - VERIFY(elementStorage.AddCustomDraw(plotRef, [=, this, handleFills = std::move(handleFills)](CustomDrawContext& ctx) + VERIFY(app.elementStorage.AddCustomDraw(plotRef, [=, &app, handleFills = std::move(handleFills), &styles](CustomDrawContext& ctx) { const IntRect inner = ctx.ElementInnerRect(); const PlotGrid::Frame f = FrameOf(v, inner); PlotGrid::DrawLines(ctx, f, PlotGrid::NiceStep(f.XSpan(), float(inner.w), minGap), v.data.yScale == PlotScale::Linear ? PlotGrid::NiceStep(f.YSpan(), float(inner.h), minGapV) : 0.0f, - { theme.curveGridColor, theme.curveGridMajorColor, theme.curveZeroColor }, px1); + { styles.curveGridColor, styles.curveGridMajorColor, styles.curveZeroColor }, px1); PlotGrid::DrawLabels(ctx, f, labels, px4, labelBelow); // The series: all overlaid and faded, or the one picked at full strength. Their @@ -379,8 +380,8 @@ namespace tachyon if (!series.visible || n == 0 || (v.state.shownSeries >= 0 && v.state.shownSeries != s)) continue; const bool alone = v.state.shownSeries == s || v.data.series.size() == 1; - const VisualColorStyleIndex full = theme.curveChannelColors[size_t(series.color)]; - const VisualColorStyleIndex faded = theme.curveChannelFadedColors[size_t(series.color)]; + const VisualColorStyleIndex full = styles.curveChannelColors[size_t(series.color)]; + const VisualColorStyleIndex faded = styles.curveChannelFadedColors[size_t(series.color)]; const float slot = (data.max - data.min) / float(n); auto top = [&](int i) { const float value = series.values[size_t(i)]; @@ -443,14 +444,14 @@ namespace tachyon continue; // out of view const float x = std::round(f.X(handle.x)); const bool active = h == v.state.activeHandle && (plotState & ElementState::Focused) != ElementState::None; - ctx.RenderQuad(IntRect{ int32_t(x), inner.y, px1, inner.h }, inner, theme.curveZeroColor); + ctx.RenderQuad(IntRect{ int32_t(x), inner.y, px1, inner.h }, inner, styles.curveZeroColor); const float y0 = float(inner.y + inner.h) + float(px1); const float2 tip{ x, y0 }, baseL{ x - handleSize, y0 + handleSize * 1.7f }, baseR{ x + handleSize, y0 + handleSize * 1.7f }; - const VisualColorStyleIndex fill = size_t(h) < handleFills.size() ? handleFills[size_t(h)] : theme.curveSelectedKeyColor; + const VisualColorStyleIndex fill = size_t(h) < handleFills.size() ? handleFills[size_t(h)] : styles.curveSelectedKeyColor; ctx.RenderTriangle(tip, baseL, baseR, fill); const int2 outline[] = { { int32_t(tip.x), int32_t(tip.y) }, { int32_t(baseL.x), int32_t(baseL.y) }, { int32_t(baseR.x), int32_t(baseR.y) } }; ctx.RenderPolyline(outline, /*closed*/ true, - LineStyle{ .colorStyleIndex = active ? theme.curveHandleColor : theme.curveKeyEdgeColor, .lineWidth = float(px1) }); + LineStyle{ .colorStyleIndex = active ? styles.curveHandleColor : styles.curveKeyEdgeColor, .lineWidth = float(px1) }); } // The value under the pointer, at the top left. @@ -463,8 +464,8 @@ namespace tachyon })); if (pushed) - (void)idManager.PopParent(); - EndVertical(); + (void)app.idManager.PopParent(); + app.EndVertical(); return changed; } } diff --git a/src/gui_controls/gui_curve_helpers.cpp b/src/gui_curves/gui_curve_helpers.cpp similarity index 99% rename from src/gui_controls/gui_curve_helpers.cpp rename to src/gui_curves/gui_curve_helpers.cpp index 0e157d9e..814c767f 100644 --- a/src/gui_controls/gui_curve_helpers.cpp +++ b/src/gui_curves/gui_curve_helpers.cpp @@ -1,4 +1,5 @@ -#include +#include +#include #include @@ -9,7 +10,7 @@ // Curves: evaluating them, the slopes the key modes work out, the presets, and the edits a // CurveField makes, each as the curves before and after so undo puts the old ones back. -namespace tachyon +namespace tachyon::curves { namespace { diff --git a/src/gui_controls/gui_curve_types.h b/src/gui_curves/gui_curve_types.h similarity index 99% rename from src/gui_controls/gui_curve_types.h rename to src/gui_curves/gui_curve_types.h index 42326fe5..4f8cbd5c 100644 --- a/src/gui_controls/gui_curve_types.h +++ b/src/gui_curves/gui_curve_types.h @@ -13,9 +13,10 @@ #include #include -namespace tachyon +namespace tachyon { class IDManager; } + +namespace tachyon::curves { - class IDManager; /// @addtogroup app /// @{ diff --git a/src/gui_curves/gui_curves.cpp b/src/gui_curves/gui_curves.cpp new file mode 100644 index 00000000..a998b75e --- /dev/null +++ b/src/gui_curves/gui_curves.cpp @@ -0,0 +1,114 @@ +#include + +#include +#include + +#include +#include + +namespace tachyon::curves +{ + 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; + StyleManager& styleManager = app.styleManager; + ITextSystem* textSystem = app.textSystem; + curveFrameAllStyleRef = theme.GetStyle("curve-frame-all"); + curveFieldStyleRef = theme.GetStyle("curve-field"); + curveWindowStyleRef = theme.GetStyle("curve-window"); + curveToolbarStyleRef = theme.GetStyle("curve-toolbar"); + curveChannelStyleRef = theme.GetStyle("curve-channel"); + curvePlotStyleRef = theme.GetStyle("curve-plot"); + curveLabelStyleRef = theme.GetStyle("curve-label"); + curveReadoutStyleRef = theme.GetStyle("curve-readout"); + curveBoxSelectStyleRef = theme.GetStyle("curve-box-select"); + curvePresetStyleRef = theme.GetStyle("curve-preset"); + curvePlotFramesStyleRef = theme.GetStyle("curve-plot-frames"); + curveTreeStyleRef = theme.GetStyle("curve-tree"); + curveTreeHeaderStyleRef = theme.GetStyle("curve-tree-header"); + curveTreeGroupStyleRef = theme.GetStyle("curve-tree-group"); + curveTreeRowStyleRef = theme.GetStyle("curve-tree-row"); + curveTreeRowHiddenStyleRef = theme.GetStyle("curve-tree-row-hidden"); + curveTreeSwatchStyleRef = theme.GetStyle("curve-tree-swatch"); + curveTreeNameStyleRef = theme.GetStyle("curve-tree-name"); + curveTreeValueStyleRef = theme.GetStyle("curve-tree-value"); + curveRulerStyleRef = theme.GetStyle("curve-ruler"); + curveRulerLabelStyleRef = theme.GetStyle("curve-ruler-label"); + curvePlayheadStyleRef = theme.GetStyle("curve-playhead"); + plotToolbarStyleRef = theme.GetStyle("plot-toolbar"); + plotChannelStyleRef = theme.GetStyle("plot-channel"); + plotStyleRef = theme.GetStyle("plot"); + plotLabelStyleRef = theme.GetStyle("plot-label"); + plotReadoutStyleRef = theme.GetStyle("plot-readout"); + curveFrameAllIcon = RegisterIcon(textSystem, "curve-frame-all", R"()"); + curveConstantIcon = RegisterIcon(textSystem, "curve-constant", R"()"); + curveLinearIcon = RegisterIcon(textSystem, "curve-linear", R"()"); + curveBezierIcon = RegisterIcon(textSystem, "curve-bezier", R"()"); + curveGridColor = theme.VariableColor(styleManager, "--curve-grid", color4f{ 0.08f, 0.09f, 0.11f, 1.0f }); + curveGridMajorColor = theme.VariableColor(styleManager, "--curve-grid-major", color4f{ 0.12f, 0.14f, 0.16f, 1.0f }); + curveZeroColor = theme.VariableColor(styleManager, "--curve-zero", color4f{ 0.2f, 0.23f, 0.27f, 1.0f }); + curveKeyEdgeColor = theme.VariableColor(styleManager, "--curve-plot", color4f{ 0.05f, 0.06f, 0.07f, 1.0f }); + curveSelectedKeyColor = theme.VariableColor(styleManager, "--text-1", color4f{ 0.91f, 0.92f, 0.94f, 1.0f }); + curveHandleColor = theme.VariableColor(styleManager, "--accent", color4f{ 0.42f, 0.61f, 1.0f, 1.0f }); + { + // Value, red, green, blue, alpha: the design's axis colors, and the warning color for one value. + static constexpr const char* kChannelVars[5] = { "--warn", "--axis-x", "--axis-y", "--axis-z", "--text-1" }; + static constexpr color4f kFallbacks[5] = { { 0.9f, 0.7f, 0.33f, 1.0f }, { 0.94f, 0.42f, 0.42f, 1.0f }, + { 0.31f, 0.77f, 0.54f, 1.0f }, { 0.42f, 0.61f, 1.0f, 1.0f }, + { 0.91f, 0.92f, 0.94f, 1.0f } }; + for (int c = 0; c < 5; ++c) + { + curveChannelColors[c] = theme.VariableColor(styleManager, kChannelVars[c], kFallbacks[c]); + color4f faded = theme.GetColor(kChannelVars[c], kFallbacks[c]); + faded.a *= 0.55f; + curveChannelFadedColors[c] = styleManager.RegisterColorStyle(ColorStyle::Create(faded)); + } + } + } + + const Styles& GetStyles(GUIApplication& app, Context& context) + { + if (context.stylesGeneration != app.StylesGeneration()) + { + context.styles.Load(app); + context.stylesGeneration = app.StylesGeneration(); + } + return context.styles; + } + + std::string SaveViewState(const CurveViewState& view) + { + if (!view.shownSet) + return {}; + const CurveRange& r = view.shown; + JsonValue state = JsonValue::MakeObject(); + state.Set("shown", JsonFloatArray({ r.timeMin, r.timeMax, r.valueMin, r.valueMax })); + return state.Write(); + } + + bool RestoreViewState(CurveViewState& view, std::string_view state) + { + const std::optional object = ParseJsonObject(state); + float r[4]; + if (!object || !JsonFloats(*object, "shown", r) || !(r[0] < r[1]) || !(r[2] < r[3])) + return false; + view.shown = CurveRange{ r[0], r[1], r[2], r[3] }; + view.shownSet = true; + return true; + } +} diff --git a/src/gui_curves/gui_curves.h b/src/gui_curves/gui_curves.h new file mode 100644 index 00000000..07ae2fb0 --- /dev/null +++ b/src/gui_curves/gui_curves.h @@ -0,0 +1,132 @@ +#pragma once + +// Curves: a curve field and its editor, and plots. A library of its own on gui_controls, in +// namespace tachyon::curves: each control is a free function that takes the application and +// a curves::Context, which the app owns. +// +// curves::Context curvesContext; // a member of the app class +// +// curves::CurveField(*this, curvesContext, falloff); +// curves::Plot(*this, curvesContext, histogram); + +#include +#include +#include + +#include +#include +#include +#include + +namespace tachyon::curves +{ + /// @addtogroup controls + /// @{ + + /// The curves' and plots' styles, icons and colors, looked up in the theme after each load. + struct Styles + { + StyleRef curveFrameAllStyleRef {}; ///< CurveEditor: Frame all, a flat button + StyleRef curveFieldStyleRef {}; ///< CurveField: the box the curve is drawn in + StyleRef curveWindowStyleRef {}; ///< its editor's window + StyleRef curveToolbarStyleRef {}; ///< the editor's rows over and under the plot + StyleRef curveChannelStyleRef {}; ///< a channel's chip; selected for the active one + StyleRef curvePlotStyleRef {}; ///< the plot; its padding holds the grid's labels + StyleRef curveLabelStyleRef {}; ///< drawn: a grid line's number + StyleRef curveReadoutStyleRef {}; ///< drawn: the selected key's time and value beside it + StyleRef curveBoxSelectStyleRef {}; ///< drawn: the box a drag on the plot selects with + StyleRef curvePresetStyleRef {}; ///< a preset's thumbnail button + StyleRef curvePlotFramesStyleRef {}; ///< the plot with fps set: no time labels under it + StyleRef curveTreeStyleRef {}; ///< the channel list down the left + StyleRef curveTreeHeaderStyleRef {}; ///< its header: Channel, and the playhead's frame + StyleRef curveTreeGroupStyleRef {}; ///< a group's row, its chevron before its name + StyleRef curveTreeRowStyleRef {}; ///< a channel's row; selected for the active one + StyleRef curveTreeRowHiddenStyleRef {}; ///< a hidden channel's row, faded + StyleRef curveTreeSwatchStyleRef {}; ///< a channel's color square + StyleRef curveTreeNameStyleRef {}; ///< a channel's name + StyleRef curveTreeValueStyleRef {}; ///< its value at the playhead + StyleRef curveRulerStyleRef {}; ///< the frame ruler over the plot + StyleRef curveRulerLabelStyleRef {}; ///< drawn: a frame number on it + StyleRef curvePlayheadStyleRef {}; ///< drawn: the playhead's frame, in its pill + StyleRef plotToolbarStyleRef {}; ///< Plot: the row of series chips over it + StyleRef plotChannelStyleRef {}; ///< a series' chip; selected for the one shown + StyleRef plotStyleRef {}; ///< the plot; its padding holds the labels and the handles + StyleRef plotLabelStyleRef {}; ///< drawn: a grid line's number + StyleRef plotReadoutStyleRef {}; ///< drawn: the values under the pointer + IconID curveFrameAllIcon {}; ///< CurveField's editor: show all the keys (four corners) + IconID curveConstantIcon {}; ///< its interpolations: a step + IconID curveLinearIcon {}; ///< straight lines + IconID curveBezierIcon {}; ///< a smooth curve + /// A curve editor's: the plot's grid, its major lines and its lines at zero; a key's edge + /// (the plot's color); a selected key and its tangent handles. + VisualColorStyleIndex curveGridColor {}; + VisualColorStyleIndex curveGridMajorColor {}; + VisualColorStyleIndex curveZeroColor {}; + VisualColorStyleIndex curveKeyEdgeColor {}; + VisualColorStyleIndex curveSelectedKeyColor {}; + VisualColorStyleIndex curveHandleColor {}; + /// A channel's color by CurveChannelColor, and the same at 55% for the channels not + /// being edited. + VisualColorStyleIndex curveChannelColors[5] {}; + VisualColorStyleIndex curveChannelFadedColors[5] {}; + + /// Looks them all up in `app`'s theme, after it loads. + void Load(GUIApplication& app); + }; + + /// What the curves keep from frame to frame, the app's to own and pass to each of them. + struct Context + { + Styles styles; + uint32_t stylesGeneration = 0; ///< the app's StylesGeneration the styles were looked up at + }; + + /// The curves' styles in `app`'s theme, looked up again after each theme load. + const Styles& GetStyles(GUIApplication& app, Context& context); + + /// @name Curves + ///@{ + + /// A curve in a box, over the curves' range: a click opens the curve editor (CurveEditor) + /// in a window under it. Every change comes to the curves' `onEdit`, already applied. + /// True on the frame after a change made in it, as a field's is. `view` is a CurveView, + /// or `{ data, state }` for one of several views of the same curves. + /// CurveView falloff; // a member: one channel, keys over 0 to 1 + /// Label("Falloff"); + /// CurveField(app, context, app.idManager.AllocateDynamicID("falloff"), falloff); + bool CurveField(GUIApplication& app, Context& context, ID id, CurveViewRef view, LayoutOverride&& constraints = {}); + /// As above, with the call site as the ID. + inline bool CurveField(GUIApplication& app, Context& context, CurveViewRef view, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return CurveField(app, context, app.idManager.AllocateDynamicID(site), view, std::move(constraints)); } + + /// The curve editor a CurveField opens, as a control of its own: the channels and the + /// selected key's time and value over the plot; the keys, their tangent handles and the + /// grid on it; the presets and the wrap modes under it. + void CurveEditor(GUIApplication& app, Context& context, ID id, CurveViewRef view, LayoutOverride&& constraints = {}); + /// As above, with the call site as the ID. + inline void CurveEditor(GUIApplication& app, Context& context, CurveViewRef view, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { CurveEditor(app, context, app.idManager.AllocateDynamicID(site), view, std::move(constraints)); } + + /// Series of values as lines, bars or areas over the x range (a histogram's channels), + /// with a chip per series to show one on its own, the values under the pointer, and + /// handles dragged along x under the plot. True on the frame after a handle moved in + /// it. `view` is a PlotView, or `{ data, state }` for one of several views of a plot. + /// + /// PlotView levels; // a member + /// levels.series = { PlotSeries{ .name = "Luma", .values = HistogramBins(lumas, 256) } }; + /// levels.handles = { { "Black", 0.0f }, { "White", 1.0f } }; + /// if (Plot(app, context, app.idManager.AllocateDynamicID("levels"), levels)) + /// ApplyLevels(levels.handles[0].x, levels.handles[1].x); + bool Plot(GUIApplication& app, Context& context, ID id, PlotViewRef view, LayoutOverride&& constraints = {}); + /// As above, with the call site as the ID. + inline bool Plot(GUIApplication& app, Context& context, PlotViewRef view, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return Plot(app, context, app.idManager.AllocateDynamicID(site), view, std::move(constraints)); } + + + ///@} + + /// A curve plot's own state as text, for a panel to keep with its layout, and back (Panel::saveState and + /// Panel::restoreState). + /// The part of a curve plot in view in its editor. Empty until the editor has shown it. + std::string SaveViewState(const CurveViewState& view); + bool RestoreViewState(CurveViewState& view, std::string_view state); + + /// @} +} diff --git a/src/gui_controls/gui_plot_grid_internal.h b/src/gui_curves/gui_plot_grid_internal.h similarity index 99% rename from src/gui_controls/gui_plot_grid_internal.h rename to src/gui_curves/gui_plot_grid_internal.h index 34782265..269367b5 100644 --- a/src/gui_controls/gui_plot_grid_internal.h +++ b/src/gui_curves/gui_plot_grid_internal.h @@ -12,7 +12,7 @@ #include #include -namespace tachyon::PlotGrid +namespace tachyon::curves::PlotGrid { /// A range shown over a rect, y up. struct Frame diff --git a/src/gui_controls/gui_plot_helpers.cpp b/src/gui_curves/gui_plot_helpers.cpp similarity index 97% rename from src/gui_controls/gui_plot_helpers.cpp rename to src/gui_curves/gui_plot_helpers.cpp index 494dc5e8..1520504f 100644 --- a/src/gui_controls/gui_plot_helpers.cpp +++ b/src/gui_curves/gui_plot_helpers.cpp @@ -1,9 +1,10 @@ -#include +#include +#include #include #include -namespace tachyon +namespace tachyon::curves { std::vector HistogramBins(std::span samples, int bins, float min, float max) { diff --git a/src/gui_controls/gui_plot_types.h b/src/gui_curves/gui_plot_types.h similarity index 98% rename from src/gui_controls/gui_plot_types.h rename to src/gui_curves/gui_plot_types.h index 0a29190a..b6bd0da9 100644 --- a/src/gui_controls/gui_plot_types.h +++ b/src/gui_curves/gui_plot_types.h @@ -3,7 +3,7 @@ // Plot: series of values drawn as lines, bars or a filled area over a range, with handles // dragged along it (a Levels control's black, gray and white points). -#include +#include #include #include #include @@ -13,7 +13,7 @@ #include #include -namespace tachyon +namespace tachyon::curves { /// @addtogroup controls /// @{ 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..80966148 100644 --- a/src/gui_dialogs/gui_dialogs_extension.cpp +++ b/src/gui_dialogs/gui_dialogs.cpp @@ -1,5 +1,5 @@ #include -#include // SetColorStyle +#include #include @@ -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/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 80% rename from src/gui_controls/gui_docking_types.h rename to src/gui_docking/gui_docking_types.h index 769bfc1c..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. @@ -122,7 +73,7 @@ namespace tachyon /// the same key. With several of one key, each gets its own: they're matched by the /// order they're in in the dock tree. /// - /// panel.saveState = [this] { return SaveViewState(graph); }; // gui_view_state.h + /// panel.saveState = [this] { return nodes::SaveViewState(graph); }; // gui_nodes.h /// panel.restoreState = [this](std::string_view s) { RestoreViewState(graph, s); }; std::function saveState; std::function restoreState; @@ -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/src/gui_controls/controls_node_view.cpp b/src/gui_nodes/controls_node_view.cpp similarity index 82% rename from src/gui_controls/controls_node_view.cpp rename to src/gui_nodes/controls_node_view.cpp index cae18169..764662d6 100644 --- a/src/gui_controls/controls_node_view.cpp +++ b/src/gui_nodes/controls_node_view.cpp @@ -1,20 +1,57 @@ -#include -#include +#include #include #include #include #include // -// Node-view widget. RenderNodeView(NodeView&) renders one graph editor; the +// Node-view widget. RenderNodeView(app, context, NodeView&) renders one graph editor; the // NodeView owns nodes, pan/zoom, z-order and drag state. Nothing is global. // -namespace tachyon +namespace tachyon::nodes { namespace { + // A socket's tooltip: its pin's name, type and value, and a wired input's source. + void ShowPinTooltip(GUIApplication& app, const NodeGraph& view, ID socketID, PropertyEndpoint pin, bool isOutput) + { + const NodeProperty& prop = view.nodes[size_t(pin.nodeIdx)].properties[size_t(pin.propIdx)]; + if (prop.name.empty() && prop.type.empty() && !prop.value) + return; + if (!app.BeginTooltip(socketID, GUIApplication::TooltipBox::Lines)) + { + app.EndTooltip(); + return; + } + auto line = [&app](std::string_view text, StyleRef style) { + if (!text.empty()) + app.RegisterElement(tachyon::Element{ .id = app.idManager.AllocateDynamicID(), .styleRef = style, + .flags = ElementFlags::NoInput }, text, LayoutOverride{}); + }; + // "Strength float 0.75" + app.RegisterElement(tachyon::Element{ .id = app.idManager.AllocateDynamicID(), .styleRef = app.theme.tooltipPinRowStyleRef, + .flags = ElementFlags::NoInput }, LayoutOverride{}); + VERIFY(app.elementStorage.BeginChildren()); + line(prop.name, app.theme.tooltipTextStyleRef); + line(prop.type, app.theme.tooltipPinTypeStyleRef); + if (prop.value) + line(prop.value(), app.theme.tooltipPinValueStyleRef); + VERIFY(app.elementStorage.EndChildren()); + // "from Source.Value" + if (!isOutput && prop.input && prop.input->valid() && size_t(prop.input->nodeIdx) < view.nodes.size()) + { + const NodeModel& source = view.nodes[size_t(prop.input->nodeIdx)]; + std::string from = "from " + source.title; + if (size_t(prop.input->propIdx) < source.properties.size() && !source.properties[size_t(prop.input->propIdx)].name.empty()) + from += "." + source.properties[size_t(prop.input->propIdx)].name; + line(from, app.theme.tooltipNoteStyleRef); + } + app.EndTooltip(); + } + + // Drag payload types for socket-to-socket connections (must be unique): a wire dragged // from an output (its value the output), and one dragged from an input (the input). constexpr uint32_t kSocketPayload = 0x534f434b; // "SOCK" @@ -124,14 +161,14 @@ namespace tachyon // - a state whose edge is hovered (or being drawn from): a ring round it // - each transition: an arrow, lit hovered, in the accent selected, its label on it // - a transition being drawn: dashed, to the state under the pointer, or the pointer - void DrawStateMachine(CustomDrawContext& ctx, const GUITheme& theme, const StyleManager& styles, ConstNodeViewRef view, + void DrawStateMachine(CustomDrawContext& ctx, const Styles& styles, const StyleManager& sm, ConstNodeViewRef view, int2 gridOrigin, std::span labels, const StateMarks& marks, int32_t gap, int32_t loop, bool canvasHovered, int2 pointer, ID pointedState, ID bandLit, int32_t band) { auto box = [&](const NodeModel& node) { return IntRect{ node.pos.x + gridOrigin.x, node.pos.y + gridOrigin.y, node.lastSize.x, node.lastSize.y }; }; - const int32_t ring = styles.Px(3); + const int32_t ring = sm.Px(3); auto around = [&](IntRect r, int32_t by) { return IntRect{ r.x - by, r.y - by, r.w + 2 * by, r.h + 2 * by }; }; // An arrowhead with its tip on `tip`, pointing away from `from`. auto head = [&](float2 tip, float2 from, VisualColorStyleIndex color) { @@ -139,7 +176,7 @@ namespace tachyon const float length = std::sqrt(d.x * d.x + d.y * d.y); if (length <= 0.0f) return; d = { d.x / length, d.y / length }; - const float l = styles.Px(10.0f), w = styles.Px(5.0f); + const float l = sm.Px(10.0f), w = sm.Px(5.0f); const float2 base{ tip.x - d.x * l, tip.y - d.y * l }; ctx.RenderTriangle(tip, { base.x - d.y * w, base.y + d.x * w }, { base.x + d.y * w, base.y - d.x * w }, color); }; @@ -151,11 +188,11 @@ namespace tachyon if (n < 0) continue; const NodeModel& node = view.graph.nodes[size_t(n)]; if (node.hidden || node.lastSize.x <= 0 || node.lastSize.y <= 0) continue; - const int32_t o = styles.Px(4); + const int32_t o = sm.Px(4); const IntRect b = box(node); const IntRect back{ b.x - o, b.y - o, b.w, b.h }; const BoxCorners* r = nullptr; - if (const VisualBoxStyle* s = styles.GetVisualBoxStyle(nested.edge, ElementState::None)) r = &s->borderRadius; + if (const VisualBoxStyle* s = sm.GetVisualBoxStyle(nested.edge, ElementState::None)) r = &s->borderRadius; ctx.RenderQuad(back, nested.fill, r ? float(r->topLeft) : 0.0f); ctx.RenderBox(back, nested.edge); } @@ -165,25 +202,25 @@ namespace tachyon const IntRect b = box(node); if (node.stableID == view.graph.activeState) { - const int32_t halo = styles.Px(3); - const VisualBoxStyle* active = styles.GetVisualBoxStyle(theme.nodeStateActiveStyleRef.visualBoxStyleIndex, ElementState::None); + const int32_t halo = sm.Px(3); + const VisualBoxStyle* active = sm.GetVisualBoxStyle(styles.nodeStateActiveStyleRef.visualBoxStyleIndex, ElementState::None); const float radius = active ? float(active->borderRadius.topLeft) : 0.0f; ctx.RenderQuad(around(b, ring + halo), marks.activeHalo, radius + float(halo)); - ctx.RenderBox(around(b, ring), theme.nodeStateActiveStyleRef.visualBoxStyleIndex); + ctx.RenderBox(around(b, ring), styles.nodeStateActiveStyleRef.visualBoxStyleIndex); } // The band a transition is drawn from, along its middle: faint while the pointer // is on the state or round it, lit on the band itself. if (node.stableID == pointedState) - ctx.RenderBox(around(b, band / 2), theme.nodeStateEdgeStyleRef.visualBoxStyleIndex, + ctx.RenderBox(around(b, band / 2), styles.nodeStateEdgeStyleRef.visualBoxStyleIndex, node.stableID == bandLit ? ElementState::Hover : ElementState::None); if (node.stableID == view.graph.initialState) { - const int32_t reach = styles.Px(28), radius = styles.Px(4); + const int32_t reach = sm.Px(28), radius = sm.Px(4); const int2 into{ b.x, b.y + b.h / 2 }; const int2 start{ b.x - reach, into.y }; - ctx.RenderDisc(start, float(radius), theme.nodeInitialStateColor); - ctx.RenderLine(start, { into.x - styles.Px(8), into.y }, LineStyle{ .colorStyleIndex = theme.nodeInitialStateColor, .lineWidth = styles.Px(2.0f) }); - head(f(into), f(start), theme.nodeInitialStateColor); + ctx.RenderDisc(start, float(radius), styles.nodeInitialStateColor); + ctx.RenderLine(start, { into.x - sm.Px(8), into.y }, LineStyle{ .colorStyleIndex = styles.nodeInitialStateColor, .lineWidth = sm.Px(2.0f) }); + head(f(into), f(start), styles.nodeInitialStateColor); } } @@ -196,9 +233,9 @@ namespace tachyon *p = *p + gridOrigin; const bool selected = view.state.selectedTransitionIDs.contains(t.stableID); const bool lit = hovered == t.stableID; - const VisualColorStyleIndex color = selected ? theme.nodeTransitionSelectedColor - : lit ? theme.nodeTransitionHoverColor : theme.nodeTransitionColor; - const LineStyle style{ .colorStyleIndex = color, .lineWidth = styles.Px(lit || selected ? 3.0f : 2.0f) }; + const VisualColorStyleIndex color = selected ? styles.nodeTransitionSelectedColor + : lit ? styles.nodeTransitionHoverColor : styles.nodeTransitionColor; + const LineStyle style{ .colorStyleIndex = color, .lineWidth = sm.Px(lit || selected ? 3.0f : 2.0f) }; // The line stops short of the tip, under the head. if (path.loop) { @@ -216,7 +253,7 @@ namespace tachyon for (const TransitionLabel& label : labels) { const IntRect chip{ label.chip.x + gridOrigin.x, label.chip.y + gridOrigin.y, label.chip.w, label.chip.h }; - ctx.RenderBox(chip, theme.nodeTransitionLabelStyleRef.visualBoxStyleIndex, label.state); + ctx.RenderBox(chip, styles.nodeTransitionLabelStyleRef.visualBoxStyleIndex, label.state); ctx.RenderText(label.text, IntRect{ chip.x + (chip.w - label.size.x) / 2, chip.y + (chip.h - label.size.y) / 2, label.size.x, label.size.y }); } @@ -228,12 +265,12 @@ namespace tachyon if (!node.hidden && node.lastSize.x > 0 && node.lastSize.y > 0) { const IntRect b = box(node); - const int2 pad{ styles.Px(6), styles.Px(2) }; - const IntRect pill{ b.x + (b.w - marks.timeSize.x) / 2 - pad.x, b.y + b.h + ring + styles.Px(5), + const int2 pad{ sm.Px(6), sm.Px(2) }; + const IntRect pill{ b.x + (b.w - marks.timeSize.x) / 2 - pad.x, b.y + b.h + ring + sm.Px(5), marks.timeSize.x + 2 * pad.x, marks.timeSize.y + 2 * pad.y }; - const VisualBoxStyle* pillStyle = styles.GetVisualBoxStyle(theme.nodeStateTimeStyleRef.visualBoxStyleIndex, ElementState::None); + const VisualBoxStyle* pillStyle = sm.GetVisualBoxStyle(styles.nodeStateTimeStyleRef.visualBoxStyleIndex, ElementState::None); ctx.RenderQuad(pill, marks.canvas, pillStyle ? float(pillStyle->borderRadius.topLeft) : 0.0f); // no arrow through it - ctx.RenderBox(pill, theme.nodeStateTimeStyleRef.visualBoxStyleIndex); + ctx.RenderBox(pill, styles.nodeStateTimeStyleRef.visualBoxStyleIndex); ctx.RenderText(marks.timeText, IntRect{ pill.x + pad.x, pill.y + pad.y, marks.timeSize.x, marks.timeSize.y }); } } @@ -262,10 +299,10 @@ namespace tachyon t = std::clamp(t, 0.0f, 1.0f); to = { cb.x + d.x * t, cb.y + d.y * t }; } - const LineStyle dashed{ .colorStyleIndex = theme.nodeTransitionHoverColor, .lineWidth = styles.Px(2.0f), .dashSize = styles.Px(5.0f) }; + const LineStyle dashed{ .colorStyleIndex = styles.nodeTransitionHoverColor, .lineWidth = sm.Px(2.0f), .dashSize = sm.Px(5.0f) }; const int2 tip{ int32_t(std::lround(to.x)), int32_t(std::lround(to.y)) }; ctx.RenderLine({ int32_t(std::lround(ca.x)), int32_t(std::lround(ca.y)) }, tip, dashed); - head(to, ca, theme.nodeTransitionHoverColor); + head(to, ca, styles.nodeTransitionHoverColor); } } @@ -285,24 +322,28 @@ namespace tachyon } - void GUIApplication::NodeText(std::string_view text) + void NodeText(GUIApplication& app, Context& context, std::string_view text) { + const Styles& styles = GetStyles(app, context); // Alignment is baked into the style (text-align); flex-grow makes the - // text box span the row body so centre/right are visible. nodeRowTextAlign + // text box span the row body so centre/right are visible. context.rowTextAlign // is set by RenderNodeView from the row's sockets before renderBody runs. - StyleRef style = theme.nodeTextLeftStyleRef; - switch (nodeRowTextAlign) + StyleRef style = styles.nodeTextLeftStyleRef; + switch (context.rowTextAlign) { - case TextAlign::Center: style = theme.nodeTextCenterStyleRef; break; - case TextAlign::End: style = theme.nodeTextRightStyleRef; break; - default: style = theme.nodeTextLeftStyleRef; break; + case TextAlign::Center: style = styles.nodeTextCenterStyleRef; break; + case TextAlign::End: style = styles.nodeTextRightStyleRef; break; + default: style = styles.nodeTextLeftStyleRef; break; } - Text(text, style, LayoutOverride{}.FlexGrow(1)); + app.Text(text, style, LayoutOverride{}.FlexGrow(1)); } - void GUIApplication::RenderNodeView(NodeViewRef view) + static void EmitNodeViewOverlays(GUIApplication& app, Context& context, NodeViewRef view, ID canvasID); + + void RenderNodeView(GUIApplication& app, Context& context, NodeViewRef view) { + const Styles& styles = GetStyles(app, context); // Coordinate spaces inside the node-view (read this before touching marquee math): // // SCREEN : absolute pixels on the OS window. Mouse events (event.state.screenPos) @@ -323,16 +364,16 @@ namespace tachyon // // A drag that ended without a Drop on us (e.g. released in empty space) leaves // a stale pending wire; clear it. - if (view.state.pendingConnection.IsActive() && !guiStateManager.Drag().IsDragging()) + if (view.state.pendingConnection.IsActive() && !app.guiStateManager.Drag().IsDragging()) CancelConnection(view); view.state.pendingConnection.target = {}; // A state machine: its nodes are states, without fields, and transitions join them. const bool stateMachine = view.graph.kind == NodeViewKind::StateMachine; - const int32_t transitionGap = styleManager.Px(6); // a pair both ways: each this far to its side - const int32_t transitionLoop = styleManager.Px(24); // how far a loop rises over its state - const float transitionReach = float(styleManager.Px(7)) / std::max(NodeViewZoom(view), 0.01f); // node.pos units - const float stateBand = float(styleManager.Px(12)) / std::max(NodeViewZoom(view), 0.01f); // node.pos units + const int32_t transitionGap = app.styleManager.Px(6); // a pair both ways: each this far to its side + const int32_t transitionLoop = app.styleManager.Px(24); // how far a loop rises over its state + const float transitionReach = float(app.styleManager.Px(7)) / std::max(NodeViewZoom(view), 0.01f); // node.pos units + const float stateBand = float(app.styleManager.Px(12)) / std::max(NodeViewZoom(view), 0.01f); // node.pos units if (view.state.renamingTransition && TransitionIndex(view, *view.state.renamingTransition) < 0) view.state.renamingTransition.reset(); std::erase_if(view.state.selectedTransitionIDs, [view](ID id) { return TransitionIndex(view, id) < 0; }); @@ -350,25 +391,25 @@ namespace tachyon view.state.lastClickedNodeID = ID::Invalid(); } - ID canvasID = idManager.AllocateDynamicID(); + ID canvasID = app.idManager.AllocateDynamicID(); view.state.canvasID = canvasID; // The canvas places its nodes by pan and zoom (view.state.transform), never by scrolling: a // scroll (a field bringing its caret into view) would move the nodes away from what the // canvas draws itself, its wires and arrows. Whatever scrolled it is undone here. { - auto& scrolling = guiStateManager.GetScrollManagement(); + auto& scrolling = app.guiStateManager.GetScrollManagement(); const auto handle = scrolling.GetScrollOffsetHandle(canvasID); if (scrolling.IsScrollOffsetHandleValid(handle) && scrolling.GetScrollOffset(handle) != int2{ 0, 0 }) scrolling.SetScrollOffset(handle, int2{ 0, 0 }); } - const ID wireMenuID = idManager.AllocateDynamicID("wire-menu"); // owns the wire context menu - const ID canvasMenuID = idManager.AllocateDynamicID("canvas-menu"); // the canvas's (onCanvasContextMenu) - const ID nodeMenuID = idManager.AllocateDynamicID("node-menu"); // a node's (onNodeContextMenu) - const ID frameMenuID = idManager.AllocateDynamicID("frame-menu"); // a frame's (onFrameContextMenu) - const ID transitionMenuID = idManager.AllocateDynamicID("transition-menu"); // a transition's + const ID wireMenuID = app.idManager.AllocateDynamicID("wire-menu"); // owns the wire context menu + const ID canvasMenuID = app.idManager.AllocateDynamicID("canvas-menu"); // the canvas's (onCanvasContextMenu) + const ID nodeMenuID = app.idManager.AllocateDynamicID("node-menu"); // a node's (onNodeContextMenu) + const ID frameMenuID = app.idManager.AllocateDynamicID("frame-menu"); // a frame's (onFrameContextMenu) + const ID transitionMenuID = app.idManager.AllocateDynamicID("transition-menu"); // a transition's // Opens one of the view's context menus at `screen`; the others close. - auto openMenu = [this, view](ID menuID, int2 screen, std::optional wire, + auto openMenu = [&app, view](ID menuID, int2 screen, std::optional wire, std::optional canvasPos, std::optional node, std::optional frame = std::nullopt, std::optional transition = std::nullopt) { @@ -377,7 +418,7 @@ namespace tachyon view.state.nodeMenuNode = node; view.state.frameMenuFrame = frame; view.state.transitionMenuTransition = transition; - OpenContextMenu(menuID, screen); + app.OpenContextMenu(menuID, screen); }; // The open context menus, before anything else: what one of their items does (add @@ -385,39 +426,39 @@ namespace tachyon // The menu a right click on a wire opened. if (view.state.wireMenuWire) { - if (BeginContextMenu(wireMenuID)) + if (app.BeginContextMenu(wireMenuID)) { const PropertyEndpoint input = WireInput(*view.state.wireMenuWire); - MenuItem("Delete wire", [view, input] { CommitNodeViewEdit(view, DisconnectEdit(view, input)); }); + app.MenuItem("Delete wire", [view, input] { CommitNodeViewEdit(view, DisconnectEdit(view, input)); }); // A reroute where it was clicked, its dot on the grid point nearest when // snapping. Its ID is the app's to release, as for its own nodes. - MenuItem("Add reroute here", [this, view, wire = *view.state.wireMenuWire] { - const int32_t grid = std::max(1, theme.nodeGridSize); + app.MenuItem("Add reroute here", [&styles, &app, view, wire = *view.state.wireMenuWire] { + const int32_t grid = std::max(1, styles.nodeGridSize); const int2 at{ int32_t(std::lround(view.state.wireMenuPos.x)) - grid, int32_t(std::lround(view.state.wireMenuPos.y)) - grid }; const int2 pos = view.graph.snapToGrid ? int2{ GridLineNearest(at.x, 0, grid), GridLineNearest(at.y, 0, grid) } : at; - const ID reroute = idManager.CreateStaticID(); + const ID reroute = app.idManager.CreateStaticID(); const NodeViewEdit edit = RerouteWireEdit(view, wire, reroute, pos); if (edit.empty()) - idManager.ReleaseStaticID(reroute); // the wire is gone + app.idManager.ReleaseStaticID(reroute); // the wire is gone else CommitNodeViewEdit(view, edit); }); } else view.state.wireMenuWire.reset(); - EndContextMenu(); + app.EndContextMenu(); } // The app's menus for the canvas and for a node, built by it while open. if (view.state.canvasMenuPos) { - if (BeginContextMenu(canvasMenuID)) + if (app.BeginContextMenu(canvasMenuID)) { if (view.state.onCanvasContextMenu) view.state.onCanvasContextMenu(*view.state.canvasMenuPos); } else view.state.canvasMenuPos.reset(); - EndContextMenu(); + app.EndContextMenu(); } if (view.state.nodeMenuNode) { @@ -425,22 +466,22 @@ namespace tachyon const auto it = std::find_if(view.graph.nodes.begin(), view.graph.nodes.end(), [&](const NodeModel& node) { return node.stableID == *view.state.nodeMenuNode; }); const bool there = it != view.graph.nodes.end(); - const bool open = there && BeginContextMenu(nodeMenuID); + const bool open = there && app.BeginContextMenu(nodeMenuID); const int node = there ? int(it - view.graph.nodes.begin()) : -1; // A reroute's menu is its own: take it out, its wire running on as it did through // it. The app's node menu is for its nodes. if (open && it->reroute) - MenuItem("Remove reroute", [view, node] { CommitNodeViewEdit(view, RemoveRerouteEdit(view, node)); }); + app.MenuItem("Remove reroute", [view, node] { CommitNodeViewEdit(view, RemoveRerouteEdit(view, node)); }); else { // A state's own first: a transition from it, as a drag from its band draws. if (open && view.graph.kind == NodeViewKind::StateMachine) - MenuItem("Add transition", [view, node] { StartTransition(view, node); }); + app.MenuItem("Add transition", [view, node] { StartTransition(view, node); }); if (open && view.state.onNodeContextMenu) view.state.onNodeContextMenu(node); } if (there) - EndContextMenu(); + app.EndContextMenu(); if (!open) view.state.nodeMenuNode.reset(); } @@ -450,11 +491,11 @@ namespace tachyon const auto it = std::find_if(view.graph.frames.begin(), view.graph.frames.end(), [&](const NodeFrame& frame) { return frame.stableID == *view.state.frameMenuFrame; }); const bool there = it != view.graph.frames.end(); - const bool open = there && BeginContextMenu(frameMenuID); + const bool open = there && app.BeginContextMenu(frameMenuID); if (open && view.state.onFrameContextMenu) view.state.onFrameContextMenu(int(it - view.graph.frames.begin())); if (there) - EndContextMenu(); + app.EndContextMenu(); if (!open) view.state.frameMenuFrame.reset(); } @@ -462,11 +503,11 @@ namespace tachyon if (view.state.transitionMenuTransition) { const int t = TransitionIndex(view, *view.state.transitionMenuTransition); - const bool open = t >= 0 && BeginContextMenu(transitionMenuID); + const bool open = t >= 0 && app.BeginContextMenu(transitionMenuID); if (open) { - MenuItem("Rename", [view, t] { RenameTransition(view, t); }); - MenuItem("Delete transition", [view, id = *view.state.transitionMenuTransition] { + app.MenuItem("Rename", [view, t] { RenameTransition(view, t); }); + app.MenuItem("Delete transition", [view, id = *view.state.transitionMenuTransition] { const ID only[] = { id }; CommitNodeViewEdit(view, RemoveTransitionsEdit(view, only)); }); @@ -474,20 +515,20 @@ namespace tachyon view.state.onTransitionContextMenu(t); } if (t >= 0) - EndContextMenu(); + app.EndContextMenu(); if (!open) view.state.transitionMenuTransition.reset(); } // Its shortcuts while the focus is on the canvas. - ClaimCommandMode(canvasID, view.state.commandMode); + app.ClaimCommandMode(canvasID, view.state.commandMode); // ---- Canvas: pan/zoom + focus capture. Everything below renders as // children of this element under the view's content transform. tachyon::Element canvas { .id = canvasID, - .eventHandler = [this, view, canvasID, wireMenuID, canvasMenuID, nodeMenuID, frameMenuID, transitionMenuID, openMenu, + .eventHandler = [&styles, &app, view, canvasID, wireMenuID, canvasMenuID, nodeMenuID, frameMenuID, transitionMenuID, openMenu, stateMachine, transitionGap, transitionLoop, transitionReach, stateBand](ElementEvent&& event)->bool { switch (event.type) @@ -498,17 +539,17 @@ namespace tachyon // that doesn't move removes the wire under the mouse, at the release. if (const MouseButtons panButton = PanDragButton(event.state); panButton != MouseButtons::None) { - view.state.pan.Press(event, elementStorage, this->guiStateManager, view.state.transform, + view.state.pan.Press(event, app.elementStorage, app.guiStateManager, view.state.transform, { .button = panButton, .focusID = canvasID, .capture = false }); return true; } // A right click opens a menu, at the release. - if (view.state.menuPress.Press(event, elementStorage, this->guiStateManager, {}, + if (view.state.menuPress.Press(event, app.elementStorage, app.guiStateManager, {}, { .button = MouseButtons::Right, .focusID = canvasID, .capture = false })) return true; if (!event.state.LeftDown()) return false; - TakeFocus(this->guiStateManager, canvasID); + TakeFocus(app.guiStateManager, canvasID); // A transition from a menu, waiting for a state: a press off the states drops it. if (view.state.transitionPicking) { @@ -520,7 +561,7 @@ namespace tachyon if (stateMachine) if (const int s = StateBandAt(view, NodeViewScreenToNodePos(view, event.state.screenPos), stateBand); s >= 0) { - view.state.transitionDrag.Press(event, elementStorage, this->guiStateManager, {}, { .focus = false }); + view.state.transitionDrag.Press(event, app.elementStorage, app.guiStateManager, {}, { .focus = false }); view.state.transitionFrom = view.graph.nodes[size_t(s)].stableID; view.state.transitionPointer = event.state.screenPos; return true; @@ -555,7 +596,7 @@ namespace tachyon // Begin marquee. Only SCREEN positions are captured here; the // screen->CANVAS_LAY conversion is done from the LIVE canvas rect each // MouseMove (see screenToCanvasLay below). - if (view.state.marquee.Press(event, elementStorage, this->guiStateManager, + if (view.state.marquee.Press(event, app.elementStorage, app.guiStateManager, { view.state.selectedNodeIDs, view.state.selectedFrameIDs, (event.state.modifiers & KeyModifier::Shift) != KeyModifier::None, (event.state.modifiers & KeyModifier::Control) != KeyModifier::None }, @@ -570,21 +611,21 @@ namespace tachyon // A transition being drawn follows the pointer. if (view.state.transitionDrag.IsPressed(event.id)) { - view.state.transitionDrag.Move(event, styleManager.Px(kDragStartDistance)); + view.state.transitionDrag.Move(event, app.styleManager.Px(kDragStartDistance)); view.state.transitionPointer = event.state.screenPos; return true; } // A right press moved past the drag distance opens no menu at its release. if (view.state.menuPress.IsPressed(event.id)) { - view.state.menuPress.Move(event, styleManager.Px(kDragStartDistance)); + view.state.menuPress.Move(event, app.styleManager.Px(kDragStartDistance)); return true; } if (view.state.pan.IsPressed(event.id) && (event.state.buttons & view.state.pan.drag.button) != MouseButtons::None) { // Pans from the first move; past the drag distance the release isn't a click. - view.state.pan.Move(event, styleManager.Px(kDragStartDistance)); - this->guiStateManager.Interaction().SetFocusID(canvasID); + view.state.pan.Move(event, app.styleManager.Px(kDragStartDistance)); + app.guiStateManager.Interaction().SetFocusID(canvasID); tachyon::float3x2 translate = tachyon::float3x2::Translate(event.state.screenDelta); view.state.transform = translate * view.state.transform; return true; @@ -592,7 +633,7 @@ namespace tachyon if (view.state.marquee.IsPressed(event.id)) { view.state.marqueeCurrentScreen = event.state.screenPos; - if (view.state.marquee.Move(event, styleManager.Px(kDragStartDistance))) + if (view.state.marquee.Move(event, app.styleManager.Px(kDragStartDistance))) { // Select nodes fully inside the marquee (CANVAS_LAY), using the // live canvas rect in case the panel moved since MouseDown. @@ -665,7 +706,7 @@ namespace tachyon { const int target = NodeAtCanvasPos(view, NodeViewScreenToNodePos(view, event.state.screenPos)); if (target >= 0 && !view.graph.nodes[size_t(target)].hidden) - AddTransitionIfNew(view, view.state.transitionFrom, view.graph.nodes[size_t(target)].stableID, idManager); + AddTransitionIfNew(view, view.state.transitionFrom, view.graph.nodes[size_t(target)].stableID, app.idManager); } view.state.transitionFrom = ID::Invalid(); return true; @@ -752,16 +793,16 @@ namespace tachyon case tachyon::EventType::MouseScroll: { // The wheel zooms or scrolls the view, as GetWheelMode says; a pinch zooms. - const WheelNavigation nav = NavigateByWheel(event.state, GetWheelMode(), 1.1f); + const WheelNavigation nav = NavigateByWheel(event.state, app.GetWheelMode(), 1.1f); if (!nav.Any()) return false; - this->guiStateManager.Interaction().SetFocusID(canvasID); + app.guiStateManager.Interaction().SetFocusID(canvasID); if (nav.zoom != 1.0f) { const int2 innerSize{ event.rect->innerRect.w, event.rect->innerRect.h }; ZoomNodeView(view, nav.zoom, event.state.screenPos - event.rect->innerRect.position - int2{ innerSize.x / 2, innerSize.y / 2 }); } - const float step = float(styleManager.Px(40)); // a notch scrolls this far + const float step = float(app.styleManager.Px(40)); // a notch scrolls this far if (nav.pan.x != 0.0f || nav.pan.y != 0.0f) view.state.transform = tachyon::float3x2::Translate(tachyon::float2{ -nav.pan.x * step, -nav.pan.y * step }) * view.state.transform; return true; @@ -790,26 +831,26 @@ namespace tachyon case tachyon::EventType::KeyDown: { // Escape during a marquee or a pan puts the selection or the view back. - if (view.state.transitionDrag.Cancel(event, guiStateManager) + if (view.state.transitionDrag.Cancel(event, app.guiStateManager) || (view.state.transitionPicking && IsDragCancelKey(event.state))) { view.state.transitionPicking = false; view.state.transitionFrom = ID::Invalid(); return true; } - if (view.state.marquee.Cancel(event, guiStateManager)) + if (view.state.marquee.Cancel(event, app.guiStateManager)) { view.state.selectedNodeIDs = view.state.marquee.before.nodes; view.state.selectedFrameIDs = view.state.marquee.before.frames; return true; } - if (view.state.pan.Cancel(event, guiStateManager, view.state.transform)) + if (view.state.pan.Cancel(event, app.guiStateManager, view.state.transform)) return true; // With the canvas focused, the keys do what the mouse does: Home frames the // selected nodes, or all of them; the arrows move the selected nodes a grid step (Shift: four), or pan // the view when none is selected; + and - zoom; Ctrl+A selects every node, // Escape none; Enter collapses or expands the selected ones. - if (guiStateManager.Interaction().GetFocusedID() != canvasID) + if (app.guiStateManager.Interaction().GetFocusedID() != canvasID) return false; const KeyCode key = event.state.lastKey; const bool shift = (event.state.modifiers & KeyModifier::Shift) != KeyModifier::None; @@ -861,7 +902,7 @@ namespace tachyon { if (!view.state.selectedNodeIDs.empty()) { - const int32_t grid = std::max(1, theme.nodeGridSize) * (shift ? 4 : 1); + const int32_t grid = std::max(1, styles.nodeGridSize) * (shift ? 4 : 1); NodeViewEdit edit; for (int i = 0; i < (int)view.graph.nodes.size(); ++i) if (view.state.selectedNodeIDs.count(view.graph.nodes[i].stableID)) @@ -870,7 +911,7 @@ namespace tachyon } else { - const float pan = float(styleManager.Px(shift ? 200 : 40)); + const float pan = float(app.styleManager.Px(shift ? 200 : 40)); view.state.transform = tachyon::float3x2::Translate(tachyon::float2{ -float(dir.x) * pan, -float(dir.y) * pan }) * view.state.transform; } return true; @@ -928,19 +969,19 @@ namespace tachyon return false; }, .textID = TextID::Invalid, - .styleRef = theme.nodeViewStyleRef, + .styleRef = styles.nodeViewStyleRef, .state = ElementState::None }; - auto canvasRes = elementStorage.Add(std::move(canvas), LayoutOverride{}.Auto()); + auto canvasRes = app.elementStorage.Add(std::move(canvas), LayoutOverride{}.Auto()); VERIFY(canvasRes.status); const tachyon::float3x2 effective = tachyon::float3x2::Translate(tachyon::float2{ (float)(view.state.lastInnerSize.x / 2), (float)(view.state.lastInnerSize.y / 2) }) * view.state.transform; - elementStorage.SetContentTransform(canvasRes.ref, effective); - VERIFY(windowRegistry.Add(canvasRes.ref)); - VERIFY(elementStorage.BeginChildren()); + app.elementStorage.SetContentTransform(canvasRes.ref, effective); + VERIFY(app.windowRegistry.Add(canvasRes.ref)); + VERIFY(app.elementStorage.BeginChildren()); const int nodeCount = (int)view.graph.nodes.size(); @@ -958,10 +999,10 @@ namespace tachyon // and a color being picked changes one in place rather than adding a style a frame. constexpr uint32_t kPaletteSize = 4096; // Under the canvas: each node view has its own. - const bool pushedPalette = idManager.PushParent(canvasID); - const ID paletteID = idManager.AllocateRangedID(kPaletteSize, "node-view-palette"); + const bool pushedPalette = app.idManager.PushParent(canvasID); + const ID paletteID = app.idManager.AllocateRangedID(kPaletteSize, "node-view-palette"); if (pushedPalette) - (void)idManager.PopParent(); + (void)app.idManager.PopParent(); view.state.wireColorStyles.clear(); auto appColor = [&](tachyon::color4f c) -> tachyon::VisualColorStyleIndex { @@ -970,8 +1011,8 @@ namespace tachyon return it->second; const uint32_t slot = uint32_t(view.state.wireColorStyles.size()); const tachyon::VisualColorStyleIndex style = slot < kPaletteSize - ? AppColorStyle(idManager.GetSubID(paletteID, slot), c) - : styleManager.RegisterColorStyle(tachyon::ColorStyle::Create(c)); // past the palette: rare + ? app.AppColorStyle(app.idManager.GetSubID(paletteID, slot), c) + : app.styleManager.RegisterColorStyle(tachyon::ColorStyle::Create(c)); // past the palette: rare view.state.wireColorStyles.emplace(key, style); return style; }; @@ -980,7 +1021,7 @@ namespace tachyon (void)appColor(cprop.socketColor); // Socket box size, from the .node-socket CSS width; dot and border insets derive from it. - const int kSocketSize = theme.socketSize; + const int kSocketSize = styles.socketSize; // This frame's socket refs for the wire pass. Index: [nodeIdx][propIdx * 2 + isOutput] NodeLists& socketRefs = view.state.socketRefs; @@ -1003,7 +1044,7 @@ namespace tachyon drivenOutputs.push_back(WireKey(cprop.input->nodeIdx, cprop.input->propIdx)); std::sort(drivenOutputs.begin(), drivenOutputs.end()); // The node's color behind a pin, looked up once for every socket. - const tachyon::color4f pinBackground = theme.GetColor("--bg-raised"); + const tachyon::color4f pinBackground = app.theme.GetColor("--bg-raised"); // -------- Helper: emit one socket Element (circle + drag/drop handler) -------- // `pinShown` false: the pin shows only while it's hovered or a drop target (a reroute's @@ -1011,14 +1052,14 @@ namespace tachyon auto emitSocket = [&](int n, int propIdx, bool isOutput, bool readonly, LayoutOverride&& layout, bool pinShown = true) -> ElementRef { - ID sockID = idManager.AllocateDynamicID("node-sock"); + ID sockID = app.idManager.AllocateDynamicID("node-sock"); PropertyEndpoint self { n, propIdx }; Element sockElem { .id = sockID, - .eventHandler = [this, view, self, isOutput, readonly, sockID](ElementEvent&& event)->bool + .eventHandler = [&app, view, self, isOutput, readonly, sockID](ElementEvent&& event)->bool { if (readonly) return false; @@ -1031,8 +1072,8 @@ namespace tachyon if (!event.state.LeftPressed() || PanDragButton(event.state) != MouseButtons::None) return false; // Arm the drag; pendingConnection activates only once it passes the threshold. view.state.pendingConnection = {}; - view.state.pendingConnection.press.Press(event, elementStorage, guiStateManager, {}, { .focus = false, .capture = false }); - guiStateManager.Drag().Begin( + view.state.pendingConnection.press.Press(event, app.elementStorage, app.guiStateManager, {}, { .focus = false, .capture = false }); + app.guiStateManager.Drag().Begin( sockID, kSocketPayload, EncodeEndpoint(self), event.state.screenPos, std::any(), DragVisualizer{}); @@ -1041,9 +1082,9 @@ namespace tachyon case EventType::MouseMove: { if ((event.state.buttons & MouseButtons::Left) == MouseButtons::None) break; - guiStateManager.Drag().UpdateFromInput(event.state); + app.guiStateManager.Drag().UpdateFromInput(event.state); // Post-threshold: the pending wire is real and tracks the cursor. - if (guiStateManager.Drag().GetDraggedID() == sockID) + if (app.guiStateManager.Drag().GetDraggedID() == sockID) { view.state.pendingConnection.press.Move(event, 0); view.state.pendingConnection.source = self; @@ -1091,8 +1132,8 @@ namespace tachyon auto& prop = view.graph.nodes[self.nodeIdx].properties[self.propIdx]; const bool wired = prop.input.has_value() && prop.input->valid(); view.state.pendingConnection = {}; - view.state.pendingConnection.press.Press(event, elementStorage, guiStateManager, {}, { .focus = false, .capture = false }); - guiStateManager.Drag().Begin( + view.state.pendingConnection.press.Press(event, app.elementStorage, app.guiStateManager, {}, { .focus = false, .capture = false }); + app.guiStateManager.Drag().Begin( sockID, wired ? kSocketPayload : kInputSocketPayload, EncodeEndpoint(wired ? *prop.input : self), event.state.screenPos, std::any(), DragVisualizer{}); return true; @@ -1100,8 +1141,8 @@ namespace tachyon case EventType::MouseMove: { if ((event.state.buttons & MouseButtons::Left) == MouseButtons::None) break; - guiStateManager.Drag().UpdateFromInput(event.state); - if (guiStateManager.Drag().GetDraggedID() != sockID) return false; + app.guiStateManager.Drag().UpdateFromInput(event.state); + if (app.guiStateManager.Drag().GetDraggedID() != sockID) return false; // First post-threshold move: a wired input is detached from its // source and the loose end handed to the dragged wire, which // starts at the source output and follows the cursor. An unwired @@ -1151,12 +1192,12 @@ namespace tachyon return false; } }, - .styleRef = theme.nodeSocketStyleRef, - .state = guiStateManager.GetCurrentState(sockID) + .styleRef = styles.nodeSocketStyleRef, + .state = app.guiStateManager.GetCurrentState(sockID) }; - auto res = elementStorage.Add(std::move(sockElem), std::move(layout)); + auto res = app.elementStorage.Add(std::move(sockElem), std::move(layout)); VERIFY(res.status); - VERIFY(windowRegistry.Add(res.ref)); + VERIFY(app.windowRegistry.Add(res.ref)); // Highlight rules: // - OUTPUT: on hover, and while a wire dragged from an input hovers it and may @@ -1164,11 +1205,11 @@ namespace tachyon // - INPUT, mid-drag: while the drag hovers it and the connection is allowed. // - INPUT, at rest: on hover when it has a connection to drag out. const tachyon::color4f dotColor = view.graph.nodes[n].properties[propIdx].socketColor; - const bool hovered = (guiStateManager.GetCurrentState(sockID) & ElementState::Hover) != ElementState::None; + const bool hovered = (app.guiStateManager.GetCurrentState(sockID) & ElementState::Hover) != ElementState::None; bool highlight; if (isOutput) { - const bool dropTarget = guiStateManager.Drag().IsDropTargetFor(sockID, kInputSocketPayload) && + const bool dropTarget = app.guiStateManager.Drag().IsDropTargetFor(sockID, kInputSocketPayload) && ConnectionAllowed(view, self, view.state.pendingConnection.source); if (dropTarget) view.state.pendingConnection.target = self; @@ -1178,7 +1219,7 @@ namespace tachyon { const auto& p = view.graph.nodes[n].properties[propIdx]; const bool connected = p.input.has_value() && p.input->valid(); - const bool dropTarget = guiStateManager.Drag().IsDropTargetFor(sockID, kSocketPayload) && + const bool dropTarget = app.guiStateManager.Drag().IsDropTargetFor(sockID, kSocketPayload) && ConnectionAllowed(view, view.state.pendingConnection.source, self); if (dropTarget) view.state.pendingConnection.target = self; @@ -1194,11 +1235,11 @@ namespace tachyon { // The radii worked out here: the callback holds only what it draws, small // enough for std::function to keep without an allocation for every socket. - const float ring = styleManager.Px(2.0f); - const float pin = (highlight ? styleManager.Px(1.0f) : 0.0f) + (float)kSocketSize - styleManager.Px(2.0f); - const float back = highlight ? pin + styleManager.Px(6.0f) : pin + 2.0f * ring; // the halo, or the outline + const float ring = app.styleManager.Px(2.0f); + const float pin = (highlight ? app.styleManager.Px(1.0f) : 0.0f) + (float)kSocketSize - app.styleManager.Px(2.0f); + const float back = highlight ? pin + app.styleManager.Px(6.0f) : pin + 2.0f * ring; // the halo, or the outline const float hole = connected ? 0.0f : pin - 2.0f * ring; - VERIFY(elementStorage.AddCustomDraw(res.ref, + VERIFY(app.elementStorage.AddCustomDraw(res.ref, [dotColor, nodeColor = pinBackground, pin, back, hole, highlight](tachyon::CustomDrawContext& ctx) { const auto inner = ctx.ElementInnerRect(); @@ -1213,7 +1254,7 @@ namespace tachyon })); } - ShowPinTooltip(view.graph, sockID, self, isOutput); + ShowPinTooltip(app, view.graph, sockID, self, isOutput); return res.ref; }; @@ -1228,7 +1269,7 @@ namespace tachyon int32_t nodeBottomChromeV = 0; // .node left chrome: where its rows start, which a stand-in's sockets are placed from. int32_t nodeLeftChrome = 0; - if (const tachyon::LayoutStyle* nodeLS = styleManager.GetLayoutStyle(theme.nodeStyleRef.layoutStyleIndex)) + if (const tachyon::LayoutStyle* nodeLS = app.styleManager.GetLayoutStyle(styles.nodeStyleRef.layoutStyleIndex)) { nodeLeftChrome = nodeLS->borderWidths.left + nodeLS->padding.left; nodeTopChromeV = nodeLS->borderWidths.top + nodeLS->padding.top; @@ -1238,20 +1279,20 @@ namespace tachyon } // A state's border (.node-state), top and bottom alike: its header fills the rest. int32_t nodeBorderV = 0; - if (const tachyon::LayoutStyle* stateLS = styleManager.GetLayoutStyle(theme.nodeStateStyleRef.layoutStyleIndex)) + if (const tachyon::LayoutStyle* stateLS = app.styleManager.GetLayoutStyle(styles.nodeStateStyleRef.layoutStyleIndex)) nodeBorderV = stateLS->borderWidths.top; // A state's edge in its own color: the border and corners its style has. - BoxEdges stateEdgeWidths = BoxEdges(uint16_t(std::max(1, styleManager.Px(1)))); + BoxEdges stateEdgeWidths = BoxEdges(uint16_t(std::max(1, app.styleManager.Px(1)))); BoxCorners stateEdgeRadius {}; - if (const VisualBoxStyle* stateBox = styleManager.GetVisualBoxStyle(theme.nodeStateStyleRef.visualBoxStyleIndex, ElementState::None)) + if (const VisualBoxStyle* stateBox = app.styleManager.GetVisualBoxStyle(styles.nodeStateStyleRef.visualBoxStyleIndex, ElementState::None)) { stateEdgeWidths = stateBox->borderWidths; stateEdgeRadius = stateBox->borderRadius; } // A node's own color over its body (--node-bg), `amount` of the way: opaque, as the // body is under it. A node without a color of its own has the accent. - const tachyon::color4f nodeBody = theme.GetColor("--node-bg", tachyon::color4f{ 0.12f, 0.14f, 0.16f, 1.0f }); - const tachyon::color4f accentColor = theme.GetColor("--accent", tachyon::color4f{ 0.42f, 0.61f, 1.0f, 1.0f }); + const tachyon::color4f nodeBody = app.theme.GetColor("--node-bg", tachyon::color4f{ 0.12f, 0.14f, 0.16f, 1.0f }); + const tachyon::color4f accentColor = app.theme.GetColor("--accent", tachyon::color4f{ 0.42f, 0.61f, 1.0f, 1.0f }); auto OverNodeBody = [&nodeBody](tachyon::color4f color, float amount) { auto mix = [amount](float a, float b) { return a + (b - a) * amount; }; return tachyon::color4f{ mix(nodeBody.r, color.r), mix(nodeBody.g, color.g), mix(nodeBody.b, color.b), 1.0f }; @@ -1263,22 +1304,22 @@ namespace tachyon // the canvas, where Enter would otherwise collapse a frame and Escape clear the selection. auto renameField = [&](const char* name, StyleRef style, IntRect rect, bool& keep) -> bool { - const ID fieldID = idManager.AllocateDynamicID(name); - const ID focused = guiStateManager.Interaction().GetFocusedID(); + const ID fieldID = app.idManager.AllocateDynamicID(name); + const ID focused = app.guiStateManager.Interaction().GetFocusedID(); keep = view.state.renameFocused && focused != fieldID; bool cancel = false; - if (inputManager && view.state.renameFocused && focused == fieldID) + if (app.inputManager && view.state.renameFocused && focused == fieldID) { - const auto& events = inputManager->GetRecordedEvents(); + const auto& events = app.inputManager->GetRecordedEvents(); for (size_t e = 0; e < events.size(); ++e) { if (events[e].type != EventType::KeyDown || events[e].consumed) continue; switch (events[e].state.lastKey) { case KeyCode::Return: case KeyCode::Return2: case KeyCode::KeyPadEnter: - keep = true; inputManager->ConsumeEvent(e); break; + keep = true; app.inputManager->ConsumeEvent(e); break; case KeyCode::Escape: - cancel = true; inputManager->ConsumeEvent(e); break; + cancel = true; app.inputManager->ConsumeEvent(e); break; default: break; } } @@ -1287,7 +1328,7 @@ namespace tachyon { keep = keep && !cancel; if (focused == fieldID) - guiStateManager.Interaction().SetFocusID(canvasID); + app.guiStateManager.Interaction().SetFocusID(canvasID); return true; } if (!view.state.renameFocused) @@ -1295,10 +1336,10 @@ namespace tachyon // Without scrolling to it: it opens where it was asked for, and the canvas's // scroll would move the nodes away from what the canvas draws itself (wires, // arrows), which its pan and zoom place instead. - guiStateManager.Interaction().SetFocusIDNoScroll(fieldID); + app.guiStateManager.Interaction().SetFocusIDNoScroll(fieldID); view.state.renameFocused = true; } - Field(fieldID, view.state.renameText, TextEditBehavior::ContinuousUpdate, style, + app.Field(fieldID, view.state.renameText, TextEditBehavior::ContinuousUpdate, style, LayoutOverride{}.FixedSize(Pixels{ rect.w }, Pixels{ rect.h }).Absolute(rect.x, rect.y)); return false; }; @@ -1312,26 +1353,26 @@ namespace tachyon { char time[32]; std::snprintf(time, sizeof(time), "%.2f s", double(view.graph.activeStateTime)); - stateMarks.timeText = textSystem->RegisterText(idManager.AllocateDynamicID("state-time"), time, theme.nodeStateTimeStyleRef, ElementState::None); - const TextMeasurement m = textSystem->MeasureText(stateMarks.timeText, TextWrapContext{}); + stateMarks.timeText = app.textSystem->RegisterText(app.idManager.AllocateDynamicID("state-time"), time, styles.nodeStateTimeStyleRef, ElementState::None); + const TextMeasurement m = app.textSystem->MeasureText(stateMarks.timeText, TextWrapContext{}); stateMarks.timeSize = { m.maxWidth, m.maxHeight }; } if (stateMachine) { - tachyon::color4f halo = theme.GetColor("--ok", tachyon::color4f{ 0.31f, 0.77f, 0.54f, 1.0f }); + tachyon::color4f halo = app.theme.GetColor("--ok", tachyon::color4f{ 0.31f, 0.77f, 0.54f, 1.0f }); halo.a *= 0.18f; - stateMarks.activeHalo = styleManager.RegisterColorStyle(tachyon::ColorStyle::Create(halo)); - stateMarks.canvas = styleManager.RegisterColorStyle(tachyon::ColorStyle::Create( - theme.GetColor("--bg-canvas", tachyon::color4f{ 0.05f, 0.06f, 0.07f, 1.0f }))); + stateMarks.activeHalo = app.styleManager.RegisterColorStyle(tachyon::ColorStyle::Create(halo)); + stateMarks.canvas = app.styleManager.RegisterColorStyle(tachyon::ColorStyle::Create( + app.theme.GetColor("--bg-canvas", tachyon::color4f{ 0.05f, 0.06f, 0.07f, 1.0f }))); } - const int2 labelPad{ styleManager.Px(6), styleManager.Px(1) }; // the chip round a label's text - const int32_t labelMargin = styleManager.Px(4); // between a label and its arrow + const int2 labelPad{ app.styleManager.Px(6), app.styleManager.Px(1) }; // the chip round a label's text + const int32_t labelMargin = app.styleManager.Px(4); // between a label and its arrow view.state.transitionLabelBoxes.clear(); if (stateMachine) { // The transition under the pointer last frame, its arrow or its label. const std::optional hoveredTransition = - view.state.hoveredTransition.Shown(guiStateManager.Interaction().GetHoveredID() == canvasID); + view.state.hoveredTransition.Shown(app.guiStateManager.Interaction().GetHoveredID() == canvasID); for (const StateTransition& t : view.graph.transitions) { if (t.label.empty() || view.state.renamingTransition == t.stableID) @@ -1339,12 +1380,12 @@ namespace tachyon ElementState labelState = ElementState::None; if (hoveredTransition == t.stableID) labelState |= ElementState::Hover; if (view.state.selectedTransitionIDs.contains(t.stableID)) labelState |= ElementState::Selected; - [[maybe_unused]] const bool pushedLabel = idManager.PushParent(IDManager::ScopedID(canvasID, t.stableID)); - const ID labelID = idManager.AllocateDynamicID("transition-label"); + [[maybe_unused]] const bool pushedLabel = app.idManager.PushParent(IDManager::ScopedID(canvasID, t.stableID)); + const ID labelID = app.idManager.AllocateDynamicID("transition-label"); if (pushedLabel) - (void)idManager.PopParent(); - const TextID text = textSystem->RegisterText(labelID, t.label, theme.nodeTransitionLabelStyleRef, labelState); - const TextMeasurement m = textSystem->MeasureText(text, TextWrapContext{}); + (void)app.idManager.PopParent(); + const TextID text = app.textSystem->RegisterText(labelID, t.label, styles.nodeTransitionLabelStyleRef, labelState); + const TextMeasurement m = app.textSystem->MeasureText(text, TextWrapContext{}); const TransitionPath path = StateTransitionPath(view, t, transitionGap, transitionLoop); if (!path.valid) continue; @@ -1361,14 +1402,14 @@ namespace tachyon const TransitionPath path = StateTransitionPath(view, transition, transitionGap, transitionLoop); // Exactly where the label is: its chip round the text as typed so far (an // empty one a few characters wide), growing as it's typed. - const TextID measured = textSystem->RegisterText(idManager.AllocateDynamicID("transition-rename-measure"), + const TextID measured = app.textSystem->RegisterText(app.idManager.AllocateDynamicID("transition-rename-measure"), view.state.renameText.empty() ? std::string(" ") : view.state.renameText, - theme.nodeTransitionLabelStyleRef, ElementState::None); - const TextMeasurement m = textSystem->MeasureText(measured, TextWrapContext{}); + styles.nodeTransitionLabelStyleRef, ElementState::None); + const TextMeasurement m = app.textSystem->MeasureText(measured, TextWrapContext{}); const int2 size{ m.maxWidth + 2 * labelPad.x, m.maxHeight + 2 * labelPad.y }; const int2 centre = TransitionLabelCentre(path, size, labelMargin); bool keep = false; - if (renameField("transition-rename", theme.nodeTransitionRenameStyleRef, + if (renameField("transition-rename", styles.nodeTransitionRenameStyleRef, IntRect{ centre.x - size.x / 2, centre.y - size.y / 2, size.x, size.y }, keep)) { if (keep && view.state.renameText != transition.label) @@ -1388,22 +1429,22 @@ namespace tachyon // drag moves the frame and what's inside it, a double-click renames it) and the right // and bottom edges and the corner between (a drag resizes it). The rest of the box // takes no input, so a marquee or a pan starts inside it as anywhere on the canvas. - view.state.gridSize = theme.nodeGridSize; - const int32_t frameGrid = std::max(1, theme.nodeGridSize); + view.state.gridSize = styles.nodeGridSize; + const int32_t frameGrid = std::max(1, styles.nodeGridSize); const int32_t frameBar = 2 * frameGrid; // the title bar: one row pitch, as a node's header struct DrawnFrame { ElementRef title; int2 size; ElementState state; tachyon::VisualColorStyleIndex fill, band; VisualBoxStyleIndex edge; }; // A frame's edge while nothing lights it: its color, or the theme's for one without. BoxCorners frameRadius {}; - if (const VisualBoxStyle* frameBox = styleManager.GetVisualBoxStyle(theme.nodeFrameStyleRef.visualBoxStyleIndex, ElementState::None)) + if (const VisualBoxStyle* frameBox = app.styleManager.GetVisualBoxStyle(styles.nodeFrameStyleRef.visualBoxStyleIndex, ElementState::None)) frameRadius = frameBox->borderRadius; - const BoxEdges frameEdgeWidths = BoxEdges(uint16_t(std::max(1, styleManager.Px(1)))); + const BoxEdges frameEdgeWidths = BoxEdges(uint16_t(std::max(1, app.styleManager.Px(1)))); // An edge's color is a palette slot, so its outline is one box style per slot. auto frameEdge = [&](tachyon::color4f c) { const tachyon::color4f clamped{ std::clamp(c.r, 0.0f, 1.0f), std::clamp(c.g, 0.0f, 1.0f), std::clamp(c.b, 0.0f, 1.0f), std::clamp(c.a, 0.0f, 1.0f) }; - return styleManager.RegisterOutline(frameEdgeWidths, frameRadius, appColor(clamped)); + return app.styleManager.RegisterOutline(frameEdgeWidths, frameRadius, appColor(clamped)); }; - const VisualBoxStyleIndex neutralFrameEdge = frameEdge(theme.GetColor("--frame-border", tachyon::color4f{ 0.56f, 0.59f, 0.65f, 0.28f })); + const VisualBoxStyleIndex neutralFrameEdge = frameEdge(app.theme.GetColor("--frame-border", tachyon::color4f{ 0.56f, 0.59f, 0.65f, 0.28f })); std::vector drawnFrames; // Nodes inside a collapsed frame: which frame (-1: none), and, for those with wires // crossing its edge, the box and their sockets on it (property, output, row). @@ -1430,8 +1471,8 @@ namespace tachyon view.state.renamingFrame.reset(); const int32_t minWidth = 6 * frameGrid, minHeight = 2 * frameBar; - const int32_t grip = styleManager.Px(6); - const bool snap = theme.nodeGridSize > 0 && view.graph.snapToGrid; + const int32_t grip = app.styleManager.Px(6); + const bool snap = styles.nodeGridSize > 0 && view.graph.snapToGrid; const int frameCount = (int)view.graph.frames.size(); for (NodeFrame& frame : view.graph.frames) { @@ -1574,27 +1615,27 @@ namespace tachyon } const ID frameID = frame.stableID; - [[maybe_unused]] const bool pushed = idManager.PushParent(IDManager::ScopedID(canvasID, frameID)); - const ID titleID = idManager.AllocateDynamicID("frame-title"); - const ID gripIDs[3] = { idManager.AllocateDynamicID("frame-right"), idManager.AllocateDynamicID("frame-bottom"), - idManager.AllocateDynamicID("frame-corner") }; + [[maybe_unused]] const bool pushed = app.idManager.PushParent(IDManager::ScopedID(canvasID, frameID)); + const ID titleID = app.idManager.AllocateDynamicID("frame-title"); + const ID gripIDs[3] = { app.idManager.AllocateDynamicID("frame-right"), app.idManager.AllocateDynamicID("frame-bottom"), + app.idManager.AllocateDynamicID("frame-corner") }; // The box shows the title's and the grips' hover, and its selection. - ElementState state = guiStateManager.GetCurrentState(titleID) & (ElementState::Hover | ElementState::Active); + ElementState state = app.guiStateManager.GetCurrentState(titleID) & (ElementState::Hover | ElementState::Active); for (const ID g : gripIDs) - state |= guiStateManager.GetCurrentState(g) & ElementState::Hover; + state |= app.guiStateManager.GetCurrentState(g) & ElementState::Hover; if (view.state.selectedFrameIDs.contains(frameID)) state |= ElementState::Selected; // A press on the title or a grip: what it moves, as it is now. - auto press = [this, view, frameID, frameIndex](const ElementEvent& event, FrameEdges edges) + auto press = [&app, view, frameID, frameIndex](const ElementEvent& event, FrameEdges edges) { const int index = frameIndex(frameID); if (index < 0) return; FrameDrag& drag = view.state.frameDrag; drag = FrameDrag{ .frameID = frameID, .edges = edges }; // The canvas has the focus already; the moves, release and Escape come here. - drag.press.Press(event, elementStorage, guiStateManager, {}, { .atOnce = edges != FrameEdges::None, .focus = false }); + drag.press.Press(event, app.elementStorage, app.guiStateManager, {}, { .atOnce = edges != FrameEdges::None, .focus = false }); drag.frames.push_back({ index, view.graph.frames[size_t(index)] }); if (edges == FrameEdges::None) { @@ -1645,21 +1686,21 @@ namespace tachyon // row per port, the input's name at the left, the output's at the right. if (frame.collapsed) { - const ID boxID = idManager.AllocateDynamicID("frame-box"); - auto boxRes = elementStorage.Add(Element{ .id = boxID, .styleRef = theme.nodeStyleRef, .flags = ElementFlags::NoInput, .state = state }, + const ID boxID = app.idManager.AllocateDynamicID("frame-box"); + auto boxRes = app.elementStorage.Add(Element{ .id = boxID, .styleRef = styles.nodeStyleRef, .flags = ElementFlags::NoInput, .state = state }, LayoutOverride{}.FixedSize(Pixels{ box.w }, Pixels{ box.h }).Absolute(box.x, box.y)); VERIFY(boxRes.status); - VERIFY(windowRegistry.Add(boxRes.ref)); - VERIFY(elementStorage.BeginChildren()); + VERIFY(app.windowRegistry.Add(boxRes.ref)); + VERIFY(app.elementStorage.BeginChildren()); tachyon::VisualColorStyleIndex tint{}; if (frame.color.a > 0.0f) tint = appColor(tachyon::color4f{ frame.color.r, frame.color.g, frame.color.b, frame.color.a * 0.32f }); - auto headerRes = elementStorage.Add(Element{ .id = idManager.AllocateDynamicID("frame-box-header"), - .styleRef = theme.nodeHeaderStyleRef, .flags = ElementFlags::NoInput, + auto headerRes = app.elementStorage.Add(Element{ .id = app.idManager.AllocateDynamicID("frame-box-header"), + .styleRef = styles.nodeHeaderStyleRef, .flags = ElementFlags::NoInput, .state = state, .colorStyleIndex = tint }, LayoutOverride{}.Height(Pixels{ std::max(1, frameBar - nodeTopChromeV) })); VERIFY(headerRes.status); - VERIFY(windowRegistry.Add(headerRes.ref)); + VERIFY(app.windowRegistry.Add(headerRes.ref)); // A port's name: its node's title, and its pin's name when it has one. Built // in the view's string, which Text has copied by the next one. auto portName = [view](const std::vector& ports, int r) -> std::string_view { @@ -1677,24 +1718,24 @@ namespace tachyon }; for (int r = 0; r < rows; ++r) { - const ID rowID = idManager.AllocateDynamicID("frame-port-row"); - auto rowRes = elementStorage.Add(Element{ .id = rowID, .styleRef = theme.nodeFramePortsStyleRef, .flags = ElementFlags::NoInput }, + const ID rowID = app.idManager.AllocateDynamicID("frame-port-row"); + auto rowRes = app.elementStorage.Add(Element{ .id = rowID, .styleRef = styles.nodeFramePortsStyleRef, .flags = ElementFlags::NoInput }, LayoutOverride{}.Height(Pixels{ frameBar })); VERIFY(rowRes.status); - VERIFY(windowRegistry.Add(rowRes.ref)); - VERIFY(elementStorage.BeginChildren()); - Text(idManager.AllocateDynamicID("frame-port-in"), portName(portsIn[size_t(f)], r), theme.nodeFramePortStyleRef, LayoutOverride{}.FlexGrow(1)); - Text(idManager.AllocateDynamicID("frame-port-out"), portName(portsOut[size_t(f)], r), theme.nodeFramePortOutStyleRef, LayoutOverride{}.FlexGrow(1)); - VERIFY(elementStorage.EndChildren()); + VERIFY(app.windowRegistry.Add(rowRes.ref)); + VERIFY(app.elementStorage.BeginChildren()); + app.Text(app.idManager.AllocateDynamicID("frame-port-in"), portName(portsIn[size_t(f)], r), styles.nodeFramePortStyleRef, LayoutOverride{}.FlexGrow(1)); + app.Text(app.idManager.AllocateDynamicID("frame-port-out"), portName(portsOut[size_t(f)], r), styles.nodeFramePortOutStyleRef, LayoutOverride{}.FlexGrow(1)); + VERIFY(app.elementStorage.EndChildren()); } - VERIFY(elementStorage.EndChildren()); + VERIFY(app.elementStorage.EndChildren()); } Element title { .id = titleID, - .eventHandler = [this, view, canvasID, frameID, titleID, frameIndex, press, restore, finish, - frameGrid, snap, chevron = styleManager.Px(28)](ElementEvent&& event) -> bool + .eventHandler = [&app, view, canvasID, frameID, titleID, frameIndex, press, restore, finish, + frameGrid, snap, chevron = app.styleManager.Px(28)](ElementEvent&& event) -> bool { FrameDrag& drag = view.state.frameDrag; switch (event.type) @@ -1703,7 +1744,7 @@ namespace tachyon { // A right press is the canvas's: a pan, or this frame's menu. if (!event.state.LeftPressed() || PanDragButton(event.state) != MouseButtons::None) return false; - TakeFocus(guiStateManager, canvasID); + TakeFocus(app.guiStateManager, canvasID); const int index = frameIndex(frameID); if (index < 0) return false; // The chevron at the title's left collapses or expands it. @@ -1740,10 +1781,10 @@ namespace tachyon case EventType::MouseMove: { if (!drag.press.IsPressed(titleID) || drag.frames.empty()) return false; - if (!drag.press.Move(event, styleManager.Px(kDragStartDistance))) return true; + if (!drag.press.Move(event, app.styleManager.Px(kDragStartDistance))) return true; // Everything moves by the frame's own step, so what's inside keeps // its place in it, on the grid when the frame is. - const int2 raw = drag.press.drag.LocalDelta(event, elementStorage); + const int2 raw = drag.press.drag.LocalDelta(event, app.elementStorage); const int2 start = drag.frames[0].second.pos; const int2 to = snap ? int2{ SnapToGrid(start.x + raw.x, frameGrid), SnapToGrid(start.y + raw.y, frameGrid) } : int2{ start.x + raw.x, start.y + raw.y }; @@ -1766,7 +1807,7 @@ namespace tachyon return true; } case EventType::KeyDown: - if (!drag.press.Cancel(event, guiStateManager)) return false; + if (!drag.press.Cancel(event, app.guiStateManager)) return false; restore(); view.state.frameDrag = {}; return true; @@ -1774,46 +1815,46 @@ namespace tachyon } return false; }, - .styleRef = theme.nodeFrameTitleStyleRef, + .styleRef = styles.nodeFrameTitleStyleRef, .state = state, }; // The chevron before the title: down while expanded, right while collapsed. if (view.state.renamingFrame != frameID) - title.textID = textSystem->RegisterText(titleID, frame.collapsed ? theme.treeArrowRight : theme.treeArrowDown, - frame.title, theme.nodeFrameTitleStyleRef, state); - auto titleRes = elementStorage.Add(std::move(title), + title.textID = app.textSystem->RegisterText(titleID, frame.collapsed ? app.theme.treeArrowRight : app.theme.treeArrowDown, + frame.title, styles.nodeFrameTitleStyleRef, state); + auto titleRes = app.elementStorage.Add(std::move(title), LayoutOverride{}.FixedSize(Pixels{ box.w }, Pixels{ frameBar }).Absolute(frame.pos.x, frame.pos.y)); VERIFY(titleRes.status); - VERIFY(windowRegistry.Add(titleRes.ref)); + VERIFY(app.windowRegistry.Add(titleRes.ref)); // With a menu for frames, a "..." button at the title bar's end opens it under the // button, the frame selected as a right click does. if (view.state.onFrameContextMenu && view.state.renamingFrame != frameID) { - const int32_t size = std::min(styleManager.Px(18), frameBar); + const int32_t size = std::min(app.styleManager.Px(18), frameBar); const int32_t pad = (frameBar - size) / 2; if (box.w > 2 * size) { - const ID menuButtonID = idManager.AllocateDynamicID("frame-menu-button"); - Button(menuButtonID, "...", [this, view, frameID, menuButtonID, frameMenuID, openMenu] { + const ID menuButtonID = app.idManager.AllocateDynamicID("frame-menu-button"); + app.Button(menuButtonID, "...", [&app, view, frameID, menuButtonID, frameMenuID, openMenu] { if (!view.state.selectedFrameIDs.contains(frameID)) { view.state.selectedNodeIDs.clear(); view.state.selectedFrameIDs = { frameID }; } - const IntRect at = elementStorage.ElementRectOnScreen(elementStorage.FindElementRefByID(menuButtonID)); + const IntRect at = app.elementStorage.ElementRectOnScreen(app.elementStorage.FindElementRefByID(menuButtonID)); openMenu(frameMenuID, int2{ at.x, at.y + at.h }, std::nullopt, std::nullopt, std::nullopt, frameID); - }, theme.nodeFrameMenuStyleRef, + }, styles.nodeFrameMenuStyleRef, LayoutOverride{}.FixedSize(Pixels{ size }, Pixels{ size }) .Absolute(frame.pos.x + box.w - pad - size, frame.pos.y + pad)); - SetTooltip("Frame menu"); + app.SetTooltip("Frame menu"); } } if (view.state.renamingFrame == frameID) { bool keep = false; - if (renameField("frame-rename", theme.nodeFrameRenameStyleRef, IntRect{ frame.pos.x, frame.pos.y, box.w, frameBar }, keep)) + if (renameField("frame-rename", styles.nodeFrameRenameStyleRef, IntRect{ frame.pos.x, frame.pos.y, box.w, frameBar }, keep)) { if (keep && view.state.renameText != frame.title) { @@ -1842,7 +1883,7 @@ namespace tachyon Element gripElement { .id = gripID, - .eventHandler = [this, view, canvasID, gripID, edges, press, restore, finish, + .eventHandler = [&app, view, canvasID, gripID, edges, press, restore, finish, frameGrid, snap, minWidth, minHeight](ElementEvent&& event) -> bool { FrameDrag& drag = view.state.frameDrag; @@ -1850,13 +1891,13 @@ namespace tachyon { case EventType::MouseDown: if (!event.state.LeftPressed() || PanDragButton(event.state) != MouseButtons::None) return false; - TakeFocus(guiStateManager, canvasID); + TakeFocus(app.guiStateManager, canvasID); press(event, edges); return true; case EventType::MouseMove: { if (!drag.press.IsPressed(gripID) || drag.frames.empty() || !drag.press.Move(event, 0)) return false; - const int2 d = drag.press.drag.LocalDelta(event, elementStorage); + const int2 d = drag.press.drag.LocalDelta(event, app.elementStorage); const NodeFrame& start = drag.frames[0].second; int2 size = start.size; if ((uint8_t(edges) & uint8_t(FrameEdges::Right)) != 0) size.x += d.x; @@ -1874,7 +1915,7 @@ namespace tachyon finish(); return true; case EventType::KeyDown: - if (!drag.press.Cancel(event, guiStateManager)) return false; + if (!drag.press.Cancel(event, app.guiStateManager)) return false; restore(); view.state.frameDrag = {}; return true; @@ -1882,18 +1923,18 @@ namespace tachyon } return false; }, - .styleRef = theme.emptyHorzStyleRef, - .state = guiStateManager.GetCurrentState(gripID), + .styleRef = app.theme.emptyHorzStyleRef, + .state = app.guiStateManager.GetCurrentState(gripID), }; - auto gripRes = elementStorage.Add(std::move(gripElement), LayoutOverride{}.FixedSize(Pixels{ r.w }, Pixels{ r.h }).Absolute(r.x, r.y)); + auto gripRes = app.elementStorage.Add(std::move(gripElement), LayoutOverride{}.FixedSize(Pixels{ r.w }, Pixels{ r.h }).Absolute(r.x, r.y)); VERIFY(gripRes.status); - VERIFY(windowRegistry.Add(gripRes.ref)); + VERIFY(app.windowRegistry.Add(gripRes.ref)); // The resize cursor while hovered or dragged. - if ((guiStateManager.GetCurrentState(gripID) & ElementState::Hover) != ElementState::None || view.state.frameDrag.press.IsPressed(gripID)) - guiStateManager.Cursor().Request(gripCursors[g]); + if ((app.guiStateManager.GetCurrentState(gripID) & ElementState::Hover) != ElementState::None || view.state.frameDrag.press.IsPressed(gripID)) + app.guiStateManager.Cursor().Request(gripCursors[g]); } if (pushed) - (void)idManager.PopParent(); + (void)app.idManager.PopParent(); // Its tint, when it has one: faint over the box, stronger over the title bar. // Collapsed, its box is an element of its own, over the wires as a node is. @@ -1904,9 +1945,9 @@ namespace tachyon if (frame.color.a > 0.0f) { const tachyon::color4f c = frame.color; - fill = appColor(tachyon::color4f{ c.r, c.g, c.b, c.a * theme.nodeTints.frameFill }); - band = appColor(tachyon::color4f{ c.r, c.g, c.b, c.a * theme.nodeTints.frameBand }); - edge = frameEdge(tachyon::color4f{ c.r, c.g, c.b, c.a * theme.nodeTints.frameBorder }); + fill = appColor(tachyon::color4f{ c.r, c.g, c.b, c.a * styles.nodeTints.frameFill }); + band = appColor(tachyon::color4f{ c.r, c.g, c.b, c.a * styles.nodeTints.frameBand }); + edge = frameEdge(tachyon::color4f{ c.r, c.g, c.b, c.a * styles.nodeTints.frameBorder }); } drawnFrames.push_back({ titleRes.ref, frame.size, state, fill, band, edge }); } @@ -1929,10 +1970,10 @@ namespace tachyon // DnD, so the requested resize cursor sticks. { // One ranged ID over the handle cache, scoped to the canvas; handle = sub-ID at its slot. - [[maybe_unused]] bool pushedHandles = idManager.PushParent(canvasID); - const int kGrab = styleManager.Px(5); // grab-band half thickness (node.pos space) + [[maybe_unused]] bool pushedHandles = app.idManager.PushParent(canvasID); + const int kGrab = app.styleManager.Px(5); // grab-band half thickness (node.pos space) const ID handleRange = view.state.wireHandleCache.empty() ? ID::Invalid() - : idManager.AllocateRangedID((uint32_t)view.state.wireHandleCache.size(), "wire-handle"); + : app.idManager.AllocateRangedID((uint32_t)view.state.wireHandleCache.size(), "wire-handle"); for (size_t hi = 0; hi < view.state.wireHandleCache.size(); ++hi) { const CachedWireHandle& wh = view.state.wireHandleCache[hi]; @@ -1943,8 +1984,8 @@ namespace tachyon else { rx = xLo; ry = wh.a.y - kGrab; rw = xHi - xLo; rh = 2 * kGrab; } if (rw <= 0 || rh <= 0) continue; - const ID handleID = idManager.GetSubID(handleRange, (uint32_t)hi); - if ((guiStateManager.GetCurrentState(handleID) & ElementState::Hover) != ElementState::None) + const ID handleID = app.idManager.GetSubID(handleRange, (uint32_t)hi); + if ((app.guiStateManager.GetCurrentState(handleID) & ElementState::Hover) != ElementState::None) handleHoveredWire = wh.wireKey; const bool dragging = view.state.wireDrag.press.IsHeld() && @@ -1955,7 +1996,7 @@ namespace tachyon Element handle { .id = handleID, - .eventHandler = [this, view, canvasID, wireKey = wh.wireKey, + .eventHandler = [&app, view, canvasID, wireKey = wh.wireKey, role = wh.role, vertical = wh.vertical, startValue] (ElementEvent&& event) -> bool { @@ -1975,7 +2016,7 @@ namespace tachyon const auto lanes = view.graph.wireOverrides.find(wireKey); drag = WireSegmentDrag{ .wireKey = wireKey, .role = role, .vertical = vertical, .startValue = startValue }; // The canvas has the focus; Escape comes here with the capture. - drag.press.Press(event, elementStorage, guiStateManager, + drag.press.Press(event, app.elementStorage, app.guiStateManager, lanes != view.graph.wireOverrides.end() ? lanes->second : WireRouteOverrides{}, { .atOnce = true, .focusID = canvasID }); return true; @@ -1984,7 +2025,7 @@ namespace tachyon { if (!mine || !drag.press.Move(event, 0)) return false; // The handle is inside the canvas: its layout space is node.pos space. - const int2 d = drag.press.drag.LocalDelta(event, elementStorage); + const int2 d = drag.press.drag.LocalDelta(event, app.elementStorage); const int32_t newVal = drag.startValue + (vertical ? d.x : d.y); WireRouteOverrides& o = view.graph.wireOverrides[wireKey]; switch (role) @@ -2012,7 +2053,7 @@ namespace tachyon return true; } case EventType::KeyDown: - if (mine && drag.press.Cancel(event, guiStateManager)) + if (mine && drag.press.Cancel(event, app.guiStateManager)) { restoreLanes(); drag = {}; @@ -2023,21 +2064,21 @@ namespace tachyon } return false; }, - .styleRef = theme.emptyHorzStyleRef, - .state = guiStateManager.GetCurrentState(handleID) + .styleRef = app.theme.emptyHorzStyleRef, + .state = app.guiStateManager.GetCurrentState(handleID) }; - auto hres = elementStorage.Add(std::move(handle), + auto hres = app.elementStorage.Add(std::move(handle), LayoutOverride{}.FixedSize(Pixels{ rw }, Pixels{ rh }).Absolute(rx, ry)); VERIFY(hres.status); - VERIFY(windowRegistry.Add(hres.ref)); + VERIFY(app.windowRegistry.Add(hres.ref)); // Resize cursor while hovered or dragged (style cursor is Default, so it isn't overridden). - const ElementState hstate = guiStateManager.GetCurrentState(handleID); + const ElementState hstate = app.guiStateManager.GetCurrentState(handleID); if (dragging || (hstate & ElementState::Hover) != ElementState::None) - guiStateManager.Cursor().Request( + app.guiStateManager.Cursor().Request( wh.vertical ? MouseCursor::EwResize : MouseCursor::NsResize); } - [[maybe_unused]] bool poppedHandles = idManager.PopParent(); + [[maybe_unused]] bool poppedHandles = app.idManager.PopParent(); } // ---- Virtual layout ---- @@ -2060,16 +2101,16 @@ namespace tachyon inViewMax = { std::max(inViewMax.x, c.x), std::max(inViewMax.y, c.y) }; } } - const ID standInRange = nodeCount > 0 ? idManager.AllocateRangedID(uint32_t(nodeCount) * 2, "node-stand-in") : ID::Invalid(); + const ID standInRange = nodeCount > 0 ? app.idManager.AllocateRangedID(uint32_t(nodeCount) * 2, "node-stand-in") : ID::Invalid(); int enteredNode = -1; // the node a stand-in's tab target took the focus into bool enteredFromAfter = false; if (standInRange != ID::Invalid()) { - const ID focused = guiStateManager.Interaction().GetFocusedID(); + const ID focused = app.guiStateManager.Interaction().GetFocusedID(); for (int n = 0; n < nodeCount && enteredNode < 0; ++n) - if (focused == idManager.GetSubID(standInRange, uint32_t(2 * n))) + if (focused == app.idManager.GetSubID(standInRange, uint32_t(2 * n))) enteredNode = n; - else if (focused == idManager.GetSubID(standInRange, uint32_t(2 * n + 1))) + else if (focused == app.idManager.GetSubID(standInRange, uint32_t(2 * n + 1))) enteredNode = n, enteredFromAfter = true; } @@ -2087,36 +2128,36 @@ namespace tachyon if (hiddenPorts[size_t(n)].empty()) continue; const IntRect box = hiddenBox[size_t(n)]; - auto res = elementStorage.Add(Element{ .id = IDManager::ScopedID(canvasID, node.stableID), .styleRef = theme.emptyHorzStyleRef, .flags = ElementFlags::NoInput }, + auto res = app.elementStorage.Add(Element{ .id = IDManager::ScopedID(canvasID, node.stableID), .styleRef = app.theme.emptyHorzStyleRef, .flags = ElementFlags::NoInput }, LayoutOverride{}.FixedSize(Pixels{ box.w }, Pixels{ box.h }).Absolute(box.x, box.y)); VERIFY(res.status); - VERIFY(windowRegistry.Add(res.ref)); + VERIFY(app.windowRegistry.Add(res.ref)); nodeRefs[n] = res.ref; - VERIFY(elementStorage.BeginChildren()); - [[maybe_unused]] const bool pushedHidden = idManager.PushParent(IDManager::ScopedID(canvasID, node.stableID)); - const int32_t pitch = 2 * std::max(1, theme.nodeGridSize); + VERIFY(app.elementStorage.BeginChildren()); + [[maybe_unused]] const bool pushedHidden = app.idManager.PushParent(IDManager::ScopedID(canvasID, node.stableID)); + const int32_t pitch = 2 * std::max(1, styles.nodeGridSize); for (const NodeHiddenPort& port : hiddenPorts[size_t(n)]) socketRefs[n][port.prop * 2 + (port.output ? 1 : 0)] = emitSocket(n, port.prop, port.output, /*readonly=*/true, LayoutOverride{}.FixedSize(Pixels{ kSocketSize }, Pixels{ kSocketSize }) .Absolute(port.output ? box.w - kSocketSize / 2 : -kSocketSize / 2, pitch + port.row * pitch + pitch / 2 - kSocketSize / 2)); if (pushedHidden) - (void)idManager.PopParent(); - VERIFY(elementStorage.EndChildren()); + (void)app.idManager.PopParent(); + VERIFY(app.elementStorage.EndChildren()); continue; } // Snap the node's top-left onto the grid. - const int32_t grid = theme.nodeGridSize; + const int32_t grid = styles.nodeGridSize; if (grid > 0 && view.graph.snapToGrid) node.pos = { SnapToGrid(node.pos.x, grid), SnapToGrid(node.pos.y, grid) }; // Width: last frame's content width rounded UP to whole grid cells (minimum on the first frame). - const int32_t minNodeWidth = (grid > 0) ? grid * 6 : styleManager.Px(120); + const int32_t minNodeWidth = (grid > 0) ? grid * 6 : app.styleManager.Px(120); int32_t nodeWidth = minNodeWidth; if (grid > 0 && node.lastSize.x > 0) nodeWidth = std::max(minNodeWidth, ((node.lastSize.x + grid - 1) / grid) * grid); // A reroute is a square one row pitch (two grid cells) wide, its dot in the middle. - const int32_t reroutePitch = grid > 0 ? 2 * grid : styleManager.Px(24); + const int32_t reroutePitch = grid > 0 ? 2 * grid : app.styleManager.Px(24); // Outer .node element: click-drag moves the node, double-click toggles collapse. // Its ID is its stable ID's in this canvas: a dynamic ID would change with z-order @@ -2130,13 +2171,13 @@ namespace tachyon && n != enteredNode && outerID != view.state.focusedNodeID && (float(node.pos.x + node.lastSize.x) < inViewMin.x || float(node.pos.x) > inViewMax.x || float(node.pos.y + node.lastSize.y) < inViewMin.y || float(node.pos.y) > inViewMax.y); - ElementState outerState = guiStateManager.GetCurrentState(elementID); + ElementState outerState = app.guiStateManager.GetCurrentState(elementID); if (view.state.selectedNodeIDs.count(outerID)) outerState |= ElementState::Selected; Element outer { .id = elementID, // Fits std::function's small buffer: the element's ID is worked out, not kept. - .eventHandler = [this, view, n, outerID, canvasID](ElementEvent&& event)->bool + .eventHandler = [&app, view, n, grid = styles.nodeGridSize, outerID, canvasID](ElementEvent&& event)->bool { switch (event.type) { @@ -2146,7 +2187,7 @@ namespace tachyon // A title or label being renamed is left: the focus goes back to the // canvas, so its field keeps what was typed and closes. if (view.state.renamingFrame || view.state.renamingTransition) - TakeFocus(guiStateManager, canvasID); + TakeFocus(app.guiStateManager, canvasID); // A state: a click finishes a transition started from a menu; a // double-click opens the machine it holds (states don't collapse). @@ -2155,7 +2196,7 @@ namespace tachyon { if (view.state.transitionPicking) { - AddTransitionIfNew(view, view.state.transitionFrom, outerID, idManager); + AddTransitionIfNew(view, view.state.transitionFrom, outerID, app.idManager); view.state.transitionPicking = false; view.state.transitionFrom = ID::Invalid(); return true; @@ -2208,14 +2249,13 @@ namespace tachyon other.startPos = other.pos; } // The moves, the release and Escape come here wherever the pointer goes. - view.state.nodeDrag.Press(event, elementStorage, guiStateManager, {}, { .focus = false }); + view.state.nodeDrag.Press(event, app.elementStorage, app.guiStateManager, {}, { .focus = false }); return true; } case EventType::MouseUp: { // The whole drag is one edit, to the grid-snapped positions; a click moves nothing. if (view.state.nodeDrag.Release(event) != PointerDrag::Ended::Drag) return true; - const int32_t grid = theme.nodeGridSize; NodeViewEdit edit; for (int i = 0; i < (int)view.graph.nodes.size(); ++i) { @@ -2254,29 +2294,29 @@ namespace tachyon if (view.graph.kind == NodeViewKind::StateMachine) view.state.stateEdgeHover.Track(AnyHeld(view.state.nodeDrag, view.state.marquee, view.state.transitionDrag), [] { return ID::Invalid(); }); if (!view.state.nodeDrag.IsPressed(IDManager::ScopedID(canvasID, outerID))) return false; - if (!view.state.nodeDrag.Move(event, styleManager.Px(kDragStartDistance))) return true; + if (!view.state.nodeDrag.Move(event, app.styleManager.Px(kDragStartDistance))) return true; // The node is inside the canvas: its layout space is node.pos space. - const int2 idelta = view.state.nodeDrag.drag.LocalDelta(event, elementStorage); + const int2 idelta = view.state.nodeDrag.drag.LocalDelta(event, app.elementStorage); // Move every node in the selection by the same delta; // always include the dragged node (see MouseDown). Onto the grid here // already, as the next layout would put them: what's drawn from their // places meanwhile (a state machine's arrows) lands where they do. - const int32_t grid = view.graph.snapToGrid ? theme.nodeGridSize : 0; + const int32_t snap = view.graph.snapToGrid ? grid : 0; for (auto& other : view.graph.nodes) { if (!view.state.selectedNodeIDs.count(other.stableID) && other.stableID != outerID) continue; other.pos = { other.startPos.x + idelta.x, other.startPos.y + idelta.y }; - if (grid > 0) - other.pos = { SnapToGrid(other.pos.x, grid), SnapToGrid(other.pos.y, grid) }; + if (snap > 0) + other.pos = { SnapToGrid(other.pos.x, snap), SnapToGrid(other.pos.y, snap) }; } return true; } case EventType::KeyDown: { // Escape during a move puts the nodes back. - if (!view.state.nodeDrag.Cancel(event, guiStateManager)) return false; + if (!view.state.nodeDrag.Cancel(event, app.guiStateManager)) return false; for (auto& other : view.graph.nodes) if (view.state.selectedNodeIDs.count(other.stableID) || other.stableID == outerID) other.pos = other.startPos; @@ -2286,21 +2326,21 @@ namespace tachyon } return false; }, - .styleRef = node.reroute ? theme.nodeRerouteStyleRef : stateMachine ? theme.nodeStateStyleRef : theme.nodeStyleRef, + .styleRef = node.reroute ? styles.nodeRerouteStyleRef : stateMachine ? styles.nodeStateStyleRef : styles.nodeStyleRef, .flags = ElementFlags::PropagatesDescendantState, .state = outerState }; // MinWidth (not Fixed): shrink-wraps content, floored at the grid-snapped width. - auto outerRes = elementStorage.Add(std::move(outer), node.reroute + auto outerRes = app.elementStorage.Add(std::move(outer), node.reroute ? LayoutOverride{}.FixedSize(Pixels{ reroutePitch }, Pixels{ reroutePitch }).Absolute(node.pos.x, node.pos.y) : standIn ? LayoutOverride{}.FixedSize(Pixels{ node.lastSize.x }, Pixels{ node.lastSize.y }).Absolute(node.pos.x, node.pos.y) : LayoutOverride{}.MinWidth(Pixels{ nodeWidth }).Absolute(node.pos.x, node.pos.y)); VERIFY(outerRes.status); - VERIFY(windowRegistry.Add(outerRes.ref)); + VERIFY(app.windowRegistry.Add(outerRes.ref)); nodeRefs[n] = outerRes.ref; // Cache the node's laid-out size for marquee hit-testing. - VERIFY(elementStorage.AddPostLayout(outerRes.ref, + VERIFY(app.elementStorage.AddPostLayout(outerRes.ref, [view, n, stableID = node.stableID](tachyon::PostLayoutContext& ctx) { // The app may change view.graph.nodes after this build and before layout. @@ -2316,11 +2356,11 @@ namespace tachyon } target->lastSize = ctx.ElementRect().size; })); - VERIFY(elementStorage.BeginChildren()); + VERIFY(app.elementStorage.BeginChildren()); // Scope this node's dynamic IDs under its stable ID (BeginChildren doesn't push // an ID parent), so they don't change when z-order reshuffles the nodes. - [[maybe_unused]] bool pushed = idManager.PushParent(elementID); + [[maybe_unused]] bool pushed = app.idManager.PushParent(elementID); // A stand-in: its sockets where its rows would put them (the first and last pitch // of each), and its two tab targets. @@ -2342,15 +2382,15 @@ namespace tachyon .Absolute(nodeWidth - socketInsetR + nodeLeftChrome, rowTop + pitch * span - pitch / 2 - kSocketSize / 2)); rowTop += pitch * span; } - tabChainManager.RegisterTabTarget(idManager.GetSubID(standInRange, uint32_t(2 * n))); - tabChainManager.RegisterTabTarget(idManager.GetSubID(standInRange, uint32_t(2 * n + 1))); - [[maybe_unused]] bool poppedStandIn = idManager.PopParent(); - VERIFY(elementStorage.EndChildren()); + app.tabChainManager.RegisterTabTarget(app.idManager.GetSubID(standInRange, uint32_t(2 * n))); + app.tabChainManager.RegisterTabTarget(app.idManager.GetSubID(standInRange, uint32_t(2 * n + 1))); + [[maybe_unused]] bool poppedStandIn = app.idManager.PopParent(); + VERIFY(app.elementStorage.EndChildren()); continue; } // Tabbed into: note its controls, to move the focus onto the first (or last). if (n == enteredNode) - tabChainManager.BeginSpan(); + app.tabChainManager.BeginSpan(); // A reroute: its first row's sockets on the square's left and right edges, their // pins showing while the reroute is hovered or selected (drag a wire in or out @@ -2373,9 +2413,9 @@ namespace tachyon && source.propIdx < (int)view.graph.nodes[size_t(source.nodeIdx)].properties.size() ? view.graph.nodes[size_t(source.nodeIdx)].properties[size_t(source.propIdx)].socketColor : row ? row->socketColor : tachyon::color4f{ 0.9f, 0.9f, 0.9f, 1.0f }; - VERIFY(elementStorage.AddCustomDraw(outerRes.ref, - [wireColor, selected, hovered, ringColor = theme.GetColor("--accent"), backColor = theme.GetColor("--bg-raised"), - dot = float(kSocketSize) - styleManager.Px(2.0f), ring = styleManager.Px(2.0f)](tachyon::CustomDrawContext& ctx) + VERIFY(app.elementStorage.AddCustomDraw(outerRes.ref, + [wireColor, selected, hovered, ringColor = app.theme.GetColor("--accent"), backColor = app.theme.GetColor("--bg-raised"), + dot = float(kSocketSize) - app.styleManager.Px(2.0f), ring = app.styleManager.Px(2.0f)](tachyon::CustomDrawContext& ctx) { const auto inner = ctx.ElementInnerRect(); const tachyon::float2 center{ inner.w * 0.5f, inner.h * 0.5f }; @@ -2383,8 +2423,8 @@ namespace tachyon ctx.RenderDot(center, size + 2.0f * ring, selected ? ringColor : backColor); ctx.RenderDot(center, size, wireColor); })); - [[maybe_unused]] bool poppedReroute = idManager.PopParent(); - VERIFY(elementStorage.EndChildren()); + [[maybe_unused]] bool poppedReroute = app.idManager.PopParent(); + VERIFY(app.elementStorage.EndChildren()); continue; } @@ -2394,22 +2434,22 @@ namespace tachyon // filled, and its edge stronger again unless the state's border shows a hover or a // selection. const tachyon::color4f ownColor = node.categoryColor.a > 0.0f ? node.categoryColor : accentColor; - ID headerID = idManager.AllocateDynamicID("node-header"); + ID headerID = app.idManager.AllocateDynamicID("node-header"); Element header { .id = headerID, - .styleRef = stateMachine ? theme.nodeHeaderStateStyleRef : theme.nodeHeaderStyleRef, + .styleRef = stateMachine ? styles.nodeHeaderStateStyleRef : styles.nodeHeaderStyleRef, .flags = ElementFlags::NoInput, .state = outerState }; - header.colorStyleIndex = appColor(OverNodeBody(ownColor, stateMachine ? theme.nodeTints.state : theme.nodeTints.header)); + header.colorStyleIndex = appColor(OverNodeBody(ownColor, stateMachine ? styles.nodeTints.state : styles.nodeTints.header)); if (stateMachine) { - const tachyon::color4f edge = OverNodeBody(ownColor, theme.nodeTints.stateBorder); - const VisualBoxStyleIndex outline = styleManager.RegisterOutline(stateEdgeWidths, stateEdgeRadius, + const tachyon::color4f edge = OverNodeBody(ownColor, styles.nodeTints.stateBorder); + const VisualBoxStyleIndex outline = app.styleManager.RegisterOutline(stateEdgeWidths, stateEdgeRadius, appColor(tachyon::color4f{ edge.r, edge.g, edge.b, 1.0f })); if ((outerState & (ElementState::Hover | ElementState::Active | ElementState::Focused | ElementState::Selected)) == ElementState::None) - VERIFY(elementStorage.AddCustomDraw(outerRes.ref, [outline](tachyon::CustomDrawContext& ctx) { + VERIFY(app.elementStorage.AddCustomDraw(outerRes.ref, [outline](tachyon::CustomDrawContext& ctx) { ctx.RenderBox(ctx.ElementRect(), outline); })); // A nested machine's second box, behind it, in its colors. @@ -2424,49 +2464,49 @@ namespace tachyon headerLayout = LayoutOverride{}.Height(Pixels{ rowPitch - 2 * nodeBorderV }); else if (rowPitch > nodeTopChromeV) headerLayout = LayoutOverride{}.Height(Pixels{ rowPitch - nodeTopChromeV }); - auto headerRes = elementStorage.Add(std::move(header), std::move(headerLayout)); + auto headerRes = app.elementStorage.Add(std::move(header), std::move(headerLayout)); VERIFY(headerRes.status); - VERIFY(windowRegistry.Add(headerRes.ref)); + VERIFY(app.windowRegistry.Add(headerRes.ref)); if (!stateMachine) { // The line under the header, over the border the style draws there. - const VisualColorStyleIndex line = appColor(OverNodeBody(ownColor, theme.nodeTints.headerLine)); - VERIFY(elementStorage.AddCustomDraw(headerRes.ref, [line, width = std::max(1, styleManager.Px(1))](tachyon::CustomDrawContext& ctx) { + const VisualColorStyleIndex line = appColor(OverNodeBody(ownColor, styles.nodeTints.headerLine)); + VERIFY(app.elementStorage.AddCustomDraw(headerRes.ref, [line, width = std::max(1, app.styleManager.Px(1))](tachyon::CustomDrawContext& ctx) { const IntRect r = ctx.ElementRect(); ctx.RenderQuad(IntRect{ r.x, r.y + r.h - width, r.w, width }, line); })); } - VERIFY(elementStorage.BeginChildren()); + VERIFY(app.elementStorage.BeginChildren()); { auto addHeaderPart = [&](const char* name, StyleRef style, std::string_view text, tachyon::VisualColorStyleIndex color) { - const ID partID = idManager.AllocateDynamicID(name); + const ID partID = app.idManager.AllocateDynamicID(name); Element part{ .id = partID, .styleRef = style, .flags = ElementFlags::NoInput, .state = outerState }; if (!text.empty()) - part.textID = textSystem->RegisterText(partID, text, style, part.state); + part.textID = app.textSystem->RegisterText(partID, text, style, part.state); part.colorStyleIndex = color; - auto res = elementStorage.Add(std::move(part), LayoutOverride{}.Auto()); + auto res = app.elementStorage.Add(std::move(part), LayoutOverride{}.Auto()); VERIFY(res.status); - VERIFY(windowRegistry.Add(res.ref)); + VERIFY(app.windowRegistry.Add(res.ref)); }; // Alpha 0 keeps the CSS default (the accent). const tachyon::VisualColorStyleIndex categoryColor = node.categoryColor.a > 0.0f ? appColor(node.categoryColor) : tachyon::VisualColorStyleIndex{}; - addHeaderPart("node-category", theme.nodeCategoryStyleRef, {}, categoryColor); - addHeaderPart("node-title", theme.nodeTitleStyleRef, node.title, {}); + addHeaderPart("node-category", styles.nodeCategoryStyleRef, {}, categoryColor); + addHeaderPart("node-title", styles.nodeTitleStyleRef, node.title, {}); if (!node.category.empty()) - addHeaderPart("node-caption", theme.nodeCaptionStyleRef, node.category, {}); + addHeaderPart("node-caption", styles.nodeCaptionStyleRef, node.category, {}); // A state holding a machine of its own: its mark at the end, two stacked boxes. if (stateMachine && node.subMachine) { - const ID markID = idManager.AllocateDynamicID("node-nested-mark"); - auto mark = elementStorage.Add(Element{ .id = markID, .styleRef = theme.nodeStateNestedMarkStyleRef, + const ID markID = app.idManager.AllocateDynamicID("node-nested-mark"); + auto mark = app.elementStorage.Add(Element{ .id = markID, .styleRef = styles.nodeStateNestedMarkStyleRef, .flags = ElementFlags::NoInput, .state = outerState }, LayoutOverride{}.Auto()); VERIFY(mark.status); - VERIFY(windowRegistry.Add(mark.ref)); - VERIFY(elementStorage.AddCustomDraw(mark.ref, - [box = theme.nodeStateNestedStyleRef.visualBoxStyleIndex, o = styleManager.Px(3)](tachyon::CustomDrawContext& ctx) { + VERIFY(app.windowRegistry.Add(mark.ref)); + VERIFY(app.elementStorage.AddCustomDraw(mark.ref, + [box = styles.nodeStateNestedStyleRef.visualBoxStyleIndex, o = app.styleManager.Px(3)](tachyon::CustomDrawContext& ctx) { const IntRect r = ctx.ElementInnerRect(); const int32_t s = std::max(1, std::min(r.w, r.h) - o); ctx.RenderBox(IntRect{ r.x + o, r.y, s, s }, box); @@ -2474,26 +2514,26 @@ namespace tachyon })); } } - VERIFY(elementStorage.EndChildren()); + VERIFY(app.elementStorage.EndChildren()); if (!node.collapsed) { // One LabelGroup ID per node, begun inside every row, so all labels in // the node share one width. - const ID nodeLabelGroupID = idManager.AllocateDynamicID("node-labelgroup"); + const ID nodeLabelGroupID = app.idManager.AllocateDynamicID("node-labelgroup"); const int propCount = stateMachine ? 0 : (int)node.properties.size(); // a state has no fields for (int p = 0; p < propCount; ++p) { NodeProperty& prop = node.properties[p]; - ID rowID = idManager.AllocateDynamicID("node-row"); + ID rowID = app.idManager.AllocateDynamicID("node-row"); // Whole row pitches so rows and socket centres stay on grid lines; rowSpan > 1 // fits tall bodies. The last row gives back the bottom chrome. const int32_t span = (prop.rowSpan > 0 ? prop.rowSpan : 1); const int32_t rowH = rowPitch * span - (p == propCount - 1 ? nodeBottomChromeV : 0); - BeginHorizontal(rowID, theme.nodeRowStyleRef, LayoutOverride{}.Height(Pixels{ rowH })); + app.BeginHorizontal(rowID, styles.nodeRowStyleRef, LayoutOverride{}.Height(Pixels{ rowH })); // Input socket at the FIRST pitch centre, output at the LAST // (same as the row centre for single-pitch rows). @@ -2503,13 +2543,13 @@ namespace tachyon if (span == 1) { Element spacer{}; - spacer.id = idManager.AllocateDynamicID("sock-spacer-l"); - spacer.styleRef = theme.emptyHorzStyleRef; + spacer.id = app.idManager.AllocateDynamicID("sock-spacer-l"); + spacer.styleRef = app.theme.emptyHorzStyleRef; spacer.flags = ElementFlags::NoInput; - auto sp = elementStorage.Add(std::move(spacer), + auto sp = app.elementStorage.Add(std::move(spacer), LayoutOverride{}.FixedSize(Pixels{ kSocketSize / 6 }, Pixels{ kSocketSize }).NoGrow().NoShrink()); VERIFY(sp.status); - VERIFY(windowRegistry.Add(sp.ref)); + VERIFY(app.windowRegistry.Add(sp.ref)); } // Input dot: OUT OF FLOW - absolutely placed straddling the node's // left border at this property's FIRST pitch, mirroring the output @@ -2524,37 +2564,37 @@ namespace tachyon // Body fills the row. The LabelGroup must begin at the depth renderBody // emits into. Multi-pitch content (images) is centred. - if (span > 1) BeginHorizontal(theme.nodeBodyCenterStyleRef, LayoutOverride{}.FlexGrow(1)); - else BeginHorizontal(LayoutOverride{}.FlexGrow(1)); - BeginLabelGroup(nodeLabelGroupID, /*defaultWidth=*/60, + if (span > 1) app.BeginHorizontal(styles.nodeBodyCenterStyleRef, LayoutOverride{}.FlexGrow(1)); + else app.BeginHorizontal(LayoutOverride{}.FlexGrow(1)); + app.BeginLabelGroup(nodeLabelGroupID, /*defaultWidth=*/60, /*minWidth=*/30, /*maxWidth=*/120, /*resizable=*/false); // A text-only body (NodeText) aligns to its sockets: an output alone puts it // at the end, by its dot; otherwise it reads from the start. - nodeRowTextAlign = (prop.output && !prop.input.has_value()) ? TextAlign::End : TextAlign::Start; + context.rowTextAlign = (prop.output && !prop.input.has_value()) ? TextAlign::End : TextAlign::Start; // Value-fields fill the body (minus the label) with room to spare, numbers // in the node's own style. - nodeRowFieldMinWidth = theme.nodeGridSize * 4; - const ControlStyles* outerControls = theme.controls; - theme.controls = &theme.nodeControls; + app.SetFieldRowFill(styles.nodeGridSize * 4); + const ControlStyles* outerControls = app.theme.controls; + app.theme.controls = &styles.nodeControls; if (prop.renderBody) prop.renderBody(); - theme.controls = outerControls; - nodeRowTextAlign = TextAlign::Start; - nodeRowFieldMinWidth = 0; - EndLabelGroup(); - EndHorizontal(); + app.theme.controls = outerControls; + context.rowTextAlign = TextAlign::Start; + app.SetFieldRowFill(0); + app.EndLabelGroup(); + app.EndHorizontal(); // Same right inset on every single-pitch row so stacked fields line up. if (span == 1) { Element rpad{}; - rpad.id = idManager.AllocateDynamicID("row-pad-r"); - rpad.styleRef = theme.emptyHorzStyleRef; + rpad.id = app.idManager.AllocateDynamicID("row-pad-r"); + rpad.styleRef = app.theme.emptyHorzStyleRef; rpad.flags = ElementFlags::NoInput; - auto rp = elementStorage.Add(std::move(rpad), + auto rp = app.elementStorage.Add(std::move(rpad), LayoutOverride{}.FixedSize(Pixels{ kSocketSize / 6 }, Pixels{ kSocketSize }).NoGrow().NoShrink()); VERIFY(rp.status); - VERIFY(windowRegistry.Add(rp.ref)); + VERIFY(app.windowRegistry.Add(rp.ref)); } // Output dot: OUT OF FLOW - absolutely placed straddling the node's // right border at this property's pitch (like the collapsed sockets). @@ -2566,7 +2606,7 @@ namespace tachyon .Absolute(nodeWidth - socketInsetR, outY)); } - EndHorizontal(); + app.EndHorizontal(); } } else @@ -2598,22 +2638,22 @@ namespace tachyon if (n == enteredNode) { - tabChainManager.EndSpan(); - const ID onto = enteredFromAfter ? tabChainManager.SpanLast() : tabChainManager.SpanFirst(); - guiStateManager.Interaction().SetFocusID(onto != ID::Invalid() ? onto : elementID); + app.tabChainManager.EndSpan(); + const ID onto = enteredFromAfter ? app.tabChainManager.SpanLast() : app.tabChainManager.SpanFirst(); + app.guiStateManager.Interaction().SetFocusID(onto != ID::Invalid() ? onto : elementID); } - [[maybe_unused]] bool popped = idManager.PopParent(); - VERIFY(elementStorage.EndChildren()); // close outer .node + [[maybe_unused]] bool popped = app.idManager.PopParent(); + VERIFY(app.elementStorage.EndChildren()); // close outer .node } // Keyboard focus moving onto a field of a node that is out of view pans the view to // it, this frame; a click doesn't, as what's clicked is already in view. { - const auto& interaction = guiStateManager.Interaction(); + const auto& interaction = app.guiStateManager.Interaction(); const ID focusedID = interaction.GetFocusedID(); // The node holding the focus is laid out whole next frame, a stand-in never. - const std::vector around = focusedID != ID::Invalid() ? CollectPropagatedAncestors(elementStorage, focusedID) : std::vector{}; + const std::vector around = focusedID != ID::Invalid() ? GUIApplication::CollectPropagatedAncestors(app.elementStorage, focusedID) : std::vector{}; view.state.focusedNodeID = ID::Invalid(); for (int n = 0; n < nodeCount; ++n) if (std::find(around.begin(), around.end(), IDManager::ScopedID(canvasID, view.graph.nodes[n].stableID)) != around.end()) @@ -2624,8 +2664,8 @@ namespace tachyon for (int n = 0; n < nodeCount; ++n) if (std::find(around.begin(), around.end(), IDManager::ScopedID(canvasID, view.graph.nodes[n].stableID)) != around.end()) { - ScrollNodeIntoView(view, n, theme.nodeGridSize); - elementStorage.SetContentTransform(canvasRes.ref, + ScrollNodeIntoView(view, n, styles.nodeGridSize); + app.elementStorage.SetContentTransform(canvasRes.ref, tachyon::float3x2::Translate(tachyon::float2{ (float)(view.state.lastInnerSize.x / 2), (float)(view.state.lastInnerSize.y / 2) }) * view.state.transform); @@ -2634,8 +2674,8 @@ namespace tachyon } } - VERIFY(elementStorage.AddPostLayout(canvasRes.ref, - [this, view, canvasID, centeredFor = view.state.lastInnerSize](tachyon::PostLayoutContext& ctx) + VERIFY(app.elementStorage.AddPostLayout(canvasRes.ref, + [&app, view, canvasID, centeredFor = view.state.lastInnerSize](tachyon::PostLayoutContext& ctx) { view.state.lastInnerSize = ctx.ElementInnerRect().size; view.state.lastCanvasRect = ctx.ElementInnerRect(); @@ -2643,7 +2683,7 @@ namespace tachyon // The nodes were centered for last frame's size. A cached panel around the // view only rebuilds when its own size changes, so ask for the redraw. if (view.state.lastInnerSize.x != centeredFor.x || view.state.lastInnerSize.y != centeredFor.y) - RebuildCachedScopesAbove(canvasID); + app.RebuildCachedScopesAbove(canvasID); })); // A state machine: the state the pointer is on or round (its band shows faintly), and @@ -2652,14 +2692,14 @@ namespace tachyon ID pointedState = ID::Invalid(), bandLit = ID::Invalid(); if (stateMachine) { - const ID hoveredID = guiStateManager.Interaction().GetHoveredID(); + const ID hoveredID = app.guiStateManager.Interaction().GetHoveredID(); const bool onCanvas = hoveredID == canvasID; bandLit = view.state.transitionDrag.IsHeld() || view.state.transitionPicking ? view.state.transitionFrom : view.state.stateEdgeHover.Shown(onCanvas); pointedState = bandLit; if (pointedState == ID::Invalid() && NodeIndex(view, hoveredID) >= 0) pointedState = hoveredID; if (bandLit != ID::Invalid()) - guiStateManager.Cursor().Request(MouseCursor::Pointer); + app.guiStateManager.Cursor().Request(MouseCursor::Pointer); } const int litState = NodeIndex(view, bandLit); const ElementRef litRef = litState >= 0 && litState < (int)nodeRefs.size() ? nodeRefs[size_t(litState)] : ElementRef::Invalid(); @@ -2669,18 +2709,18 @@ namespace tachyon // AddCustomDrawAfter anchors to the last element of the canvas subtree - a child // of the frontmost node - and is skipped with that node when it leaves view. // Endpoints are CANVAS_LAY, so they pan/zoom with the sockets and clip to the viewport. - VERIFY(elementStorage.AddCustomDraw(canvasRes.ref, + VERIFY(app.elementStorage.AddCustomDraw(canvasRes.ref, // The socket and node refs are the view's, as built this frame. - [this, view, &socketRefs, &nodeRefs, drawnFrames = std::move(drawnFrames), + [&styles, &app, view, &socketRefs, &nodeRefs, drawnFrames = std::move(drawnFrames), transitionLabels = std::move(transitionLabels), stateMarks = std::move(stateMarks), transitionGap, transitionLoop, pointedState, bandLit, stateBand, - canvasHovered = guiStateManager.Interaction().GetHoveredID() == canvasID, - handleHoveredWire, mouseScreen = windowManager->GetScreenMousePos()](tachyon::CustomDrawContext& ctx) + canvasHovered = app.guiStateManager.Interaction().GetHoveredID() == canvasID, + handleHoveredWire, mouseScreen = app.windowManager->GetScreenMousePos()](tachyon::CustomDrawContext& ctx) { // Nodes are positioned relative to the canvas BORDER box, but this draw's // origin is the CONTENT box; offset the grid by the difference. const tachyon::int2 gridOrigin = ctx.ElementRect().position - ctx.ElementInnerRect().position; - // theme.nodeGridSize is the single pitch for node snap, wire snap and this + // styles.nodeGridSize is the single pitch for node snap, wire snap and this // grid. No subdivisions; density halves per zoom-out octave. // Clamp to the content box: take the (window-local, pan/zoom-correct) ClipRect, // deflate by the canvas chrome, and map into the current space. @@ -2704,8 +2744,8 @@ namespace tachyon std::max(cc0.x, cc1.x) - std::min(cc0.x, cc1.x), std::max(cc0.y, cc1.y) - std::min(cc0.y, cc1.y) }; - RenderCanvasGrid(ctx, theme.nodeGridSize, theme.GetColor("--canvas-dot"), - styleManager.Px(2.0f), gridOrigin, content); + RenderCanvasGrid(ctx, styles.nodeGridSize, app.theme.GetColor("--canvas-dot"), + app.styleManager.Px(2.0f), gridOrigin, content); // The frames, back to front, under the wires: the box, then the title bar over // its top, where the title element lies. @@ -2713,8 +2753,8 @@ namespace tachyon { const tachyon::IntRect title = ctx.GetElementRect(frame.title); const tachyon::IntRect box{ title.x, title.y, frame.size.x, frame.size.y }; - ctx.RenderBox(box, theme.nodeFrameStyleRef.visualBoxStyleIndex, frame.state, frame.fill); - ctx.RenderBox(title, theme.nodeFrameBandStyleRef.visualBoxStyleIndex, frame.state, frame.band); + ctx.RenderBox(box, styles.nodeFrameStyleRef.visualBoxStyleIndex, frame.state, frame.fill); + ctx.RenderBox(title, styles.nodeFrameBandStyleRef.visualBoxStyleIndex, frame.state, frame.band); // At rest, edged in its color; hovered or selected, its style's border shows that. if ((frame.state & (ElementState::Hover | ElementState::Active | ElementState::Selected)) == ElementState::None) ctx.RenderBox(box, frame.edge); @@ -2723,7 +2763,7 @@ namespace tachyon // A state machine: transitions between the states in place of wires. if (view.graph.kind == NodeViewKind::StateMachine) { - DrawStateMachine(ctx, theme, styleManager, view, gridOrigin, transitionLabels, stateMarks, transitionGap, transitionLoop, + DrawStateMachine(ctx, styles, app.styleManager, view, gridOrigin, transitionLabels, stateMarks, transitionGap, transitionLoop, canvasHovered, ctx.ScreenToCurrent(view.state.transitionPointer), pointedState, bandLit, int32_t(std::lround(stateBand * NodeViewZoom(view)))); view.state.wireHandleCache.clear(); @@ -2754,13 +2794,13 @@ namespace tachyon // Curved wires: their control points at least two rows out from the sockets. const bool curved = view.graph.wireShape == NodeWireShape::Curved; - const int32_t curveReach = theme.nodeGridSize > 0 ? 4 * theme.nodeGridSize : styleManager.Px(48); + const int32_t curveReach = styles.nodeGridSize > 0 ? 4 * styles.nodeGridSize : app.styleManager.Px(48); auto drawWire = [&](const std::vector& points, bool isCurve, const tachyon::LineStyle& style) { if (isCurve && points.size() == 4) ctx.RenderLine(points[0], points[1], points[2], points[3], style); else - ctx.RenderPolyline(points, /*closed=*/false, style, 0.5f * float(theme.nodeGridSize)); + ctx.RenderPolyline(points, /*closed=*/false, style, 0.5f * float(styles.nodeGridSize)); }; // Draggable interior segments collected this frame (node.pos @@ -2831,11 +2871,11 @@ namespace tachyon : BuildWireRoute(socketPoint(src.nodeIdx, srcRefs[srcOutIdx]), socketPoint(n, tgtRefs[tgtInIdx]), nodeRect(src.nodeIdx), nodeRect(n), - theme.nodeGridSize, gridOrigin, ov); + styles.nodeGridSize, gridOrigin, ov); // Wire takes its source socket's colour (style cached above). const tachyon::color4f srcColor = view.graph.nodes[src.nodeIdx].properties[src.propIdx].socketColor; - tachyon::VisualColorStyleIndex wireColorIdx = theme.lineYellowStyle; + tachyon::VisualColorStyleIndex wireColorIdx = styles.lineYellowStyle; if (auto cit = view.state.wireColorStyles.find(PackColor(srcColor)); cit != view.state.wireColorStyles.end()) wireColorIdx = cit->second; drawn.push_back(DrawnWire{ .wireKey = wireKey, .points = route.points, .curved = route.curved }); @@ -2863,14 +2903,14 @@ namespace tachyon if (handleHoveredWire) return handleHoveredWire; if (canvasHovered) - return WireAt(drawn, ctx.ScreenToCurrent(mouseScreen), float(styleManager.Px(5)) / NodeViewZoom(view)); + return WireAt(drawn, ctx.ScreenToCurrent(mouseScreen), float(app.styleManager.Px(5)) / NodeViewZoom(view)); return std::nullopt; }); for (size_t w = 0; w < drawn.size(); ++w) { const bool hovered = view.state.hoveredWire.part == drawn[w].wireKey; const tachyon::LineStyle wireStyle{ .colorStyleIndex = drawnColors[w], - .lineWidth = styleManager.Px(hovered ? 4.f : 2.f) }; + .lineWidth = app.styleManager.Px(hovered ? 4.f : 2.f) }; drawWire(drawn[w].points, drawn[w].curved, wireStyle); } @@ -2888,7 +2928,7 @@ namespace tachyon const int srcSockIdx = src.propIdx * 2 + srcSide; if (srcSockIdx >= 0 && srcSockIdx < (int)srcRefs.size() && srcRefs[srcSockIdx].IsValid()) { - const int32_t grid = theme.nodeGridSize; + const int32_t grid = styles.nodeGridSize; // currentScreen is a screen-space input; ScreenToCurrent brings it // into CANVAS_LAY, snapped to the grid like a socket (a curve // follows the cursor). @@ -2927,11 +2967,11 @@ namespace tachyon const PropertyEndpoint colorFrom = pendingOut.valid() && pendingOut.nodeIdx < nodeCount ? pendingOut : src; const tachyon::color4f srcColor = view.graph.nodes[colorFrom.nodeIdx].properties[colorFrom.propIdx].socketColor; - tachyon::VisualColorStyleIndex wireColorIdx = theme.lineYellowStyle; + tachyon::VisualColorStyleIndex wireColorIdx = styles.lineYellowStyle; if (auto cit = view.state.wireColorStyles.find(PackColor(srcColor)); cit != view.state.wireColorStyles.end()) wireColorIdx = cit->second; - const tachyon::LineStyle wireStyle{ .colorStyleIndex = wireColorIdx, .lineWidth = styleManager.Px(2.f), - .dashSize = styleManager.Px(4.f) }; + const tachyon::LineStyle wireStyle{ .colorStyleIndex = wireColorIdx, .lineWidth = app.styleManager.Px(2.f), + .dashSize = app.styleManager.Px(4.f) }; drawWire(route.points, route.curved, wireStyle); } } @@ -2944,9 +2984,9 @@ namespace tachyon // pointer, where a drag would draw a transition from, and a dashed stub on to the // pointer, which shows even where the cursor covers the dot. The ring is the band's middle, as DrawStateMachine draws it. if (stateMachine && litRef.IsValid() && !view.state.transitionDrag.IsHeld() && !view.state.transitionPicking) - VERIFY(elementStorage.AddCustomDrawAfter(canvasRes.ref, - [this, litRef, half = int32_t(std::lround(stateBand * NodeViewZoom(view))) / 2, - mouseScreen = windowManager->GetScreenMousePos()](tachyon::CustomDrawContext& ctx) + VERIFY(app.elementStorage.AddCustomDrawAfter(canvasRes.ref, + [&styles, &app, litRef, half = int32_t(std::lround(stateBand * NodeViewZoom(view))) / 2, + mouseScreen = app.windowManager->GetScreenMousePos()](tachyon::CustomDrawContext& ctx) { const IntRect box = ctx.GetElementRect(litRef); const IntRect ring{ box.x - half, box.y - half, box.w + 2 * half, box.h + 2 * half }; @@ -2964,14 +3004,14 @@ namespace tachyon else if (least == top) dot.y = ring.y; else dot.y = ring.y + ring.h; } - ctx.RenderLine(dot, mouse, LineStyle{ .colorStyleIndex = theme.nodeTransitionSelectedColor, - .lineWidth = styleManager.Px(2.0f), .dashSize = styleManager.Px(3.0f) }); - ctx.RenderDisc(dot, styleManager.Px(4.0f), theme.nodeTransitionSelectedColor); + ctx.RenderLine(dot, mouse, LineStyle{ .colorStyleIndex = styles.nodeTransitionSelectedColor, + .lineWidth = app.styleManager.Px(2.0f), .dashSize = app.styleManager.Px(3.0f) }); + ctx.RenderDisc(dot, app.styleManager.Px(4.0f), styles.nodeTransitionSelectedColor); })); // Marquee rectangle - drawn after the nodes so it sits on top of them. - VERIFY(elementStorage.AddCustomDrawAfter(canvasRes.ref, - [this, view](tachyon::CustomDrawContext& ctx) + VERIFY(app.elementStorage.AddCustomDrawAfter(canvasRes.ref, + [&styles, &app, view](tachyon::CustomDrawContext& ctx) { if (view.state.marquee.Phase() != GesturePhase::Dragging) return; @@ -2986,17 +3026,17 @@ namespace tachyon const int y1 = std::max(startLay.y, currentLay.y); const IntRect marqueeRectLay{ x0, y0, x1 - x0, y1 - y0 }; - ctx.RenderQuad(marqueeRectLay, theme.marqueeFillColorStyle, 0.0f); - const tachyon::LineStyle border{ .colorStyleIndex = theme.lineWhiteStyle, .lineWidth = styleManager.Px(1.f) }; + ctx.RenderQuad(marqueeRectLay, styles.marqueeFillColorStyle, 0.0f); + const tachyon::LineStyle border{ .colorStyleIndex = styles.lineWhiteStyle, .lineWidth = app.styleManager.Px(1.f) }; ctx.RenderLine({ x0, y0 }, { x1, y0 }, border); ctx.RenderLine({ x1, y0 }, { x1, y1 }, border); ctx.RenderLine({ x1, y1 }, { x0, y1 }, border); ctx.RenderLine({ x0, y1 }, { x0, y0 }, border); })); - VERIFY(elementStorage.EndChildren()); + VERIFY(app.elementStorage.EndChildren()); - EmitNodeViewOverlays(view, canvasID); + EmitNodeViewOverlays(app, context, view, canvasID); // The selection, however it changed since the view last looked (a click, the marquee, // a key, a removed node, the app): once, with the frame's other changes made. @@ -3010,81 +3050,82 @@ namespace tachyon } } - void GUIApplication::EmitNodeViewOverlays(NodeViewRef view, ID canvasID) + static void EmitNodeViewOverlays(GUIApplication& app, Context& context, NodeViewRef view, ID canvasID) { + const Styles& styles = GetStyles(app, context); // Siblings after the canvas, anchored to its corners: out of the canvas's // pan/zoom, and out of the parent's flow. - const int32_t inset = styleManager.Px(8); + const int32_t inset = app.styleManager.Px(8); auto corner = [&](AnchorPlacement placement, int32_t dx, int32_t dy) { return LayoutOverride{}.Anchored(canvasID, placement, dx, dy); }; if (!view.state.breadcrumb.empty()) - Breadcrumb(idManager.AllocateDynamicID("node-view-breadcrumb"), view.state.breadcrumb, view.state.onBreadcrumb, - theme.nodeViewOverlayStyleRef, + app.Breadcrumb(app.idManager.AllocateDynamicID("node-view-breadcrumb"), view.state.breadcrumb, view.state.onBreadcrumb, + styles.nodeViewOverlayStyleRef, corner(AnchorPlacement::InsideLeft | AnchorPlacement::InsideTop, inset, inset)); if (view.state.showZoomControls) { - const ID barID = idManager.AllocateDynamicID("node-view-zoom"); - if (BeginHorizontal(barID, theme.nodeViewOverlayStyleRef, + const ID barID = app.idManager.AllocateDynamicID("node-view-zoom"); + if (app.BeginHorizontal(barID, styles.nodeViewOverlayStyleRef, corner(AnchorPlacement::InsideLeft | AnchorPlacement::InsideBottom, inset, -inset))) { - [[maybe_unused]] const bool pushed = idManager.PushParent(barID); + [[maybe_unused]] const bool pushed = app.idManager.PushParent(barID); constexpr float kZoomStep = 1.25f; - const StyleRef button = theme.nodeViewOverlayButtonStyleRef; - Button(idManager.AllocateDynamicID(), "\u2212", [view] { ZoomNodeView(view, 1.0f / kZoomStep); }, button); + const StyleRef button = styles.nodeViewOverlayButtonStyleRef; + app.Button(app.idManager.AllocateDynamicID(), "\u2212", [view] { ZoomNodeView(view, 1.0f / kZoomStep); }, button); // The zoom; clicking it goes back to 100%. const std::string percent = std::to_string(int(std::lround(NodeViewZoom(view) * 100.0f))) + "%"; - Button(idManager.AllocateDynamicID(), percent, [view] { ZoomNodeView(view, 1.0f / NodeViewZoom(view)); }, button); - Button(idManager.AllocateDynamicID(), "+", [view] { ZoomNodeView(view, kZoomStep); }, button); - RegisterElement(Element{ .id = idManager.AllocateDynamicID("divider"), .styleRef = theme.nodeViewOverlayDividerStyleRef, + app.Button(app.idManager.AllocateDynamicID(), percent, [view] { ZoomNodeView(view, 1.0f / NodeViewZoom(view)); }, button); + app.Button(app.idManager.AllocateDynamicID(), "+", [view] { ZoomNodeView(view, kZoomStep); }, button); + app.RegisterElement(Element{ .id = app.idManager.AllocateDynamicID("divider"), .styleRef = styles.nodeViewOverlayDividerStyleRef, .flags = ElementFlags::NoInput }, LayoutOverride{}); - Button(idManager.AllocateDynamicID(), "Fit", [view] { FrameSelectedNodes(view); }, button); + app.Button(app.idManager.AllocateDynamicID(), "Fit", [view] { FrameSelectedNodes(view); }, button); if (pushed) - (void)idManager.PopParent(); - EndHorizontal(); + (void)app.idManager.PopParent(); + app.EndHorizontal(); } } if (view.state.showMinimap) { // Clicking or dragging in the minimap centres the view there; Escape puts it back. - const ID minimapID = idManager.AllocateDynamicID("node-view-minimap"); + const ID minimapID = app.idManager.AllocateDynamicID("node-view-minimap"); Element minimap { .id = minimapID, - .eventHandler = [this, view](ElementEvent&& event) -> bool + .eventHandler = [&app, view](ElementEvent&& event) -> bool { if (event.type == EventType::KeyDown) { - return view.state.minimapDrag.Cancel(event, guiStateManager, view.state.transform); + return view.state.minimapDrag.Cancel(event, app.guiStateManager, view.state.transform); } if (view.state.minimapDrag.Release(event) != PointerDrag::Ended::No) return true; if (view.state.minimapScale <= 0.0f) return false; // A press starts it (Escape comes here with the capture); a move goes on with it. - if (!view.state.minimapDrag.Press(event, elementStorage, guiStateManager, view.state.transform, { .atOnce = true, .focus = false }) + if (!view.state.minimapDrag.Press(event, app.elementStorage, app.guiStateManager, view.state.transform, { .atOnce = true, .focus = false }) && !view.state.minimapDrag.Move(event, 0)) return false; - const int2 local = event.LocalCursor(elementStorage) - event.rect->innerRect.position; + const int2 local = event.LocalCursor(app.elementStorage) - event.rect->innerRect.position; SetNodeViewCenter(view, float2{ view.state.minimapOrigin.x + float(local.x) / view.state.minimapScale, view.state.minimapOrigin.y + float(local.y) / view.state.minimapScale }, NodeViewZoom(view)); return true; }, - .styleRef = theme.nodeViewMinimapStyleRef, + .styleRef = styles.nodeViewMinimapStyleRef, }; - auto res = elementStorage.Add(std::move(minimap), + auto res = app.elementStorage.Add(std::move(minimap), corner(AnchorPlacement::InsideRight | AnchorPlacement::InsideBottom, -inset, -inset) .Size(140, 88)); VERIFY(res.status); - VERIFY(windowRegistry.Add(res.ref)); - VERIFY(elementStorage.AddCustomDraw(res.ref, - [this, view, nodeColor = styleManager.RegisterColorStyle(ColorStyle::Create(theme.GetColor("--line-strong"))), - frameColor = styleManager.RegisterColorStyle(ColorStyle::Create(theme.GetColor("--frame-band"))), - pad = float(styleManager.Px(6))](CustomDrawContext& ctx) + VERIFY(app.windowRegistry.Add(res.ref)); + VERIFY(app.elementStorage.AddCustomDraw(res.ref, + [&app, view, nodeColor = app.styleManager.RegisterColorStyle(ColorStyle::Create(app.theme.GetColor("--line-strong"))), + frameColor = app.styleManager.RegisterColorStyle(ColorStyle::Create(app.theme.GetColor("--frame-band"))), + pad = float(app.styleManager.Px(6))](CustomDrawContext& ctx) { // Bounds of the nodes and the visible area, in canvas coordinates. const float2 halfView{ float(view.state.lastInnerSize.x) * 0.5f, float(view.state.lastInnerSize.y) * 0.5f }; @@ -3133,7 +3174,7 @@ namespace tachyon const int2 b = toMap(float(node.pos.x + node.lastSize.x), float(node.pos.y + node.lastSize.y)); const bool selected = view.state.selectedNodeIDs.count(node.stableID) != 0; ctx.RenderQuad(IntRect{ a.x, a.y, std::max(1, b.x - a.x), std::max(1, b.y - a.y) }, - selected ? theme.treeDropIndicatorStyle : nodeColor, 2.0f); + selected ? app.theme.treeDropIndicatorStyle : nodeColor, 2.0f); } // The visible area. @@ -3141,7 +3182,7 @@ namespace tachyon const int2 b = toMap(std::max(v0.x, v1.x), std::max(v0.y, v1.y)); const int2 frame[] = { a, { b.x, a.y }, b, { a.x, b.y } }; ctx.RenderPolyline(frame, /*closed=*/true, - LineStyle{ .colorStyleIndex = theme.treeDropIndicatorStyle, .lineWidth = styleManager.Px(1.0f) }); + LineStyle{ .colorStyleIndex = app.theme.treeDropIndicatorStyle, .lineWidth = app.styleManager.Px(1.0f) }); })); } } diff --git a/src/gui_controls/gui_node_view_helpers.cpp b/src/gui_nodes/gui_node_view_helpers.cpp similarity index 99% rename from src/gui_controls/gui_node_view_helpers.cpp rename to src/gui_nodes/gui_node_view_helpers.cpp index 63dccdbe..f8cf1691 100644 --- a/src/gui_controls/gui_node_view_helpers.cpp +++ b/src/gui_nodes/gui_node_view_helpers.cpp @@ -1,4 +1,4 @@ -#include +#include #include @@ -6,7 +6,7 @@ #include #include -namespace tachyon +namespace tachyon::nodes { namespace { diff --git a/src/gui_controls/gui_node_view_helpers.h b/src/gui_nodes/gui_node_view_helpers.h similarity index 99% rename from src/gui_controls/gui_node_view_helpers.h rename to src/gui_nodes/gui_node_view_helpers.h index ac79ec0f..32bb2cb7 100644 --- a/src/gui_controls/gui_node_view_helpers.h +++ b/src/gui_nodes/gui_node_view_helpers.h @@ -1,6 +1,6 @@ #pragma once -#include // NodeModel, NodeView +#include // NodeModel, NodeView #include #include @@ -12,12 +12,16 @@ #include namespace tachyon +{ + class CustomDrawContext; + struct LineStyle; +} + +namespace tachyon::nodes { /// @addtogroup controls_nodes /// @{ - class CustomDrawContext; - struct LineStyle; /// The element a view last built for the node, frame or transition `stableID` names: its /// stable ID scoped to the view's canvas, so another view of the graph has its own. diff --git a/src/gui_controls/gui_node_view_types.h b/src/gui_nodes/gui_node_view_types.h similarity index 99% rename from src/gui_controls/gui_node_view_types.h rename to src/gui_nodes/gui_node_view_types.h index e491cb22..5a8583c1 100644 --- a/src/gui_controls/gui_node_view_types.h +++ b/src/gui_nodes/gui_node_view_types.h @@ -20,7 +20,7 @@ // Node-view (graph editor) data model. The caller owns one NodeView per view. -namespace tachyon +namespace tachyon::nodes { /// @addtogroup controls_nodes /// @{ diff --git a/src/gui_nodes/gui_nodes.cpp b/src/gui_nodes/gui_nodes.cpp new file mode 100644 index 00000000..37992dd2 --- /dev/null +++ b/src/gui_nodes/gui_nodes.cpp @@ -0,0 +1,127 @@ +#include + +#include +#include + +#include +#include +#include +#include + +namespace tachyon::nodes +{ + void Styles::Load(GUIApplication& app) + { + GUITheme& theme = app.theme; + StyleManager& styleManager = app.styleManager; + ITextSystem* textSystem = app.textSystem; + nodeFrameMenuStyleRef = theme.GetStyle("node-frame-menu"); + nodeViewOverlayDividerStyleRef = theme.GetStyle("node-view-overlay-divider"); + nodeStateTimeStyleRef = theme.GetStyle("node-state-time"); + nodeStateNestedMarkStyleRef = theme.GetStyle("node-state-nested-mark"); + nodeViewStyleRef = theme.GetStyle("node-view"); + nodeStyleRef = theme.GetStyle("node"); + nodeRerouteStyleRef = theme.GetStyle("node-reroute"); + nodeFrameStyleRef = theme.GetStyle("node-frame"); + nodeFrameBandStyleRef = theme.GetStyle("node-frame-band"); + nodeFrameTitleStyleRef = theme.GetStyle("node-frame-title"); + nodeFrameRenameStyleRef = theme.GetStyle("node-frame-rename"); + nodeTransitionLabelStyleRef = theme.GetStyle("node-transition-label"); + nodeTransitionRenameStyleRef = theme.GetStyle("node-transition-rename"); + nodeStateActiveStyleRef = theme.GetStyle("node-state-active"); + nodeStateEdgeStyleRef = theme.GetStyle("node-state-edge"); + nodeStateNestedStyleRef = theme.GetStyle("node-state-nested"); + nodeFramePortsStyleRef = theme.GetStyle("node-frame-ports"); + nodeFramePortStyleRef = theme.GetStyle("node-frame-port"); + nodeFramePortOutStyleRef = theme.GetStyle("node-frame-port-out"); + nodeHeaderStyleRef = theme.GetStyle("node-header"); + nodeHeaderStateStyleRef = theme.GetStyle("node-header-state"); + nodeStateStyleRef = theme.GetStyle("node-state"); + nodeCategoryStyleRef = theme.GetStyle("node-category"); + nodeTitleStyleRef = theme.GetStyle("node-title"); + nodeCaptionStyleRef = theme.GetStyle("node-caption"); + nodeViewOverlayStyleRef = theme.GetStyle("node-view-overlay"); + nodeViewOverlayButtonStyleRef = theme.GetStyle("node-view-overlay-button"); + nodeViewMinimapStyleRef = theme.GetStyle("node-view-minimap"); + nodeRowStyleRef = theme.GetStyle("node-row"); + nodeBodyCenterStyleRef = theme.GetStyle("node-body-center"); + nodeSocketStyleRef = theme.GetStyle("node-socket"); + lineYellowStyle = theme.VariableColor(styleManager, "--warn", color4f{ 1.0f, 0.8f, 0.2f, 1.0f }); + lineWhiteStyle = theme.VariableColor(styleManager, "--text-1", color4f{ 1.0f, 1.0f, 1.0f, 1.0f }); + nodeTransitionColor = theme.VariableColor(styleManager, "--text-3", color4f{ 0.56f, 0.59f, 0.65f, 1.0f }); + nodeTransitionHoverColor = theme.VariableColor(styleManager, "--text-1", color4f{ 0.91f, 0.92f, 0.94f, 1.0f }); + nodeTransitionSelectedColor = theme.VariableColor(styleManager, "--accent", color4f{ 0.42f, 0.61f, 1.0f, 1.0f }); + nodeInitialStateColor = theme.VariableColor(styleManager, "--text-1", color4f{ 0.91f, 0.92f, 0.94f, 1.0f }); + nodeTextLeftStyleRef = theme.GetStyle("node-text"); + nodeTextCenterStyleRef = theme.GetStyle("node-text-center"); + nodeTextRightStyleRef = theme.GetStyle("node-text-end"); + nodeControls = theme.regularControls; + nodeControls.number = theme.GetStyle("node-number-field"); + marqueeFillColorStyle = styleManager.RegisterColorStyle(ColorStyle::Create(color4f{ 0.3f, 0.6f, 1.0f, 0.15f })); + if (const LayoutStyle* p = styleManager.GetLayoutStyle(nodeSocketStyleRef.layoutStyleIndex); p && p->layoutData.width > 0) + socketSize = p->layoutData.width; + + nodeTints = {}; + auto tint = [&](const char* name, float& out) { + if (const CustomProperty* prop = theme.GetVariable(name); prop && prop->hasNumber && prop->dimCount == 1) + out = std::clamp(prop->number, 0.0f, 1.0f); + }; + tint("--node-header-tint", nodeTints.header); + tint("--node-header-line-tint", nodeTints.headerLine); + tint("--state-tint", nodeTints.state); + tint("--state-border-tint", nodeTints.stateBorder); + tint("--frame-fill-tint", nodeTints.frameFill); + tint("--frame-band-tint", nodeTints.frameBand); + tint("--frame-border-tint", nodeTints.frameBorder); + + // The grid: half a property row, so rows' edges and centers (the sockets) are on grid + // lines. The row lays the field out at its margin box, so the margin is included. + if (textSystem) + { + const StyleRef textbox = theme.regularControls.textbox; + const TextID probeID = textSystem->RegisterText(ID::Invalid(), "Mg", textbox, ElementState::None); + const LayoutStyle* tb = styleManager.GetLayoutStyle(textbox.layoutStyleIndex); + int32_t box = textSystem->GetTextMeasurement(probeID).minHeight; + if (tb) + box += tb->padding.Vertical() + tb->borderWidths.Vertical(); + float fieldHeight = float(std::max(1, box)); + if (tb) + fieldHeight += float(tb->margin.Vertical()); + nodeGridSize = int32_t(std::ceil(fieldHeight / 2.0f)); // one row is two grid cells + } + } + + const Styles& GetStyles(GUIApplication& app, Context& context) + { + if (context.stylesGeneration != app.StylesGeneration()) + { + context.styles.Load(app); + context.stylesGeneration = app.StylesGeneration(); + } + return context.styles; + } + + std::string SaveViewState(const NodeViewState& view) + { + const float3x2& t = view.transform; + JsonValue state = JsonValue::MakeObject(); + state.Set("transform", JsonFloatArray({ t.r0.x, t.r0.y, t.r0.z, t.r1.x, t.r1.y, t.r1.z })); + return state.Write(); + } + + bool RestoreViewState(NodeViewState& view, std::string_view state) + { + const std::optional object = ParseJsonObject(state); + float m[6]; + if (!object || !JsonFloats(*object, "transform", m)) + return false; + // A damaged state: a transform that can't be inverted (or isn't a number) would put + // the canvas nowhere. + const float det = m[0] * m[4] - m[1] * m[3]; + if (!std::all_of(std::begin(m), std::end(m), [](float v) { return std::isfinite(v); }) || std::fabs(det) < 1e-12f) + return false; + view.transform.r0 = float3{ m[0], m[1], m[2] }; + view.transform.r1 = float3{ m[3], m[4], m[5] }; + return true; + } +} diff --git a/src/gui_nodes/gui_nodes.h b/src/gui_nodes/gui_nodes.h new file mode 100644 index 00000000..d06d7f40 --- /dev/null +++ b/src/gui_nodes/gui_nodes.h @@ -0,0 +1,126 @@ +#pragma once + +// Nodes: the node view, a graph editor of nodes and wires, and of state machines. A library of +// its own on gui_controls, in namespace tachyon::nodes: each control is a free function that +// takes the application and a nodes::Context, which the app owns. +// +// nodes::Context nodesContext; // a member of the app class +// nodes::NodeView graph; +// +// nodes::RenderNodeView(*this, nodesContext, graph); + +#include +#include +#include + +#include +#include +#include + +namespace tachyon::nodes +{ + /// @addtogroup controls + /// @{ + + /// The node view's styles, colors and sizes, looked up in the theme after each load. + struct Styles + { + StyleRef nodeFrameMenuStyleRef {}; ///< a node frame's "..." button, at its title bar's end + StyleRef nodeViewOverlayDividerStyleRef {}; ///< the line before Fit in a node view's zoom bar + StyleRef nodeStateTimeStyleRef {}; ///< the pill under a state machine's active state: its time in it + StyleRef nodeStateNestedMarkStyleRef {}; ///< the mark at the end of a state holding a machine (its size) + StyleRef nodeViewStyleRef {}; ///< NodeView: the canvas + StyleRef nodeStyleRef {}; ///< single node container (vertical column with border + bg) + StyleRef nodeRerouteStyleRef {}; ///< a reroute node's square (the dot is drawn on it) + StyleRef nodeFrameStyleRef {}; ///< a frame's box (drawn behind the wires) + StyleRef nodeFrameBandStyleRef {}; ///< its title bar's band, over the top of the box + StyleRef nodeFrameTitleStyleRef {}; ///< the title on it + StyleRef nodeFrameRenameStyleRef {}; ///< the field over the title bar while renaming + StyleRef nodeTransitionLabelStyleRef {}; ///< a state machine transition's label: its text and its chip + StyleRef nodeTransitionRenameStyleRef {}; ///< the field over a transition's label while relabelling + StyleRef nodeStateActiveStyleRef {}; ///< the ring round the state a machine is in + StyleRef nodeStateEdgeStyleRef {}; ///< the ring round a state whose edge is hovered (a transition starts there) + StyleRef nodeStateNestedStyleRef {}; ///< the mark on a state that holds a machine of its own + StyleRef nodeFramePortsStyleRef {}; ///< a collapsed frame's row, a wire in and one out + StyleRef nodeFramePortStyleRef {}; ///< the name of the input on it + StyleRef nodeFramePortOutStyleRef {}; ///< the name of the output on it + StyleRef nodeHeaderStyleRef {}; ///< node title bar (distinct background, sits at top of node) + StyleRef nodeHeaderStateStyleRef {}; ///< a state machine's state: the title bar alone, no line under it + StyleRef nodeStateStyleRef {}; ///< a state machine's state: a node box with nothing under its title bar + StyleRef nodeCategoryStyleRef {}; ///< the category square in a node header + StyleRef nodeTitleStyleRef {}; ///< a node header's title + StyleRef nodeCaptionStyleRef {}; ///< a node header's category name, right-aligned + StyleRef nodeViewOverlayStyleRef {}; ///< panel floating over the node view (breadcrumb, zoom bar) + StyleRef nodeViewOverlayButtonStyleRef {}; ///< flat button in such a panel + StyleRef nodeViewMinimapStyleRef {}; ///< the node view's minimap + StyleRef nodeRowStyleRef {}; ///< node property row (socket | body | socket) + StyleRef nodeBodyCenterStyleRef {}; ///< centered body for full-body content (image previews) + StyleRef nodeSocketStyleRef {}; + VisualColorStyleIndex lineYellowStyle {}; ///< --warn + VisualColorStyleIndex lineWhiteStyle {}; ///< --text-1 + /// A state machine's transitions: an arrow, a hovered one, a selected one; and the mark + /// of its initial state. + VisualColorStyleIndex nodeTransitionColor {}; + VisualColorStyleIndex nodeTransitionHoverColor {}; + VisualColorStyleIndex nodeTransitionSelectedColor {}; + VisualColorStyleIndex nodeInitialStateColor {}; + VisualColorStyleIndex marqueeFillColorStyle {}; ///< selection-marquee fill (fixed translucent blue) + StyleRef nodeTextLeftStyleRef {}; ///< a text-only property's body, at the start (.node-text) + StyleRef nodeTextCenterStyleRef {}; ///< centered (.node-text-center) + StyleRef nodeTextRightStyleRef {}; ///< at the end (.node-text-end) + /// The controls in a node's rows: the regular ones, numbers in .node-number-field. + ControlStyles nodeControls {}; + /// How strongly a node view's colors show, each over what's under it (0 to 1): a node's + /// header and the line under it over --node-bg, a state's fill and border over + /// --node-bg, and a frame's box, title bar and border over the canvas. + /// --node-header-tint, --node-header-line-tint, --state-tint, --state-border-tint, + /// --frame-fill-tint, --frame-band-tint, --frame-border-tint. + struct NodeTints + { + float header = 0.24f, headerLine = 0.38f; + float state = 0.26f, stateBorder = 0.50f; + float frameFill = 0.07f, frameBand = 0.20f, frameBorder = 0.45f; + }; + NodeTints nodeTints {}; + /// The .node-socket box's size in pixels; the dot drawn and the insets on the border + /// come from it. + int socketSize = 12; + /// The grid's pitch in pixels: half a property row, so rows' edges and centers (the + /// sockets) are on grid lines. Nodes, wires and frames snap to it. + int32_t nodeGridSize = 0; + + /// Looks them all up in `app`'s theme, after it loads. + void Load(GUIApplication& app); + }; + + /// What the node views keep, the app's to own and pass to each of them. + struct Context + { + Styles styles; + uint32_t stylesGeneration = 0; ///< the app's StylesGeneration the styles were looked up at + /// How NodeText aligns: set around each property's renderBody, by its sockets. + TextAlign rowTextAlign = TextAlign::Start; + }; + + /// The node views' styles in `app`'s theme, looked up again after each theme load. + const Styles& GetStyles(GUIApplication& app, Context& context); + + // ---- Node view: self-contained graph editor ---- + // All state lives in the graph and its view state, so several views can coexist, + // of one graph too (a NodeViewState each). + /// Builds `view` (canvas, nodes, wires and overlays) in the current container: a NodeView, + /// or `{ graph, state }` for one of several views of a graph. + void RenderNodeView(GUIApplication& app, Context& context, NodeViewRef view); + + /// Text property body aligned by the row's sockets: left => left, right => right, + /// both => centre. Call inside NodeProperty::renderBody. + void NodeText(GUIApplication& app, Context& context, std::string_view text); + + /// A node view's state as text, for a panel to keep with its layout, and back (Panel::saveState and + /// Panel::restoreState). + /// A node view's pan and zoom (NodeViewState::transform). + std::string SaveViewState(const NodeViewState& view); + bool RestoreViewState(NodeViewState& view, std::string_view state); + + /// @} +} diff --git a/src/gui_controls/controls_grid_view.cpp b/src/gui_views/controls_grid_view.cpp similarity index 73% rename from src/gui_controls/controls_grid_view.cpp rename to src/gui_views/controls_grid_view.cpp index 04e7b714..a5595abd 100644 --- a/src/gui_controls/controls_grid_view.cpp +++ b/src/gui_views/controls_grid_view.cpp @@ -1,10 +1,11 @@ -#include -#include +#include +#include +#include #include #include -namespace tachyon +namespace tachyon::views { @@ -12,16 +13,16 @@ namespace tachyon // GridView // --------------------------------------------------------------------------- - bool GUIApplication::BeginGridView(ID id, int* selectedIndex, StyleRef style, + bool BeginGridView(GUIApplication& app, Context& context, ID id, int* selectedIndex, StyleRef style, MultiSelectState* multiSelect, ItemDragDropConfig* dragDrop, LayoutOverride&& constraints) { - m_gridViewState = {}; - m_gridViewState.containerID = id; - m_gridViewState.selectedIndex = selectedIndex; - m_gridViewState.multiSelect = multiSelect; - m_gridViewState.dragDrop = dragDrop; + context.gridViewState = {}; + context.gridViewState.containerID = id; + context.gridViewState.selectedIndex = selectedIndex; + context.gridViewState.multiSelect = multiSelect; + context.gridViewState.dragDrop = dragDrop; if (multiSelect) multiSelect->orderedItemIDs.clear(); @@ -32,14 +33,14 @@ namespace tachyon tachyon::Element container{}; container.id = id; container.styleRef = style; - container.state = guiStateManager.GetCurrentState(id); - container.eventHandler = [this, id, selIdx, multiSelect](ElementEvent&& event) -> bool + container.state = app.guiStateManager.GetCurrentState(id); + container.eventHandler = [&context, &app, id, selIdx, multiSelect](ElementEvent&& event) -> bool { switch (event.type) { case tachyon::EventType::MouseDown: if (!event.state.LeftPressed()) break; - TakeFocus(guiStateManager, event.id); + TakeFocus(app.guiStateManager, event.id); return true; case tachyon::EventType::KeyDown: @@ -47,10 +48,10 @@ namespace tachyon // F2 - rename the last-clicked item (multi-select grids). if (event.state.lastKey == tachyon::KeyCode::F2 && multiSelect) { - auto it = m_gridItemRenameByID.find(multiSelect->lastClickedID); - if (it != m_gridItemRenameByID.end() && it->second.renameBuf) + auto it = context.gridItemRenameByID.find(multiSelect->lastClickedID); + if (it != context.gridItemRenameByID.end() && it->second.renameBuf) { - (*m_renameSub).Start(multiSelect->lastClickedID, + context.rename.Start(multiSelect->lastClickedID, it->second.renameBuf, it->second.renameSeed); return true; } @@ -59,8 +60,8 @@ namespace tachyon if (!selIdx) break; // Compute grid dimensions from laid-out child rects - auto containerRef = elementStorage.FindElementRefByID(id); - auto childRange = elementStorage.GetChildRange(containerRef); + auto containerRef = app.elementStorage.FindElementRefByID(id); + auto childRange = app.elementStorage.GetChildRange(containerRef); int total = static_cast(childRange.Size()); if (total <= 0) break; @@ -68,11 +69,11 @@ namespace tachyon // wrapping included), not innerWidth / itemWidth. uint32_t childDepth = containerRef.depth + 1; int cols = 1; - if (const auto* firstRect = elementStorage.GetElementRectPtr(ElementRef{childDepth, childRange.begin})) + if (const auto* firstRect = app.elementStorage.GetElementRectPtr(ElementRef{childDepth, childRange.begin})) { while (cols < total) { - const auto* r = elementStorage.GetElementRectPtr( + const auto* r = app.elementStorage.GetElementRectPtr( ElementRef{ childDepth, childRange.begin + static_cast(cols) }); if (!r || r->rect.y != firstRect->rect.y) break; ++cols; @@ -104,32 +105,33 @@ namespace tachyon return false; }; - RegisterElement(std::move(container), std::move(constraints)); - RegisterTabStop(id); - VERIFY(elementStorage.BeginChildren()); + app.RegisterElement(std::move(container), std::move(constraints)); + app.RegisterTabStop(id); + VERIFY(app.elementStorage.BeginChildren()); return true; } - void GUIApplication::EndGridView() + void EndGridView(GUIApplication& app, Context& context) { - VERIFY(elementStorage.EndChildren()); - m_gridViewState = {}; + VERIFY(app.elementStorage.EndChildren()); + context.gridViewState = {}; } - bool GUIApplication::GridViewItem(ID id, const GUIContent& content, + bool GridViewItem(GUIApplication& app, Context& context, ID id, const GUIContent& content, tachyon::ElementState extraState, std::string* renameBuffer, StyleRef itemStyle, LayoutOverride&& constraints) { + const Styles& styles = GetStyles(app, context); const IconID icon = content.icon; const std::string_view text = content.text; - ShowContentTooltip(id, content); - int itemIndex = m_gridViewState.nextItemIndex++; - int* selectedIndex = m_gridViewState.selectedIndex; - MultiSelectState* multi = m_gridViewState.multiSelect; - tachyon::ID containerID = m_gridViewState.containerID; - ItemDragDropConfig* dd = m_gridViewState.dragDrop; - DoubleClickTracker* clickTracker = m_gridViewState.clickTracker; - tachyon::ID* pendingRename = m_gridViewState.pendingRenameClick; + app.ShowContentTooltip(id, content); + int itemIndex = context.gridViewState.nextItemIndex++; + int* selectedIndex = context.gridViewState.selectedIndex; + MultiSelectState* multi = context.gridViewState.multiSelect; + tachyon::ID containerID = context.gridViewState.containerID; + ItemDragDropConfig* dd = context.gridViewState.dragDrop; + DoubleClickTracker* clickTracker = context.gridViewState.clickTracker; + tachyon::ID* pendingRename = context.gridViewState.pendingRenameClick; bool selected = false; if (multi) @@ -137,52 +139,52 @@ namespace tachyon else if (selectedIndex) selected = *selectedIndex == itemIndex; - StyleRef style = (itemStyle != StyleRef{}) ? itemStyle : theme.gridViewItemStyleRef; + StyleRef style = (itemStyle != StyleRef{}) ? itemStyle : styles.gridViewItemStyleRef; // Record the rename binding for the F2 / Ctrl+Shift+Click / slow re-click triggers. if (renameBuffer) { - auto& info = m_gridItemRenameByID[id]; + auto& info = context.gridItemRenameByID[id]; info.renameBuf = renameBuffer; info.renameSeed.assign(text); } // Drop the rename when its editor lost focus (click-away cancel). - if (renameBuffer && (*m_renameSub).isActive && - (*m_renameSub).targetID == id && - !(*m_renameSub).firstFrame && - guiStateManager.Interaction().GetFocusedID() != id) + if (renameBuffer && context.rename.isActive && + context.rename.targetID == id && + !context.rename.firstFrame && + app.guiStateManager.Interaction().GetFocusedID() != id) { - (*m_renameSub).Cancel(); + context.rename.Cancel(); } // Renaming: the cell becomes [icon, one-line inline editor], laid out like the // item's icon placement. Not selectable / draggable while editing. - if (renameBuffer && (*m_renameSub).isActive && (*m_renameSub).targetID == id) + if (renameBuffer && context.rename.isActive && context.rename.targetID == id) { if (multi) multi->orderedItemIDs.push_back(id); const VisualTextStyle* vts = - styleManager.GetVisualTextStyle(style.visualTextStyleIndex, tachyon::ElementState::None); + app.styleManager.GetVisualTextStyle(style.visualTextStyleIndex, tachyon::ElementState::None); const bool iconBeside = vts && (vts->iconSide == IconSide::Left || vts->iconSide == IconSide::Right); - const int32_t iconSize = (vts && vts->iconSize > 0) ? vts->iconSize : styleManager.Px(16); + const int32_t iconSize = (vts && vts->iconSize > 0) ? vts->iconSize : app.styleManager.Px(16); // The parts' IDs under the item's own, so they don't depend on what came before. - [[maybe_unused]] const bool pushed = idManager.PushParent(id); - const tachyon::ID boxID = idManager.AllocateDynamicID("rename_box"); - const tachyon::ID iconElemID = idManager.AllocateDynamicID("rename_icon"); - if (pushed) (void)idManager.PopParent(); + [[maybe_unused]] const bool pushed = app.idManager.PushParent(id); + const tachyon::ID boxID = app.idManager.AllocateDynamicID("rename_box"); + const tachyon::ID iconElemID = app.idManager.AllocateDynamicID("rename_icon"); + if (pushed) (void)app.idManager.PopParent(); tachyon::Element box{}; box.id = boxID; - box.styleRef = iconBeside ? theme.gridViewRenameListItemStyleRef - : theme.gridViewRenameItemStyleRef; - box.state = guiStateManager.GetCurrentState(boxID); - auto boxRes = elementStorage.Add(std::move(box), std::move(constraints)); + box.styleRef = iconBeside ? styles.gridViewRenameListItemStyleRef + : styles.gridViewRenameItemStyleRef; + box.state = app.guiStateManager.GetCurrentState(boxID); + auto boxRes = app.elementStorage.Add(std::move(box), std::move(constraints)); VERIFY(boxRes.status); - VERIFY(windowRegistry.Add(boxRes.ref)); - VERIFY(elementStorage.BeginChildren()); + VERIFY(app.windowRegistry.Add(boxRes.ref)); + VERIFY(app.elementStorage.BeginChildren()); if (icon != IconID::Invalid) { @@ -190,37 +192,37 @@ namespace tachyon icn.id = iconElemID; icn.iconID = icon; icn.flags = tachyon::ElementFlags::NoInput; - icn.styleRef = theme.gridViewRenameIconStyleRef; - icn.state = guiStateManager.GetCurrentState(iconElemID); - auto icnRes = elementStorage.Add(std::move(icn), + icn.styleRef = styles.gridViewRenameIconStyleRef; + icn.state = app.guiStateManager.GetCurrentState(iconElemID); + auto icnRes = app.elementStorage.Add(std::move(icn), LayoutOverride{}.Size(Pixels{ iconSize }, Pixels{ iconSize }).NoGrow().NoShrink()); VERIFY(icnRes.status); - VERIFY(windowRegistry.Add(icnRes.ref)); + VERIFY(app.windowRegistry.Add(icnRes.ref)); } - TreeItemRenameCheck(id, renameBuffer, - iconBeside ? theme.treeTableTextEditStyleRef - : theme.gridViewRenameEditStyleRef); + TreeItemRenameCheck(app, context, id, renameBuffer, + iconBeside ? styles.treeTableTextEditStyleRef + : styles.gridViewRenameEditStyleRef); - VERIFY(elementStorage.EndChildren()); + VERIFY(app.elementStorage.EndChildren()); return false; } - if (selected) guiStateManager.Construction().PushSelected(); + if (selected) app.guiStateManager.Construction().PushSelected(); tachyon::Element item{}; item.id = id; - item.state = guiStateManager.GetCurrentState(id) | extraState; + item.state = app.guiStateManager.GetCurrentState(id) | extraState; // The item a drag would drop into stands out: shown as pressed (:active). - if (dd && dd->payloadType != 0 && guiStateManager.Drag().IsDropTargetFor(id, dd->payloadType) - && (!dd->canDrop || dd->canDrop(guiStateManager.Drag().GetPayloadValue(), id))) + if (dd && dd->payloadType != 0 && app.guiStateManager.Drag().IsDropTargetFor(id, dd->payloadType) + && (!dd->canDrop || dd->canDrop(app.guiStateManager.Drag().GetPayloadValue(), id))) item.state |= tachyon::ElementState::Active; item.styleRef = style; item.iconID = icon; - item.textID = textSystem->RegisterText(id, icon, text, style, item.state); + item.textID = app.textSystem->RegisterText(id, icon, text, style, item.state); - item.eventHandler = [this, containerID, id, itemIndex, selectedIndex, multi, dd, - clickTracker, pendingRename, onOpen = m_gridViewState.onOpen, + item.eventHandler = [&app, &context, containerID, id, itemIndex, selectedIndex, multi, dd, + clickTracker, pendingRename, onOpen = context.gridViewState.onOpen, wasSelected = selected, canRename = (renameBuffer != nullptr)] (ElementEvent&& event) -> bool { @@ -236,10 +238,10 @@ namespace tachyon // Ctrl+Shift+Click - start rename (same as table rows). if (canRename && ctrl && shift) { - auto it = m_gridItemRenameByID.find(id); - if (it != m_gridItemRenameByID.end() && it->second.renameBuf) + auto it = context.gridItemRenameByID.find(id); + if (it != context.gridItemRenameByID.end() && it->second.renameBuf) { - (*m_renameSub).Start(id, it->second.renameBuf, it->second.renameSeed); + context.rename.Start(id, it->second.renameBuf, it->second.renameSeed); if (clickTracker) clickTracker->Reset(); return true; } @@ -319,15 +321,15 @@ namespace tachyon *selectedIndex = itemIndex; } - TakeFocus(guiStateManager, containerID); - guiStateManager.Interaction().SetClicked(id); + TakeFocus(app.guiStateManager, containerID); + app.guiStateManager.Interaction().SetClicked(id); // Prime a pending drag (promoted once past the threshold). Inlined rather // than chaining MakeDragSourceHandler: Chain stops at the `return true` below. if (dd && dd->payloadType != 0) { uintptr_t payloadValue = dd->getPayload ? dd->getPayload(id) : 0; - guiStateManager.Drag().Begin(id, dd->payloadType, payloadValue, + app.guiStateManager.Drag().Begin(id, dd->payloadType, payloadValue, event.state.screenPos, std::any(), dd->visualizer); } @@ -338,12 +340,12 @@ namespace tachyon { if (!dd || dd->payloadType == 0) break; if ((event.state.buttons & tachyon::MouseButtons::Left) == tachyon::MouseButtons::None) break; - guiStateManager.Drag().UpdateFromInput(event.state); + app.guiStateManager.Drag().UpdateFromInput(event.state); // A press that became a drag doesn't rename on release, even dropped back on // the item: the drop ends the drag before the item sees its MouseUp. - if (pendingRename && *pendingRename == id && guiStateManager.Drag().IsDragging()) + if (pendingRename && *pendingRename == id && app.guiStateManager.Drag().IsDragging()) *pendingRename = tachyon::ID::Invalid(); - return guiStateManager.Drag().GetDraggedID() == id; + return app.guiStateManager.Drag().GetDraggedID() == id; } case tachyon::EventType::MouseUp: @@ -353,12 +355,12 @@ namespace tachyon { *pendingRename = tachyon::ID::Invalid(); // A promoted drag supersedes the armed rename. - if (!guiStateManager.Drag().IsDragging()) + if (!app.guiStateManager.Drag().IsDragging()) { - auto it = m_gridItemRenameByID.find(id); - if (it != m_gridItemRenameByID.end() && it->second.renameBuf) + auto it = context.gridItemRenameByID.find(id); + if (it != context.gridItemRenameByID.end() && it->second.renameBuf) { - (*m_renameSub).Start(id, it->second.renameBuf, it->second.renameSeed); + context.rename.Start(id, it->second.renameBuf, it->second.renameSeed); return true; } } @@ -389,12 +391,12 @@ namespace tachyon })); } - auto addRes = elementStorage.Add(std::move(item), std::move(constraints)); + auto addRes = app.elementStorage.Add(std::move(item), std::move(constraints)); VERIFY(addRes.status); - VERIFY(windowRegistry.Add(addRes.ref)); + VERIFY(app.windowRegistry.Add(addRes.ref)); - if (selected) guiStateManager.Construction().PopSelected(); - return guiStateManager.Interaction().HasBeenClicked(id); + if (selected) app.guiStateManager.Construction().PopSelected(); + return app.guiStateManager.Interaction().HasBeenClicked(id); } // --------------------------------------------------------------------------- @@ -402,7 +404,7 @@ namespace tachyon // Only visible rows are emitted; spacers stand in for the rest so the // content height (and scrollbar) spans the whole grid. // --------------------------------------------------------------------------- - void GUIApplication::VirtualGridView(ID id, GridViewVirtualState& vstate, + void VirtualGridView(GUIApplication& app, Context& context, ID id, GridViewVirtualState& vstate, int itemCount, int2 cellSize, const std::function& generateItem, int* selectedIndex, @@ -412,26 +414,27 @@ namespace tachyon StyleRef rowStyle, LayoutOverride&& constraints) { - if (scrollStyle == StyleRef{}) scrollStyle = theme.gridViewScrollStyleRef; - if (rowStyle == StyleRef{}) rowStyle = theme.gridViewRowStyleRef; + const Styles& styles = GetStyles(app, context); + if (scrollStyle == StyleRef{}) scrollStyle = styles.gridViewScrollStyleRef; + if (rowStyle == StyleRef{}) rowStyle = styles.gridViewRowStyleRef; // Per-frame state read by GridViewItem (selection / drag-drop / id). - m_gridViewState = {}; - m_gridViewState.containerID = id; - m_gridViewState.selectedIndex = selectedIndex; - m_gridViewState.multiSelect = multiSelect; - m_gridViewState.dragDrop = dragDrop; - m_gridViewState.clickTracker = &vstate.internal.itemClickTracker; - m_gridViewState.pendingRenameClick = &vstate.internal.pendingRenameClick; - m_gridViewState.onOpen = &vstate.onOpen; + context.gridViewState = {}; + context.gridViewState.containerID = id; + context.gridViewState.selectedIndex = selectedIndex; + context.gridViewState.multiSelect = multiSelect; + context.gridViewState.dragDrop = dragDrop; + context.gridViewState.clickTracker = &vstate.internal.itemClickTracker; + context.gridViewState.pendingRenameClick = &vstate.internal.pendingRenameClick; + context.gridViewState.onOpen = &vstate.onOpen; if (multiSelect) multiSelect->orderedItemIDs.clear(); // Wheel-scroll and the scrollbar both need the scroll-offset handle to exist. - auto& scrollManagement = guiStateManager.GetScrollManagement(); + auto& scrollManagement = app.guiStateManager.GetScrollManagement(); (void)scrollManagement.GetOrCreateScrollOffsetHandle(id); - const LayoutStyle* rowLayout = styleManager.GetLayoutStyle(rowStyle.layoutStyleIndex); + const LayoutStyle* rowLayout = app.styleManager.GetLayoutStyle(rowStyle.layoutStyleIndex); const int kGap = rowLayout ? rowLayout->layoutData.flex.gap : 0; constexpr int kBufferRows = 2; @@ -447,7 +450,7 @@ namespace tachyon int availW = viewW; int cols = colsForWidth(availW); int totalRows = (itemCount + cols - 1) / cols; - const int scrollbarThickness = theme.scrollbarThickness; + const int scrollbarThickness = app.theme.scrollbarThickness; if (static_cast(totalRows) * rowStride > viewH && viewW > scrollbarThickness) { availW = viewW - scrollbarThickness; @@ -474,7 +477,7 @@ namespace tachyon if (scrollManagement.IsScrollOffsetHandleValid(handle)) scrollY = -scrollManagement.GetScrollOffset(handle).y; // negative offset = scrolled down } - const auto range = tachyon::TableHelpers::ComputeVirtualRowRange( + const auto range = tachyon::views::TableHelpers::ComputeVirtualRowRange( scrollY, viewH, rowStride, totalRows, kBufferRows); const int firstRow = range.firstVisible; const int lastRow = range.lastVisible; @@ -483,15 +486,15 @@ namespace tachyon tachyon::Element container{}; container.id = id; container.styleRef = scrollStyle; - container.state = guiStateManager.GetCurrentState(id); + container.state = app.guiStateManager.GetCurrentState(id); container.eventHandler = - [this, selectedIndex, multiSelect, itemCount, vsPtr = &vstate](ElementEvent&& event) -> bool + [&context, &app, selectedIndex, multiSelect, itemCount, vsPtr = &vstate](ElementEvent&& event) -> bool { switch (event.type) { case tachyon::EventType::MouseDown: if (!event.state.LeftPressed()) break; - TakeFocus(guiStateManager, event.id); + TakeFocus(app.guiStateManager, event.id); return true; case tachyon::EventType::KeyDown: @@ -504,12 +507,12 @@ namespace tachyon target = multiSelect->lastClickedID; else if (selectedIndex && *selectedIndex >= 0 && vsPtr->internal.itemsRangeID != tachyon::ID::Invalid()) - target = idManager.GetSubID(vsPtr->internal.itemsRangeID, + target = app.idManager.GetSubID(vsPtr->internal.itemsRangeID, static_cast(*selectedIndex)); - auto it = m_gridItemRenameByID.find(target); - if (it != m_gridItemRenameByID.end() && it->second.renameBuf) + auto it = context.gridItemRenameByID.find(target); + if (it != context.gridItemRenameByID.end() && it->second.renameBuf) { - (*m_renameSub).Start(target, it->second.renameBuf, it->second.renameSeed); + context.rename.Start(target, it->second.renameBuf, it->second.renameSeed); return true; } break; @@ -524,7 +527,7 @@ namespace tachyon target = multiSelect->selectedIDs.count(multiSelect->lastClickedID) ? multiSelect->lastClickedID : tachyon::ID::Invalid(); else if (selectedIndex && *selectedIndex >= 0 && *selectedIndex < itemCount && vsPtr->internal.itemsRangeID != tachyon::ID::Invalid()) - target = idManager.GetSubID(vsPtr->internal.itemsRangeID, static_cast(*selectedIndex)); + target = app.idManager.GetSubID(vsPtr->internal.itemsRangeID, static_cast(*selectedIndex)); if (target == tachyon::ID::Invalid()) break; vsPtr->onOpen(target); @@ -547,7 +550,7 @@ namespace tachyon // Scroll the new item's row into view; it may lie outside the // virtualization window, so work from the row pitch, not an element. - auto& sm = guiStateManager.GetScrollManagement(); + auto& sm = app.guiStateManager.GetScrollManagement(); const auto handle = sm.GetOrCreateScrollOffsetHandle(event.id); const int2 offset = sm.GetScrollOffset(handle); const int top = (next / navCols) * vsPtr->internal.rowStride; @@ -575,15 +578,15 @@ namespace tachyon return !dd->canDrop || dd->canDrop(payloadValue, id); })); } - RegisterElement(std::move(container), std::move(constraints)); - RegisterTabStop(id); + app.RegisterElement(std::move(container), std::move(constraints)); + app.RegisterTabStop(id); // Capture this frame's viewport for next frame's column / row-window math. - const auto containerRef = elementStorage.FindElementRefByID(id); + const auto containerRef = app.elementStorage.FindElementRefByID(id); if (containerRef.IsValid()) { GridViewVirtualState* vs = &vstate; - (void)elementStorage.AddPostLayout(containerRef, + (void)app.elementStorage.AddPostLayout(containerRef, [vs](tachyon::PostLayoutContext& plctx) { const auto inner = plctx.ElementInnerRect(); @@ -594,15 +597,15 @@ namespace tachyon // Scope internal dynamic IDs under `id`: the emitted row count varies with scroll and // would otherwise shift the IDs of later siblings. The scrollbar ID comes first so it's stable. - (void)idManager.PushParent(id); - const tachyon::ID scrollbarID = idManager.AllocateDynamicID("_grid_vscroll"); + (void)app.idManager.PushParent(id); + const tachyon::ID scrollbarID = app.idManager.AllocateDynamicID("_grid_vscroll"); // One ranged ID spans all items; an item's ID is the sub-ID at its dataset index, // so it's stable across frames and the index is recoverable from it. const uint64_t prevItemsHash = vstate.internal.itemsRangeID != tachyon::ID::Invalid() ? vstate.internal.itemsRangeID.value.rangedParts.hashValue : 0; const tachyon::ID itemsRangeID = (itemCount > 0) - ? idManager.AllocateRangedID(static_cast(itemCount), "_grid_items") + ? app.idManager.AllocateRangedID(static_cast(itemCount), "_grid_items") : tachyon::ID::Invalid(); vstate.internal.itemsRangeID = itemsRangeID; // read by the container's F2 handler @@ -625,19 +628,19 @@ namespace tachyon if (selectedIndex && *selectedIndex >= itemCount) *selectedIndex = itemCount - 1; - VERIFY(elementStorage.BeginChildren()); + VERIFY(app.elementStorage.BeginChildren()); // Transparent, non-interactive block reserving the height of the rows // scrolled off above / below the visible window. - auto emitSpacer = [this](int height) + auto emitSpacer = [&app](int height) { if (height <= 0) return; - const tachyon::ID spacerID = idManager.AllocateDynamicID("_grid_spacer"); + const tachyon::ID spacerID = app.idManager.AllocateDynamicID("_grid_spacer"); tachyon::Element spacer{}; spacer.id = spacerID; - spacer.styleRef = theme.emptyHorzStyleRef; + spacer.styleRef = app.theme.emptyHorzStyleRef; spacer.flags = tachyon::ElementFlags::NoInput; - RegisterElement(std::move(spacer), + app.RegisterElement(std::move(spacer), tachyon::LayoutOverride{}.Height(Pixels{ height }).NoGrow().NoShrink()); }; @@ -645,13 +648,13 @@ namespace tachyon for (int r = firstRow; r < lastRow; ++r) { - const tachyon::ID rowID = idManager.AllocateDynamicID("_grid_row"); + const tachyon::ID rowID = app.idManager.AllocateDynamicID("_grid_row"); tachyon::Element row{}; row.id = rowID; row.styleRef = rowStyle; - RegisterElement(std::move(row), + app.RegisterElement(std::move(row), tachyon::LayoutOverride{}.Height(Pixels{ rowStride }).NoGrow().NoShrink()); - VERIFY(elementStorage.BeginChildren()); + VERIFY(app.elementStorage.BeginChildren()); const int base = r * cols; for (int c = 0; c < cols; ++c) { @@ -661,20 +664,20 @@ namespace tachyon vstate.cellStretchedW = std::max(cellW, colBound(c + 1) - colBound(c)); // GridViewItem reads nextItemIndex as the dataset index, so // per-item selection and drag payloads map to the real index. - m_gridViewState.nextItemIndex = idx; - const tachyon::ID itemID = idManager.GetSubID(itemsRangeID, static_cast(idx)); + context.gridViewState.nextItemIndex = idx; + const tachyon::ID itemID = app.idManager.GetSubID(itemsRangeID, static_cast(idx)); generateItem(idx, itemID); } - VERIFY(elementStorage.EndChildren()); + VERIFY(app.elementStorage.EndChildren()); } emitSpacer((totalRows - lastRow) * rowStride); // Vertical scrollbar overlay - self-hides when there's no overflow. - VerticalScrollbar(scrollbarID, id); + app.VerticalScrollbar(scrollbarID, id); - VERIFY(elementStorage.EndChildren()); - (void)idManager.PopParent(); - m_gridViewState = {}; + VERIFY(app.elementStorage.EndChildren()); + (void)app.idManager.PopParent(); + context.gridViewState = {}; } } \ No newline at end of file diff --git a/src/gui_controls/controls_settings.cpp b/src/gui_views/controls_settings.cpp similarity index 66% rename from src/gui_controls/controls_settings.cpp rename to src/gui_views/controls_settings.cpp index df668c2b..3ceabada 100644 --- a/src/gui_controls/controls_settings.cpp +++ b/src/gui_views/controls_settings.cpp @@ -1,17 +1,19 @@ -#include +#include +#include -namespace tachyon +namespace tachyon::views { // Settings panel: page tree | sizer | selected page's render callback. // SettingsPanelState owns only selection + tree width; page content state // belongs to the application and is captured by each render lambda. - void GUIApplication::RenderSettingsPanel(SettingsPanelState& state) + void RenderSettingsPanel(GUIApplication& app, Context& context, SettingsPanelState& state) { + const Styles& styles = GetStyles(app, context); // flexFillRow (flex-basis:0 + grow:1) bounds the split to the panel height so an // overflowing page scrolls inside its own viewport. Must hold down the whole chain. - BeginHorizontal(idManager.AllocateDynamicID(), - theme.flexFillRowStyleRef, + app.BeginHorizontal(app.idManager.AllocateDynamicID(), + app.theme.flexFillRowStyleRef, tachyon::LayoutOverride::Auto().FlexGrow(1)); // Left: flat page tree. Selection lives on internal.tableState as sub-range row IDs and is @@ -48,44 +50,44 @@ namespace tachyon if (selFlat >= 0 && state.internal.tableState.internal.rowsRangeID != tachyon::ID::Invalid()) { - const tachyon::ID expected = idManager.GetSubID( + const tachyon::ID expected = app.idManager.GetSubID( state.internal.tableState.internal.rowsRangeID, static_cast(selFlat)); if (state.internal.tableState.selectedRowID != expected) state.internal.tableState.selectedRowID = expected; } - const tachyon::ID treeID = idManager.AllocateDynamicID(); - VirtualTreeView(treeID, state.internal.rows, state.internal.visibleIdx, - state.internal.tableState, theme.settingsPageSelectionRef, + const tachyon::ID treeID = app.idManager.AllocateDynamicID(); + VirtualTreeView(app, context, treeID, state.internal.rows, state.internal.visibleIdx, + state.internal.tableState, styles.settingsPageSelectionRef, tachyon::LayoutOverride::Auto().FixedWidth(state.treeWidth).NoGrow(), state.header); } // Middle: draggable sizer, drawn as a 1px line. { - tachyon::ID sizerID = idManager.AllocateDynamicID(); + tachyon::ID sizerID = app.idManager.AllocateDynamicID(); tachyon::Element sizer{}; sizer.id = sizerID; - sizer.styleRef = theme.settingsSizerStyleRef; - sizer.state = guiStateManager.GetCurrentState(sizerID); + sizer.styleRef = styles.settingsSizerStyleRef; + sizer.state = app.guiStateManager.GetCurrentState(sizerID); sizer.eventHandler = tachyon::MakeHorizontalSizerHandler( - guiStateManager, elementStorage, state.treeWidth.value, 120, 500, nullptr, nullptr, false, styleManager.GetUIScale()); - auto sRes = elementStorage.Add(std::move(sizer), tachyon::LayoutOverride::FixedWidth(4)); + app.guiStateManager, app.elementStorage, state.treeWidth.value, 120, 500, nullptr, nullptr, false, app.styleManager.GetUIScale()); + auto sRes = app.elementStorage.Add(std::move(sizer), tachyon::LayoutOverride::FixedWidth(4)); VERIFY(sRes.status); - VERIFY(windowRegistry.Add(sRes.ref)); + VERIFY(app.windowRegistry.Add(sRes.ref)); } // Right: page content (dock-content layout plus left padding off the sizer). - tachyon::ID contentID = idManager.AllocateDynamicID(); + tachyon::ID contentID = app.idManager.AllocateDynamicID(); tachyon::Element content{}; content.id = contentID; - content.styleRef = theme.settingsPageStyleRef; - content.state = guiStateManager.GetCurrentState(contentID); - auto cRes = elementStorage.Add(std::move(content), tachyon::LayoutOverride::Auto().FlexGrow(1)); + content.styleRef = styles.settingsPageStyleRef; + content.state = app.guiStateManager.GetCurrentState(contentID); + auto cRes = app.elementStorage.Add(std::move(content), tachyon::LayoutOverride::Auto().FlexGrow(1)); VERIFY(cRes.status); - VERIFY(windowRegistry.Add(cRes.ref)); - VERIFY(elementStorage.BeginChildren()); + VERIFY(app.windowRegistry.Add(cRes.ref)); + VERIFY(app.elementStorage.BeginChildren()); // Render the selected page; a stale selection renders nothing. for (const auto& page : state.pages) @@ -97,7 +99,7 @@ namespace tachyon } } - VERIFY(elementStorage.EndChildren()); // content - EndHorizontal(); // split + VERIFY(app.elementStorage.EndChildren()); // content + app.EndHorizontal(); // split } } \ No newline at end of file diff --git a/src/gui_views/controls_table.cpp b/src/gui_views/controls_table.cpp new file mode 100644 index 00000000..54461384 --- /dev/null +++ b/src/gui_views/controls_table.cpp @@ -0,0 +1,125 @@ +#include +// Public table API: BeginTable/EndTable + BeginRow/EndRow. Thin recording +// shell - the real work happens when EndTable hands the recorded cells to +// VirtualTable (controls_table_virtual.cpp). +// +// Cell record-builders live in controls_table_cells.cpp; event-handler +// builders in controls_table_handlers.cpp; shared helpers in +// controls_table_internal.h. + +#include + +#include +#include + +namespace tachyon::views +{ + using namespace tachyon::views::TableInternal; + + // BeginTable opens a recording. Cell(app, context)/TreeCell(app, context) push records onto + // context.tableEmit->columnCells; EndTable hands the populated optional to + // VirtualTable, which drains them per row. + bool BeginTable(GUIApplication&, Context& context, ID id, VirtualTableColumn* columns, size_t columnCount, + TableState& state, StyleRef style, + LayoutOverride&& constraints) + { + context.outerTableEmits.push_back(std::move(context.tableEmit)); + context.tableEmit.emplace(); + context.tableEmit->containerID = id; + context.tableEmit->columns = columns; + context.tableEmit->columnCount = columnCount; + context.tableEmit->userState = &state; + context.tableEmit->style = style; + context.tableEmit->constraints = std::move(constraints); + context.tableEmit->isRecording = true; + context.tableEmit->columnCells.assign(columnCount, {}); + + // Lazy-init persisted widths. + if (state.columnWidths.size() != columnCount) + { + state.columnWidths.assign(columnCount, 0); + for (size_t c = 0; c < columnCount; c++) + state.columnWidths[c] = columns[c].column.initialWidth.value; + } + + // Clamp persisted selectedColumn. + if (columnCount == 0) + state.selectedColumn = 0; + else if (state.selectedColumn < 0 || state.selectedColumn >= int(columnCount)) + state.selectedColumn = std::clamp(state.selectedColumn, 0, int(columnCount) - 1); + + // Reset per-column scratch on the user-owned VirtualTableColumn array. + // Cell(app, context)/TreeCell(app, context) grow internal.maxContentWidth during replay. + for (size_t c = 0; c < columnCount; c++) + { + columns[c].internal.maxContentWidth = 0; + columns[c].internal.headerRef = tachyon::ElementRef::Invalid(); + columns[c].internal.dragOffsetX = 0; + } + + // Reset per-frame maps for TreeCell; clear() keeps the buckets allocated. + if (state.internal.treeRowInfo) state.internal.treeRowInfo->clear(); + + return true; + } + + + void EndTable(GUIApplication& app, Context& context) + { + if (!context.tableEmit.has_value() || !context.tableEmit->isRecording) + { + app.ReportMisuse("GUIApplication: EndTable without BeginTable (ignored)"); + return; + } + TableState& state = *context.tableEmit->userState; + VirtualTableColumn* columns = context.tableEmit->columns; + const size_t columnCount = context.tableEmit->columnCount; + const tachyon::ID containerID = context.tableEmit->containerID; + const StyleRef style = context.tableEmit->style; + tachyon::LayoutOverride constraints = std::move(context.tableEmit->constraints); + const int rowCount = context.tableEmit->rowCount; + const auto recorded = std::move(context.tableEmit->columnCells); + + // Replay the recorded cells through the same per-column path a + // direct VirtualTable caller drives with its own generateCell. + // The lambdas point into `recorded`, which outlives the call. + for (size_t c = 0; c < columnCount; c++) + { + columns[c].generateCell = [cells = &recorded[c]](int row) + { + if (row < 0 || size_t(row) >= cells->size()) return; + if (const auto& replay = (*cells)[size_t(row)]) replay(); + }; + } + + VirtualTable(app, context, containerID, state, std::span(columns, columnCount), + rowCount, /*rowHeight*/0, style, std::move(constraints)); + + for (size_t c = 0; c < columnCount; c++) + columns[c].generateCell = nullptr; + } + + + bool BeginRow(GUIApplication& app, Context& context) + { + if (!context.tableEmit.has_value()) + { + app.ReportMisuse("GUIApplication: BeginRow outside a table (ignored)"); + return true; + } + context.tableEmit->currentCol = 0; + context.tableEmit->rowCount++; + return true; + } + + + void EndRow(GUIApplication& app, Context& context) + { + if (!context.tableEmit.has_value()) + { + app.ReportMisuse("GUIApplication: EndRow outside a table (ignored)"); + return; + } + context.tableEmit->currentCol = 0; + } +} diff --git a/src/gui_controls/controls_table_cells.cpp b/src/gui_views/controls_table_cells.cpp similarity index 71% rename from src/gui_controls/controls_table_cells.cpp rename to src/gui_views/controls_table_cells.cpp index 206a68f7..184a2829 100644 --- a/src/gui_controls/controls_table_cells.cpp +++ b/src/gui_views/controls_table_cells.cpp @@ -1,20 +1,21 @@ +#include // Body cells: -// - Cell(text), Cell(lambda), TreeCell - called from a column's generateCell; +// - Cell(app, context, text), Cell(app, context, lambda), TreeCell - called from a column's generateCell; // allocate IDs, resolve selection, and emit into the open body section. // - EmitDirectCell{Text,Custom,Tree} - emit one cell element (plus children). // // Header cells, row backdrops, sizers and the surrounding section/scrollbar // geometry live in controls_table_virtual.cpp. -#include "controls_table_internal.h" +#include #include #include #include -namespace tachyon +namespace tachyon::views { - using namespace tachyon::TableInternal; + using namespace tachyon::views::TableInternal; namespace { @@ -43,7 +44,7 @@ namespace tachyon // Recording mode: store one replay closure at (currentCol, current // row), padding skipped cells, then advance to the next column. // EndTable replays the closures through VirtualTable's row loop. - void RecordReplayCell(tachyon::TableEmit& emit, std::function replay) + void RecordReplayCell(tachyon::views::TableEmit& emit, std::function replay) { if (emit.rowCount <= 0) { @@ -65,15 +66,16 @@ namespace tachyon // ---- Tree-cell child emitters: each emits one flex-row child of the tree cell ---- // Indent spacer (depth>0). Pushes arrow/icon/text rightward. - void EmitTreeCellIndent(GUIApplication& app, int depth) + void EmitTreeCellIndent(GUIApplication& app, Context& context, int depth) { + const Styles& styles = GetStyles(app, context); if (depth <= 0) return; tachyon::Element spacer{}; spacer.id = app.idManager.AllocateDynamicID(); - spacer.styleRef = app.theme.treeTableIndentStyleRef; + spacer.styleRef = styles.treeTableIndentStyleRef; spacer.flags = tachyon::ElementFlags::NoInput; auto res = app.elementStorage.Add(std::move(spacer), - tachyon::LayoutOverride::FixedWidth(Pixels{ depth * app.theme.treeTableIndent })); + tachyon::LayoutOverride::FixedWidth(Pixels{ depth * styles.treeTableIndent })); VERIFY(res.status); VERIFY(app.windowRegistry.Add(res.ref)); } @@ -81,14 +83,15 @@ namespace tachyon // Arrow (branch, isOpen set) or invisible spacer (leaf). // Both use the arrow style's width so text-column X is the same on branch + leaf rows. // The arrow uses a flex wrapper + inner glyph for a larger hit target. - void EmitTreeCellArrowOrLeafSpacer(GUIApplication& app, TreeOpenRef isOpen) + void EmitTreeCellArrowOrLeafSpacer(GUIApplication& app, Context& context, TreeOpenRef isOpen) { + const Styles& styles = GetStyles(app, context); if (isOpen) { tachyon::ID arrowID = app.idManager.AllocateDynamicID(); tachyon::Element arrow{}; arrow.id = arrowID; - arrow.styleRef = app.theme.treeTableArrowStyleRef; + arrow.styleRef = styles.treeTableArrowStyleRef; arrow.state = app.guiStateManager.GetCurrentState(arrowID); arrow.eventHandler = [isOpen](ElementEvent&& event) -> bool { if (event.type == tachyon::EventType::MouseDown && event.state.LeftPressed()) @@ -104,18 +107,18 @@ namespace tachyon tachyon::ID glyphID = app.idManager.AllocateDynamicID(); tachyon::Element glyph{}; glyph.id = glyphID; - glyph.styleRef = app.theme.treeTableArrowGlyphStyleRef; + glyph.styleRef = styles.treeTableArrowGlyphStyleRef; glyph.flags = tachyon::ElementFlags::NoInput; glyph.state = app.guiStateManager.GetCurrentState(glyphID); // Explicit size - the arrow SVG is 8x8 intrinsic. - const float glyphSize = static_cast(app.theme.treeTableArrowGlyphSize); + const float glyphSize = static_cast(styles.treeTableArrowGlyphSize); tachyon::ContentRun arrowRun[] = { { .type = tachyon::ContentRun::Icon, .iconID = (isOpen.IsOpen() ? app.theme.treeArrowDown : app.theme.treeArrowRight), .iconWidth = glyphSize, .iconHeight = glyphSize } }; glyph.textID = app.textSystem->RegisterRichText(glyphID, arrowRun, - app.theme.treeTableArrowGlyphStyleRef, glyph.state); + styles.treeTableArrowGlyphStyleRef, glyph.state); auto gRes = app.elementStorage.Add(std::move(glyph), tachyon::LayoutOverride::Auto()); VERIFY(gRes.status); VERIFY(app.windowRegistry.Add(gRes.ref)); @@ -126,7 +129,7 @@ namespace tachyon { tachyon::Element spacer{}; spacer.id = app.idManager.AllocateDynamicID(); - spacer.styleRef = app.theme.treeTableArrowStyleRef; + spacer.styleRef = styles.treeTableArrowStyleRef; spacer.flags = tachyon::ElementFlags::NoInput; auto res = app.elementStorage.Add(std::move(spacer), tachyon::LayoutOverride{}); VERIFY(res.status); @@ -138,24 +141,25 @@ namespace tachyon // icon is hittable: a double-click toggles the branch. Single // clicks return false so the row backdrop's selection / drag-prime still // sees them. - void EmitTreeCellIcon(GUIApplication& app, IconID icon, TreeOpenRef isOpen, - tachyon::DoubleClickTracker* tracker) + void EmitTreeCellIcon(GUIApplication& app, Context& context, IconID icon, TreeOpenRef isOpen, + DoubleClickTracker* tracker) { + const Styles& styles = GetStyles(app, context); if (icon == IconID::Invalid) return; tachyon::ID iconElemID = app.idManager.AllocateDynamicID(); tachyon::Element iconElem{}; iconElem.id = iconElemID; - iconElem.styleRef = app.theme.treeTableIconStyleRef; + iconElem.styleRef = styles.treeTableIconStyleRef; const bool hittable = static_cast(isOpen); iconElem.state = app.guiStateManager.GetCurrentState(iconElemID); if (!hittable) iconElem.flags |= tachyon::ElementFlags::NoInput; - const float iconSize = static_cast(app.theme.treeTableIconSize); + const float iconSize = static_cast(styles.treeTableIconSize); tachyon::ContentRun iconRun[] = { { .type = tachyon::ContentRun::Icon, .iconID = icon, .iconWidth = iconSize, .iconHeight = iconSize } }; iconElem.textID = app.textSystem->RegisterRichText(iconElemID, iconRun, - app.theme.treeTableIconStyleRef, iconElem.state); + styles.treeTableIconStyleRef, iconElem.state); if (hittable) { iconElem.eventHandler = [isOpen, tracker](tachyon::ElementEvent&& event) -> bool @@ -177,39 +181,40 @@ namespace tachyon VERIFY(app.windowRegistry.Add(res.ref)); } - void GUIApplication::Cell(std::string_view text) + void Cell(GUIApplication& app, Context& context, std::string_view text) { - if (!m_tableEmit.has_value()) + const Styles& styles = GetStyles(app, context); + if (!context.tableEmit.has_value()) { - ReportMisuse("GUIApplication: a table cell outside a table (ignored)"); + app.ReportMisuse("GUIApplication: a table cell outside a table (ignored)"); return; } - if (m_tableEmit->isRecording) + if (context.tableEmit->isRecording) { - RecordReplayCell(*m_tableEmit, [this, text = std::string(text)] - { Cell(std::string_view(text)); }); + RecordReplayCell(*context.tableEmit, [&app, text = std::string(text), &context] + { Cell(app, context, std::string_view(text)); }); return; } - const int c = CurrentCellCol(); - TableEmit& emit = *m_tableEmit; + const int c = CurrentCellCol(app, context); + TableEmit& emit = *context.tableEmit; TableState* state = emit.userState; const bool cellMode = emit.cellMode; const tachyon::ID rowID = emit.currentRowID; const StyleRef columnStyle = emit.columns[c].column.cellStyle; const StyleRef styleRef = (columnStyle.layoutStyleIndex != LayoutStyleIndex::Invalid) ? columnStyle : (emit.cellStyleRef.layoutStyleIndex != LayoutStyleIndex::Invalid) ? emit.cellStyleRef - : theme.tableCellStyleRef; + : styles.tableCellStyleRef; - const tachyon::ID cellID = idManager.AllocateDynamicID(); + const tachyon::ID cellID = app.idManager.AllocateDynamicID(); auto [cellState, cellSelected] = ComputeCellSelectionBits( - guiStateManager, state, cellID, rowID, c, cellMode); + app.guiStateManager, state, cellID, rowID, c, cellMode); const tachyon::ElementFlags cellFlags = cellMode ? tachyon::ElementFlags::None : tachyon::ElementFlags::NoInput; - const tachyon::TextID textID = textSystem->RegisterText( + const tachyon::TextID textID = app.textSystem->RegisterText( cellID, text, styleRef, cellState); - const int32_t cellW = textSystem->GetTextMeasurement(textID).maxWidth; + const int32_t cellW = app.textSystem->GetTextMeasurement(textID).maxWidth; emit.columns[c].internal.maxContentWidth = std::max(emit.columns[c].internal.maxContentWidth, cellW); @@ -220,7 +225,7 @@ namespace tachyon cellHandler = emit.sharedCellHandler; } - EmitDirectCellText(emit.columns[c], emit, + EmitDirectCellText(app, emit.columns[c], emit, cellID, cellState, cellFlags, styleRef, std::move(cellHandler), textID, c, emit.directColStart, @@ -228,28 +233,29 @@ namespace tachyon } - void GUIApplication::Cell(std::function emit_fn) + void Cell(GUIApplication& app, Context& context, std::function emit_fn) { - if (!m_tableEmit.has_value()) + const Styles& styles = GetStyles(app, context); + if (!context.tableEmit.has_value()) { - ReportMisuse("GUIApplication: a table cell outside a table (ignored)"); + app.ReportMisuse("GUIApplication: a table cell outside a table (ignored)"); return; } - if (m_tableEmit->isRecording) + if (context.tableEmit->isRecording) { - RecordReplayCell(*m_tableEmit, [this, fn = std::move(emit_fn)] - { Cell(fn); }); + RecordReplayCell(*context.tableEmit, [&app, fn = std::move(emit_fn), &context] + { Cell(app, context, fn); }); return; } - const int c = CurrentCellCol(); - TableEmit& emit = *m_tableEmit; + const int c = CurrentCellCol(app, context); + TableEmit& emit = *context.tableEmit; TableState* state = emit.userState; const bool cellMode = emit.cellMode; const tachyon::ID rowID = emit.currentRowID; const StyleRef columnStyle = emit.columns[c].column.cellStyle; const StyleRef styleRef = (columnStyle.layoutStyleIndex != LayoutStyleIndex::Invalid) ? columnStyle : (emit.cellStyleRef.layoutStyleIndex != LayoutStyleIndex::Invalid) ? emit.cellStyleRef - : theme.tableCellStyleRef; + : styles.tableCellStyleRef; // Row-mode cells are NoInput (click -> select row), except columns that // host their own widget - those stay hittable so the widget gets input. Such a @@ -257,9 +263,9 @@ namespace tachyon // focus to the row, so the row stays highlighted over them. The widgets keep // their own IDs and handlers. const bool rowPart = !cellMode && emit.columns[c].column.interactiveContent; - const tachyon::ID cellID = rowPart ? rowID : idManager.AllocateDynamicID(); + const tachyon::ID cellID = rowPart ? rowID : app.idManager.AllocateDynamicID(); auto [cellState, cellSelected] = ComputeCellSelectionBits( - guiStateManager, state, cellID, rowID, c, cellMode); + app.guiStateManager, state, cellID, rowID, c, cellMode); const tachyon::ElementFlags cellFlags = rowPart ? tachyon::ElementFlags::SharesID | tachyon::ElementFlags::PropagatesDescendantState : cellMode ? tachyon::ElementFlags::None @@ -272,7 +278,7 @@ namespace tachyon cellHandler = emit.sharedCellHandler; } - EmitDirectCellCustom(emit.columns[c], emit, + EmitDirectCellCustom(app, emit.columns[c], emit, cellID, cellState, cellFlags, styleRef, std::move(cellHandler), cellSelected, std::move(emit_fn), c, emit.directColStart, @@ -280,27 +286,28 @@ namespace tachyon } - void GUIApplication::TreeCell(std::string_view text, int depth, TreeOpenRef isOpen, + void TreeCell(GUIApplication& app, Context& context, std::string_view text, int depth, TreeOpenRef isOpen, IconID icon, uint32_t ancestorLineMask, bool isLastSibling, std::string* renameBuffer, bool reserveExpander) { - if (!m_tableEmit.has_value()) + const Styles& styles = GetStyles(app, context); + if (!context.tableEmit.has_value()) { - ReportMisuse("GUIApplication: a table cell outside a table (ignored)"); + app.ReportMisuse("GUIApplication: a table cell outside a table (ignored)"); return; } - if (m_tableEmit->isRecording) + if (context.tableEmit->isRecording) { - RecordReplayCell(*m_tableEmit, - [this, text = std::string(text), depth, isOpen, icon, - ancestorLineMask, isLastSibling, renameBuffer, reserveExpander] - { TreeCell(text, depth, isOpen, icon, ancestorLineMask, + RecordReplayCell(*context.tableEmit, + [&app, text = std::string(text), depth, isOpen, icon, + ancestorLineMask, isLastSibling, renameBuffer, reserveExpander, &context] + { TreeCell(app, context, text, depth, isOpen, icon, ancestorLineMask, isLastSibling, renameBuffer, reserveExpander); }); return; } - const int c = CurrentCellCol(); - TableEmit& emit = *m_tableEmit; + const int c = CurrentCellCol(app, context); + TableEmit& emit = *context.tableEmit; TableState* state = emit.userState; const bool cellMode = emit.cellMode; const tachyon::ID rowID = emit.currentRowID; @@ -314,24 +321,24 @@ namespace tachyon if (renameBuffer != nullptr) info.renameSeed.assign(text); else info.renameSeed.clear(); - const tachyon::ID cellID = cellMode ? idManager.AllocateDynamicID() : rowID; + const tachyon::ID cellID = cellMode ? app.idManager.AllocateDynamicID() : rowID; auto [cellState, cellSelected] = ComputeCellSelectionBits( - guiStateManager, state, cellID, rowID, c, cellMode); + app.guiStateManager, state, cellID, rowID, c, cellMode); // In row mode the cell is the row (its state follows the row's): it shares the row's ID. const tachyon::ElementFlags cellFlags = cellID == rowID ? tachyon::ElementFlags::SharesID : tachyon::ElementFlags::None; - const tachyon::ID bodyID = idManager.AllocateDynamicID(); + const tachyon::ID bodyID = app.idManager.AllocateDynamicID(); - if (renameBuffer && (*m_renameSub).isActive && - (*m_renameSub).targetID == rowID && - !(*m_renameSub).firstFrame && - guiStateManager.Interaction().GetFocusedID() != bodyID) + if (renameBuffer && context.rename.isActive && + context.rename.targetID == rowID && + !context.rename.firstFrame && + app.guiStateManager.Interaction().GetFocusedID() != bodyID) { - (*m_renameSub).Cancel(); + context.rename.Cancel(); } const bool renameActive = (renameBuffer != nullptr) && - (*m_renameSub).isActive && - (*m_renameSub).targetID == rowID; + context.rename.isActive && + context.rename.targetID == rowID; tachyon::EventHandler cellHandler; if (cellMode) @@ -346,28 +353,28 @@ namespace tachyon if (isOpen) cellHandler = MakeTreeCellDoubleClickToggle(&state->internal.treeCellClickTracker, isOpen, std::move(cellHandler)); - const StyleRef textStyle = theme.treeTableTextStyleRef; - const tachyon::ElementState textState = guiStateManager.GetCurrentState(bodyID); - const tachyon::TextID bodyTextID = textSystem->RegisterText( + const StyleRef textStyle = styles.treeTableTextStyleRef; + const tachyon::ElementState textState = app.guiStateManager.GetCurrentState(bodyID); + const tachyon::TextID bodyTextID = app.textSystem->RegisterText( bodyID, text, textStyle, textState); // Branches always reserve the arrow / leaf-spacer column (the arrow lives // there); leaves only when reserveExpander is set. const bool hasExpanderColumn = reserveExpander || static_cast(isOpen); info.expanderColumn = hasExpanderColumn; - int32_t prefix = (depth > 0 ? depth * theme.treeTableIndent : 0) - + (hasExpanderColumn ? theme.treeTableExpanderWidth : 0) - + (icon != IconID::Invalid ? theme.treeTableIconSize : 0); - if (const tachyon::LayoutStyle* ts = styleManager.GetLayoutStyle(textStyle.layoutStyleIndex)) + int32_t prefix = (depth > 0 ? depth * styles.treeTableIndent : 0) + + (hasExpanderColumn ? styles.treeTableExpanderWidth : 0) + + (icon != IconID::Invalid ? styles.treeTableIconSize : 0); + if (const tachyon::LayoutStyle* ts = app.styleManager.GetLayoutStyle(textStyle.layoutStyleIndex)) prefix += ts->padding.Horizontal() + ts->borderWidths.Horizontal(); - const int32_t treeRowW = textSystem->GetTextMeasurement(bodyTextID).maxWidth + prefix; + const int32_t treeRowW = app.textSystem->GetTextMeasurement(bodyTextID).maxWidth + prefix; emit.columns[c].internal.maxContentWidth = std::max(emit.columns[c].internal.maxContentWidth, treeRowW); - const StyleRef cellStyleRef = cellMode ? theme.treeTableCellStyleRef - : theme.treeTableCellRowModeStyleRef; + const StyleRef cellStyleRef = cellMode ? styles.treeTableCellStyleRef + : styles.treeTableCellRowModeStyleRef; info.cellID = cellID; - info.cellRef = EmitDirectCellTree(emit.columns[c], emit, + info.cellRef = EmitDirectCellTree(app, context, emit.columns[c], emit, cellID, cellState, cellFlags, cellStyleRef, std::move(cellHandler), cellSelected, bodyTextID, depth, isOpen, icon, ancestorLineMask, isLastSibling, @@ -377,7 +384,7 @@ namespace tachyon } - void GUIApplication::EmitDirectCellText(const VirtualTableColumn& column, TableEmit& emit, + void EmitDirectCellText(GUIApplication& app, const VirtualTableColumn& column, TableEmit& emit, tachyon::ID cellID, tachyon::ElementState cellState, tachyon::ElementFlags cellFlags, tachyon::StyleRef cellStyleRef, tachyon::EventHandler cellHandler, tachyon::TextID textID, @@ -399,13 +406,13 @@ namespace tachyon .GridColumn(static_cast(colIdx - colStart)) .GridRow(gridRow) .ColumnTrack(track), emit, colIdx); - auto cRes = elementStorage.Add(std::move(cell), std::move(cellLo)); + auto cRes = app.elementStorage.Add(std::move(cell), std::move(cellLo)); VERIFY(cRes.status); - VERIFY(windowRegistry.Add(cRes.ref)); + VERIFY(app.windowRegistry.Add(cRes.ref)); } - void GUIApplication::EmitDirectCellCustom(const VirtualTableColumn& column, TableEmit& emit, + void EmitDirectCellCustom(GUIApplication& app, const VirtualTableColumn& column, TableEmit& emit, tachyon::ID cellID, tachyon::ElementState cellState, tachyon::ElementFlags cellFlags, tachyon::StyleRef cellStyleRef, tachyon::EventHandler cellHandler, bool cellSelected, @@ -427,19 +434,19 @@ namespace tachyon .GridColumn(static_cast(colIdx - colStart)) .GridRow(gridRow) .ColumnTrack(track), emit, colIdx); - auto cRes = elementStorage.Add(std::move(cell), std::move(cellLo)); + auto cRes = app.elementStorage.Add(std::move(cell), std::move(cellLo)); VERIFY(cRes.status); - VERIFY(windowRegistry.Add(cRes.ref)); + VERIFY(app.windowRegistry.Add(cRes.ref)); - VERIFY(elementStorage.BeginChildren()); - if (cellSelected) guiStateManager.Construction().PushSelected(); + VERIFY(app.elementStorage.BeginChildren()); + if (cellSelected) app.guiStateManager.Construction().PushSelected(); if (emit_fn) emit_fn(); - if (cellSelected) guiStateManager.Construction().PopSelected(); - VERIFY(elementStorage.EndChildren()); + if (cellSelected) app.guiStateManager.Construction().PopSelected(); + VERIFY(app.elementStorage.EndChildren()); } - tachyon::ElementRef GUIApplication::EmitDirectCellTree(const VirtualTableColumn& column, TableEmit& emit, + tachyon::ElementRef EmitDirectCellTree(GUIApplication& app, Context& context, const VirtualTableColumn& column, TableEmit& emit, tachyon::ID cellID, tachyon::ElementState cellState, tachyon::ElementFlags cellFlags, tachyon::StyleRef cellStyleRef, tachyon::EventHandler cellHandler, bool cellSelected, @@ -450,6 +457,7 @@ namespace tachyon tachyon::ID treeBodyID, bool reserveExpander, int colIdx, int colStart, int16_t gridRow) { + const Styles& styles = GetStyles(app, context); // Pre-resolved per-column track from VirtualTable's setup pass. const GridTrack& track = column.internal.columnTrack; @@ -465,24 +473,24 @@ namespace tachyon .GridColumn(static_cast(colIdx - colStart)) .GridRow(gridRow) .ColumnTrack(track), emit, colIdx); - auto cRes = elementStorage.Add(std::move(cell), std::move(cellLo)); + auto cRes = app.elementStorage.Add(std::move(cell), std::move(cellLo)); VERIFY(cRes.status); - VERIFY(windowRegistry.Add(cRes.ref)); + VERIFY(app.windowRegistry.Add(cRes.ref)); // Tree-cell guide lines via custom-draw. The cell's overflow:visible // lets the lines extend into padding so they connect to the next // row's lines. if (treeDepth > 0) { - [[maybe_unused]] auto cdResult = elementStorage.AddCustomDraw(cRes.ref, + [[maybe_unused]] auto cdResult = app.elementStorage.AddCustomDraw(cRes.ref, [depth = treeDepth, ancestorMask = treeAncestorMask, isLastSibling = treeIsLastSibling, hasArrow = static_cast(treeIsOpen), - lineColor = theme.treeGuideLineStyle, - treeIndent = theme.treeTableIndent, - sm = &styleManager, - cellStyle = theme.treeTableCellStyleRef] + lineColor = styles.treeGuideLineStyle, + treeIndent = styles.treeTableIndent, + sm = &app.styleManager, + cellStyle = styles.treeTableCellStyleRef] (tachyon::CustomDrawContext& ctx) { // Vertical guides span the full OUTER row so consecutive rows' @@ -516,36 +524,36 @@ namespace tachyon }); } - VERIFY(elementStorage.BeginChildren()); - if (cellSelected) guiStateManager.Construction().PushSelected(); + VERIFY(app.elementStorage.BeginChildren()); + if (cellSelected) app.guiStateManager.Construction().PushSelected(); - EmitTreeCellIndent(*this, treeDepth); + EmitTreeCellIndent(app, context, treeDepth); // Branches always keep their arrow; leaves keep the spacer only when // the tree reserves an expander column (false for flat trees). if (reserveExpander || treeIsOpen) - EmitTreeCellArrowOrLeafSpacer(*this, treeIsOpen); - EmitTreeCellIcon(*this, treeIcon, treeIsOpen, &emit.userState->internal.treeCellClickTracker); + EmitTreeCellArrowOrLeafSpacer(app, context, treeIsOpen); + EmitTreeCellIcon(app, context, treeIcon, treeIsOpen, &emit.userState->internal.treeCellClickTracker); if (treeRenameActive) { - TreeItemRenameCheck(treeBodyID, treeRenameBuffer, - theme.treeTableTextEditStyleRef); + TreeItemRenameCheck(app, context, treeBodyID, treeRenameBuffer, + styles.treeTableTextEditStyleRef); } else { tachyon::Element textElem{}; textElem.id = treeBodyID; - textElem.styleRef = theme.treeTableTextStyleRef; + textElem.styleRef = styles.treeTableTextStyleRef; textElem.flags = tachyon::ElementFlags::NoInput; - textElem.state = guiStateManager.GetCurrentState(treeBodyID); + textElem.state = app.guiStateManager.GetCurrentState(treeBodyID); textElem.textID = textID; - auto res = elementStorage.Add(std::move(textElem), tachyon::LayoutOverride::Auto()); + auto res = app.elementStorage.Add(std::move(textElem), tachyon::LayoutOverride::Auto()); VERIFY(res.status); - VERIFY(windowRegistry.Add(res.ref)); + VERIFY(app.windowRegistry.Add(res.ref)); } - if (cellSelected) guiStateManager.Construction().PopSelected(); - VERIFY(elementStorage.EndChildren()); + if (cellSelected) app.guiStateManager.Construction().PopSelected(); + VERIFY(app.elementStorage.EndChildren()); return cRes.ref; } diff --git a/src/gui_controls/controls_table_handlers.cpp b/src/gui_views/controls_table_handlers.cpp similarity index 87% rename from src/gui_controls/controls_table_handlers.cpp rename to src/gui_views/controls_table_handlers.cpp index 4b3f5bdb..5bd97422 100644 --- a/src/gui_controls/controls_table_handlers.cpp +++ b/src/gui_views/controls_table_handlers.cpp @@ -1,3 +1,4 @@ +#include // Event-handler builders attached by BeginTable / BeginRow: // - BuildTableContainerHandler: MouseDown (focus), MouseScroll (routed to the // section body under the cursor), KeyDown (keyboard nav). @@ -7,27 +8,27 @@ // Cell-emission: controls_table_cells.cpp. Structural emission: // controls_table.cpp. Shared helpers: controls_table_internal.h. -#include "controls_table_internal.h" +#include #include #include -namespace tachyon +namespace tachyon::views { - using namespace tachyon::TableInternal; + using namespace tachyon::views::TableInternal; - tachyon::EventHandler GUIApplication::BuildTableContainerHandler(TableState* state, + tachyon::EventHandler BuildTableContainerHandler(GUIApplication& app, Context& context, TableState* state, tachyon::ID /*containerID*/) { TableState* statePtr = state; - return [this, statePtr](ElementEvent&& event) -> bool + return [&context, &app, statePtr](ElementEvent&& event) -> bool { switch (event.type) { case tachyon::EventType::MouseDown: if (!event.state.LeftPressed()) break; - TakeFocus(guiStateManager, event.id); + TakeFocus(app.guiStateManager, event.id); return true; case tachyon::EventType::MouseScroll: @@ -37,7 +38,7 @@ namespace tachyon // gets mirrored across all sections by MirrorTableScroll. const int n = statePtr->internal.sectionCount; if (n <= 0) break; - const float step = styleManager.Px(kWheelScrollStep); + const float step = app.styleManager.Px(kWheelScrollStep); const int2 delta { static_cast(event.state.scroll.x * step), static_cast(event.state.scroll.y * step) @@ -47,13 +48,13 @@ namespace tachyon tachyon::ID targetBodyID = tachyon::ID::Invalid(); // Compare against rect coords in layout space - convert the // screen cursor through any ancestor contentTransform first. - const int2 localCursor = event.LocalCursor(elementStorage); + const int2 localCursor = event.LocalCursor(app.elementStorage); for (int i = 0; i < n; i++) { const tachyon::ID id = statePtr->SectionBodyID(i); - auto ref = elementStorage.FindElementRefByID(id); + auto ref = app.elementStorage.FindElementRefByID(id); if (!ref.IsValid()) continue; - const auto& r = elementStorage.GetElementRectUnsafe(ref).rect; + const auto& r = app.elementStorage.GetElementRectUnsafe(ref).rect; if (localCursor.x >= r.x && localCursor.x < r.x + r.w && localCursor.y >= r.y && localCursor.y < r.y + r.h) { @@ -64,11 +65,11 @@ namespace tachyon if (targetBodyID == tachyon::ID::Invalid()) targetBodyID = statePtr->SectionBodyID(0); - auto bodyRef = elementStorage.FindElementRefByID(targetBodyID); + auto bodyRef = app.elementStorage.FindElementRefByID(targetBodyID); if (!bodyRef.IsValid()) return false; - const auto& bodyRect = elementStorage.GetElementRectUnsafe(bodyRef); + const auto& bodyRect = app.elementStorage.GetElementRectUnsafe(bodyRef); - auto& scrollManagement = guiStateManager.GetScrollManagement(); + auto& scrollManagement = app.guiStateManager.GetScrollManagement(); auto handle = scrollManagement.GetOrCreateScrollOffsetHandle(targetBodyID); const int2 offset = scrollManagement.GetScrollOffset(handle); const int2 requested { offset.x + delta.x, offset.y + delta.y }; @@ -120,9 +121,9 @@ namespace tachyon { const tachyon::ID sid = statePtr->SectionBodyID(i); if (sid == tachyon::ID::Invalid()) continue; - auto sref = elementStorage.FindElementRefByID(sid); + auto sref = app.elementStorage.FindElementRefByID(sid); if (!sref.IsValid()) continue; - const auto& sr = elementStorage.GetElementRectUnsafe(sref); + const auto& sr = app.elementStorage.GetElementRectUnsafe(sref); if (sr.contentBounds.w > sr.innerRect.w) { hOverflow = true; @@ -131,13 +132,13 @@ namespace tachyon } } const int32_t hPadKb = hOverflow - ? theme.scrollbarThickness : 0; + ? app.theme.scrollbarThickness : 0; const int32_t headerRowH = statePtr->internal.hasHeaders ? rh : 0; const int rowsPerPage = std::max(1, (innerH - headerRowH - hPadKb) / rh); // First fully visible row, from the body's scroll-Y. int firstFullVis = 0; { - auto& sm = guiStateManager.GetScrollManagement(); + auto& sm = app.guiStateManager.GetScrollManagement(); const auto h = sm.GetScrollOffsetHandle(statePtr->internal.bodyID); if (sm.IsScrollOffsetHandleValid(h)) firstFullVis = std::max(0, -sm.GetScrollOffset(h).y / rh); @@ -183,7 +184,7 @@ namespace tachyon { const auto* info = statePtr->FindTreeRow(statePtr->selectedRowID); if (info && info->isOpen) - { info->isOpen.Toggle(); guiStateManager.Interaction().SuppressHover(); return true; } + { info->isOpen.Toggle(); app.guiStateManager.Interaction().SuppressHover(); return true; } } return false; case tachyon::KeyCode::F2: @@ -192,10 +193,10 @@ namespace tachyon const auto* info = statePtr->FindTreeRow(statePtr->selectedRowID); if (info && info->renameBuf) { - (*m_renameSub).Start(statePtr->selectedRowID, + context.rename.Start(statePtr->selectedRowID, info->renameBuf, info->renameSeed); - guiStateManager.Interaction().SuppressHover(); + app.guiStateManager.Interaction().SuppressHover(); return true; } } @@ -206,7 +207,7 @@ namespace tachyon { const auto* info = statePtr->FindTreeRow(statePtr->selectedRowID); const bool isOpenBranch = (info && info->isOpen.IsOpen()); - if (isOpenBranch) { info->isOpen.SetOpen(false); guiStateManager.Interaction().SuppressHover(); return true; } + if (isOpenBranch) { info->isOpen.SetOpen(false); app.guiStateManager.Interaction().SuppressHover(); return true; } if (info && info->depth > 0) { // Walk back to the parent (nearest shallower row); @@ -214,7 +215,7 @@ namespace tachyon const int myDepth = info->depth; for (int i = idx - 1; i >= 0; --i) { - const tachyon::ID prevID = idManager.GetSubID( + const tachyon::ID prevID = app.idManager.GetSubID( statePtr->internal.rowsRangeID, static_cast(i)); const auto* sib = statePtr->FindTreeRow(prevID); if (!sib) break; // outside emit window @@ -230,10 +231,10 @@ namespace tachyon const auto* info = statePtr->FindTreeRow(statePtr->selectedRowID); if (info && info->isOpen) { - if (!info->isOpen.IsOpen()) { info->isOpen.SetOpen(true); guiStateManager.Interaction().SuppressHover(); return true; } + if (!info->isOpen.IsOpen()) { info->isOpen.SetOpen(true); app.guiStateManager.Interaction().SuppressHover(); return true; } if (idx + 1 < totalRows) { - const tachyon::ID childID = idManager.GetSubID( + const tachyon::ID childID = app.idManager.GetSubID( statePtr->internal.rowsRangeID, static_cast(idx + 1)); const auto* child = statePtr->FindTreeRow(childID); if (child && child->depth == info->depth + 1) @@ -253,7 +254,7 @@ namespace tachyon tachyon::ID newID = tachyon::ID::Invalid(); if (next != idx && next >= 0 && next < totalRows) { - newID = idManager.GetSubID(statePtr->internal.rowsRangeID, + newID = app.idManager.GetSubID(statePtr->internal.rowsRangeID, static_cast(next)); } if (newID != tachyon::ID::Invalid() && newID != statePtr->selectedRowID) @@ -275,9 +276,9 @@ namespace tachyon } if (changed) { - guiStateManager.Interaction().SuppressHover(); - tachyon::ElementRef rowRef = elementStorage.FindElementRefByID(statePtr->selectedRowID); - auto& scrollManagement = guiStateManager.GetScrollManagement(); + app.guiStateManager.Interaction().SuppressHover(); + tachyon::ElementRef rowRef = app.elementStorage.FindElementRefByID(statePtr->selectedRowID); + auto& scrollManagement = app.guiStateManager.GetScrollManagement(); // Scroll the row clear of the sticky header (top) and the // H-scrollbar overlay (bottom, when shown). @@ -285,16 +286,16 @@ namespace tachyon ? std::max(1, statePtr->internal.actualRowHeight) : 0; const int32_t hPad = hOverflow - ? theme.scrollbarThickness : 0; + ? app.theme.scrollbarThickness : 0; if (rowRef != tachyon::ElementRef::Invalid()) { // Inflate the target by the header (top) and scrollbar (bottom). - const auto& rrect = elementStorage.GetElementRectUnsafe(rowRef).rect; + const auto& rrect = app.elementStorage.GetElementRectUnsafe(rowRef).rect; tachyon::IntRect target = rrect; target.y -= headerH; target.h += headerH + hPad; scrollManagement.MakeRectVisibleHierarchically( - elementStorage, target, rowRef); + app.elementStorage, target, rowRef); } else if (statePtr->internal.rowsRangeID != tachyon::ID::Invalid() && statePtr->internal.actualRowHeight > 0 @@ -320,9 +321,9 @@ namespace tachyon { const tachyon::ID sid = statePtr->SectionBodyID(i); if (sid == tachyon::ID::Invalid()) continue; - auto sref = elementStorage.FindElementRefByID(sid); + auto sref = app.elementStorage.FindElementRefByID(sid); if (!sref.IsValid()) continue; - const auto& srect = elementStorage.GetElementRectUnsafe(sref); + const auto& srect = app.elementStorage.GetElementRectUnsafe(sref); auto h = scrollManagement.GetOrCreateScrollOffsetHandle(sid); const int2 cur = scrollManagement.GetScrollOffset(h); @@ -367,10 +368,10 @@ namespace tachyon // One row-backdrop handler shared by every row; the row ID is the event's // element ID. With state->rowDragDrop set it also handles drag-and-drop with // Before/Inside/After zones (same contract as MakeTreeRowDragDropHandler). - tachyon::EventHandler GUIApplication::BuildRowBackdropHandler(TableState* state, + tachyon::EventHandler BuildRowBackdropHandler(GUIApplication& app, Context& context, TableState* state, tachyon::ID containerID) { - return [this, state, containerID](ElementEvent&& event) -> bool + return [&context, &app, state, containerID](ElementEvent&& event) -> bool { const tachyon::ID rowID = event.id; ItemDragDropConfig* dd = state->rowDragDrop; @@ -405,7 +406,7 @@ namespace tachyon for (int v = firstVis; v <= lastVis; ++v) { const int ds = state->VisualToDataset(v); - ms.selectedIDs.insert(idManager.GetSubID( + ms.selectedIDs.insert(app.idManager.GetSubID( state->internal.rowsRangeID, static_cast(ds))); } } @@ -451,7 +452,7 @@ namespace tachyon if (dd->dropInsideOnly) return TreeDropPosition::InsideLast; // rect is in layout space - convert cursor through any // ancestor contentTransform first. - const int32_t cursorY = event.LocalCursor(elementStorage).y; + const int32_t cursorY = event.LocalCursor(app.elementStorage).y; int relY = cursorY - rect.position.y; int h = rect.size.y; if (h <= 0) return TreeDropPosition::None; @@ -502,17 +503,17 @@ namespace tachyon if (state->internal.sectionCount <= 0) return; const tachyon::ID body0 = state->SectionBodyID(0); if (body0 == tachyon::ID::Invalid()) return; - auto bodyRef = elementStorage.FindElementRefByID(body0); + auto bodyRef = app.elementStorage.FindElementRefByID(body0); if (!bodyRef.IsValid()) return; - const auto& bodyRect = elementStorage.GetElementRectUnsafe(bodyRef); - const int kEdgeZoneHeight = styleManager.Px(30); - const int kAutoScrollPerEvent = styleManager.Px(12); + const auto& bodyRect = app.elementStorage.GetElementRectUnsafe(bodyRef); + const int kEdgeZoneHeight = app.styleManager.Px(30); + const int kAutoScrollPerEvent = app.styleManager.Px(12); const int32_t headerH = state->internal.hasHeaders ? std::max(0, state->internal.actualRowHeight) : 0; const int32_t hPad = state->internal.anyHorzOverflow - ? theme.scrollbarThickness : 0; + ? app.theme.scrollbarThickness : 0; // bodyRect.innerRect is layout-space - convert cursor too. - const int32_t mouseY = event.LocalCursor(elementStorage).y; + const int32_t mouseY = event.LocalCursor(app.elementStorage).y; const int32_t innerTop = bodyRect.innerRect.y + headerH; const int32_t innerBot = bodyRect.innerRect.y + bodyRect.innerRect.h - hPad; int32_t scrollDelta = 0; @@ -522,15 +523,15 @@ namespace tachyon scrollDelta = -kAutoScrollPerEvent; if (scrollDelta == 0) return; - auto& sm = guiStateManager.GetScrollManagement(); + auto& sm = app.guiStateManager.GetScrollManagement(); const int n = state->internal.sectionCount; for (int i = 0; i < n; i++) { const tachyon::ID sid = state->SectionBodyID(i); if (sid == tachyon::ID::Invalid()) continue; - auto sref = elementStorage.FindElementRefByID(sid); + auto sref = app.elementStorage.FindElementRefByID(sid); if (!sref.IsValid()) continue; - const auto& srect = elementStorage.GetElementRectUnsafe(sref); + const auto& srect = app.elementStorage.GetElementRectUnsafe(sref); auto h = sm.GetOrCreateScrollOffsetHandle(sid); const int2 cur = sm.GetScrollOffset(h); const int2 requested { cur.x, cur.y + scrollDelta }; @@ -544,12 +545,12 @@ namespace tachyon case tachyon::EventType::MouseMove: { if ((event.state.buttons & tachyon::MouseButtons::Left) == tachyon::MouseButtons::None) break; - guiStateManager.Drag().UpdateFromInput(event.state); + app.guiStateManager.Drag().UpdateFromInput(event.state); // A real drag cancels the deferred click selection: the drag manager has // decided it, so the press is a drag at any distance. - if (guiStateManager.Drag().GetDraggedID() == rowID) + if (app.guiStateManager.Drag().GetDraggedID() == rowID) state->internal.pendingRowClick.Move(event, 0); - return guiStateManager.Drag().GetDraggedID() == rowID; + return app.guiStateManager.Drag().GetDraggedID() == rowID; } case tachyon::EventType::DragEnter: case tachyon::EventType::DragOver: @@ -562,33 +563,33 @@ namespace tachyon if (event.state.dragSourceID == rowID || (dd->canDrop && !dd->canDrop(event.state.dragPayloadValue, rowID))) { - if (m_treeDropState.targetRowID == rowID) m_treeDropState = {}; + if (context.treeDrop.targetRowID == rowID) context.treeDrop = {}; return true; } const DropTarget target = resolveTarget(computeZone(event.rect->rect)); if (target.rowID == event.state.dragSourceID) // right above the dragged row: it stays { - m_treeDropState = {}; + context.treeDrop = {}; return true; } - m_treeDropState.targetRowID = target.rowID; - m_treeDropState.position = target.position; - m_treeDropState.targetDepth = target.depth; + context.treeDrop.targetRowID = target.rowID; + context.treeDrop.position = target.position; + context.treeDrop.targetDepth = target.depth; return true; } case tachyon::EventType::DragOut: { if (event.state.dragPayloadType != dd->payloadType) return false; - if (m_treeDropState.targetRowID == rowID) m_treeDropState = {}; + if (context.treeDrop.targetRowID == rowID) context.treeDrop = {}; return true; } case tachyon::EventType::Drop: { if (event.state.dragPayloadType != dd->payloadType) return false; - if (event.state.dragSourceID == rowID) { m_treeDropState = {}; return true; } + if (event.state.dragSourceID == rowID) { context.treeDrop = {}; return true; } if (dd->canDrop && !dd->canDrop(event.state.dragPayloadValue, rowID)) { - m_treeDropState = {}; + context.treeDrop = {}; return true; } const DropTarget target = resolveTarget(event.rect @@ -596,7 +597,7 @@ namespace tachyon : TreeDropPosition::None); if (target.position != TreeDropPosition::None && dd->onReorder) dd->onReorder(event.state.dragPayloadValue, target.rowID, target.position); - m_treeDropState = {}; + context.treeDrop = {}; return true; } default: break; @@ -626,7 +627,7 @@ namespace tachyon // next frame's TreeItemRenameCheck moves focus to the editor. if (hasRename && ctrlShift) { - (*m_renameSub).Start(rowID, info->renameBuf, info->renameSeed); + context.rename.Start(rowID, info->renameBuf, info->renameSeed); state->internal.rowClickTracker.Reset(); return true; } @@ -638,14 +639,14 @@ namespace tachyon { state->onRowDoubleClick(rowID); state->internal.rowClickTracker.Reset(); - if (!(*m_renameSub).firstFrame) (*m_renameSub).Cancel(); + if (!context.rename.firstFrame) context.rename.Cancel(); return true; } if (info && info->isOpen) { info->isOpen.Toggle(); state->internal.rowClickTracker.Reset(); - if (!(*m_renameSub).firstFrame) (*m_renameSub).Cancel(); + if (!context.rename.firstFrame) context.rename.Cancel(); return true; } } @@ -658,26 +659,26 @@ namespace tachyon && dblMs >= std::max(500.0f, DoubleClickMilliseconds()) && dblMs < 3000.0f && !dragDropEnabled) { - (*m_renameSub).Start(rowID, info->renameBuf, info->renameSeed); + context.rename.Start(rowID, info->renameBuf, info->renameSeed); state->internal.rowClickTracker.Reset(); return true; } // Plain click cancels rename (not on its activation frame). - if (!(*m_renameSub).firstFrame) (*m_renameSub).Cancel(); + if (!context.rename.firstFrame) context.rename.Cancel(); - TakeFocus(guiStateManager, containerID); - guiStateManager.Interaction().SetClicked(rowID); + TakeFocus(app.guiStateManager, containerID); + app.guiStateManager.Interaction().SetClicked(rowID); if (dragDropEnabled) { // Defer selection to MouseUp so a drag doesn't select the source row. - state->internal.pendingRowClick.Press(event, elementStorage, guiStateManager, event.state.modifiers, + state->internal.pendingRowClick.Press(event, app.elementStorage, app.guiStateManager, event.state.modifiers, { .focus = false, .capture = false }); // Prime a drag (inlined: Chain stops at our `return true`). uintptr_t payloadValue = dd->getPayload ? dd->getPayload(rowID) : 0; - guiStateManager.Drag().Begin(rowID, dd->payloadType, payloadValue, + app.guiStateManager.Drag().Begin(rowID, dd->payloadType, payloadValue, event.state.screenPos, std::any(), dd->visualizer); } diff --git a/src/gui_views/controls_table_internal.h b/src/gui_views/controls_table_internal.h new file mode 100644 index 00000000..5e7578ae --- /dev/null +++ b/src/gui_views/controls_table_internal.h @@ -0,0 +1,214 @@ +#pragma once + +// Not installed: the views' helpers shared between their files. + +#include + +#include + +namespace tachyon::views::TableInternal +{ + // Hit-strip width of an active (draggable) sizer overlay (CSS pixels). + constexpr int32_t kActiveSizerWidth = 4; + // Cross-axis size for full-height sizers/separators (clipped by parent). + constexpr int32_t kStretchHeight = 32768; + + + // Double-click / slow-re-click tracker; each TableState holds its own. + using DoubleClickTracker = DoubleClickTracker; + + + // Column GridTrack: 1fr when stretchy, else Fixed. The table's last column + // turns Fixed during a column drag so cells don't paint under the V scrollbar. + // columnWidths are CSS pixels (laid out at the UI scale); lastColDragFixedWidth is pixels. + inline GridTrack ComputeColumnTrack(const StyleManager& sm, + int c, + int globalColumnCount, + const tachyon::views::VirtualTableColumn* /*columns*/, + const std::vector& columnWidths, + bool dragActive, + int32_t lastColDragFixedWidth, + bool isStretch) + { + const bool isLastGlobal = (c + 1 == globalColumnCount); + const float width = static_cast(sm.Px(columnWidths[c])); + if (isStretch) + { + if (isLastGlobal && dragActive) + return GridTrack::Fixed(static_cast(lastColDragFixedWidth)); + return GridTrack::Fractional(1.0f, width); + } + return GridTrack::Fixed(width); + } + + // Overload with implicit stretch on the table's last column. Frozen mode passes + // `isStretch` explicitly (only the middle section's last column stretches). + inline GridTrack ComputeColumnTrack(const StyleManager& sm, int c, int globalColumnCount, + const tachyon::views::VirtualTableColumn* columns, + const std::vector& columnWidths, + bool dragActive, int32_t lastColDragFixedWidth) + { + const bool isLastGlobal = (c + 1 == globalColumnCount); + const bool isStretch = isLastGlobal + || columns[c].column.sizing == tachyon::views::ColumnSizing::Stretch; + return ComputeColumnTrack(sm, c, globalColumnCount, columns, columnWidths, + dragActive, lastColDragFixedWidth, isStretch); + } + + // Persistent hover/focus state for the cell ID + cell-mode Selected. + // Callers add NoInput themselves when needed (Cell does in row mode; + // TreeCell stays hittable so its arrow/text can be clicked). + struct CellStateBits + { + tachyon::ElementState state; + bool selected; + }; + + inline CellStateBits ComputeCellSelectionBits(GUIStateManager& sm, + const tachyon::views::TableState* userState, + tachyon::ID cellID, tachyon::ID currentRowID, + int c, bool cellMode) + { + tachyon::ElementState st = sm.GetCurrentState(cellID); + const bool selected = cellMode + && userState->selectedRowID == currentRowID + && userState->selectedColumn == c; + if (selected) st |= tachyon::ElementState::Selected; + return { st, selected }; + } +} + +namespace tachyon::views +{ + // Tree-cell flex-row children - emitted at drain time by EndTable's + // body-section drain. Defined in controls_table_cells.cpp. + void EmitTreeCellIndent(GUIApplication& app, Context& context, int depth); + void EmitTreeCellArrowOrLeafSpacer(GUIApplication& app, Context& context, TreeOpenRef isOpen); + void EmitTreeCellIcon(GUIApplication& app, Context& context, IconID icon, TreeOpenRef isOpen, + DoubleClickTracker* tracker); + + /// `context`, with its styles looked up again when the app's styles loaded since, and + /// the last frame's maps cleared at the first view of a frame: what each view does first. + Context& Prepare(GUIApplication& app, Context& context); + + /// The table being built's current column. + inline int CurrentCellCol(GUIApplication&, Context& context) + { + const int c = context.tableEmit->currentCol; + assert(c < int(context.tableEmit->columnCount)); + return c; + } + + /// Column-boundary sizers for [colStart, colEnd), anchored to each header cell's right edge. + /// skipDragged leaves out the dragged column's sizer; EmitDraggedColumnOnTop emits it last. + void EmitColumnSizers(GUIApplication& app, Context& context, TableEmit& emit, int colStart, int colEnd, + bool skipDragged = false); + /// 1px column dividers for headerless tables, which have no sizers. + void EmitColumnSeparators(GUIApplication& app, Context& context, TableEmit& emit, int colStart, int colEnd); + /// Full-height strips for columns with columnBackground: above the row backdrops, below the cells. + void EmitColumnBackgrounds(GUIApplication& app, Context& context, TableEmit& emit, int colStart, int colEnd); + + /// followTail, run from the body section's post-layout hook (final viewport/content height). + void UpdateTableFollowTail(GUIApplication& app, TableState& state, int32_t viewportH, int32_t contentH); + void ScrollTableSectionsToBottom(GUIApplication& app, TableState& state); + /// 1px separator between adjacent frozen sections. + void EmitTableSectionSeparator(GUIApplication& app, Context& context); + + /// Adds column c's reorder-drag X offset while a drag is live. + inline tachyon::LayoutOverride ApplyColumnDragOffsetX(tachyon::LayoutOverride lo, + const TableEmit& emit, int c) + { + if (emit.dragActive) + lo = std::move(lo).PositionX(tachyon::PositionConstraintAxis::Relative(emit.columns[c].internal.dragOffsetX)); + return lo; + } + /// Mirrors Y across the left/mid/right bodies and X to the mid header; absent sections have invalid IDs. + void MirrorTableScroll(GUIApplication& app, TableState* state); + /// `gridCol` is section-local. `sectionMin/Max` are the inclusive global columns + /// the reorder drag may move this header within. + void EmitTableHeaderCell(GUIApplication& app, Context& context, TableEmit& emit, tachyon::ID tableID, int c, int16_t gridCol, + bool isStretchTrack, int sectionMin, int sectionMax, + int effectiveSortCol, IconID sortIcon); + /// Header cells go into row 0 of the section's body grid, StickyY-pinned to the top. + void EmitTableHeaderSection(GUIApplication& app, Context& context, TableEmit& emit, tachyon::ID tableID, + int colStart, int colEnd, bool lastColIsStretch, + int effectiveSortCol, IconID sortIcon); + /// Stretch for Stretch columns and the middle section's last column; fitContent + /// forces Fixed (fit-content sections have no leftover space to absorb). + GridTrack ComputeSectionColumnTrack(GUIApplication& app, const TableEmit& emit, int c, int colEnd, + bool isMiddle, bool fitContent = false); + /// Follow with the row loop and CloseTableBodySection. `sampleViewport` records the + /// viewport size for next frame (primary section only). + void OpenTableBodySection(GUIApplication& app, Context& context, TableEmit& emit, tachyon::ID sectionID, tachyon::StyleRef sectionStyle, + tachyon::LayoutOverride&& layout, bool sampleViewport); + /// Emits sizers and the section's H scrollbar (the rightmost section also gets the + /// shared V scrollbar). suppressHorzScrollbar is for fit-content sections. + void CloseTableBodySection(GUIApplication& app, TableEmit& emit, + tachyon::ID sectionBodyID, bool emitVerticalScrollbar, + bool suppressHorzScrollbar = false); + /// Row loop for an open body section: spacers for off-screen rows, backdrop + cells for visible ones. + void EmitVirtualBodyRows(GUIApplication& app, Context& context, TableEmit& emit, + int colStart, int colEnd, + int totalRowCount, int32_t actualRowHeight, + int firstVisible, int lastVisible, + tachyon::ID rowsRangeID, + bool isLastSection); + + /// Emits the dragged column (cells, header, sizer) last so it paints on top. + /// Only when emit.dragActive and draggedCol is in [colStart, colEnd). + void EmitDraggedColumnOnTop(GUIApplication& app, Context& context, TableEmit& emit, tachyon::ID tableID, + int colStart, int colEnd, + int firstVisible, int lastVisible, + tachyon::ID rowsRangeID, + bool lastColIsStretch, + int effectiveSortCol, IconID sortIcon); + /// Cell emitters for Cell(GUIApplication& app, Context& context) / TreeCell(app, context), into the open body section. + void EmitDirectCellText(GUIApplication& app, const VirtualTableColumn& column, TableEmit& emit, + tachyon::ID cellID, tachyon::ElementState cellState, tachyon::ElementFlags cellFlags, + tachyon::StyleRef cellStyleRef, tachyon::EventHandler cellHandler, + tachyon::TextID textID, + int colIdx, int colStart, int16_t gridRow); + void EmitDirectCellCustom(GUIApplication& app, const VirtualTableColumn& column, TableEmit& emit, + tachyon::ID cellID, tachyon::ElementState cellState, tachyon::ElementFlags cellFlags, + tachyon::StyleRef cellStyleRef, tachyon::EventHandler cellHandler, + bool cellSelected, + std::function emit_fn, + int colIdx, int colStart, int16_t gridRow); + /// Returns the cell's element. + tachyon::ElementRef EmitDirectCellTree(GUIApplication& app, Context& context, const VirtualTableColumn& column, TableEmit& emit, + tachyon::ID cellID, tachyon::ElementState cellState, tachyon::ElementFlags cellFlags, + tachyon::StyleRef cellStyleRef, tachyon::EventHandler cellHandler, + bool cellSelected, + tachyon::TextID textID, + int treeDepth, TreeOpenRef treeIsOpen, IconID treeIcon, + uint32_t treeAncestorMask, bool treeIsLastSibling, + std::string* treeRenameBuffer, bool treeRenameActive, + tachyon::ID treeBodyID, bool reserveExpander, + int colIdx, int colStart, int16_t gridRow); + /// One element spanning [colStart, colEnd) at gridRow. + void EmitDirectRowBackdrop(GUIApplication& app, Context& context, tachyon::ID rowID, int16_t gridRow, + int colStart, int colEnd, + tachyon::ElementState backdropState, + tachyon::ElementFlags backdropFlags, + tachyon::StyleRef rowStyle, + tachyon::EventHandler backdropHandler, + TableState* tableState, + bool isLastSection); + /// Invisible row of `height` pixels at gridRow. + void EmitDirectRowSpacer(GUIApplication& app, Context& context, int16_t gridRow, + int colStart, int colEnd, int32_t height); + /// Row-mode backdrop MouseDown handler, shared by all rows (the row comes from the event id): + /// selection, double-click toggle, rename start. + tachyon::EventHandler BuildRowBackdropHandler(GUIApplication& app, Context& context, TableState* state, + tachyon::ID containerID); + /// Focus on click, scroll routing to the middle body, keyboard navigation. + tachyon::EventHandler BuildTableContainerHandler(GUIApplication& app, Context& context, TableState* state, + tachyon::ID containerID); + + /// Tree/list item construction helpers (OnGUI only, not from handlers). + bool IsTreeItemSelected(const Context& context, tachyon::ID id, int itemIndex); + tachyon::TextID TreeItemRegisterText(GUIApplication& app, tachyon::ID id, std::string_view text, IconID icon, StyleRef style, tachyon::ElementState state); + void TreeItemRowCustomDraw(GUIApplication& app, Context& context, const tachyon::ElementRef& rowRef, bool hasArrow, tachyon::ID rowID); + tachyon::EventHandler MakeTreeRowDragDropHandler(GUIApplication& app, Context& context, tachyon::ID rowID, bool rowHasChildren, ItemDragDropConfig* dd, bool* isOpen = nullptr); + bool TreeItemRenameCheck(GUIApplication& app, Context& context, tachyon::ID bodyID, std::string* renameBuffer, StyleRef textStyle); +} diff --git a/src/gui_controls/controls_table_virtual.cpp b/src/gui_views/controls_table_virtual.cpp similarity index 78% rename from src/gui_controls/controls_table_virtual.cpp rename to src/gui_views/controls_table_virtual.cpp index 0edf0f26..11759b21 100644 --- a/src/gui_controls/controls_table_virtual.cpp +++ b/src/gui_views/controls_table_virtual.cpp @@ -1,28 +1,30 @@ +#include // VirtualTable: the geometry pipeline. Builds the header section, body // sections, scrollbar overlays, and column sizers for one frame's worth of // the table widget. The body-row loop calls each column's user-supplied -// generateCell, which routes through Cell()/TreeCell() (in +// generateCell, which routes through Cell(app, context)/TreeCell(app, context) (in // controls_table_cells.cpp) to emit cells directly. // // Event-handler builders live in controls_table_handlers.cpp. -#include "controls_table_internal.h" +#include -#include +#include #include #include #include #include -namespace tachyon +namespace tachyon::views { - using namespace tachyon::TableInternal; + using namespace tachyon::views::TableInternal; - void GUIApplication::EmitTableHeaderCell(TableEmit& emit, tachyon::ID tableID, int c, int16_t gridCol, + void EmitTableHeaderCell(GUIApplication& app, Context& context, TableEmit& emit, tachyon::ID tableID, int c, int16_t gridCol, bool isStretchTrack, int sectionMin, int sectionMax, int effectiveSortCol, IconID sortIcon) { + const Styles& styles = GetStyles(app, context); TableState* state = emit.userState; VirtualTableColumn* columns = emit.columns; const size_t colCount = emit.columnCount; @@ -42,20 +44,20 @@ namespace tachyon const bool isInteractive = isSortable || isReorderable; // Over cells aligned to the end (numbers), the header is too, so it sits over its values. bool cellsAtEnd = false; - if (const LayoutStyle* cs = styleManager.GetLayoutStyle(columns[c].column.cellStyle.layoutStyleIndex)) + if (const LayoutStyle* cs = app.styleManager.GetLayoutStyle(columns[c].column.cellStyle.layoutStyleIndex)) { const TextAlign align = cs->textLayoutStyle.horizontalAlignment; cellsAtEnd = align == TextAlign::End || align == TextAlign::Right; } - const StyleRef headerStyle = isInteractive ? (cellsAtEnd ? theme.tableHeaderEndStyleRef : theme.tableHeaderStyleRef) - : (cellsAtEnd ? theme.tableHeaderLockedEndStyleRef : theme.tableHeaderLockedStyleRef); + const StyleRef headerStyle = isInteractive ? (cellsAtEnd ? styles.tableHeaderEndStyleRef : styles.tableHeaderStyleRef) + : (cellsAtEnd ? styles.tableHeaderLockedEndStyleRef : styles.tableHeaderLockedStyleRef); // Stable per-column header ID from VirtualTable's prologue: emit order changes // during a drag (dragged column last), which would shift a dynamic ID and lose capture. const tachyon::ID cellID = emit.columns[c].internal.headerCellID != tachyon::ID::Invalid() ? emit.columns[c].internal.headerCellID - : idManager.AllocateDynamicID(); - tachyon::ElementState cellState = guiStateManager.GetCurrentState(cellID); + : app.idManager.AllocateDynamicID(); + tachyon::ElementState cellState = app.guiStateManager.GetCurrentState(cellID); tachyon::Element cell{}; cell.id = cellID; cell.state = cellState; @@ -70,10 +72,10 @@ namespace tachyon if (!columns[c].column.header.empty()) { - cell.textID = textSystem->RegisterText(cellID, + cell.textID = app.textSystem->RegisterText(cellID, isSortCol ? sortIcon : IconID::Invalid, columns[c].column.header, headerStyle, cellState); - const int32_t headerW = textSystem->GetTextMeasurement(cell.textID).maxWidth; + const int32_t headerW = app.textSystem->GetTextMeasurement(cell.textID).maxWidth; columns[c].internal.maxContentWidth = std::max(columns[c].internal.maxContentWidth, headerW); } @@ -100,7 +102,7 @@ namespace tachyon statePtr->sortDescending = false; } }; - auto moveColumn = [this, statePtr](int from, int to) + auto moveColumn = [&app, statePtr](int from, int to) { TableState::ReorderColumnsFn* onReorder = statePtr->onReorderColumns.get(); if (from == to || !onReorder || !*onReorder) @@ -123,7 +125,7 @@ namespace tachyon if (from < to) std::rotate(widths.begin() + from, widths.begin() + from + 1, widths.begin() + to + 1); else std::rotate(widths.begin() + to, widths.begin() + from, widths.begin() + from + 1); } - transitionManager.Clear(); + app.transitionManager.Clear(); return true; }; // With the header focused: Space or Enter sorts by it, Alt+Left / Right moves the @@ -131,9 +133,9 @@ namespace tachyon // (header IDs go by position). const ID leftHeaderID = isReorderable && colIdx - 1 >= minTarget ? columns[colIdx - 1].internal.headerCellID : tachyon::ID::Invalid(); const ID rightHeaderID = isReorderable && colIdx + 1 <= maxTarget ? columns[colIdx + 1].internal.headerCellID : tachyon::ID::Invalid(); - auto headerKeys = [this, colIdx, isSortable, sortBy, moveColumn, leftHeaderID, rightHeaderID](const ElementEvent& event) -> bool + auto headerKeys = [&app, colIdx, isSortable, sortBy, moveColumn, leftHeaderID, rightHeaderID](const ElementEvent& event) -> bool { - if (event.type != tachyon::EventType::KeyDown || guiStateManager.Interaction().GetFocusedID() != event.id) + if (event.type != tachyon::EventType::KeyDown || app.guiStateManager.Interaction().GetFocusedID() != event.id) return false; if (isSortable && IsActivationKey(event)) { @@ -146,7 +148,7 @@ namespace tachyon { const ID target = left ? leftHeaderID : rightHeaderID; if (target != tachyon::ID::Invalid() && moveColumn(colIdx, left ? colIdx - 1 : colIdx + 1)) - guiStateManager.Interaction().SetFocusID(target); + app.guiStateManager.Interaction().SetFocusID(target); return true; } return false; @@ -154,11 +156,11 @@ namespace tachyon if (isReorderable) { - cell.eventHandler = [this, statePtr, tableID, colIdx, isSortable, minTarget, maxTarget, + cell.eventHandler = [&context, &app, statePtr, tableID, colIdx, isSortable, minTarget, maxTarget, sectionIdx, colCount, sortBy, moveColumn, headerKeys] (ElementEvent&& event) -> bool { - auto& drag = m_columnDrag; + auto& drag = context.columnDrag; switch (event.type) { case tachyon::EventType::MouseDown: @@ -175,7 +177,7 @@ namespace tachyon { tachyon::IntRect r{}; if (i < statePtr->internal.headerRefs.size()) - if (auto* rp = elementStorage.GetElementRectPtr(statePtr->internal.headerRefs[i])) + if (auto* rp = app.elementStorage.GetElementRectPtr(statePtr->internal.headerRefs[i])) r = rp->rect; drag.headerRects.push_back(r); } @@ -184,12 +186,12 @@ namespace tachyon int32_t startScrollX = 0; if (drag.sectionBodyID != tachyon::ID::Invalid()) { - auto& sm = guiStateManager.GetScrollManagement(); + auto& sm = app.guiStateManager.GetScrollManagement(); const auto h = sm.GetScrollOffsetHandle(drag.sectionBodyID); if (sm.IsScrollOffsetHandleValid(h)) startScrollX = sm.GetScrollOffset(h).x; } - drag.press.Press(event, elementStorage, guiStateManager, startScrollX); + drag.press.Press(event, app.elementStorage, app.guiStateManager, startScrollX); return true; } @@ -197,21 +199,21 @@ namespace tachyon { if (drag.tableID != tableID || drag.fromCol != colIdx || !drag.press.IsPressed(event.id)) break; // headerRects and the body's rect are in layout space; the cursor too. - const int32_t mouseX = event.LocalCursor(elementStorage).x; + const int32_t mouseX = event.LocalCursor(app.elementStorage).x; drag.offsetX = mouseX - drag.press.drag.pressLocal.x; - if (drag.press.Move(event, styleManager.Px(kDragStartDistance)) && !drag.headerRects.empty()) + if (drag.press.Move(event, app.styleManager.Px(kDragStartDistance)) && !drag.headerRects.empty()) { // Auto-scroll near the body's left/right edges, before // resolving the drop target so it uses the new scroll. int32_t curScrollX = drag.press.before; if (drag.sectionBodyID != tachyon::ID::Invalid()) { - auto bodyRef = elementStorage.FindElementRefByID(drag.sectionBodyID); + auto bodyRef = app.elementStorage.FindElementRefByID(drag.sectionBodyID); if (bodyRef.IsValid()) { - const auto& bodyRect = elementStorage.GetElementRectUnsafe(bodyRef); - const int kEdgeZoneWidth = styleManager.Px(30); - const int kAutoScrollPerEvent = styleManager.Px(12); + const auto& bodyRect = app.elementStorage.GetElementRectUnsafe(bodyRef); + const int kEdgeZoneWidth = app.styleManager.Px(30); + const int kAutoScrollPerEvent = app.styleManager.Px(12); const int32_t innerLeft = bodyRect.innerRect.x; const int32_t innerRight = bodyRect.innerRect.x + bodyRect.innerRect.w; int32_t scrollDelta = 0; @@ -220,7 +222,7 @@ namespace tachyon else if (mouseX > innerRight - kEdgeZoneWidth) scrollDelta = -kAutoScrollPerEvent; // scroll content left - auto& sm = guiStateManager.GetScrollManagement(); + auto& sm = app.guiStateManager.GetScrollManagement(); const auto h = sm.GetOrCreateScrollOffsetHandle(drag.sectionBodyID); const int2 cur = sm.GetScrollOffset(h); if (scrollDelta != 0) @@ -252,11 +254,11 @@ namespace tachyon const int from = drag.fromCol; const int to = drag.toCol; drag = {}; - guiStateManager.Interaction().ReleaseCaptureID(); + app.guiStateManager.Interaction().ReleaseCaptureID(); if (committed) { if (moveColumn(from, to)) - TakeFocus(guiStateManager, tachyon::ID::Invalid()); + TakeFocus(app.guiStateManager, tachyon::ID::Invalid()); } else if (isSortable) sortBy(); @@ -265,7 +267,7 @@ namespace tachyon case tachyon::EventType::KeyDown: { - if (drag.tableID == tableID && drag.fromCol == colIdx && drag.press.Cancel(event, guiStateManager)) + if (drag.tableID == tableID && drag.fromCol == colIdx && drag.press.Cancel(event, app.guiStateManager)) { drag = {}; return true; @@ -280,11 +282,11 @@ namespace tachyon } else if (isSortable) { - cell.eventHandler = [this, sortBy, headerKeys](ElementEvent&& event) -> bool + cell.eventHandler = [&app, sortBy, headerKeys](ElementEvent&& event) -> bool { if (event.type == tachyon::EventType::MouseDown && event.state.LeftPressed()) { - TakeFocus(guiStateManager, event.id); + TakeFocus(app.guiStateManager, event.id); sortBy(); return true; } @@ -295,10 +297,10 @@ namespace tachyon if (isInteractive) { cell.flags |= ElementFlags::IsControl; - RegisterTabStop(cellID); + app.RegisterTabStop(cellID); } - const GridTrack track = ComputeColumnTrack(styleManager, + const GridTrack track = ComputeColumnTrack(app.styleManager, c, int(colCount), columns, state->columnWidths, emit.dragActive, emit.lastColDragFixedWidth, isStretchTrack); @@ -307,16 +309,16 @@ namespace tachyon tachyon::LayoutOverride lo; lo = ApplyColumnDragOffsetX( std::move(lo).GridColumn(gridCol).GridRow(0).ColumnTrack(track).StickyY(), emit, c); - auto hRes = elementStorage.Add(std::move(cell), std::move(lo)); + auto hRes = app.elementStorage.Add(std::move(cell), std::move(lo)); VERIFY(hRes.status); - VERIFY(windowRegistry.Add(hRes.ref)); + VERIFY(app.windowRegistry.Add(hRes.ref)); columns[c].internal.headerRef = hRes.ref; if (state->internal.headerRefs.size() != colCount) state->internal.headerRefs.resize(colCount); state->internal.headerRefs[size_t(c)] = hRes.ref; } - void GUIApplication::EmitTableHeaderSection(TableEmit& emit, tachyon::ID tableID, + void EmitTableHeaderSection(GUIApplication& app, Context& context, TableEmit& emit, tachyon::ID tableID, int colStart, int colEnd, bool lastColIsStretch, int effectiveSortCol, IconID sortIcon) { @@ -331,22 +333,22 @@ namespace tachyon const bool explicitStretch = emit.columns[c].column.sizing == ColumnSizing::Stretch; const bool implicitStretch = lastColIsStretch && isLastInSection && emit.columns[c].column.sizing != ColumnSizing::Fixed; - EmitTableHeaderCell(emit, tableID, c, static_cast(c - colStart), + EmitTableHeaderCell(app, context, emit, tableID, c, static_cast(c - colStart), explicitStretch || implicitStretch, colStart, colEnd - 1, effectiveSortCol, sortIcon); } } - GridTrack GUIApplication::ComputeSectionColumnTrack(const TableEmit& emit, int c, int colEnd, - bool isMiddle, bool fitContent) const + GridTrack ComputeSectionColumnTrack(GUIApplication& app, const TableEmit& emit, int c, int colEnd, + bool isMiddle, bool fitContent) { const bool isLastInSection = (c + 1 == colEnd); const bool explicitStretch = emit.columns[c].column.sizing == ColumnSizing::Stretch; const bool implicitStretch = isMiddle && isLastInSection && emit.columns[c].column.sizing != ColumnSizing::Fixed; const bool stretch = !fitContent && (explicitStretch || implicitStretch); - return ComputeColumnTrack(styleManager, c, int(emit.columnCount), + return ComputeColumnTrack(app.styleManager, c, int(emit.columnCount), emit.columns, emit.userState->columnWidths, emit.dragActive, emit.lastColDragFixedWidth, @@ -356,7 +358,7 @@ namespace tachyon // ---- Direct-emit primitives ---- - void GUIApplication::EmitDirectRowBackdrop(tachyon::ID rowID, int16_t gridRow, + void EmitDirectRowBackdrop(GUIApplication& app, Context& context, tachyon::ID rowID, int16_t gridRow, int colStart, int colEnd, tachyon::ElementState backdropState, tachyon::ElementFlags backdropFlags, @@ -371,27 +373,27 @@ namespace tachyon backdrop.state = backdropState; backdrop.styleRef = rowStyle; backdrop.eventHandler = std::move(backdropHandler); - auto bRes = elementStorage.Add(std::move(backdrop), + auto bRes = app.elementStorage.Add(std::move(backdrop), tachyon::LayoutOverride{} .GridColumn(0, static_cast(colEnd - colStart)) .GridRow(gridRow)); VERIFY(bRes.status); - VERIFY(windowRegistry.Add(bRes.ref)); + VERIFY(app.windowRegistry.Add(bRes.ref)); // Tree-reorder drop indicator on the row backdrop (spans the whole section): // a line at Before / After, or Inside (indented). The line starts where the // tree cell's items do at the target's depth: columns before the tree's and the // cell's padding come first. - [[maybe_unused]] auto cdRes = elementStorage.AddCustomDraw(bRes.ref, - [this, rowID, tableState, isLastSection, - lineColor = theme.treeDropIndicatorStyle] + [[maybe_unused]] auto cdRes = app.elementStorage.AddCustomDraw(bRes.ref, + [&context, &app, rowID, tableState, isLastSection, + lineColor = app.theme.treeDropIndicatorStyle] (tachyon::CustomDrawContext& ctx) { - // A cancelled drag fires neither Drop nor DragOut, so m_treeDropState + // A cancelled drag fires neither Drop nor DragOut, so context.treeDrop // can be stale; gate on the live drag. - if (!guiStateManager.Drag().IsDragging()) return; - if (m_treeDropState.targetRowID != rowID - || m_treeDropState.position == TreeDropPosition::None) return; + if (!app.guiStateManager.Drag().IsDragging()) return; + if (context.treeDrop.targetRowID != rowID + || context.treeDrop.position == TreeDropPosition::None) return; // Span the outer rect so insets match the row's visual edges. const auto outer = ctx.ElementRect(); @@ -400,25 +402,25 @@ namespace tachyon const int32_t h = outer.h; const int32_t topY = outer.y - inner.y; const int32_t leftX = outer.x - inner.x; - const int32_t kIndent = theme.treeTableIndent; - const int32_t kThick = styleManager.Px(3); + const int32_t kIndent = context.styles.treeTableIndent; + const int32_t kThick = app.styleManager.Px(3); const int32_t half = kThick / 2; // insets that keep the line inside the row // Where the tree cell's items start: its content edge, the x its indent and // guide lines start from. The row's edge when it has no tree cell this frame. int32_t itemsX = leftX; int32_t expanderW = 0; // the arrow column before an item's icon, when the tree has one if (const auto* info = tableState ? tableState->FindTreeRow(rowID) : nullptr; - info && elementStorage.IsValidRef(info->cellRef) - && elementStorage.GetElementUnsafe(info->cellRef).id == info->cellID) + info && app.elementStorage.IsValidRef(info->cellRef) + && app.elementStorage.GetElementUnsafe(info->cellRef).id == info->cellID) { itemsX = ctx.GetElementRect(info->cellRef).x; - const tachyon::StyleRef cellStyle = elementStorage.GetElementUnsafe(info->cellRef).styleRef; - if (const tachyon::LayoutStyle* ls = styleManager.GetLayoutStyle(cellStyle.layoutStyleIndex)) + const tachyon::StyleRef cellStyle = app.elementStorage.GetElementUnsafe(info->cellRef).styleRef; + if (const tachyon::LayoutStyle* ls = app.styleManager.GetLayoutStyle(cellStyle.layoutStyleIndex)) itemsX += ls->borderWidths.left + ls->padding.left; - if (info->expanderColumn) expanderW = theme.treeTableExpanderWidth; + if (info->expanderColumn) expanderW = context.styles.treeTableExpanderWidth; } // The target's arrow column: the box around a row for InsideLast starts there. - const int32_t depthX = itemsX + m_treeDropState.targetDepth * kIndent; + const int32_t depthX = itemsX + context.treeDrop.targetDepth * kIndent; // A line marks where the item lands: it starts at the icons of the items at // that depth, past their arrow column. const int32_t lineX = depthX + expanderW; @@ -426,13 +428,13 @@ namespace tachyon // On the rightmost section, always stop short of the V-scrollbar // overlay (+2 px gap), whether or not the bar is currently shown. const int32_t scrollbarPad = isLastSection - ? theme.scrollbarThickness + styleManager.Px(2) : 0; + ? app.theme.scrollbarThickness + app.styleManager.Px(2) : 0; const int32_t rightEdge = leftX + w - scrollbarPad; tachyon::LineStyle indStyle { .colorStyleIndex = lineColor, .lineWidth = float(kThick) }; // InsideLast -> rectangle around the row (drop as last child). - if (m_treeDropState.position == TreeDropPosition::InsideLast) + if (context.treeDrop.position == TreeDropPosition::InsideLast) { const int32_t leftL = depthX; const int32_t rightL = rightEdge - 1; @@ -449,7 +451,7 @@ namespace tachyon // so a line at y=h would be hidden by the next row. int32_t lineLeft; int32_t y; - switch (m_treeDropState.position) + switch (context.treeDrop.position) { case TreeDropPosition::Before: lineLeft = lineX; @@ -471,45 +473,46 @@ namespace tachyon } - void GUIApplication::EmitDirectRowSpacer(int16_t gridRow, + void EmitDirectRowSpacer(GUIApplication& app, Context& context, int16_t gridRow, int colStart, int colEnd, int32_t height) { + const Styles& styles = GetStyles(app, context); if (height <= 0) return; - tachyon::ID spacerID = idManager.AllocateDynamicID("_table_spacer"); + tachyon::ID spacerID = app.idManager.AllocateDynamicID("_table_spacer"); tachyon::Element spacer{}; spacer.id = spacerID; - spacer.styleRef = theme.tableCellStyleRef; + spacer.styleRef = styles.tableCellStyleRef; spacer.flags = tachyon::ElementFlags::NoInput; - spacer.state = guiStateManager.GetCurrentState(spacerID); - auto rSpRes = elementStorage.Add(std::move(spacer), + spacer.state = app.guiStateManager.GetCurrentState(spacerID); + auto rSpRes = app.elementStorage.Add(std::move(spacer), tachyon::LayoutOverride{} .GridColumn(0, static_cast(colEnd - colStart)) .GridRow(gridRow) .RowTrack(GridTrack::Fixed(static_cast(height)))); VERIFY(rSpRes.status); - VERIFY(windowRegistry.Add(rSpRes.ref)); + VERIFY(app.windowRegistry.Add(rSpRes.ref)); } - void GUIApplication::OpenTableBodySection(TableEmit& emit, tachyon::ID sectionID, tachyon::StyleRef sectionStyle, + void OpenTableBodySection(GUIApplication& app, Context& context, TableEmit& emit, tachyon::ID sectionID, tachyon::StyleRef sectionStyle, tachyon::LayoutOverride&& layout, bool sampleViewport) { - auto bsRes = elementStorage.Add( + auto bsRes = app.elementStorage.Add( tachyon::Element { .id = sectionID, .styleRef = sectionStyle, - .state = guiStateManager.GetCurrentState(sectionID) + .state = app.guiStateManager.GetCurrentState(sectionID) }, std::move(layout)); VERIFY(bsRes.status); - VERIFY(windowRegistry.Add(bsRes.ref)); + VERIFY(app.windowRegistry.Add(bsRes.ref)); // Sample overflow on every section so next frame knows which scrollbars to emit. // sampleViewport (rightmost section only) also records the viewport size. TableState* statePtr = emit.userState; [[maybe_unused]] - auto cdResult = elementStorage.AddPostLayout(bsRes.ref, - [this, statePtr, sampleViewport](tachyon::PostLayoutContext& plctx) + auto cdResult = app.elementStorage.AddPostLayout(bsRes.ref, + [&context, &app, statePtr, sampleViewport](tachyon::PostLayoutContext& plctx) { const auto innerRect = plctx.ElementInnerRect(); const int2 contentSize = plctx.GetContentSize(plctx.Ref()); @@ -523,11 +526,11 @@ namespace tachyon // are final (and after the keyboard/scroll handlers, so it // observes this frame's scroll position). if (statePtr->followTail) - UpdateTableFollowTail(*statePtr, innerRect.h, contentSize.y); + UpdateTableFollowTail(app, *statePtr, innerRect.h, contentSize.y); } }); - VERIFY(elementStorage.BeginChildren()); + VERIFY(app.elementStorage.BeginChildren()); } @@ -535,17 +538,17 @@ namespace tachyon // trick as the keyboard End handler: aim the scroll way past the end and let // ClampScrollOffsetToContent settle on the true max (which accounts for row // gaps + the bottom pad). Runs post-layout, so the section rects are final. - void GUIApplication::ScrollTableSectionsToBottom(TableState& state) + void ScrollTableSectionsToBottom(GUIApplication& app, TableState& state) { - auto& sm = guiStateManager.GetScrollManagement(); + auto& sm = app.guiStateManager.GetScrollManagement(); int32_t writtenY = 0; for (int i = 0; i < state.internal.sectionCount; i++) { const tachyon::ID sid = state.SectionBodyID(i); if (sid == tachyon::ID::Invalid()) continue; - auto sref = elementStorage.FindElementRefByID(sid); + auto sref = app.elementStorage.FindElementRefByID(sid); if (!sref.IsValid()) continue; - const auto& srect = elementStorage.GetElementRectUnsafe(sref); + const auto& srect = app.elementStorage.GetElementRectUnsafe(sref); auto h = sm.GetOrCreateScrollOffsetHandle(sid); const tachyon::int2 cur = sm.GetScrollOffset(h); const tachyon::int2 clamped = LayoutHelpers::ClampScrollOffsetToContent( @@ -567,9 +570,9 @@ namespace tachyon // last) on the very first laid-out frame, and again whenever the row count // grows while still pinned; scrolling up clears the pin, scrolling back sets // it. Scroll offset Y is <= 0 (content shifts up), so -y is the magnitude. - void GUIApplication::UpdateTableFollowTail(TableState& state, int32_t viewportH, int32_t contentH) + void UpdateTableFollowTail(GUIApplication& app, TableState& state, int32_t viewportH, int32_t contentH) { - auto& sm = guiStateManager.GetScrollManagement(); + auto& sm = app.guiStateManager.GetScrollManagement(); const int32_t maxScroll = std::max(0, contentH - viewportH); int32_t curMag = 0; if (state.internal.bodyID != tachyon::ID::Invalid()) @@ -594,7 +597,7 @@ namespace tachyon if (pin) { - ScrollTableSectionsToBottom(state); + ScrollTableSectionsToBottom(app, state); // Select the row shown at the bottom (the last VISUAL row under a sort). if (state.internal.rowsRangeID != tachyon::ID::Invalid() && state.internal.totalRowCount > 0) { @@ -618,13 +621,14 @@ namespace tachyon // Emit the dragged column's cells, header and sizer last in the section so it // paints over its neighbours. The other emit phases skip it. - void GUIApplication::EmitDraggedColumnOnTop(TableEmit& emit, tachyon::ID tableID, + void EmitDraggedColumnOnTop(GUIApplication& app, Context& context, TableEmit& emit, tachyon::ID tableID, int colStart, int colEnd, int firstVisible, int lastVisible, tachyon::ID rowsRangeID, bool lastColIsStretch, int effectiveSortCol, IconID sortIcon) { + const Styles& styles = GetStyles(app, context); const int draggedCol = emit.draggedCol; if (draggedCol < colStart || draggedCol >= colEnd) return; @@ -643,7 +647,7 @@ namespace tachyon for (int visualIdx = firstVisible; visualIdx < lastVisible; visualIdx++) { const int datasetIdx = state->VisualToDataset(visualIdx); - const tachyon::ID rowID = idManager.GetSubID(rowsRangeID, + const tachyon::ID rowID = app.idManager.GetSubID(rowsRangeID, static_cast(datasetIdx)); const bool rowSelected = state->multiSelect ? state->multiSelect->selectedIDs.count(rowID) > 0 @@ -656,9 +660,9 @@ namespace tachyon // colour) so the dragged column isn't transparent over // overlapped neighbour content. const StyleRef rowStyle = (state->rowStyle.layoutStyleIndex != LayoutStyleIndex::Invalid) ? state->rowStyle - : (visualIdx % 2 == 0) ? theme.tableRowStyleRef : theme.tableRowAltStyleRef; - const tachyon::ID bgID = idManager.AllocateDynamicID("_table_drag_col_bg"); - tachyon::ElementState bgState = guiStateManager.GetCurrentState(bgID); + : (visualIdx % 2 == 0) ? styles.tableRowStyleRef : styles.tableRowAltStyleRef; + const tachyon::ID bgID = app.idManager.AllocateDynamicID("_table_drag_col_bg"); + tachyon::ElementState bgState = app.guiStateManager.GetCurrentState(bgID); if (!cellMode && rowSelected) bgState |= tachyon::ElementState::Selected; tachyon::Element bg{}; bg.id = bgID; @@ -669,13 +673,13 @@ namespace tachyon .GridColumn(static_cast(draggedCol - colStart)) .GridRow(static_cast(emit.directGridRow)); bgLo = ApplyColumnDragOffsetX(std::move(bgLo), emit, draggedCol); - auto bgRes = elementStorage.Add(std::move(bg), std::move(bgLo)); + auto bgRes = app.elementStorage.Add(std::move(bg), std::move(bgLo)); VERIFY(bgRes.status); - VERIFY(windowRegistry.Add(bgRes.ref)); + VERIFY(app.windowRegistry.Add(bgRes.ref)); - if (rowModeSelected) guiStateManager.Construction().PushSelected(); + if (rowModeSelected) app.guiStateManager.Construction().PushSelected(); generateCell(datasetIdx); - if (rowModeSelected) guiStateManager.Construction().PopSelected(); + if (rowModeSelected) app.guiStateManager.Construction().PopSelected(); } emit.currentRowID = tachyon::ID::Invalid(); } @@ -687,7 +691,7 @@ namespace tachyon const bool explicitStretch = emit.columns[draggedCol].column.sizing == ColumnSizing::Stretch; const bool implicitStretch = lastColIsStretch && isLastInSection && emit.columns[draggedCol].column.sizing != ColumnSizing::Fixed; - EmitTableHeaderCell(emit, tableID, draggedCol, + EmitTableHeaderCell(app, context, emit, tableID, draggedCol, static_cast(draggedCol - colStart), explicitStretch || implicitStretch, colStart, colEnd - 1, effectiveSortCol, sortIcon); @@ -698,12 +702,12 @@ namespace tachyon if (emit.showHeaders && draggedCol + 1 < colEnd) { // A 2-column slice emits exactly this one sizer. - EmitColumnSizers(emit, draggedCol, draggedCol + 2, /*skipDragged*/false); + EmitColumnSizers(app, context, emit, draggedCol, draggedCol + 2, /*skipDragged*/false); } } - void GUIApplication::CloseTableBodySection(TableEmit& emit, + void CloseTableBodySection(GUIApplication& app, TableEmit& emit, tachyon::ID sectionBodyID, bool emitVerticalScrollbar, bool suppressHorzScrollbar) { @@ -717,7 +721,7 @@ namespace tachyon const bool emitVert = emit.anyVertOverflow; if (emitVerticalScrollbar) { - ScrollbarOverlay(sectionBodyID, + app.ScrollbarOverlay(sectionBodyID, int2{ state->internal.lastViewportW, state->internal.lastViewportH }, state->internal.vertScrollbarID, state->internal.horzScrollbarID, @@ -726,21 +730,22 @@ namespace tachyon } else if (emitHorz) { - const tachyon::ID hbarID = idManager.AllocateDynamicID("_table_section_hbar"); - HorizontalScrollbar(hbarID, sectionBodyID); + const tachyon::ID hbarID = app.idManager.AllocateDynamicID("_table_section_hbar"); + app.HorizontalScrollbar(hbarID, sectionBodyID); } - VERIFY(elementStorage.EndChildren()); + VERIFY(app.elementStorage.EndChildren()); } - void GUIApplication::EmitVirtualBodyRows(TableEmit& emit, + void EmitVirtualBodyRows(GUIApplication& app, Context& context, TableEmit& emit, int colStart, int colEnd, int totalRowCount, int32_t actualRowHeight, int firstVisible, int lastVisible, tachyon::ID rowsRangeID, bool isLastSection) { + const Styles& styles = GetStyles(app, context); if (colStart >= colEnd) return; TableState* state = emit.userState; @@ -749,8 +754,8 @@ namespace tachyon // Hot-path locals. const bool cellMode = emit.cellMode; const bool customRows = state->rowStyle.layoutStyleIndex != LayoutStyleIndex::Invalid; - const StyleRef rowStyleEven = customRows ? state->rowStyle : theme.tableRowStyleRef; - const StyleRef rowStyleOdd = customRows ? state->rowStyle : theme.tableRowAltStyleRef; + const StyleRef rowStyleEven = customRows ? state->rowStyle : styles.tableRowStyleRef; + const StyleRef rowStyleOdd = customRows ? state->rowStyle : styles.tableRowAltStyleRef; const tachyon::EventHandler& sharedHandler = emit.sharedRowHandler; // Section grid rows: [header] | [top spacer] | visible rows | [bottom spacer]. @@ -768,7 +773,7 @@ namespace tachyon // Between the optional sticky header and the first visible row. if (firstVisible > 0) { - EmitDirectRowSpacer(static_cast(headerRowOffset), + EmitDirectRowSpacer(app, context, static_cast(headerRowOffset), colStart, colEnd, firstVisible * actualRowHeight); } @@ -778,13 +783,13 @@ namespace tachyon for (int visualIdx = firstVisible; visualIdx < lastVisible; visualIdx++) { const int datasetIdx = state->VisualToDataset(visualIdx); - const tachyon::ID rowID = idManager.GetSubID(rowsRangeID, + const tachyon::ID rowID = app.idManager.GetSubID(rowsRangeID, static_cast(datasetIdx)); const bool rowSelected = state->multiSelect ? state->multiSelect->selectedIDs.count(rowID) > 0 : (state->selectedRowID == rowID); const StyleRef rowStyle = (visualIdx % 2 == 0) ? rowStyleEven : rowStyleOdd; - tachyon::ElementState backdropState = guiStateManager.GetCurrentState(rowID); + tachyon::ElementState backdropState = app.guiStateManager.GetCurrentState(rowID); if (!cellMode && rowSelected) backdropState |= tachyon::ElementState::Selected; // A row spans its sections: each section after the first (colStart > 0) has a // backdrop of its own with the row's ID. @@ -792,7 +797,7 @@ namespace tachyon (cellMode ? tachyon::ElementFlags::NoInput : tachyon::ElementFlags::None) | (colStart > 0 ? tachyon::ElementFlags::SharesID : tachyon::ElementFlags::None); - EmitDirectRowBackdrop(rowID, static_cast(gridRowOf(visualIdx)), + EmitDirectRowBackdrop(app, context, rowID, static_cast(gridRowOf(visualIdx)), colStart, colEnd, backdropState, backdropFlags, rowStyle, sharedHandler, state, isLastSection); @@ -800,7 +805,7 @@ namespace tachyon } // ---- Column backgrounds (full-height, over backdrops, under cells) ---- - EmitColumnBackgrounds(emit, colStart, colEnd); + EmitColumnBackgrounds(app, context, emit, colStart, colEnd); // ---- Cells, column by column ---- emit.currentRowHandler = sharedHandler; @@ -816,7 +821,7 @@ namespace tachyon for (int visualIdx = firstVisible; visualIdx < lastVisible; visualIdx++) { const int datasetIdx = state->VisualToDataset(visualIdx); - const tachyon::ID rowID = idManager.GetSubID(rowsRangeID, + const tachyon::ID rowID = app.idManager.GetSubID(rowsRangeID, static_cast(datasetIdx)); const bool rowSelected = state->multiSelect ? state->multiSelect->selectedIDs.count(rowID) > 0 @@ -826,9 +831,9 @@ namespace tachyon emit.directGridRow = gridRowOf(visualIdx); emit.currentRowID = rowID; - if (rowModeSelected) guiStateManager.Construction().PushSelected(); + if (rowModeSelected) app.guiStateManager.Construction().PushSelected(); generateCell(datasetIdx); - if (rowModeSelected) guiStateManager.Construction().PopSelected(); + if (rowModeSelected) app.guiStateManager.Construction().PopSelected(); } } @@ -837,20 +842,20 @@ namespace tachyon { for (int visualIdx = firstVisible; visualIdx < lastVisible; visualIdx++) { - const tachyon::ID rowID = idManager.GetSubID(rowsRangeID, + const tachyon::ID rowID = app.idManager.GetSubID(rowsRangeID, static_cast(state->VisualToDataset(visualIdx))); const bool rowSelected = state->multiSelect ? state->multiSelect->selectedIDs.count(rowID) > 0 : (state->selectedRowID == rowID); if (!rowSelected) continue; tachyon::Element bar{}; - bar.id = idManager.AllocateDynamicID("_table_row_bar"); + bar.id = app.idManager.AllocateDynamicID("_table_row_bar"); bar.flags = tachyon::ElementFlags::NoInput; - bar.styleRef = theme.tableRowBarStyleRef; - auto barRes = elementStorage.Add(std::move(bar), tachyon::LayoutOverride{} + bar.styleRef = styles.tableRowBarStyleRef; + auto barRes = app.elementStorage.Add(std::move(bar), tachyon::LayoutOverride{} .GridColumn(0).GridRow(static_cast(gridRowOf(visualIdx)))); VERIFY(barRes.status); - VERIFY(windowRegistry.Add(barRes.ref)); + VERIFY(app.windowRegistry.Add(barRes.ref)); } } @@ -860,22 +865,22 @@ namespace tachyon // ---- Bottom spacer ---- // Pad by the scrollbar thickness only when some section overflows X, so the // H-scrollbar doesn't cover the last row. - const int32_t hScrollPad = emit.anyHorzOverflow ? theme.scrollbarThickness : 0; + const int32_t hScrollPad = emit.anyHorzOverflow ? app.theme.scrollbarThickness : 0; const int32_t belowVisibleH = (totalRowCount - lastVisible) * actualRowHeight + hScrollPad; - EmitDirectRowSpacer(static_cast(gridRowFirst + visibleCount), + EmitDirectRowSpacer(app, context, static_cast(gridRowFirst + visibleCount), colStart, colEnd, belowVisibleH); } - void GUIApplication::MirrorTableScroll(TableState* state) + void MirrorTableScroll(GUIApplication& app, TableState* state) { // Y is shared: the section the user scrolled wins and is copied to the rest. // X isn't mirrored; headers live in each section's own scroll container. const int n = state->internal.sectionCount; if (n <= 0) return; - auto& sm = guiStateManager.GetScrollManagement(); + auto& sm = app.guiStateManager.GetScrollManagement(); std::array offsets{}; for (int i = 0; i < n; i++) @@ -931,28 +936,30 @@ namespace tachyon } - void GUIApplication::EmitTableSectionSeparator() + void EmitTableSectionSeparator(GUIApplication& app, Context& context) { - const tachyon::ID sepID = idManager.AllocateDynamicID(); + const Styles& styles = GetStyles(app, context); + const tachyon::ID sepID = app.idManager.AllocateDynamicID(); tachyon::Element sep{}; sep.id = sepID; - sep.styleRef = theme.tableSeparatorStyleRef; + sep.styleRef = styles.tableSeparatorStyleRef; sep.flags = tachyon::ElementFlags::NoInput; - sep.state = guiStateManager.GetCurrentState(sepID); - auto sRes = elementStorage.Add(std::move(sep), + sep.state = app.guiStateManager.GetCurrentState(sepID); + auto sRes = app.elementStorage.Add(std::move(sep), tachyon::LayoutOverride{}.NoGrow().NoShrink()); VERIFY(sRes.status); - VERIFY(windowRegistry.Add(sRes.ref)); + VERIFY(app.windowRegistry.Add(sRes.ref)); } - void GUIApplication::EmitColumnSeparators(TableEmit& emit, int colStart, int colEnd) + void EmitColumnSeparators(GUIApplication& app, Context& context, TableEmit& emit, int colStart, int colEnd) { + const Styles& styles = GetStyles(app, context); // 1px dividers between columns for headerless tables (sizers mark them otherwise). // Placed by absolute X from the column tracks; boundaries past a Stretch track are skipped. if (colEnd - colStart < 2) return; int32_t gap = 0; - if (const tachyon::LayoutStyle* ls = styleManager.GetLayoutStyle(theme.tableScrollableBodyStyleRef.layoutStyleIndex)) + if (const tachyon::LayoutStyle* ls = app.styleManager.GetLayoutStyle(styles.tableScrollableBodyStyleRef.layoutStyleIndex)) gap = ls->layoutData.grid.column.gap; int32_t x = 0; @@ -963,33 +970,34 @@ namespace tachyon if (track.type != GridTrack::Type::Fixed) { sawFractional = true; break; } x += static_cast(track.value) + gap; - const tachyon::ID sepID = idManager.AllocateDynamicID("_table_col_sep"); - auto sRes = elementStorage.Add( + const tachyon::ID sepID = app.idManager.AllocateDynamicID("_table_col_sep"); + auto sRes = app.elementStorage.Add( tachyon::Element{ .id = sepID, - .styleRef = theme.tableSizerStyleRef, + .styleRef = styles.tableSizerStyleRef, .flags = tachyon::ElementFlags::NoInput, - .state = guiStateManager.GetCurrentState(sepID) + .state = app.guiStateManager.GetCurrentState(sepID) }, tachyon::LayoutOverride{} .PositionX(tachyon::PositionConstraintAxis::Absolute(static_cast(x - gap))) .PositionY(tachyon::PositionConstraintAxis::Absolute(0)) - .Size(Pixels{ styleManager.Px(1) }, Pixels{ kStretchHeight })); + .Size(Pixels{ app.styleManager.Px(1) }, Pixels{ kStretchHeight })); VERIFY(sRes.status); - VERIFY(windowRegistry.Add(sRes.ref)); + VERIFY(app.windowRegistry.Add(sRes.ref)); } (void)sawFractional; } - void GUIApplication::EmitColumnBackgrounds(TableEmit& emit, int colStart, int colEnd) + void EmitColumnBackgrounds(GUIApplication& app, Context& context, TableEmit& emit, int colStart, int colEnd) { + const Styles& styles = GetStyles(app, context); // Full-height fill behind a fixed-width column's cells. Positioned by // absolute X from the resolved tracks (same cumulative walk as the // separators) and stretched to the body height, so it covers the rows // AND the empty space past the last one. Skips anything past a // fractional track, whose pixel offset isn't known here. int32_t gap = 0; - if (const tachyon::LayoutStyle* ls = styleManager.GetLayoutStyle(theme.tableScrollableBodyStyleRef.layoutStyleIndex)) + if (const tachyon::LayoutStyle* ls = app.styleManager.GetLayoutStyle(styles.tableScrollableBodyStyleRef.layoutStyleIndex)) gap = ls->layoutData.grid.column.gap; int32_t x = 0; @@ -1001,28 +1009,29 @@ namespace tachyon const tachyon::StyleRef bg = emit.columns[c].column.columnBackground; if (bg != tachyon::StyleRef::Invalid()) { - const tachyon::ID bgID = idManager.AllocateDynamicID("_table_col_bg"); - auto bRes = elementStorage.Add( + const tachyon::ID bgID = app.idManager.AllocateDynamicID("_table_col_bg"); + auto bRes = app.elementStorage.Add( tachyon::Element{ .id = bgID, .styleRef = bg, .flags = tachyon::ElementFlags::NoInput, - .state = guiStateManager.GetCurrentState(bgID) + .state = app.guiStateManager.GetCurrentState(bgID) }, tachyon::LayoutOverride{} .PositionX(tachyon::PositionConstraintAxis::Absolute(static_cast(x))) .PositionY(tachyon::PositionConstraintAxis::Absolute(0)) .Size(Pixels{ static_cast(track.value) }, Pixels{ kStretchHeight })); VERIFY(bRes.status); - VERIFY(windowRegistry.Add(bRes.ref)); + VERIFY(app.windowRegistry.Add(bRes.ref)); } x += static_cast(track.value) + gap; } } - void GUIApplication::EmitColumnSizers(TableEmit& emit, int colStart, int colEnd, + void EmitColumnSizers(GUIApplication& app, Context& context, TableEmit& emit, int colStart, int colEnd, bool skipDragged) { + const Styles& styles = GetStyles(app, context); // Each sizer is anchored to header cell c's right edge, so layout handles // widths, stretch and drag offsets. TableState* state = emit.userState; @@ -1044,40 +1053,40 @@ namespace tachyon tachyon::EventHandler sizerHandler{}; tachyon::ElementFlags sizerFlags = tachyon::ElementFlags::NoInput; - const int sizerWidth = styleManager.Px(isDraggable ? kActiveSizerWidth : 1); + const int sizerWidth = app.styleManager.Px(isDraggable ? kActiveSizerWidth : 1); if (isDraggable) { // No upper bound: when columns can't grow further the table just // starts scrolling horizontally. sizerFlags = tachyon::ElementFlags::None; - auto headerStyleIndex = theme.tableHeaderStyleRef.layoutStyleIndex; - auto cellStyleIndex = theme.tableCellStyleRef.layoutStyleIndex; + auto headerStyleIndex = styles.tableHeaderStyleRef.layoutStyleIndex; + auto cellStyleIndex = styles.tableCellStyleRef.layoutStyleIndex; sizerHandler = tachyon::MakeHorizontalSizerHandler( - guiStateManager, elementStorage, + app.guiStateManager, app.elementStorage, state->columnWidths[c], col.minWidth.value, std::numeric_limits::max(), nullptr, // when double-clicking the sizer, snap to content width (plus padding/borders) - [state, c, sm = &styleManager, cellStyleIndex, headerStyleIndex]() -> int { + [state, c, sm = &app.styleManager, cellStyleIndex, headerStyleIndex]() -> int { const auto& widths = state->internal.maxContentWidths; const int32_t maxWidth = size_t(c) < widths.size() ? widths[size_t(c)] : 0; return maxWidth + 1 + std::max(sm->GetBorderBoxWidth(headerStyleIndex), sm->GetBorderBoxWidth(cellStyleIndex)); }, - false, styleManager.GetUIScale()); + false, app.styleManager.GetUIScale()); } const tachyon::ID sizerID = vcol.internal.sizerID; - const tachyon::ID leftHeaderID = elementStorage.GetElementUnsafe(vcol.internal.headerRef).id; - auto sRes = elementStorage.Add( + const tachyon::ID leftHeaderID = app.elementStorage.GetElementUnsafe(vcol.internal.headerRef).id; + auto sRes = app.elementStorage.Add( tachyon::Element{ .id = sizerID, .eventHandler = std::move(sizerHandler), - .styleRef = theme.tableSizerStyleRef, + .styleRef = styles.tableSizerStyleRef, .flags = sizerFlags, - .state = guiStateManager.GetCurrentState(sizerID) + .state = app.guiStateManager.GetCurrentState(sizerID) }, tachyon::LayoutOverride{} .PositionX(tachyon::PositionConstraintAxis::Anchored( @@ -1085,7 +1094,7 @@ namespace tachyon .PositionY(tachyon::PositionConstraintAxis::Absolute(0)) .Size(Pixels{ sizerWidth }, Pixels{ kStretchHeight })); VERIFY(sRes.status); - VERIFY(windowRegistry.Add(sRes.ref)); + VERIFY(app.windowRegistry.Add(sRes.ref)); }; // The dragged column's sizer is emitted by EmitDraggedColumnOnTop when skipDragged. @@ -1096,13 +1105,14 @@ namespace tachyon } - void GUIApplication::VirtualTable(ID id, TableState& state, + void VirtualTable(GUIApplication& app, Context& context, ID id, TableState& state, std::span columns, int totalRowCount, CssPx rowHeight, StyleRef style, LayoutOverride&& constraints) { + const Styles& styles = GetStyles(app, context); const bool showHeaders = state.showHeaders; const bool columnSeparators = state.columnSeparators; const StyleRef cellStyle = state.cellStyle; @@ -1111,14 +1121,14 @@ namespace tachyon // Sync this frame's section scroll into internal.bodyID before virtualizing, or the // row range lags a frame and fast scrollbar drags flash empty. - MirrorTableScroll(&state); + MirrorTableScroll(app, &state); // Visible row range from this frame's scroll + last frame's viewport. int32_t scrollY = 0; int32_t viewportH = state.internal.lastViewportH; if (state.internal.bodyID != tachyon::ID::Invalid()) { - auto& scrollManagement = guiStateManager.GetScrollManagement(); + auto& scrollManagement = app.guiStateManager.GetScrollManagement(); auto scrollHandle = scrollManagement.GetScrollOffsetHandle(state.internal.bodyID); if (scrollManagement.IsScrollOffsetHandleValid(scrollHandle)) scrollY = -scrollManagement.GetScrollOffset(scrollHandle).y; @@ -1126,23 +1136,23 @@ namespace tachyon // Effective body-cell style: caller override, or the theme default. const bool hasCustomCellStyle = (cellStyle.layoutStyleIndex != LayoutStyleIndex::Invalid); - const StyleRef effectiveCellStyle = hasCustomCellStyle ? cellStyle : theme.tableCellStyleRef; + const StyleRef effectiveCellStyle = hasCustomCellStyle ? cellStyle : styles.tableCellStyleRef; // Row height must match the rendered cell so virtual scroll stays stable. - // Default style: theme.tableRowHeight (measured at theme init); otherwise + // Default style: styles.tableRowHeight (measured at theme init); otherwise // measured here (cached by the text system). int32_t styleRowHeight = 1; - if (!hasCustomCellStyle && theme.tableRowHeight > 0) - styleRowHeight = theme.tableRowHeight; - else if (textSystem) + if (!hasCustomCellStyle && styles.tableRowHeight > 0) + styleRowHeight = styles.tableRowHeight; + else if (app.textSystem) { - const TextID probeID = textSystem->RegisterText(ID::Invalid(), "Mg", effectiveCellStyle, tachyon::ElementState::None); - int32_t h = textSystem->GetTextMeasurement(probeID).minHeight; - if (const LayoutStyle* ls = styleManager.GetLayoutStyle(effectiveCellStyle.layoutStyleIndex)) + const TextID probeID = app.textSystem->RegisterText(ID::Invalid(), "Mg", effectiveCellStyle, tachyon::ElementState::None); + int32_t h = app.textSystem->GetTextMeasurement(probeID).minHeight; + if (const LayoutStyle* ls = app.styleManager.GetLayoutStyle(effectiveCellStyle.layoutStyleIndex)) h += ls->padding.Vertical() + ls->borderWidths.Vertical(); styleRowHeight = std::max(1, h); } - const int32_t actualRowHeight = std::max(styleRowHeight, rowHeight.value > 0 ? styleManager.Px(rowHeight.value) : 0); + const int32_t actualRowHeight = std::max(styleRowHeight, rowHeight.value > 0 ? app.styleManager.Px(rowHeight.value) : 0); constexpr int kBufferRows = 5; const auto rowRange = TableHelpers::ComputeVirtualRowRange( @@ -1150,7 +1160,7 @@ namespace tachyon const int firstVisible = rowRange.firstVisible; const int lastVisible = rowRange.lastVisible; - (void)idManager.PushParent(id); + (void)app.idManager.PushParent(id); // One ranged ID for all rows and one for all sizers, scoped under the table's // id so two tables under the same parent don't collide. @@ -1161,7 +1171,7 @@ namespace tachyon ? state.internal.rowsRangeID.value.rangedParts.hashValue : 0; if (totalRowCount > 0) { - rowsRangeID = idManager.AllocateRangedID(static_cast(totalRowCount)); + rowsRangeID = app.idManager.AllocateRangedID(static_cast(totalRowCount)); // Stored on TableState so keyboard nav can reach rows outside the window. state.internal.rowsRangeID = rowsRangeID; state.internal.totalRowCount = totalRowCount; @@ -1237,14 +1247,14 @@ namespace tachyon } if (columnCount > 0) { - const tachyon::ID bodyRange = idManager.AllocateRangedID(static_cast(columnCount), "_table_bodies"); - const tachyon::ID sizerRange = idManager.AllocateRangedID(static_cast(columnCount), "_table_sizers"); - const tachyon::ID hdrRange = idManager.AllocateRangedID(static_cast(columnCount), "_table_headers"); + const tachyon::ID bodyRange = app.idManager.AllocateRangedID(static_cast(columnCount), "_table_bodies"); + const tachyon::ID sizerRange = app.idManager.AllocateRangedID(static_cast(columnCount), "_table_sizers"); + const tachyon::ID hdrRange = app.idManager.AllocateRangedID(static_cast(columnCount), "_table_headers"); for (size_t c = 0; c < columnCount; ++c) { - columns[c].internal.bodyID = idManager.GetSubID(bodyRange, static_cast(c)); - columns[c].internal.sizerID = idManager.GetSubID(sizerRange, static_cast(c)); - columns[c].internal.headerCellID = idManager.GetSubID(hdrRange, static_cast(c)); + columns[c].internal.bodyID = app.idManager.GetSubID(bodyRange, static_cast(c)); + columns[c].internal.sizerID = app.idManager.GetSubID(sizerRange, static_cast(c)); + columns[c].internal.headerCellID = app.idManager.GetSubID(hdrRange, static_cast(c)); } } } @@ -1260,11 +1270,11 @@ namespace tachyon state.internal.rowOrderDirty = false; } - state.internal.horzScrollbarID = idManager.AllocateDynamicID("_table_horz_scrollbar"); - state.internal.vertScrollbarID = idManager.AllocateDynamicID("_table_vert_scrollbar"); - const tachyon::ID rowID = idManager.AllocateDynamicID("_table_bodies_row"); + state.internal.horzScrollbarID = app.idManager.AllocateDynamicID("_table_horz_scrollbar"); + state.internal.vertScrollbarID = app.idManager.AllocateDynamicID("_table_vert_scrollbar"); + const tachyon::ID rowID = app.idManager.AllocateDynamicID("_table_bodies_row"); - (void)idManager.PopParent(); + (void)app.idManager.PopParent(); // Lazy-init persisted widths on a fresh state / when columnCount changed. if (state.columnWidths.size() != columnCount) @@ -1293,22 +1303,22 @@ namespace tachyon // Via EndTable the recording state is already in place (BeginTable stashed the outer one); // a direct call stashes whatever table it interrupts. - if (!(m_tableEmit && m_tableEmit->isRecording)) - m_outerTableEmits.push_back(std::move(m_tableEmit)); - m_tableEmit.emplace(); - m_tableEmit->columns = columns.data(); - m_tableEmit->columnCount = columnCount; - m_tableEmit->userState = &state; - TableEmit& emit = *m_tableEmit; + if (!(context.tableEmit && context.tableEmit->isRecording)) + context.outerTableEmits.push_back(std::move(context.tableEmit)); + context.tableEmit.emplace(); + context.tableEmit->columns = columns.data(); + context.tableEmit->columnCount = columnCount; + context.tableEmit->userState = &state; + TableEmit& emit = *context.tableEmit; // A column press can't finish if its column is gone (the column set shrank) or it // lost its capture (the table wasn't shown when the button went up): cancel it. - if (m_columnDrag.tableID == id && - (m_columnDrag.fromCol >= int(columnCount) || - guiStateManager.Interaction().GetCaptureID() == tachyon::ID::Invalid())) - m_columnDrag = {}; - emit.dragActive = m_columnDrag.IsDragging() && m_columnDrag.tableID == id; + if (context.columnDrag.tableID == id && + (context.columnDrag.fromCol >= int(columnCount) || + app.guiStateManager.Interaction().GetCaptureID() == tachyon::ID::Invalid())) + context.columnDrag = {}; + emit.dragActive = context.columnDrag.IsDragging() && context.columnDrag.tableID == id; emit.cellMode = (state.selectionMode == TableSelectionMode::Cell); - emit.draggedCol = emit.dragActive ? m_columnDrag.fromCol : -1; + emit.draggedCol = emit.dragActive ? context.columnDrag.fromCol : -1; emit.showHeaders = showHeaders; emit.columnSeparators = columnSeparators; emit.cellStyleRef = effectiveCellStyle; @@ -1332,26 +1342,26 @@ namespace tachyon if (emit.dragActive && columnCount > 0) { const size_t lastIdx = columnCount - 1; - const int32_t lastW = styleManager.Px(state.columnWidths[lastIdx]); + const int32_t lastW = app.styleManager.Px(state.columnWidths[lastIdx]); int32_t snapshotW = lastW; - if (lastIdx < m_columnDrag.headerRects.size()) - snapshotW = std::max(snapshotW, m_columnDrag.headerRects[lastIdx].w); + if (lastIdx < context.columnDrag.headerRects.size()) + snapshotW = std::max(snapshotW, context.columnDrag.headerRects[lastIdx].w); emit.lastColDragFixedWidth = std::max( lastW, - snapshotW - theme.scrollbarThickness); + snapshotW - app.theme.scrollbarThickness); } // Pre-compute per-column reorder-drag X offsets. if (emit.dragActive && columnCount > 0) { - const auto& drag = m_columnDrag; + const auto& drag = context.columnDrag; const int fromCol = drag.fromCol; const int toCol = std::clamp(drag.toCol, 0, int(columnCount) - 1); const int32_t draggedWidth = (size_t(fromCol) == columnCount - 1) ? emit.lastColDragFixedWidth - : styleManager.Px(state.columnWidths[fromCol]); + : app.styleManager.Px(state.columnWidths[fromCol]); int32_t gap = 0; - if (const tachyon::LayoutStyle* ls = styleManager.GetLayoutStyle(theme.tableScrollableBodyStyleRef.layoutStyleIndex)) + if (const tachyon::LayoutStyle* ls = app.styleManager.GetLayoutStyle(styles.tableScrollableBodyStyleRef.layoutStyleIndex)) gap = ls->layoutData.grid.column.gap; const int32_t shiftBy = draggedWidth + gap; tachyon::IntRect draggedRect{}; @@ -1380,14 +1390,14 @@ namespace tachyon } } - StyleRef containerStyle = (style != StyleRef{}) ? style : theme.tableStyleRef; + StyleRef containerStyle = (style != StyleRef{}) ? style : styles.tableStyleRef; TableState* statePtr = &state; tachyon::Element container{ .id = id, - .eventHandler = BuildTableContainerHandler(statePtr, id), + .eventHandler = BuildTableContainerHandler(app, context, statePtr, id), .styleRef = containerStyle, - .state = guiStateManager.GetCurrentState(id), + .state = app.guiStateManager.GetCurrentState(id), }; // Resolve the sort indicator. If any column is sortable, snap an @@ -1414,7 +1424,7 @@ namespace tachyon { statePtr->EnsureCellLookup(); emit.sharedCellHandler = - [this, statePtr, id](ElementEvent&& event) -> bool + [&app, statePtr, id](ElementEvent&& event) -> bool { if (event.type != tachyon::EventType::MouseDown) return false; if (!event.state.LeftPressed()) return false; @@ -1422,8 +1432,8 @@ namespace tachyon if (!hit) return false; statePtr->selectedRowID = hit->rowID; statePtr->selectedColumn = hit->columnIdx; - TakeFocus(guiStateManager, id); - guiStateManager.Interaction().SetClicked(hit->rowID); + TakeFocus(app.guiStateManager, id); + app.guiStateManager.Interaction().SetClicked(hit->rowID); return true; }; } @@ -1431,33 +1441,33 @@ namespace tachyon // The arrow points opposite to the sort direction: ascending (a->z) // shows a down arrow, descending (z->a) shows an up arrow. const IconID sortIcon = (effectiveSortCol < 0) ? IconID::Invalid - : (statePtr->sortDescending ? theme.sortArrowUpIcon : theme.sortArrowDownIcon); + : (statePtr->sortDescending ? styles.sortArrowUpIcon : styles.sortArrowDownIcon); // Build the shared row-backdrop handler once. The handler reads the // row's id from event.id, so a single instance covers every row. // (Empty in cell-selection mode - cell backdrops are NoInput.) if (!emit.cellMode) - emit.sharedRowHandler = BuildRowBackdropHandler(statePtr, id); + emit.sharedRowHandler = BuildRowBackdropHandler(app, context, statePtr, id); - RegisterElement(std::move(container), std::move(constraints)); - RegisterTabStop(id); + app.RegisterElement(std::move(container), std::move(constraints)); + app.RegisterTabStop(id); - VERIFY(elementStorage.BeginChildren()); // outer wrapper's children + VERIFY(app.elementStorage.BeginChildren()); // outer wrapper's children { // One bodies row holding every section; each section's header (StickyY, // row 0) and body share one scrolling grid. The row's ID is state.internal.bodyID, // the canonical scroll-Y (kept in sync by MirrorTableScroll). state.internal.bodyID = rowID; - auto res = elementStorage.Add( + auto res = app.elementStorage.Add( tachyon::Element{ .id = rowID, - .styleRef = theme.tableBodiesRowStyleRef, - .state = guiStateManager.GetCurrentState(rowID), + .styleRef = styles.tableBodiesRowStyleRef, + .state = app.guiStateManager.GetCurrentState(rowID), }, tachyon::LayoutOverride{}); VERIFY(res.status); - VERIFY(windowRegistry.Add(res.ref)); - VERIFY(elementStorage.BeginChildren()); + VERIFY(app.windowRegistry.Add(res.ref)); + VERIFY(app.elementStorage.BeginChildren()); int sectionIdx = 0; int sectionStart = 0; @@ -1469,7 +1479,7 @@ namespace tachyon && sectionIdx + 1 < TableState::kMaxTableSections); if (!boundary) continue; - if (sectionIdx > 0) EmitTableSectionSeparator(); + if (sectionIdx > 0) EmitTableSectionSeparator(app, context); const int colEnd = c; const bool isLast = (c == int(columnCount)); @@ -1481,7 +1491,7 @@ namespace tachyon int sectionFixedWidth = 0; for (int cc = sectionStart; cc < colEnd; cc++) { - columns[cc].internal.columnTrack = ComputeSectionColumnTrack( + columns[cc].internal.columnTrack = ComputeSectionColumnTrack(app, emit, cc, colEnd, /*isMiddle*/!fitContent, /*fitContent*/fitContent); if (fitContent) sectionFixedWidth += static_cast(columns[cc].internal.columnTrack.value); @@ -1492,29 +1502,29 @@ namespace tachyon state.internal.sectionCount = static_cast(sectionIdx + 1); // Scope IDs under the section body so sections can't collide via the dynamic counter. - (void)idManager.PushParent(bodyID); + (void)app.idManager.PushParent(bodyID); // Body rows are emitted before headers so the sticky header paints on top // (grid rows are explicit, so only paint order changes). The rightmost // section samples the viewport. - OpenTableBodySection(emit, bodyID, - fitContent ? theme.tableFitContentBodyStyleRef - : theme.tableScrollableBodyStyleRef, + OpenTableBodySection(app, context, emit, bodyID, + fitContent ? styles.tableFitContentBodyStyleRef + : styles.tableScrollableBodyStyleRef, fitContent ? tachyon::LayoutOverride{}.Width(Pixels{ sectionFixedWidth }) : tachyon::LayoutOverride{}.MinWidth(0), /*sampleViewport*/isLast); // Non-dragged content first; EmitDraggedColumnOnTop adds the dragged column last. - EmitVirtualBodyRows(emit, sectionStart, colEnd, + EmitVirtualBodyRows(app, context, emit, sectionStart, colEnd, totalRowCount, actualRowHeight, firstVisible, lastVisible, rowsRangeID, /*isLastSection*/isLast); if (emit.showHeaders) { - EmitTableHeaderSection(emit, id, + EmitTableHeaderSection(app, context, emit, id, sectionStart, colEnd, /*lastColIsStretch*/!fitContent, effectiveSortCol, sortIcon); - EmitColumnSizers(emit, sectionStart, colEnd, /*skipDragged*/true); + EmitColumnSizers(app, context, emit, sectionStart, colEnd, /*skipDragged*/true); } else { @@ -1522,40 +1532,40 @@ namespace tachyon // still read. Emit thin static separators at each internal // boundary (unless the caller opted out). if (emit.columnSeparators) - EmitColumnSeparators(emit, sectionStart, colEnd); + EmitColumnSeparators(app, context, emit, sectionStart, colEnd); } if (emit.dragActive && emit.draggedCol >= sectionStart && emit.draggedCol < colEnd) { - EmitDraggedColumnOnTop(emit, id, + EmitDraggedColumnOnTop(app, context, emit, id, sectionStart, colEnd, firstVisible, lastVisible, rowsRangeID, /*lastColIsStretch*/!fitContent, effectiveSortCol, sortIcon); } - CloseTableBodySection(emit, bodyID, + CloseTableBodySection(app, emit, bodyID, /*emitVerticalScrollbar*/isLast, /*suppressHorzScrollbar*/fitContent); - (void)idManager.PopParent(); + (void)app.idManager.PopParent(); sectionIdx++; sectionStart = c; } - VERIFY(elementStorage.EndChildren()); + VERIFY(app.elementStorage.EndChildren()); - MirrorTableScroll(statePtr); + MirrorTableScroll(app, statePtr); } - VERIFY(elementStorage.EndChildren()); // table container + VERIFY(app.elementStorage.EndChildren()); // table container state.internal.maxContentWidths.resize(columnCount); for (size_t c = 0; c < columnCount; c++) state.internal.maxContentWidths[c] = columns[c].internal.maxContentWidth; - m_tableEmit = std::move(m_outerTableEmits.back()); - m_outerTableEmits.pop_back(); + context.tableEmit = std::move(context.outerTableEmits.back()); + context.outerTableEmits.pop_back(); // Its shortcuts while the focus is in it. - ClaimCommandMode(id, state.commandMode); + app.ClaimCommandMode(id, state.commandMode); // The context menu: a shown row's, for that row; the sections' bodies', below the rows. if (state.contextMenu) @@ -1563,15 +1573,15 @@ namespace tachyon for (int visualIdx = firstVisible; visualIdx < lastVisible && rowsRangeID != tachyon::ID::Invalid(); visualIdx++) { const int datasetIdx = state.VisualToDataset(visualIdx); - if (BeginContextMenu(idManager.GetSubID(rowsRangeID, static_cast(datasetIdx)))) + if (app.BeginContextMenu(app.idManager.GetSubID(rowsRangeID, static_cast(datasetIdx)))) state.contextMenu(datasetIdx); - EndContextMenu(); + app.EndContextMenu(); } for (int i = 0; i < state.internal.sectionCount; i++) { - if (BeginContextMenu(state.SectionBodyID(i))) + if (app.BeginContextMenu(state.SectionBodyID(i))) state.contextMenu(-1); - EndContextMenu(); + app.EndContextMenu(); } } } diff --git a/src/gui_controls/controls_tree_list.cpp b/src/gui_views/controls_tree_list.cpp similarity index 69% rename from src/gui_controls/controls_tree_list.cpp rename to src/gui_views/controls_tree_list.cpp index e2f9b971..e4080054 100644 --- a/src/gui_controls/controls_tree_list.cpp +++ b/src/gui_views/controls_tree_list.cpp @@ -1,10 +1,11 @@ -#include -#include +#include +#include +#include #include #include -namespace tachyon +namespace tachyon::views { @@ -12,19 +13,19 @@ namespace tachyon // Tree/List shared helpers // --------------------------------------------------------------------------- - bool GUIApplication::IsTreeItemSelected(tachyon::ID id, int itemIndex) const + bool IsTreeItemSelected(const Context& context, tachyon::ID id, int itemIndex) { - if (m_treeState.multiSelect) - return m_treeState.multiSelect->selectedIDs.count(id) > 0; - if (m_treeState.selectedID) - return *m_treeState.selectedID == id; - if (m_treeState.selectedIndex) - return *m_treeState.selectedIndex == itemIndex; + if (context.treeState.multiSelect) + return context.treeState.multiSelect->selectedIDs.count(id) > 0; + if (context.treeState.selectedID) + return *context.treeState.selectedID == id; + if (context.treeState.selectedIndex) + return *context.treeState.selectedIndex == itemIndex; return false; } - tachyon::TextID GUIApplication::TreeItemRegisterText(tachyon::ID id, std::string_view text, IconID icon, StyleRef style, tachyon::ElementState state) + tachyon::TextID TreeItemRegisterText(GUIApplication& app, tachyon::ID id, std::string_view text, IconID icon, StyleRef style, tachyon::ElementState state) { if (icon != IconID::Invalid) { @@ -32,9 +33,9 @@ namespace tachyon { .type = tachyon::ContentRun::Icon, .iconID = icon, .iconWidth = 16.0f, .iconHeight = 16.0f }, { .type = tachyon::ContentRun::Text, .text = text } }; - return textSystem->RegisterRichText(id, runs, style, state); + return app.textSystem->RegisterRichText(id, runs, style, state); } - return textSystem->RegisterText(id, text, style, state); + return app.textSystem->RegisterText(id, text, style, state); } @@ -46,9 +47,9 @@ namespace tachyon // which primes the drag alongside selection (Chain stops at its `return true`). // // Zones: branches use thirds (Before/Inside/After), leaves halves (Before/After). - tachyon::EventHandler GUIApplication::MakeTreeRowDragDropHandler(tachyon::ID rowID, bool rowHasChildren, ItemDragDropConfig* dd, bool* isOpen) + tachyon::EventHandler MakeTreeRowDragDropHandler(GUIApplication& app, Context& context, tachyon::ID rowID, bool rowHasChildren, ItemDragDropConfig* dd, bool* isOpen) { - return [this, rowID, rowHasChildren, dd, isOpen](tachyon::ElementEvent&& event) -> bool + return [&context, &app, rowID, rowHasChildren, dd, isOpen](tachyon::ElementEvent&& event) -> bool { if (!dd || dd->payloadType == 0) return false; @@ -57,7 +58,7 @@ namespace tachyon if (dd->dropInsideOnly) return TreeDropPosition::InsideLast; // rect is layout-space - convert cursor through any ancestor // contentTransform first (e.g. a node-view canvas). - const int32_t cursorY = event.LocalCursor(elementStorage).y; + const int32_t cursorY = event.LocalCursor(app.elementStorage).y; int relY = cursorY - rect.position.y; int h = rect.size.y; if (h <= 0) return TreeDropPosition::None; @@ -85,8 +86,8 @@ namespace tachyon case tachyon::EventType::MouseMove: { if ((event.state.buttons & tachyon::MouseButtons::Left) == tachyon::MouseButtons::None) break; - guiStateManager.Drag().UpdateFromInput(event.state); - return guiStateManager.Drag().GetDraggedID() == rowID; + app.guiStateManager.Drag().UpdateFromInput(event.state); + return app.guiStateManager.Drag().GetDraggedID() == rowID; } case tachyon::EventType::DragEnter: case tachyon::EventType::DragOver: @@ -97,26 +98,26 @@ namespace tachyon // rows that refuse this payload (canDrop). if (event.state.dragSourceID == rowID || (dd->canDrop && !dd->canDrop(event.state.dragPayloadValue, rowID))) { - if (m_treeDropState.targetRowID == rowID) m_treeDropState = {}; + if (context.treeDrop.targetRowID == rowID) context.treeDrop = {}; return true; } - m_treeDropState.targetRowID = rowID; - m_treeDropState.position = computeZone(event.rect->rect); + context.treeDrop.targetRowID = rowID; + context.treeDrop.position = computeZone(event.rect->rect); return true; } case tachyon::EventType::DragOut: { if (event.state.dragPayloadType != dd->payloadType) return false; - if (m_treeDropState.targetRowID == rowID) m_treeDropState = {}; + if (context.treeDrop.targetRowID == rowID) context.treeDrop = {}; return true; } case tachyon::EventType::Drop: { if (event.state.dragPayloadType != dd->payloadType) return false; - if (event.state.dragSourceID == rowID) { m_treeDropState = {}; return true; } + if (event.state.dragSourceID == rowID) { context.treeDrop = {}; return true; } if (dd->canDrop && !dd->canDrop(event.state.dragPayloadValue, rowID)) { - m_treeDropState = {}; + context.treeDrop = {}; return true; } TreeDropPosition pos = event.rect @@ -124,7 +125,7 @@ namespace tachyon : TreeDropPosition::None; if (pos != TreeDropPosition::None && dd->onReorder) dd->onReorder(event.state.dragPayloadValue, rowID, pos); - m_treeDropState = {}; + context.treeDrop = {}; return true; } default: break; @@ -135,16 +136,17 @@ namespace tachyon // One AddCustomDraw for both the guide line and the drop indicator, so both get the // row's overflow:visible clip (AddCustomDrawAfter's tighter clip cuts off edge lines). - void GUIApplication::TreeItemRowCustomDraw(const tachyon::ElementRef& rowRef, bool hasArrow, tachyon::ID rowID) + void TreeItemRowCustomDraw(GUIApplication& app, Context& context, const tachyon::ElementRef& rowRef, bool hasArrow, tachyon::ID rowID) { - bool drawGuideLine = (m_treeState.depth > 0); + const Styles& styles = GetStyles(app, context); + bool drawGuideLine = (context.treeState.depth > 0); [[maybe_unused]] auto result = - elementStorage.AddCustomDraw(rowRef, - [this, hasArrow, rowID, drawGuideLine, - lineColor = theme.treeGuideLineStyle, - indicatorColor = theme.treeDropIndicatorStyle] + app.elementStorage.AddCustomDraw(rowRef, + [&context, &app, hasArrow, rowID, drawGuideLine, + lineColor = styles.treeGuideLineStyle, + indicatorColor = app.theme.treeDropIndicatorStyle] (tachyon::CustomDrawContext& ctx) { // Span the outer rect so lines are continuous between rows. Coords are @@ -174,9 +176,9 @@ namespace tachyon tachyon::ElementRef nextSibling = ctx.GetNextSiblingRef(ctx.Ref()); int32_t bottom = nextSibling.IsValid() ? topY + h : centerY; - int32_t tickRight = left + (hasArrow ? 0 : styleManager.Px(10)); + int32_t tickRight = left + (hasArrow ? 0 : app.styleManager.Px(10)); - tachyon::LineStyle style { .colorStyleIndex = lineColor, .lineWidth = styleManager.Px(1.f) }; + tachyon::LineStyle style { .colorStyleIndex = lineColor, .lineWidth = app.styleManager.Px(1.f) }; ctx.RenderLine({ lineX, topY }, { lineX, bottom }, style); ctx.RenderLine({ lineX, centerY }, { tickRight, centerY }, style); } @@ -184,17 +186,17 @@ namespace tachyon // -------- Drop indicator (when this is the current drop target) -------- // A cancelled drag fires neither Drop nor DragOut; gate on the live drag. - if (guiStateManager.Drag().IsDragging() - && m_treeDropState.targetRowID == rowID - && m_treeDropState.position != TreeDropPosition::None) + if (app.guiStateManager.Drag().IsDragging() + && context.treeDrop.targetRowID == rowID + && context.treeDrop.position != TreeDropPosition::None) { - const int32_t kIndent = styleManager.Px(16); // one visual indent level - const int32_t thick = styleManager.Px(3); + const int32_t kIndent = app.styleManager.Px(16); // one visual indent level + const int32_t thick = app.styleManager.Px(3); const int32_t half = thick / 2; // insets that keep the line inside the row tachyon::LineStyle indStyle { .colorStyleIndex = indicatorColor, .lineWidth = float(thick) }; // InsideLast -> rectangle around the row (drop as last child). - if (m_treeDropState.position == TreeDropPosition::InsideLast) + if (context.treeDrop.position == TreeDropPosition::InsideLast) { const int32_t leftX = left; const int32_t rightX = left + w - 1; @@ -211,7 +213,7 @@ namespace tachyon int32_t lineRight = left + w; int32_t y; - switch (m_treeDropState.position) + switch (context.treeDrop.position) { case TreeDropPosition::Before: y = topY + half; @@ -232,38 +234,38 @@ namespace tachyon }); } - bool GUIApplication::TreeItemRenameCheck(tachyon::ID bodyID, std::string* renameBuffer, StyleRef textStyle) + bool TreeItemRenameCheck(GUIApplication& app, Context& context, tachyon::ID bodyID, std::string* renameBuffer, StyleRef textStyle) { bool modified = false; - guiStateManager.Interaction().SetFocusID(bodyID); - guiStateManager.TextEditorFocus().Set(bodyID); + app.guiStateManager.Interaction().SetFocusID(bodyID); + app.guiStateManager.TextEditorFocus().Set(bodyID); // Escape cancels the rename; everything else goes to the text box handler. - tachyon::EventHandler textHandler = MakeTextBoxHandler(guiStateManager); + tachyon::EventHandler textHandler = MakeTextBoxHandler(app.guiStateManager); tachyon::EventHandler editHandler = - [this, inner = std::move(textHandler)](tachyon::ElementEvent&& event) -> bool + [&context, &app, inner = std::move(textHandler)](tachyon::ElementEvent&& event) -> bool { if (event.type == tachyon::EventType::KeyDown && event.state.lastKey == tachyon::KeyCode::Escape) { - (*m_renameSub).Cancel(); + context.rename.Cancel(); return true; } return inner ? inner(std::move(event)) : false; }; - RegisterControl(tachyon::Element{ .id = bodyID, .eventHandler = std::move(editHandler), .styleRef = textStyle }, - [this, &modified, renameBuffer](tachyon::Element& element) + app.RegisterControl(tachyon::Element{ .id = bodyID, .eventHandler = std::move(editHandler), .styleRef = textStyle }, + [&app, &modified, renameBuffer](tachyon::Element& element) { - return textSystem->RegisterEditableText(element.id, *renameBuffer, tachyon::TextEditBehavior::None, element.styleRef, element.state, modified); + return app.textSystem->RegisterEditableText(element.id, *renameBuffer, tachyon::TextEditBehavior::None, element.styleRef, element.state, modified); }, tachyon::LayoutOverride::Auto()); // Skip commit check on first frame - SwitchTextEditor(..., Invalid) from a // previous deactivation leaves a stale pending_text_committed. - if ((*m_renameSub).firstFrame) - (*m_renameSub).firstFrame = false; + if (context.rename.firstFrame) + context.rename.firstFrame = false; else if (modified) - (*m_renameSub).Cancel(); + context.rename.Cancel(); return modified; } @@ -272,31 +274,31 @@ namespace tachyon // ListView // --------------------------------------------------------------------------- - bool GUIApplication::BeginListView(ID id, int* selectedIndex, int itemCount, + bool BeginListView(GUIApplication& app, Context& context, ID id, int* selectedIndex, int itemCount, ItemDragDropConfig* dragDrop, StyleRef style, LayoutOverride&& constraints) { - m_treeState = {}; - m_treeState.containerID = id; - m_treeState.selectedIndex = selectedIndex; - m_treeState.totalItemCount = itemCount; - m_treeState.dragDrop = dragDrop; + context.treeState = {}; + context.treeState.containerID = id; + context.treeState.selectedIndex = selectedIndex; + context.treeState.totalItemCount = itemCount; + context.treeState.dragDrop = dragDrop; tachyon::Element container{}; container.id = id; container.styleRef = style; - container.state = guiStateManager.GetCurrentState(id); - container.eventHandler = [this, selectedIndex, itemCount](ElementEvent&& event) -> bool + container.state = app.guiStateManager.GetCurrentState(id); + container.eventHandler = [&app, selectedIndex, itemCount](ElementEvent&& event) -> bool { switch (event.type) { case tachyon::EventType::MouseDown: if (!event.state.LeftPressed()) break; - TakeFocus(guiStateManager, event.id); + TakeFocus(app.guiStateManager, event.id); return true; case tachyon::EventType::KeyDown: { - if ((guiStateManager.GetCurrentState(event.id) & ElementState::Focused) == ElementState::None) + if ((app.guiStateManager.GetCurrentState(event.id) & ElementState::Focused) == ElementState::None) break; if (!selectedIndex) break; switch (event.state.lastKey) @@ -312,76 +314,77 @@ namespace tachyon return false; }; - RegisterElement(std::move(container), std::move(constraints)); - RegisterTabStop(id); - VERIFY(elementStorage.BeginChildren()); + app.RegisterElement(std::move(container), std::move(constraints)); + app.RegisterTabStop(id); + VERIFY(app.elementStorage.BeginChildren()); return true; } - void GUIApplication::EndListView() + void EndListView(GUIApplication& app, Context& context) { - VERIFY(elementStorage.EndChildren()); - m_treeState = {}; + VERIFY(app.elementStorage.EndChildren()); + context.treeState = {}; } - bool GUIApplication::ListItem(ID id, const GUIContent& content, StyleRef style, LayoutOverride&& constraints) + bool ListItem(GUIApplication& app, Context& context, ID id, const GUIContent& content, StyleRef style, LayoutOverride&& constraints) { + const Styles& styles = GetStyles(app, context); const IconID icon = content.icon; const std::string_view text = content.text; - ShowContentTooltip(id, content); - if (m_treeState.containerID == ID::Invalid()) + app.ShowContentTooltip(id, content); + if (context.treeState.containerID == ID::Invalid()) { - ReportMisuse("GUIApplication: ListItem outside a list or tree view (ignored)"); + app.ReportMisuse("GUIApplication: ListItem outside a list or tree view (ignored)"); return false; } - int itemIndex = m_treeState.nextItemIndex++; - bool selected = IsTreeItemSelected(id, itemIndex); + int itemIndex = context.treeState.nextItemIndex++; + bool selected = IsTreeItemSelected(context, id, itemIndex); - // Capture user-owned pointers; m_treeState is gone by the time handlers run. - tachyon::ID containerID = m_treeState.containerID; - int* selectedIndex = m_treeState.selectedIndex; - ItemDragDropConfig* dd = m_treeState.dragDrop; + // Capture user-owned pointers; context.treeState is gone by the time handlers run. + tachyon::ID containerID = context.treeState.containerID; + int* selectedIndex = context.treeState.selectedIndex; + ItemDragDropConfig* dd = context.treeState.dragDrop; const bool dragEnabled = (dd && dd->payloadType != 0); // Record this item's index so end-of-frame onReorder lambdas can resolve target IDs. - // This map is on the Application (not m_treeState) so it survives EndListView. + // This map is on the Application (not context.treeState) so it survives EndListView. if (dd) - m_listItemIndexByID[id] = itemIndex; + context.listItemIndexByID[id] = itemIndex; - if (selected) guiStateManager.Construction().PushSelected(); + if (selected) app.guiStateManager.Construction().PushSelected(); // --------------------------------------------------------------------- // Non-draggable path: single leaf element. // --------------------------------------------------------------------- if (!dragEnabled) { - if (style == StyleRef{}) style = theme.listItemStyleRef; + if (style == StyleRef{}) style = styles.listItemStyleRef; tachyon::Element item{}; item.id = id; - item.state = guiStateManager.GetCurrentState(id); + item.state = app.guiStateManager.GetCurrentState(id); item.styleRef = style; - item.textID = TreeItemRegisterText(id, text, icon, style, item.state); - item.eventHandler = [this, containerID, id, itemIndex, selectedIndex](ElementEvent&& event) -> bool + item.textID = TreeItemRegisterText(app, id, text, icon, style, item.state); + item.eventHandler = [&app, containerID, id, itemIndex, selectedIndex](ElementEvent&& event) -> bool { if (event.type == tachyon::EventType::MouseDown && event.state.LeftPressed()) { if (selectedIndex) *selectedIndex = itemIndex; - auto& scrollManagement = guiStateManager.GetScrollManagement(); - scrollManagement.MakeElementVisibleHierarchically(elementStorage, event.elementRef); - TakeFocus(guiStateManager, containerID); - guiStateManager.Interaction().SetClicked(id); + auto& scrollManagement = app.guiStateManager.GetScrollManagement(); + scrollManagement.MakeElementVisibleHierarchically(app.elementStorage, event.elementRef); + TakeFocus(app.guiStateManager, containerID); + app.guiStateManager.Interaction().SetClicked(id); return true; } return false; }; - auto addRes = elementStorage.Add(std::move(item), std::move(constraints)); + auto addRes = app.elementStorage.Add(std::move(item), std::move(constraints)); VERIFY(addRes.status); - VERIFY(windowRegistry.Add(addRes.ref)); + VERIFY(app.windowRegistry.Add(addRes.ref)); - if (selected) guiStateManager.Construction().PopSelected(); - return guiStateManager.Interaction().HasBeenClicked(id); + if (selected) app.guiStateManager.Construction().PopSelected(); + return app.guiStateManager.Interaction().HasBeenClicked(id); } // --------------------------------------------------------------------- @@ -398,47 +401,47 @@ namespace tachyon // 1) Outer row container. tachyon::Element row{}; row.id = id; - row.state = guiStateManager.GetCurrentState(id); - row.styleRef = theme.listItemRowStyleRef; + row.state = app.guiStateManager.GetCurrentState(id); + row.styleRef = styles.listItemRowStyleRef; // Row handler: only DragDrop events matter here (from children bubbling up). // MouseDown on the row itself (margin area) also just selects. - row.eventHandler = [this, containerID, id, itemIndex, selectedIndex](ElementEvent&& event) -> bool + row.eventHandler = [&app, containerID, id, itemIndex, selectedIndex](ElementEvent&& event) -> bool { if (event.type == tachyon::EventType::MouseDown && event.state.LeftPressed()) { if (selectedIndex) *selectedIndex = itemIndex; - auto& scrollManagement = guiStateManager.GetScrollManagement(); - scrollManagement.MakeElementVisibleHierarchically(elementStorage, event.elementRef); - TakeFocus(guiStateManager, containerID); - guiStateManager.Interaction().SetClicked(id); + auto& scrollManagement = app.guiStateManager.GetScrollManagement(); + scrollManagement.MakeElementVisibleHierarchically(app.elementStorage, event.elementRef); + TakeFocus(app.guiStateManager, containerID); + app.guiStateManager.Interaction().SetClicked(id); return true; } return false; }; row.eventHandler = tachyon::Chain(std::move(row.eventHandler), - MakeTreeRowDragDropHandler(id, /*rowHasChildren=*/false, dd)); + MakeTreeRowDragDropHandler(app, context, id, /*rowHasChildren=*/false, dd)); - auto rowRes = elementStorage.Add(std::move(row), std::move(constraints)); + auto rowRes = app.elementStorage.Add(std::move(row), std::move(constraints)); VERIFY(rowRes.status); - VERIFY(windowRegistry.Add(rowRes.ref)); + VERIFY(app.windowRegistry.Add(rowRes.ref)); // Drop indicator line for this row when it's the current drop target. - TreeItemRowCustomDraw(rowRes.ref, /*hasArrow=*/false, id); + TreeItemRowCustomDraw(app, context, rowRes.ref, /*hasArrow=*/false, id); - VERIFY(elementStorage.BeginChildren()); + VERIFY(app.elementStorage.BeginChildren()); // 2) Drag knob child (leftmost). It captures the mouse on MouseDown, so the drag // must be advanced from its own MouseMove. { // The parts' IDs under the item's own, so they don't depend on what came before. - [[maybe_unused]] const bool pushed = idManager.PushParent(id); - tachyon::ID knobID = idManager.AllocateDynamicID("list_drag_knob"); - if (pushed) (void)idManager.PopParent(); + [[maybe_unused]] const bool pushed = app.idManager.PushParent(id); + tachyon::ID knobID = app.idManager.AllocateDynamicID("list_drag_knob"); + if (pushed) (void)app.idManager.PopParent(); tachyon::Element knob{}; knob.id = knobID; - knob.state = guiStateManager.GetCurrentState(knobID); - knob.styleRef = theme.listItemDragKnobVertStyleRef; - knob.eventHandler = [this, rowID = id, itemIndex, selectedIndex, dd](ElementEvent&& event) -> bool + knob.state = app.guiStateManager.GetCurrentState(knobID); + knob.styleRef = app.theme.listItemDragKnobVertStyleRef; + knob.eventHandler = [&app, rowID = id, itemIndex, selectedIndex, dd](ElementEvent&& event) -> bool { switch (event.type) { @@ -449,10 +452,10 @@ namespace tachyon if (selectedIndex) *selectedIndex = itemIndex; // Focus moves on MouseUp, not here, so grabbing the thumb doesn't // interrupt editing another control. - guiStateManager.Interaction().SetClicked(rowID); + app.guiStateManager.Interaction().SetClicked(rowID); // Prime the drag. Payload = source index (via FindListItemIndex). uintptr_t payloadValue = dd->getPayload ? dd->getPayload(rowID) : 0; - guiStateManager.Drag().Begin(rowID, dd->payloadType, payloadValue, + app.guiStateManager.Drag().Begin(rowID, dd->payloadType, payloadValue, event.state.screenPos, std::any(), dd->visualizer); return true; @@ -460,22 +463,22 @@ namespace tachyon case tachyon::EventType::MouseMove: { if ((event.state.buttons & tachyon::MouseButtons::Left) == tachyon::MouseButtons::None) break; - guiStateManager.Drag().UpdateFromInput(event.state); - return guiStateManager.Drag().GetDraggedID() == rowID; + app.guiStateManager.Drag().UpdateFromInput(event.state); + return app.guiStateManager.Drag().GetDraggedID() == rowID; } case tachyon::EventType::MouseUp: { if (!event.state.LeftReleased()) break; // Focus the row's first control, if any; otherwise leave focus alone. - const ElementRef rowRef = elementStorage.GetParentRef(event.elementRef); + const ElementRef rowRef = app.elementStorage.GetParentRef(event.elementRef); if (rowRef.IsValid()) { const ID firstControl = - LabelBinding::FindFirstControlInSubtree(elementStorage, rowRef); + LabelBinding::FindFirstControlInSubtree(app.elementStorage, rowRef); // Skip the knob itself in case it is ever flagged as a control. if (firstControl != ID::Invalid() && firstControl != event.id) { - TakeFocus(guiStateManager, firstControl); + TakeFocus(app.guiStateManager, firstControl); } } // Don't consume - the drag system also wants to see MouseUp. @@ -487,51 +490,51 @@ namespace tachyon }; // Grip icon, sized by the knob style's -tachyon-icon-size. - knob.textID = textSystem->RegisterText(knobID, theme.dragHandleIcon, "", knob.styleRef, knob.state); - auto knobRes = elementStorage.Add(std::move(knob), LayoutOverride{}); + knob.textID = app.textSystem->RegisterText(knobID, app.theme.dragHandleIcon, "", knob.styleRef, knob.state); + auto knobRes = app.elementStorage.Add(std::move(knob), LayoutOverride{}); VERIFY(knobRes.status); - VERIFY(windowRegistry.Add(knobRes.ref)); + VERIFY(app.windowRegistry.Add(knobRes.ref)); } // 3) Body child (text + icon, flex-grows to fill the remaining width). { - [[maybe_unused]] const bool pushed = idManager.PushParent(id); - tachyon::ID bodyID = idManager.AllocateDynamicID("list_item_body"); - if (pushed) (void)idManager.PopParent(); + [[maybe_unused]] const bool pushed = app.idManager.PushParent(id); + tachyon::ID bodyID = app.idManager.AllocateDynamicID("list_item_body"); + if (pushed) (void)app.idManager.PopParent(); tachyon::Element body{}; body.id = bodyID; - body.state = guiStateManager.GetCurrentState(bodyID); - body.styleRef = theme.listItemBodyStyleRef; - body.textID = TreeItemRegisterText(bodyID, text, icon, theme.listItemBodyStyleRef, body.state); - body.eventHandler = [this, rowID = id, itemIndex, selectedIndex, containerID](ElementEvent&& event) -> bool + body.state = app.guiStateManager.GetCurrentState(bodyID); + body.styleRef = styles.listItemBodyStyleRef; + body.textID = TreeItemRegisterText(app, bodyID, text, icon, styles.listItemBodyStyleRef, body.state); + body.eventHandler = [&app, rowID = id, itemIndex, selectedIndex, containerID](ElementEvent&& event) -> bool { if (event.type == tachyon::EventType::MouseDown && event.state.LeftPressed()) { if (selectedIndex) *selectedIndex = itemIndex; - auto& scrollManagement = guiStateManager.GetScrollManagement(); - scrollManagement.MakeElementVisibleHierarchically(elementStorage, event.elementRef); - TakeFocus(guiStateManager, containerID); - guiStateManager.Interaction().SetClicked(rowID); + auto& scrollManagement = app.guiStateManager.GetScrollManagement(); + scrollManagement.MakeElementVisibleHierarchically(app.elementStorage, event.elementRef); + TakeFocus(app.guiStateManager, containerID); + app.guiStateManager.Interaction().SetClicked(rowID); return true; } return false; }; - auto bodyRes = elementStorage.Add(std::move(body), LayoutOverride::Auto()); + auto bodyRes = app.elementStorage.Add(std::move(body), LayoutOverride::Auto()); VERIFY(bodyRes.status); - VERIFY(windowRegistry.Add(bodyRes.ref)); + VERIFY(app.windowRegistry.Add(bodyRes.ref)); } - VERIFY(elementStorage.EndChildren()); + VERIFY(app.elementStorage.EndChildren()); - if (selected) guiStateManager.Construction().PopSelected(); - return guiStateManager.Interaction().HasBeenClicked(id); + if (selected) app.guiStateManager.Construction().PopSelected(); + return app.guiStateManager.Interaction().HasBeenClicked(id); } - int GUIApplication::FindListItemIndex(tachyon::ID id) const + int FindListItemIndex(const Context& context, tachyon::ID id) { - auto it = m_listItemIndexByID.find(id); - return (it != m_listItemIndexByID.end()) ? it->second : -1; + auto it = context.listItemIndexByID.find(id); + return (it != context.listItemIndexByID.end()) ? it->second : -1; } @@ -542,12 +545,12 @@ namespace tachyon // scroll, and drag-and-drop live on the supplied TableState. // ----------------------------------------------------------------------- - void GUIApplication::RebuildTreeViewIndex(std::vector& rows) + void RebuildTreeViewIndex(std::vector& rows) { TreeUtils::RebuildTreeIndex(rows); } - void GUIApplication::WalkTreeViewVisibility(const std::vector& rows, + void WalkTreeViewVisibility(const std::vector& rows, const std::unordered_set& openRows, std::vector& visibleIdx) { @@ -625,7 +628,7 @@ namespace tachyon } } - void GUIApplication::WalkTreeViewVisibility(const std::vector& rows, + void WalkTreeViewVisibility(const std::vector& rows, std::vector& visibleIdx, TableState& state) { WalkTreeViewVisibility(rows, state.openRows, visibleIdx); @@ -646,7 +649,7 @@ namespace tachyon } } - void GUIApplication::VirtualTreeView(tachyon::ID id, + void VirtualTreeView(GUIApplication& app, Context& context, tachyon::ID id, std::vector& rows, std::vector& visibleIdx, TableState& state, @@ -654,6 +657,7 @@ namespace tachyon LayoutOverride&& constraints, std::string_view header) { + const Styles& styles = GetStyles(app, context); // Rebuild the visible-row list each frame from the expand/collapse state. WalkTreeViewVisibility(rows, visibleIdx, state); @@ -665,11 +669,11 @@ namespace tachyon VirtualTableColumn cols[] = { { { .header = header }, - [this, &rows, &visibleIdx, &state, anyExpandable](int rowIdx) { + [&context, &app, &rows, &visibleIdx, &state, anyExpandable](int rowIdx) { if (rowIdx < 0 || rowIdx >= int(visibleIdx.size())) return; const size_t flat = size_t(visibleIdx[rowIdx]); TreeViewRow& r = rows[flat]; - TreeCell(r.name, r.depth, + TreeCell(app, context, r.name, r.depth, TreeViewOpenRef(rows, flat, state), r.icon, r.ancestorLineMask, @@ -680,14 +684,14 @@ namespace tachyon } }; - const StyleRef tableStyle = (style != StyleRef{}) ? style : theme.treeViewStyleRef; + const StyleRef tableStyle = (style != StyleRef{}) ? style : styles.treeViewStyleRef; // A tree is a list: rounded rows without stripes, unless the caller picked its own. const StyleRef callerRowStyle = state.rowStyle; if (callerRowStyle.layoutStyleIndex == LayoutStyleIndex::Invalid) - state.rowStyle = theme.listRowStyleRef; + state.rowStyle = styles.listRowStyleRef; state.showHeaders = !header.empty(); - VirtualTable(id, state, + VirtualTable(app, context, id, state, std::span(cols, 1), int(visibleIdx.size()), 0, tableStyle, std::move(constraints)); diff --git a/src/gui_controls/gui_table_helpers.cpp b/src/gui_views/gui_table_helpers.cpp similarity index 96% rename from src/gui_controls/gui_table_helpers.cpp rename to src/gui_views/gui_table_helpers.cpp index be90600e..a136b0d8 100644 --- a/src/gui_controls/gui_table_helpers.cpp +++ b/src/gui_views/gui_table_helpers.cpp @@ -1,9 +1,9 @@ -#include +#include #include -namespace tachyon::TableHelpers +namespace tachyon::views::TableHelpers { VirtualRowRange ComputeVirtualRowRange(int32_t scrollY, int32_t viewportH, diff --git a/src/gui_controls/gui_table_helpers.h b/src/gui_views/gui_table_helpers.h similarity index 97% rename from src/gui_controls/gui_table_helpers.h rename to src/gui_views/gui_table_helpers.h index 6f8d7ec2..f90ef947 100644 --- a/src/gui_controls/gui_table_helpers.h +++ b/src/gui_views/gui_table_helpers.h @@ -10,7 +10,7 @@ namespace tachyon struct VisualTextStyle; } -namespace tachyon::TableHelpers +namespace tachyon::views::TableHelpers { /// @addtogroup controls_data /// @{ diff --git a/src/gui_controls/gui_table_types.h b/src/gui_views/gui_table_types.h similarity index 98% rename from src/gui_controls/gui_table_types.h rename to src/gui_views/gui_table_types.h index 23671a58..ee7c2b97 100644 --- a/src/gui_controls/gui_table_types.h +++ b/src/gui_views/gui_table_types.h @@ -25,7 +25,7 @@ // Table widget data model: column descriptors, the user-owned persistent // TableState, drag/drop state and the per-emit TableEmit. -namespace tachyon +namespace tachyon::views { /// @addtogroup controls_data /// @{ @@ -82,11 +82,12 @@ namespace tachyon /// /// std::vector columns = { /// { .column = { .header = "Name", .initialWidth = 160 }, - /// .generateCell = [this](int row) { Cell(rows[row].name); }, + /// .generateCell = [this](int row) { views::Cell(*this, viewsContext, rows[row].name); }, /// .sortAscending = [this](int a, int b) { return rows[a].name < rows[b].name; } }, /// }; - /// VirtualTable(tableID, tableState, columns, int(rows.size()), 0, theme.tableFillStyleRef, - /// LayoutOverride::Auto().FlexGrow(1).MinHeight(0)); + /// views::VirtualTable(*this, viewsContext, tableID, tableState, columns, int(rows.size()), 0, + /// views::GetStyles(*this, viewsContext).tableFillStyleRef, + /// LayoutOverride::Auto().FlexGrow(1).MinHeight(0)); struct VirtualTableColumn { TableColumn column; /// Emits the cell of dataset row `rowIndex`; null in the BeginTable/Cell flow. diff --git a/src/gui_controls/gui_tree_grid_types.h b/src/gui_views/gui_tree_grid_types.h similarity index 99% rename from src/gui_controls/gui_tree_grid_types.h rename to src/gui_views/gui_tree_grid_types.h index db5a0256..d0b979b2 100644 --- a/src/gui_controls/gui_tree_grid_types.h +++ b/src/gui_views/gui_tree_grid_types.h @@ -10,7 +10,7 @@ // TreeView / ListView / GridView data + construction state. -namespace tachyon +namespace tachyon::views { /// @addtogroup controls_data /// @{ @@ -18,7 +18,7 @@ namespace tachyon // ---- Transient tree/list construction state (valid between Begin/End) ---- // // Valid only between Begin*/End* (reset in End*). Event handlers run at end of frame, - // so they must capture the user-owned pointers instead of reading m_treeState. + // so they must capture the user-owned pointers instead of reading context.treeState. // /// Construction state of the current TreeView / ListView; internal. struct TreeViewState { diff --git a/src/gui_controls/gui_tree_utils.h b/src/gui_views/gui_tree_utils.h similarity index 99% rename from src/gui_controls/gui_tree_utils.h rename to src/gui_views/gui_tree_utils.h index d2d81aca..37e1d397 100644 --- a/src/gui_controls/gui_tree_utils.h +++ b/src/gui_views/gui_tree_utils.h @@ -14,7 +14,7 @@ #include #include -namespace tachyon::TreeUtils +namespace tachyon::views::TreeUtils { /// @addtogroup controls_data /// @{ diff --git a/src/gui_views/gui_views.cpp b/src/gui_views/gui_views.cpp new file mode 100644 index 00000000..abd66576 --- /dev/null +++ b/src/gui_views/gui_views.cpp @@ -0,0 +1,235 @@ +#include +#include + +#include +#include + +#include +#include +#include +#include + +namespace tachyon::views +{ + 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; + StyleManager& styleManager = app.styleManager; + ITextSystem* textSystem = app.textSystem; + tableStyleRef = theme.GetStyle("table"); + tableFillStyleRef = theme.GetStyle("table-fill"); + tableHeaderSectionStyleRef = theme.GetStyle("table-header-section"); + tableBodiesRowStyleRef = theme.GetStyle("table-bodies-row"); + tableScrollableBodyStyleRef = theme.GetStyle("table-scrollable-body"); + tableFitContentBodyStyleRef = theme.GetStyle("table-fit-content-body"); + tableRowStyleRef = theme.GetStyle("table-row"); + tableRowAltStyleRef = theme.GetStyle("table-row-alt"); + tableRowBarStyleRef = theme.GetStyle("table-row-bar"); + listRowStyleRef = theme.GetStyle("list-row"); + treeTableCellRowModeStyleRef = theme.GetStyle("tree-table-cell-row-mode"); + treeTableArrowGlyphStyleRef = theme.GetStyle("tree-table-arrow-glyph"); + treeTableTextEditStyleRef = theme.GetStyle("tree-table-text-edit"); + tableHeaderStyleRef = theme.GetStyle("table-header"); + tableHeaderLockedStyleRef = theme.GetStyle("table-header-locked"); + tableHeaderEndStyleRef = theme.GetStyle("table-header-end"); + tableHeaderLockedEndStyleRef = theme.GetStyle("table-header-locked-end"); + tableSizerStyleRef = theme.GetStyle("table-sizer"); + tableSeparatorStyleRef = theme.GetStyle("table-separator"); + tableCellStyleRef = theme.GetStyle("table-cell"); + tableCellNumberStyleRef = theme.GetStyle("table-cell-number"); + tableCellCompactStyleRef = theme.GetStyle("table-cell-compact"); + treeTableCellStyleRef = theme.GetStyle("tree-table-cell"); + treeTableIndentStyleRef = theme.GetStyle("tree-table-indent"); + treeTableArrowStyleRef = theme.GetStyle("tree-table-arrow"); + treeTableIconStyleRef = theme.GetStyle("tree-table-icon"); + treeTableTextStyleRef = theme.GetStyle("tree-table-text"); + listViewStyleRef = theme.GetStyle("list-view"); + listItemStyleRef = theme.GetStyle("list-item"); + listItemRowStyleRef = theme.GetStyle("list-item-row"); + listItemBodyStyleRef = theme.GetStyle("list-item-body"); + treeViewStyleRef = theme.GetStyle("tree-view"); + gridViewStyleRef = theme.GetStyle("grid-view"); + gridViewItemStyleRef = theme.GetStyle("grid-view-item"); + gridViewScrollStyleRef = theme.GetStyle("grid-view-scroll"); + gridViewRowStyleRef = theme.GetStyle("grid-view-row"); + gridViewRenameItemStyleRef = theme.GetStyle("grid-view-rename-item"); + gridViewRenameListItemStyleRef = theme.GetStyle("grid-view-rename-list-item"); + gridViewRenameIconStyleRef = theme.GetStyle("grid-view-rename-icon"); + gridViewRenameEditStyleRef = theme.GetStyle("grid-view-rename-edit"); + settingsPageSelectionRef = theme.GetStyle("settings-page-selection"); + settingsPageStyleRef = theme.GetStyle("settings-page"); + settingsSizerStyleRef = theme.GetStyle("settings-sizer"); + sortArrowUpIcon = RegisterIcon(textSystem, "sort-arrow-up", R"()"); + sortArrowDownIcon = RegisterIcon(textSystem, "sort-arrow-down", R"()"); + treeGuideLineStyle = theme.VariableColor(styleManager, "--tree-guide", color4f{ 0.5f, 0.5f, 0.5f, 1.0f }); + if (!textSystem) + return; + + // Rows: "Mg" (ascender + descender) in both cell styles, the larger, so a table that + // mixes them has one row height. Real metrics: VirtualTable's spacer math uses it as + // is, and an estimate makes the largest scroll keep changing. + auto measure = [&](StyleRef style) -> int32_t { + const TextID probeID = textSystem->RegisterText(ID::Invalid(), "Mg", style, ElementState::None); + int32_t h = textSystem->GetTextMeasurement(probeID).minHeight; + if (const LayoutStyle* ls = styleManager.GetLayoutStyle(style.layoutStyleIndex)) + h += ls->padding.Vertical() + ls->borderWidths.Vertical(); + return std::max(1, h); + }; + tableRowHeight = std::max(measure(tableCellStyleRef), measure(treeTableCellStyleRef)); + + // Tree-table cells: the stylesheet has them; a missing value falls back to the text's + // line height, so it still follows the font. + const TextID probeID = textSystem->RegisterText(ID::Invalid(), "Mg", treeTableTextStyleRef, ElementState::None); + const int32_t lineHeight = std::max(1, textSystem->GetTextMeasurement(probeID).minHeight); + auto cssWidth = [&](StyleRef s) -> int32_t { + const LayoutStyle* ls = styleManager.GetLayoutStyle(s.layoutStyleIndex); + return (ls && ls->layoutData.width != LayoutData::kAutoSize) ? ls->layoutData.width : lineHeight; + }; + auto cssIconSize = [&](StyleRef s, int32_t fallback) -> int32_t { + const LayoutStyle* ls = styleManager.GetLayoutStyle(s.layoutStyleIndex); + return (ls && ls->iconSize > 0) ? static_cast(ls->iconSize) : fallback; + }; + treeTableIndent = cssWidth(treeTableIndentStyleRef); + treeTableExpanderWidth = cssWidth(treeTableArrowStyleRef); + treeTableIconSize = cssIconSize(treeTableIconStyleRef, lineHeight); + treeTableArrowGlyphSize = cssIconSize(treeTableArrowGlyphStyleRef, treeTableIconSize); + } + + Context& Prepare(GUIApplication& app, Context& context) + { + // The first view of a frame: the maps the last frame's handlers read start again. + if (context.frameEnded) + { + context.frameEnded = false; + context.listItemIndexByID.clear(); + context.gridItemRenameByID.clear(); + } + 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 EndGUI(GUIApplication& app, Context& context) + { + (void)app; + if (context.tableEmit.has_value() || !context.outerTableEmits.empty()) + { + GUIApplication::ReportMisuse("views: unbalanced BeginTable/EndTable at end of frame (closed)"); + context.tableEmit.reset(); + context.outerTableEmits.clear(); + } + if (context.treeState.containerID != ID::Invalid()) + { + GUIApplication::ReportMisuse("views: unbalanced BeginListView/EndListView at end of frame (closed)"); + context.treeState = {}; + } + if (context.gridViewState.containerID != ID::Invalid()) + { + GUIApplication::ReportMisuse("views: unbalanced BeginGridView/EndGridView at end of frame (closed)"); + context.gridViewState = {}; + } + context.frameEnded = true; + } + + void PersistTable(GUIApplication& app, std::string key, TableState& state, std::span columns) + { + TableState* table = &state; + // Each column by its header, with its width. + auto save = [table, columns] + { + JsonValue saved = JsonValue::MakeArray(); + for (size_t i = 0; i < columns.size(); ++i) + { + const TableColumn& column = columns[i].column; + const int32_t width = i < table->columnWidths.size() ? table->columnWidths[i] : column.initialWidth.value; + JsonValue c = JsonValue::MakeObject(); + c.Set("column", std::string(column.header)); + c.Set("width", width); + saved.Push(std::move(c)); + } + return saved; + }; + // The columns in their saved order (new ones after), with their saved widths. + auto restore = [table, columns](const JsonValue& saved) + { + if (!saved.IsArray()) + return; + const size_t count = columns.size(); + std::vector order; + std::vector widths; + std::vector taken(count, false); + for (const JsonValue& c : saved.Items()) + { + const std::string& header = c.Find("column") ? c.Find("column")->AsString() : std::string(); + for (size_t i = 0; i < count; ++i) + if (!taken[i] && columns[i].column.header == header) + { + taken[i] = true; + order.push_back(i); + const TableColumn& col = columns[i].column; + const double w = c.Find("width") ? c.Find("width")->AsNumber(col.initialWidth.value) : col.initialWidth.value; + widths.push_back(std::clamp(int32_t(std::lround(w)), col.minWidth.value, col.maxWidth.value)); + break; + } + } + for (size_t i = 0; i < count; ++i) + if (!taken[i]) { order.push_back(i); widths.push_back(columns[i].column.initialWidth.value); } + + std::vector reordered; + reordered.reserve(count); + for (const size_t i : order) reordered.push_back(std::move(columns[i])); + std::move(reordered.begin(), reordered.end(), columns.begin()); + if (table->sortColumn >= 0 && size_t(table->sortColumn) < count) + table->sortColumn = int(std::find(order.begin(), order.end(), size_t(table->sortColumn)) - order.begin()); + table->columnWidths = std::move(widths); + }; + app.PersistJson("tables", std::move(key), std::move(save), std::move(restore)); + } + + std::string SaveViewState(const SettingsPanelState& settings) + { + for (const SettingsPanelState::Page& page : settings.pages) + if (page.id == settings.selectedID) + { + JsonValue state = JsonValue::MakeObject(); + state.Set("page", page.name); + return state.Write(); + } + return {}; + } + + bool RestoreViewState(SettingsPanelState& settings, std::string_view state) + { + const std::optional object = ParseJsonObject(state); + const JsonValue* name = object ? object->Find("page") : nullptr; + if (!name || !name->IsString()) + return false; + for (const SettingsPanelState::Page& page : settings.pages) + if (page.name == name->AsString()) + { + settings.selectedID = page.id; + return true; + } + return false; + } +} diff --git a/src/gui_views/gui_views.h b/src/gui_views/gui_views.h new file mode 100644 index 00000000..a9202493 --- /dev/null +++ b/src/gui_views/gui_views.h @@ -0,0 +1,529 @@ +#pragma once + +// Views: list views, tree views, grid views, tables and the settings panel. A library of its +// own on gui_controls, in namespace tachyon::views: each control is a free function that takes +// the application and a views::Context, which the app owns. +// +// views::Context viewsContext; // a member of the app class +// +// if (auto table = views::Table(*this, viewsContext, columns, tableState)) +// for (const Asset& asset : assets) +// if (auto row = views::Row(*this, viewsContext)) +// views::Cell(*this, viewsContext, asset.name); +// views::EndGUI(*this, viewsContext); // last in OnGUI + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace tachyon::views +{ + /// @addtogroup controls + /// @{ + + /// The views' styles, icons and sizes, looked up in the theme after each load. + struct Styles + { + StyleRef tableStyleRef {}; ///< Table: the table + StyleRef tableFillStyleRef {}; + StyleRef tableHeaderSectionStyleRef {}; + StyleRef tableBodiesRowStyleRef {}; ///< row holding the table's body sections, bounded to the table + StyleRef tableScrollableBodyStyleRef {}; ///< a scrolling section body + StyleRef tableFitContentBodyStyleRef {}; + StyleRef tableRowStyleRef {}; ///< row backdrop (odd rows) + StyleRef tableRowAltStyleRef {}; ///< row backdrop (even rows) + StyleRef tableRowBarStyleRef {}; ///< accent bar on a selected row's left + StyleRef listRowStyleRef {}; ///< rounded row without stripes (tree views, TableState::rowStyle) + StyleRef treeTableCellRowModeStyleRef {}; + StyleRef treeTableArrowGlyphStyleRef {}; + StyleRef treeTableTextEditStyleRef {}; + StyleRef tableHeaderStyleRef {}; ///< a column header + StyleRef tableHeaderLockedStyleRef {}; + StyleRef tableHeaderEndStyleRef {}; ///< as tableHeaderStyleRef, over cells aligned to the end (numbers) + StyleRef tableHeaderLockedEndStyleRef {}; ///< as tableHeaderLockedStyleRef, over cells aligned to the end + StyleRef tableSizerStyleRef {}; ///< a column's resize handle + StyleRef tableSeparatorStyleRef {}; ///< the divider between table sections + StyleRef tableCellStyleRef {}; ///< a cell + StyleRef tableCellNumberStyleRef {}; ///< right-aligned number cell (TableColumn::cellStyle) + StyleRef tableCellCompactStyleRef {}; ///< tighter-padded cell for dense tables (opt-in via VirtualTable cellStyle) + StyleRef treeTableCellStyleRef {}; + StyleRef treeTableIndentStyleRef {}; + StyleRef treeTableArrowStyleRef {}; + StyleRef treeTableIconStyleRef {}; + StyleRef treeTableTextStyleRef {}; + StyleRef listViewStyleRef {}; ///< BeginListView's default + StyleRef listItemStyleRef {}; ///< ListItem's default + StyleRef listItemRowStyleRef {}; ///< reorderable list item outer container + StyleRef listItemBodyStyleRef {}; ///< reorderable list item text/icon body + StyleRef treeViewStyleRef {}; ///< a tree view + StyleRef gridViewStyleRef {}; ///< BeginGridView's default + StyleRef gridViewItemStyleRef {}; ///< a grid view cell, by default + StyleRef gridViewScrollStyleRef {}; ///< virtualized grid scroll viewport (column) + StyleRef gridViewRowStyleRef {}; ///< one row strip of cells in the virtual grid + StyleRef gridViewRenameItemStyleRef {}; ///< rename-mode cell: icon above inline editor + StyleRef gridViewRenameListItemStyleRef {}; ///< rename-mode list row: icon left of editor + StyleRef gridViewRenameIconStyleRef {}; ///< the icon child of a renaming cell + StyleRef gridViewRenameEditStyleRef {}; ///< grid-mode inline editor (full cell width) + StyleRef settingsPageSelectionRef {}; ///< the settings page list (.settings-page-selection) + StyleRef settingsPageStyleRef {}; ///< settings page body - dock-content layout + left padding off the sizer + StyleRef settingsSizerStyleRef {}; ///< between the page list and the page: a 1px line, lit while hovered + IconID sortArrowUpIcon {}; ///< table header: sorted descending + IconID sortArrowDownIcon {}; ///< table header: sorted ascending + VisualColorStyleIndex treeGuideLineStyle {}; ///< --tree-guide: tree guide lines (transparent: none) + + /// Table row height in pixels, measured from the font: it must match the rows as + /// drawn, or the largest scroll keeps changing. + int32_t tableRowHeight = 0; + /// @name Tree table metrics + /// Pixels, from the stylesheet; a theme without one gets the text's line height. + ///@{ + int32_t treeTableIndent = 0; ///< per indent level + int32_t treeTableExpanderWidth = 0; ///< the expander column (arrow or leaf spacer) + int32_t treeTableIconSize = 0; ///< a node's icon + int32_t treeTableArrowGlyphSize = 0; ///< the expander arrow + ///@} + + /// Looks them all up in `app`'s theme, after it loads. + void Load(GUIApplication& app); + }; + + /// In-place rename of a tree / list / grid row (F2, Ctrl+Shift+Click or a slow re-click); + /// the target row emits a text field instead of its label. One rename at a time. + struct RenameState + { + tachyon::ID targetID = tachyon::ID::Invalid(); ///< the row being renamed + bool isActive = false; + /// Set on the frame the rename starts, when a commit left over from an earlier edit + /// must not end it; cleared once the field is built. + bool firstFrame = false; + std::string* editBuffer = nullptr; ///< the caller's buffer the field edits + + /// Starts renaming row `id`: `buffer` is set to `text` and edited in place. + void Start(tachyon::ID id, std::string* buffer, std::string_view text) + { + targetID = id; isActive = true; firstFrame = true; + editBuffer = buffer; *buffer = text; + } + /// Ends the rename without touching the buffer. + void Cancel() + { + targetID = tachyon::ID::Invalid(); isActive = false; firstFrame = false; editBuffer = nullptr; + } + }; + + /// What the views keep from frame to frame, the app's to own and pass to each of them. + /// Handlers 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 + bool frameEnded = false; ///< EndGUI ran: the next view starts a frame + + RenameState rename; ///< the inline rename open, if any + ColumnDragState columnDrag; ///< a table column being dragged + TreeDropState treeDrop; ///< where a drag over a tree would drop + + /// The list items by ID, for the handlers that run after the frame is built; filled + /// by the lists with drag and drop. + std::unordered_map listItemIndexByID; + /// The grid items' rename buffers by ID, likewise. + std::unordered_map gridItemRenameByID; + + /// Between a Begin and its End only: the list or tree, the grid, the table being built + /// (and the tables around it, innermost last). Handlers run later, so they hold + /// pointers and never read these. + TreeViewState treeState; + GridViewState gridViewState; + std::optional tableEmit; + std::vector> outerTableEmits; + }; + + /// The views' styles in `app`'s theme, looked up again after each theme load. + const Styles& GetStyles(GUIApplication& app, Context& context); + + /// After everything the frame builds: reports (and closes) a list, grid or table left + /// open. Call it last in OnGUI, every frame. + void EndGUI(GUIApplication& app, Context& context); + + /// @name List and tree views + ///@{ + + // ---- ListView: scrollable list with selectable items ---- + /// Opens a list view of ListItems. selectedIndex (optional) holds the selection, which a + /// click or Up / Down changes; itemCount bounds the keys. dragDrop (optional) lets items be dragged. + bool BeginListView(GUIApplication& app, Context& context, ID id, int* selectedIndex, int itemCount, ItemDragDropConfig* dragDrop, StyleRef style, LayoutOverride&& constraints = {}); + /// As above, without drag and drop. + inline bool BeginListView(GUIApplication& app, Context& context, ID id, int* selectedIndex, int itemCount, StyleRef style, LayoutOverride&& constraints = {}) { return BeginListView(app, context, id, selectedIndex, itemCount, nullptr, style, std::move(constraints)); } + /// As above, without drag and drop, in the theme's list style. + inline bool BeginListView(GUIApplication& app, Context& context, ID id, int* selectedIndex, int itemCount, LayoutOverride&& constraints = {}) { return BeginListView(app, context, id, selectedIndex, itemCount, nullptr, GetStyles(app, context).listViewStyleRef, std::move(constraints)); } + /// As above, with the call site as the ID. + inline bool BeginListView(GUIApplication& app, Context& context, int* selectedIndex, int itemCount, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return BeginListView(app, context, app.idManager.AllocateDynamicID(site), selectedIndex, itemCount, nullptr, GetStyles(app, context).listViewStyleRef, std::move(constraints)); } + /// As above, with drag and drop, in the theme's list style. + inline bool BeginListView(GUIApplication& app, Context& context, ID id, int* selectedIndex, int itemCount, ItemDragDropConfig* dragDrop, LayoutOverride&& constraints = {}) { return BeginListView(app, context, id, selectedIndex, itemCount, dragDrop, GetStyles(app, context).listViewStyleRef, std::move(constraints)); } + /// As above, with the call site as the ID. + inline bool BeginListView(GUIApplication& app, Context& context, int* selectedIndex, int itemCount, ItemDragDropConfig* dragDrop, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return BeginListView(app, context, app.idManager.AllocateDynamicID(site), selectedIndex, itemCount, dragDrop, GetStyles(app, context).listViewStyleRef, std::move(constraints)); } + /// As above, with the call site as the ID, in `style`. + inline bool BeginListView(GUIApplication& app, Context& context, int* selectedIndex, int itemCount, ItemDragDropConfig* dragDrop, StyleRef style, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return BeginListView(app, context, app.idManager.AllocateDynamicID(site), selectedIndex, itemCount, dragDrop, style, std::move(constraints)); } + /// As above, without drag and drop, with the call site as the ID, in `style`. + inline bool BeginListView(GUIApplication& app, Context& context, int* selectedIndex, int itemCount, StyleRef style, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return BeginListView(app, context, app.idManager.AllocateDynamicID(site), selectedIndex, itemCount, nullptr, style, std::move(constraints)); } + /// Closes BeginListView. + void EndListView(GUIApplication& app, Context& context); + + /// A list item's index by ID, for end-of-frame handlers; -1 if unknown. Filled only for + /// lists with drag and drop. + int FindListItemIndex(const Context& context, tachyon::ID id); + + /// One item of a list view, drawn selected when it is the selected index. True when clicked. + bool ListItem(GUIApplication& app, Context& context, ID id, const GUIContent& content, StyleRef style, LayoutOverride&& constraints = {}); + /// As above, in the theme's item style. + inline bool ListItem(GUIApplication& app, Context& context, ID id, const GUIContent& content, LayoutOverride&& constraints = {}) { return ListItem(app, context, id, content, GetStyles(app, context).listItemStyleRef, std::move(constraints)); } + /// As above, with the call site as the ID. + inline bool ListItem(GUIApplication& app, Context& context, const GUIContent& content, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return ListItem(app, context, app.idManager.AllocateDynamicID(site), content, GetStyles(app, context).listItemStyleRef, std::move(constraints)); } + /// As above, with the call site as the ID, in `style`. + inline bool ListItem(GUIApplication& app, Context& context, const GUIContent& content, StyleRef style, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return ListItem(app, context, app.idManager.AllocateDynamicID(site), content, style, std::move(constraints)); } + + + /// Recomputes skipCount / ancestorLineMask / isLastSibling from row depths. + /// Call after any structural change. O(n^2) worst case. + void RebuildTreeViewIndex(std::vector& rows); + + /// Writes the flat indices of the rows shown to visibleIdx: those under no closed + /// branch, the open ones being in `openRows` (by TreeViewRowKey). + void WalkTreeViewVisibility(const std::vector& rows, + const std::unordered_set& openRows, + std::vector& visibleIdx); + /// As above, for a tree drawn by a table with `state`, open as its openRows says: when + /// rows were opened or closed, its selection stays on the same rows (row IDs are + /// visible positions). For a tree built on VirtualTable directly; VirtualTreeView does + /// this itself. + void WalkTreeViewVisibility(const std::vector& rows, + std::vector& visibleIdx, TableState& state); + /// The TreeCell open state of flat row `flat` in the view with `state`: its key in + /// state.openRows, or nothing for a row without children. + inline TreeOpenRef TreeViewOpenRef(const std::vector& rows, size_t flat, TableState& state) + { + const TreeViewRow& row = rows[flat]; + return row.HasChildren() ? TreeOpenRef{ .set = &state.openRows, .key = TreeViewRowKey(row, flat) } : TreeOpenRef{}; + } + + /// Single-column virtualized tree view (a VirtualTable with one TreeCell column). + /// A non-empty header shows the header row. + void VirtualTreeView(GUIApplication& app, Context& context, ID id, + std::vector& rows, + std::vector& visibleIdx, + TableState& state, + StyleRef style = {}, + LayoutOverride&& constraints = {}, + std::string_view header = {}); + /// As above, with the call site as the ID. + inline void VirtualTreeView(GUIApplication& app, Context& context, std::vector& rows, std::vector& visibleIdx, TableState& state, + StyleRef style = {}, LayoutOverride&& constraints = {}, std::string_view header = {}, + std::source_location site = std::source_location::current()) + { VirtualTreeView(app, context, app.idManager.AllocateDynamicID(site), rows, visibleIdx, state, style, std::move(constraints), header); } + + /// The tree row a drag is over (drives the drop indicator), or Invalid. + inline ID TreeDropTargetRow(const Context& context) { return context.treeDrop.targetRowID; } + + ///@} + + /// @name Grid views + ///@{ + + // ---- GridView: 2D icon grid (like file explorer) ---- + /// Opens a grid view of GridViewItems. selectedIndex (optional) holds a single selection, + /// multiSelect (optional) a multi-selection; dragDrop (optional) lets items be dragged. + /// Arrow keys move the selection. + bool BeginGridView(GUIApplication& app, Context& context, ID id, int* selectedIndex, StyleRef style, MultiSelectState* multiSelect = nullptr, ItemDragDropConfig* dragDrop = nullptr, LayoutOverride&& constraints = {}); + /// As above, in the theme's grid style. + inline bool BeginGridView(GUIApplication& app, Context& context, ID id, int* selectedIndex = nullptr, MultiSelectState* multiSelect = nullptr, ItemDragDropConfig* dragDrop = nullptr, LayoutOverride&& constraints = {}) { return BeginGridView(app, context, id, selectedIndex, GetStyles(app, context).gridViewStyleRef, multiSelect, dragDrop, std::move(constraints)); } + /// As above, with the call site as the ID, in `style`. + inline bool BeginGridView(GUIApplication& app, Context& context, int* selectedIndex, StyleRef style, MultiSelectState* multiSelect = nullptr, ItemDragDropConfig* dragDrop = nullptr, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return BeginGridView(app, context, app.idManager.AllocateDynamicID(site), selectedIndex, style, multiSelect, dragDrop, std::move(constraints)); } + /// As above, with the call site as the ID, in the theme's grid style. + inline bool BeginGridView(GUIApplication& app, Context& context, int* selectedIndex, MultiSelectState* multiSelect = nullptr, ItemDragDropConfig* dragDrop = nullptr, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) { return BeginGridView(app, context, app.idManager.AllocateDynamicID(site), selectedIndex, GetStyles(app, context).gridViewStyleRef, multiSelect, dragDrop, std::move(constraints)); } + /// Closes BeginGridView. + void EndGridView(GUIApplication& app, Context& context); + + /// renameBuffer (optional) enables in-place rename: F2, Ctrl+Shift+Click or a slow + /// re-click opens an editor. Enter commits; Escape or focus loss cancels. + bool GridViewItem(GUIApplication& app, Context& context, ID id, const GUIContent& content, + tachyon::ElementState extraState = tachyon::ElementState::None, + std::string* renameBuffer = nullptr, + StyleRef itemStyle = {}, + LayoutOverride&& constraints = {}); + /// As above, without rename. + inline bool GridViewItem(GUIApplication& app, Context& context, ID id, const GUIContent& content, LayoutOverride&& constraints) + { return GridViewItem(app, context, id, content, tachyon::ElementState::None, nullptr, {}, std::move(constraints)); } + /// As above, with the call site as the ID. + inline bool GridViewItem(GUIApplication& app, Context& context, const GUIContent& content, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) + { return GridViewItem(app, context, app.idManager.AllocateDynamicID(site), content, tachyon::ElementState::None, nullptr, {}, std::move(constraints)); } + /// Without rename, in `style`. + inline bool GridViewItem(GUIApplication& app, Context& context, ID id, const GUIContent& content, StyleRef style, LayoutOverride&& constraints = {}) + { return GridViewItem(app, context, id, content, tachyon::ElementState::None, nullptr, style, std::move(constraints)); } + /// Without rename, with the call site as the ID, in `style`. + inline bool GridViewItem(GUIApplication& app, Context& context, const GUIContent& content, StyleRef style, LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) + { return GridViewItem(app, context, app.idManager.AllocateDynamicID(site), content, tachyon::ElementState::None, nullptr, style, std::move(constraints)); } + + /// Whether an inline rename editor (a grid item's, a tree row's) is open; an app that + /// sorts by name re-sorts once it closes. + inline bool IsRenaming(const Context& context) { return context.rename.isActive; } + + /// generateItem(index, itemID) must emit exactly one cell, typically GridViewItem(app, context, itemID, ...). + /// itemID is a stable ranged sub-ID (index = id.value.subRangeParts.index), used for + /// selection and drag payloads. Cells are cellSize, with a 4px gap between columns. + void VirtualGridView(GUIApplication& app, Context& context, ID id, GridViewVirtualState& vstate, + int itemCount, int2 cellSize, + const std::function& generateItem, + int* selectedIndex = nullptr, + MultiSelectState* multiSelect = nullptr, + ItemDragDropConfig* dragDrop = nullptr, + StyleRef scrollStyle = {}, + StyleRef rowStyle = {}, + LayoutOverride&& constraints = {}); + /// As above, with the call site as the ID. + inline void VirtualGridView(GUIApplication& app, Context& context, GridViewVirtualState& vstate, int itemCount, int2 cellSize, + const std::function& generateItem, + int* selectedIndex = nullptr, MultiSelectState* multiSelect = nullptr, + ItemDragDropConfig* dragDrop = nullptr, StyleRef scrollStyle = {}, StyleRef rowStyle = {}, + LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) + { VirtualGridView(app, context, app.idManager.AllocateDynamicID(site), vstate, itemCount, cellSize, generateItem, selectedIndex, multiSelect, dragDrop, scrollStyle, rowStyle, std::move(constraints)); } + + ///@} + + /// @name Tables + ///@{ + + // ---- Table: row x column data grid ---- + /// Opens a table. Columns are described each frame; widths, selection and sort state + /// live in the caller's TableState. Rows are BeginRow / EndRow with Cell(text) or + /// Cell(emit); EndTable builds them as a VirtualTable. `columns` must stay valid until + /// EndTable. + bool BeginTable(GUIApplication& app, Context& context, ID id, VirtualTableColumn* columns, size_t columnCount, + TableState& state, StyleRef style, + LayoutOverride&& constraints = {}); + /// As above, in the theme's table style. + inline bool BeginTable(GUIApplication& app, Context& context, ID id, VirtualTableColumn* columns, size_t columnCount, + TableState& state, LayoutOverride&& constraints = {}) + { return BeginTable(app, context, id, columns, columnCount, state, GetStyles(app, context).tableStyleRef, std::move(constraints)); } + /// As above, for a C array of columns. + template + inline bool BeginTable(GUIApplication& app, Context& context, ID id, VirtualTableColumn (&columns)[N], TableState& state, + StyleRef style, LayoutOverride&& constraints = {}) + { return BeginTable(app, context, id, columns, N, state, style, std::move(constraints)); } + /// As above, for a C array of columns, in the theme's table style. + template + inline bool BeginTable(GUIApplication& app, Context& context, ID id, VirtualTableColumn (&columns)[N], TableState& state, + LayoutOverride&& constraints = {}) + { return BeginTable(app, context, id, columns, N, state, GetStyles(app, context).tableStyleRef, std::move(constraints)); } + /// As above, with the call site as the ID. + inline bool BeginTable(GUIApplication& app, Context& context, VirtualTableColumn* columns, size_t columnCount, TableState& state, StyleRef style, + LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) + { return BeginTable(app, context, app.idManager.AllocateDynamicID(site), columns, columnCount, state, style, std::move(constraints)); } + /// As above, with the call site as the ID, in the theme's table style. + inline bool BeginTable(GUIApplication& app, Context& context, VirtualTableColumn* columns, size_t columnCount, TableState& state, + LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) + { return BeginTable(app, context, app.idManager.AllocateDynamicID(site), columns, columnCount, state, GetStyles(app, context).tableStyleRef, std::move(constraints)); } + /// As above, for a C array of columns, with the call site as the ID. + template + inline bool BeginTable(GUIApplication& app, Context& context, VirtualTableColumn (&columns)[N], TableState& state, StyleRef style, + LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) + { return BeginTable(app, context, app.idManager.AllocateDynamicID(site), columns, N, state, style, std::move(constraints)); } + /// As above, for a C array of columns, with the call site as the ID, in the theme's table style. + template + inline bool BeginTable(GUIApplication& app, Context& context, VirtualTableColumn (&columns)[N], TableState& state, + LayoutOverride&& constraints = {}, std::source_location site = std::source_location::current()) + { return BeginTable(app, context, app.idManager.AllocateDynamicID(site), columns, N, state, GetStyles(app, context).tableStyleRef, std::move(constraints)); } + /// Builds the recorded rows as a VirtualTable. + void EndTable(GUIApplication& app, Context& context); + + /// Starts a row; its Cells fill the columns in order. + bool BeginRow(GUIApplication& app, Context& context); + /// Ends the row. + void EndRow(GUIApplication& app, Context& context); + + /// Cells auto-advance to the next column. + void Cell(GUIApplication& app, Context& context, std::string_view text); + + /// Custom-content cell: `emit` runs inside the cell during EndTable, so its + /// captures must live until then. + void Cell(GUIApplication& app, Context& context, std::function emit); + + /// Tree-style first column: [indent][arrow or spacer][optional icon][text]. + /// + /// depth horizontal indent (pixels = depth * Styles::treeTableIndent). + /// isOpen where the row's open state lives: empty for leaves (no + /// arrow), else a bool of yours or a view's open rows (see + /// TreeViewOpenRef). Clicks toggle it. + /// icon optional leading icon rendered between arrow and text. + /// ancestorLineMask bit d set iff the ancestor at depth d+1 has a next sibling + /// (its guide line passes through this row at column d). + /// isLastSibling true -> own-depth L-tick stops at row center. + /// renameBuffer optional; enables in-place rename (F2 / Ctrl+Shift+Click / slow re-click). + /// reserveExpander false drops the arrow slot for leaves (for flat trees). + /// + /// Arrow clicks toggle without selecting; other clicks select the row. + void TreeCell(GUIApplication& app, Context& context, std::string_view text, int depth, TreeOpenRef isOpen, + IconID icon = IconID::Invalid, + uint32_t ancestorLineMask = 0, + bool isLastSibling = true, + std::string* renameBuffer = nullptr, + bool reserveExpander = true); + /// As above, the open state a bool of yours; null for leaves. + inline void TreeCell(GUIApplication& app, Context& context, std::string_view text, int depth, bool* isOpen, + IconID icon = IconID::Invalid, + uint32_t ancestorLineMask = 0, + bool isLastSibling = true, + std::string* renameBuffer = nullptr, + bool reserveExpander = true) + { TreeCell(app, context, text, depth, TreeOpenRef{ .flag = isOpen }, icon, ancestorLineMask, isLastSibling, renameBuffer, reserveExpander); } + + /// Virtual-scrolled table: emits only the visible rows, under one ranged ID. + /// Frozen columns get their own body section (left / mid / right), scroll-synced. + /// + /// columns : each carries its own generateCell(rowIndex), so reordering + /// the array reorders headers and cells together. A C array + /// converts to the span. + /// rowHeight : row-height floor; 0 uses the style's natural row height. + /// Headers, cell style and separators are TableState options. + void VirtualTable(GUIApplication& app, Context& context, ID id, TableState& state, + std::span columns, + int totalRowCount, + CssPx rowHeight = 0, + StyleRef style = {}, + LayoutOverride&& constraints = {}); + /// As above, with the call site as the ID. + inline void VirtualTable(GUIApplication& app, Context& context, TableState& state, std::span columns, int totalRowCount, + CssPx rowHeight = 0, StyleRef style = {}, LayoutOverride&& constraints = {}, + std::source_location site = std::source_location::current()) + { VirtualTable(app, context, app.idManager.AllocateDynamicID(site), state, columns, totalRowCount, rowHeight, style, std::move(constraints)); } + + ///@} + + /// @name Settings panel + ///@{ + + // ------------------------------------------------------------------ + // Settings panel + // ------------------------------------------------------------------ + // Two-pane settings panel: a page tree, a sizer, and the selected page's content. + // Owns only selection and tree width; page state belongs to the application. + /// What RenderSettingsPanel shows: its pages, the selected one and the tree width. + struct SettingsPanelState + { + /// A page: a stable ID, its name in the tree, and render, which builds its content. + struct Page + { + /// Stable across frames. + tachyon::ID id; + /// Shown in the page tree. + std::string name; + /// Builds the page's content while it is selected. + std::function render; + /// Before its name in the page list; optional. + IconID icon = IconID::Invalid; + }; + + /// Added with AddPage. + std::vector pages; + /// Above the page list, as a small caption ("Preferences"); none when empty. + std::string header; + /// The page shown; a click in the tree changes it. + tachyon::ID selectedID = tachyon::ID::Invalid(); + /// The page tree's width; its sizer changes it. + CssPx treeWidth = 200; + + /// Tree-view backing state, rebuilt per frame; not part of the API. + struct Internal + { + std::vector rows; + std::vector visibleIdx; + TableState tableState; + } internal; + + /// `id` must be stable. The first page added is selected initially. + tachyon::ID AddPage(tachyon::ID id, std::string_view name, + std::function render) + { + return AddPage(id, name, IconID::Invalid, std::move(render)); + } + /// As above, with an icon before its name in the page list. + tachyon::ID AddPage(tachyon::ID id, std::string_view name, IconID icon, + std::function render) + { + pages.push_back({ id, std::string(name), std::move(render), icon }); + if (selectedID == tachyon::ID::Invalid()) selectedID = id; + return id; + } + }; + + /// Renders into the current container; the caller provides the outer panel. + void RenderSettingsPanel(GUIApplication& app, Context& context, SettingsPanelState& state); + + ///@} + + /// Keeps the table's column widths and order in the app's saved UI state, matching columns + /// by header (GUIApplication::PersistJson, in its "tables" section). + void PersistTable(GUIApplication& app, std::string key, TableState& state, std::span columns); + + /// The settings page open, by its name, as text for a panel to keep with its layout + /// (Panel::saveState and Panel::restoreState), and back. False when no page has that name: the one open + /// stays. + std::string SaveViewState(const SettingsPanelState& settings); + bool RestoreViewState(SettingsPanelState& settings, std::string_view state); + + /// A container's scope: its End runs when the scope leaves (or at End()). True when the + /// container's content is to be built, as its Begin returned. + /// + /// if (auto list = views::ListView(*this, viewsContext, &selected, count)) { ...items... } + template + class [[nodiscard]] Scope + { + public: + /// Made by the scope functions below. + Scope(GUIApplication& app, Context& context, bool open) : m_app(&app), m_context(&context), m_open(open) {} + Scope(Scope&& other) noexcept : m_app(std::exchange(other.m_app, nullptr)), m_context(other.m_context), m_open(other.m_open) {} + Scope(const Scope&) = delete; + Scope& operator=(const Scope&) = delete; + Scope& operator=(Scope&&) = delete; + ~Scope() { End(); } + + /// Ends the container now instead of when the scope leaves. + void End() + { + if (GUIApplication* app = std::exchange(m_app, nullptr)) + EndFn(*app, *m_context); + } + explicit operator bool() const { return m_open; } + + private: + GUIApplication* m_app; + Context* m_context; + bool m_open; + }; + + /// @name Container scopes + /// Scopes for the Begin / End pairs, taking the Begin's arguments. + ///@{ + template auto Table(GUIApplication& app, Context& context, A&&... a) { return Scope<&EndTable>(app, context, BeginTable(app, context, std::forward(a)...)); } + template auto Row(GUIApplication& app, Context& context, A&&... a) { return Scope<&EndRow>(app, context, BeginRow(app, context, std::forward(a)...)); } + template auto ListView(GUIApplication& app, Context& context, A&&... a) { return Scope<&EndListView>(app, context, BeginListView(app, context, std::forward(a)...)); } + template auto GridView(GUIApplication& app, Context& context, A&&... a) { return Scope<&EndGridView>(app, context, BeginGridView(app, context, std::forward(a)...)); } + ///@} + + /// @} +} diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 735189b6..dfbfa621 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -21,8 +21,6 @@ list(APPEND GUI_CORE_TEST_FILES progress_composites_test.cpp node_view_frame_test.cpp node_view_state_machine_test.cpp - timeline_test.cpp - timeline_editor_test.cpp theme_variables_test.cpp box_fields_test.cpp curve_test.cpp @@ -68,11 +66,9 @@ list(APPEND GUI_CORE_TEST_FILES node_view_wire_edit_test.cpp node_view_edit_test.cpp edit_id_release_test.cpp - timeline_internal_test.cpp 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 @@ -80,7 +76,6 @@ list(APPEND GUI_CORE_TEST_FILES navigation_test.cpp math3d_test.cpp image_batcher_test.cpp - viewport_test.cpp harness_self_test.cpp frame_pipeline_test.cpp frame_clock_test.cpp @@ -131,7 +126,6 @@ list(APPEND GUI_CORE_TEST_FILES static_id_release_test.cpp controls_documents_test.cpp node_view_two_views_test.cpp - timeline_two_views_test.cpp curve_plot_two_views_test.cpp controls_notifications_test.cpp skribidi_shaping_test.cpp @@ -163,7 +157,6 @@ list(APPEND GUI_CORE_TEST_FILES scoped_temp_dir.h fake_clock.h skribidi_test_fixture.h - headless_gui_app.cpp mock_window_backend.h window_registry_test.cpp text_editor_coordinate_test.cpp @@ -182,6 +175,14 @@ if(TACHYON_VULKAN) frame_waits_test.cpp) endif() +# The headless app the tests drive (HeadlessGUIApp) and its mock window backend, for every +# test program that builds controls. +add_library(tachyon_test_harness STATIC headless_gui_app.cpp headless_gui_app.h mock_window_backend.h) +target_include_directories(tachyon_test_harness PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}") +target_link_libraries(tachyon_test_harness PUBLIC gui_controls GTest::gtest GTest::gmock) +tachyon_apply_compile_options(tachyon_test_harness) +set_target_properties(tachyon_test_harness PROPERTIES FOLDER "Tests") + add_executable(gui_core_tests ${GUI_CORE_TEST_FILES}) source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${GUI_CORE_TEST_FILES}) # The tutorial's app (docs/tutorial.md), whose panels tutorial_test.cpp drives. @@ -199,7 +200,7 @@ target_compile_definitions(gui_core_tests PRIVATE TACHYON_FRAME_ALLOC_BENCH=$>) tachyon_apply_compile_options(${target}) 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/box_fields_test.cpp b/tests/box_fields_test.cpp index 87591ac1..4fcba2f1 100644 --- a/tests/box_fields_test.cpp +++ b/tests/box_fields_test.cpp @@ -2,6 +2,7 @@ // them, and the ranges they keep to. #include +#include #include "headless_gui_app.h" @@ -17,6 +18,7 @@ namespace tachyon { protected: HeadlessGUIApp app; + color::Context colorContext; ID fieldID {}; void SetUp() override @@ -182,7 +184,7 @@ namespace tachyon TEST_F(BoxFieldsTest, AShadowsParts) { BoxShadow value{ .x = 0, .y = 4, .blur = 0, .spread = 0, .color = { 0, 0, 0, 90 } }; - auto field = [&] { return app.ShadowField(fieldID, value); }; + auto field = [&] { return color::ShadowField(app, colorContext, fieldID, value); }; Emit(field); const auto children = Children(fieldID); ASSERT_EQ(children.size(), 2u) << "the color, and the sizes"; @@ -208,7 +210,7 @@ namespace tachyon TEST_F(BoxFieldsTest, AShadowsSizesAreHeld) { BoxShadow value{ .x = -300, .y = 300, .blur = 400, .spread = -5, .color = { 0, 0, 0, 90 } }; - auto field = [&] { return app.ShadowField(fieldID, value); }; + auto field = [&] { return color::ShadowField(app, colorContext, fieldID, value); }; Emit(field); EXPECT_EQ(value.x, -256); EXPECT_EQ(value.y, 256); diff --git a/tests/color_field_hex_test.cpp b/tests/color_field_hex_test.cpp index c0d74f2d..82c092cf 100644 --- a/tests/color_field_hex_test.cpp +++ b/tests/color_field_hex_test.cpp @@ -5,9 +5,9 @@ #include "headless_gui_app.h" #include "mock_window_backend.h" -#include +#include #include -#include +#include namespace { @@ -23,7 +23,7 @@ namespace { app.Frame([&] { app.BeginRootWindow({ 800, 600 }); - app.ColorField(color, false, LayoutOverride{}.Width(300)); + color::ColorField(app, colorContext, color, false, LayoutOverride{}.Width(300)); app.EndRootWindow(); }); } @@ -41,22 +41,23 @@ namespace } HeadlessGUIApp app; + color::Context colorContext; color4f color{ 0.0f, 0.0f, 1.0f, 0.5f }; }; TEST_F(ColorFieldHex, HasASwatchAHexFieldAndAlpha) { Emit(); - EXPECT_NE(FindByStyle(app.theme.colorSwatchStyleRef), ID::Invalid()); - EXPECT_NE(FindByStyle(app.theme.colorHexStyleRef), ID::Invalid()); - EXPECT_NE(FindByStyle(app.theme.colorAlphaInputStyleRef), ID::Invalid()); - EXPECT_EQ(app.GetElementRect(FindByStyle(app.theme.colorSwatchStyleRef)).w, app.styleManager.Px(56)); + EXPECT_NE(FindByStyle(color::GetStyles(app, colorContext).colorSwatchStyleRef), ID::Invalid()); + EXPECT_NE(FindByStyle(color::GetStyles(app, colorContext).colorHexStyleRef), ID::Invalid()); + EXPECT_NE(FindByStyle(color::GetStyles(app, colorContext).colorAlphaInputStyleRef), ID::Invalid()); + EXPECT_EQ(app.GetElementRect(FindByStyle(color::GetStyles(app, colorContext).colorSwatchStyleRef)).w, app.styleManager.Px(56)); } TEST_F(ColorFieldHex, TypingAHexColorSetsIt) { Emit(); - const ID hexID = FindByStyle(app.theme.colorHexStyleRef); + const ID hexID = FindByStyle(color::GetStyles(app, colorContext).colorHexStyleRef); ASSERT_NE(hexID, ID::Invalid()); app.ClickAt(app.CenterOf(hexID)); Emit(); @@ -82,7 +83,7 @@ namespace void Open() { Emit(); - app.ClickAt(app.CenterOf(FindByStyle(app.theme.colorSwatchStyleRef))); + app.ClickAt(app.CenterOf(FindByStyle(color::GetStyles(app, colorContext).colorSwatchStyleRef))); Emit(); Emit(); } @@ -99,7 +100,7 @@ namespace TEST_F(ColorPickerDialog, TheSwatchOpensIt) { Open(); - const ID square = FindByStyle(app.theme.colorPickerSquareStyleRef); + const ID square = FindByStyle(color::GetStyles(app, colorContext).colorPickerSquareStyleRef); ASSERT_NE(square, ID::Invalid()) << "the dialog is open"; EXPECT_EQ(app.GetElementRect(square).w, app.styleManager.Px(240)); EXPECT_NE(FindByStyle(app.theme.dialogPrimaryButtonStyleRef), ID::Invalid()) << "with an OK button"; @@ -109,7 +110,7 @@ namespace TEST_F(ColorPickerDialog, NewIsOverOriginalNamedBeside) { Open(); - const ID preview = FindByStyle(app.theme.colorPickerPreviewStyleRef); + const ID preview = FindByStyle(color::GetStyles(app, colorContext).colorPickerPreviewStyleRef); const ID newText = app.FindByText("New"), originalText = app.FindByText("Original"); ASSERT_NE(preview, ID::Invalid()); ASSERT_NE(newText, ID::Invalid()); @@ -148,12 +149,12 @@ namespace TEST_F(ColorPickerDialog, TheAppSetsTheSwatchesAndAddsRecentColors) { const color4f palette[] = { { 1, 0, 0, 1 }, { 0, 1, 0, 1 }, { 0, 0, 1, 0.5f } }; - app.SetColorSwatches(palette); + color::SetColorSwatches(app, colorContext, palette); for (int i = 0; i < 10; ++i) - app.AddRecentColor(color4f{ float(i) / 10.0f, 0, 0, 1 }); - app.AddRecentColor(color4f{ 0.5f, 0, 0, 1 }); // already there: moved to the front - ASSERT_EQ(app.ColorSwatches().size(), 3u); - EXPECT_EQ(app.ColorSwatches()[2], palette[2]); + color::AddRecentColor(app, colorContext, color4f{ float(i) / 10.0f, 0, 0, 1 }); + color::AddRecentColor(app, colorContext, color4f{ 0.5f, 0, 0, 1 }); // already there: moved to the front + ASSERT_EQ(color::ColorSwatches(app, colorContext).size(), 3u); + EXPECT_EQ(color::ColorSwatches(app, colorContext)[2], palette[2]); Open(); auto count = [&](StyleRef style) { @@ -164,38 +165,38 @@ namespace if (e.styleRef == style) ++n; return n; }; - EXPECT_EQ(count(app.theme.colorPickerSwatchStyleRef), 3); - EXPECT_EQ(count(app.theme.colorPickerRecentStyleRef), 8) << "at most 8, the field's own color first"; + EXPECT_EQ(count(color::GetStyles(app, colorContext).colorPickerSwatchStyleRef), 3); + EXPECT_EQ(count(color::GetStyles(app, colorContext).colorPickerRecentStyleRef), 8) << "at most 8, the field's own color first"; } // With nothing set, the swatches are the theme's palette of twelve. TEST_F(ColorPickerDialog, TheDefaultSwatchesAreTwelve) { - EXPECT_EQ(app.ColorSwatches().size(), 12u); + EXPECT_EQ(color::ColorSwatches(app, colorContext).size(), 12u); } TEST_F(ColorPickerDialog, CancelRestoresTheColor) { const color4f original = color; Open(); - Click(app.theme.colorPickerSquareStyleRef); + Click(color::GetStyles(app, colorContext).colorPickerSquareStyleRef); EXPECT_NE(color.r, original.r) << "the square changed the color"; Click(app.theme.dialogButtonStyleRef); EXPECT_EQ(color.r, original.r); EXPECT_EQ(color.b, original.b); - EXPECT_EQ(FindByStyle(app.theme.colorPickerSquareStyleRef), ID::Invalid()) << "and closed the dialog"; + EXPECT_EQ(FindByStyle(color::GetStyles(app, colorContext).colorPickerSquareStyleRef), ID::Invalid()) << "and closed the dialog"; } TEST_F(ColorPickerDialog, OkKeepsTheColor) { const color4f original = color; Open(); - Click(app.theme.colorPickerSquareStyleRef); + Click(color::GetStyles(app, colorContext).colorPickerSquareStyleRef); const color4f picked = color; EXPECT_NE(picked.r, original.r); Click(app.theme.dialogPrimaryButtonStyleRef); EXPECT_EQ(color.r, picked.r); - EXPECT_EQ(FindByStyle(app.theme.colorPickerSquareStyleRef), ID::Invalid()) << "and closed the dialog"; + EXPECT_EQ(FindByStyle(color::GetStyles(app, colorContext).colorPickerSquareStyleRef), ID::Invalid()) << "and closed the dialog"; } // Escape in the dialog is Cancel, and the keyboard goes back to the swatch. @@ -203,9 +204,9 @@ namespace { const color4f original = color; Open(); - Click(app.theme.colorPickerSquareStyleRef); + Click(color::GetStyles(app, colorContext).colorPickerSquareStyleRef); ASSERT_NE(color.r, original.r); - app.activeWindow = app.m_colorPickerSub->State().windowID; // the dialog has the keyboard + app.activeWindow = colorContext.picker.windowID; // the dialog has the keyboard Emit(); app.InjectKey(KeyCode::Escape); Emit(); @@ -213,15 +214,15 @@ namespace app.activeWindow = ID::Invalid(); EXPECT_EQ(color.r, original.r); EXPECT_EQ(color.b, original.b); - EXPECT_EQ(FindByStyle(app.theme.colorPickerSquareStyleRef), ID::Invalid()) << "closed"; - EXPECT_EQ(app.guiStateManager.Interaction().GetFocusedID(), FindByStyle(app.theme.colorSwatchStyleRef)); + EXPECT_EQ(FindByStyle(color::GetStyles(app, colorContext).colorPickerSquareStyleRef), ID::Invalid()) << "closed"; + EXPECT_EQ(app.guiStateManager.Interaction().GetFocusedID(), FindByStyle(color::GetStyles(app, colorContext).colorSwatchStyleRef)); } // The square and the strips work from the keyboard: arrows move their point. TEST_F(ColorPickerDialog, TheArrowsMoveTheSquareAndStrips) { Open(); - app.activeWindow = app.m_colorPickerSub->State().windowID; + app.activeWindow = colorContext.picker.windowID; Emit(); auto press = [&](ID id, KeyCode key, KeyModifier mods = KeyModifier::None) { app.guiStateManager.Interaction().SetFocusID(id); @@ -230,7 +231,7 @@ namespace Emit(); Emit(); }; - const ID square = FindByStyle(app.theme.colorPickerSquareStyleRef); + const ID square = FindByStyle(color::GetStyles(app, colorContext).colorPickerSquareStyleRef); ASSERT_NE(square, ID::Invalid()); const color4f before = color; press(square, KeyCode::Down, KeyModifier::Shift); @@ -245,8 +246,8 @@ namespace const auto& storage = app.elementStorage; for (auto it = storage.TopDownDepthScanBegin(); it != storage.TopDownDepthScanEnd(); ++it) for (const Element& e : it->GetChildren(storage)) - if (e.styleRef.layoutStyleIndex == app.theme.colorPickerStripStyleRef.layoutStyleIndex - && e.styleRef.visualBoxStyleIndex == app.theme.colorPickerStripStyleRef.visualBoxStyleIndex) + if (e.styleRef.layoutStyleIndex == color::GetStyles(app, colorContext).colorPickerStripStyleRef.layoutStyleIndex + && e.styleRef.visualBoxStyleIndex == color::GetStyles(app, colorContext).colorPickerStripStyleRef.visualBoxStyleIndex) strips.push_back(e.id); ASSERT_EQ(strips.size(), 2u); press(strips[1], KeyCode::End); @@ -264,14 +265,14 @@ namespace app.InjectKey(KeyCode::Escape); Emit(); Emit(); - EXPECT_NE(FindByStyle(app.theme.colorPickerSquareStyleRef), ID::Invalid()); + EXPECT_NE(FindByStyle(color::GetStyles(app, colorContext).colorPickerSquareStyleRef), ID::Invalid()); } // The header is the dialog's title bar: it drags the window, its close button doesn't. TEST_F(ColorPickerDialog, TheHeaderDragsTheDialog) { Open(); - const ID window = GUIApplicationInternals::ColorPicker(app).State().windowID; + const ID window = colorContext.picker.windowID; const IntRect header = app.GetElementRect(FindByStyle(app.theme.dialogHeaderStyleRef)); EXPECT_EQ(app.TitleBarHitTest(window, { header.x + header.w / 2, header.y + header.h / 2 }), WindowHitArea::Caption); EXPECT_EQ(app.TitleBarHitTest(window, app.CenterOf(FindByStyle(app.theme.dialogCloseStyleRef))), WindowHitArea::Client); @@ -282,7 +283,7 @@ namespace TEST_F(ColorPickerDialog, AThemeReloadRecreatesItsStyles) { Open(); - auto& cp = GUIApplicationInternals::ColorPicker(app).State(); + auto& cp = colorContext.picker; cp.hueStrip = app.theme.accentColor; GUIApplicationInternals::ReloadThemeNextFrame(app); Emit(); @@ -294,7 +295,7 @@ namespace // gradient's stop limit (more stops used to be dropped, cutting it off at cyan). TEST(ColorPickerHueStrip, GoesAllTheWayAround) { - const Gradient g = HueStripGradient(ColorSpace::HSV); + const Gradient g = color::HueStripGradient(ColorSpace::HSV); ASSERT_GE(g.stopCount, 2); const color4f first = g.stops[0].GetColor4f(); const color4f last = g.stops[size_t(g.stopCount - 1)].GetColor4f(); @@ -306,10 +307,10 @@ namespace // A dialog's header names the edited field after its title, unless it only repeats it. TEST(DialogHeader, ShowsTheFieldUnlessItRepeatsTheTitle) { - EXPECT_EQ(DialogContext("Base color", "Color"), "Base color"); - EXPECT_EQ(DialogContext("Color", "Color"), ""); - EXPECT_EQ(DialogContext("color", "Color"), "") << "regardless of case"; - EXPECT_EQ(DialogContext("", "Color"), ""); + EXPECT_EQ(color::DialogContext("Base color", "Color"), "Base color"); + EXPECT_EQ(color::DialogContext("Color", "Color"), ""); + EXPECT_EQ(color::DialogContext("color", "Color"), "") << "regardless of case"; + EXPECT_EQ(color::DialogContext("", "Color"), ""); } // The eyedropper: pressed and released, the color is the screen's under the cursor, opaque. @@ -338,7 +339,7 @@ namespace { const color4f original = color; Open(); - const ID square = FindByStyle(app.theme.colorPickerSquareStyleRef); + const ID square = FindByStyle(color::GetStyles(app, colorContext).colorPickerSquareStyleRef); ASSERT_NE(square, ID::Invalid()); const IntRect r = app.GetElementRect(square); const int2 from{ r.x + r.w / 4, r.y + r.h / 4 }; @@ -356,7 +357,7 @@ namespace EXPECT_NEAR(color.r, original.r, 1e-4f); EXPECT_NEAR(color.g, original.g, 1e-4f); EXPECT_NEAR(color.b, original.b, 1e-4f); - EXPECT_NE(FindByStyle(app.theme.colorPickerSquareStyleRef), ID::Invalid()) << "only the drag was cancelled"; + EXPECT_NE(FindByStyle(color::GetStyles(app, colorContext).colorPickerSquareStyleRef), ID::Invalid()) << "only the drag was cancelled"; app.InjectMouseMove({ r.x + r.w / 2, r.y + r.h / 2 }, MouseButtons::Left); app.InjectMouseUp({ r.x + r.w / 2, r.y + r.h / 2 }); diff --git a/tests/color_field_test.cpp b/tests/color_field_test.cpp index cd9baa54..b0d17d4e 100644 --- a/tests/color_field_test.cpp +++ b/tests/color_field_test.cpp @@ -6,7 +6,7 @@ #include "headless_gui_app.h" #include -#include +#include #include @@ -20,6 +20,7 @@ namespace tachyon { protected: HeadlessGUIApp app; + color::Context colorContext; tachyon::color4f color{ 0.2f, 0.4f, 0.8f, 1.0f }; void SetUp() override { ASSERT_TRUE(app.Initialize()); } @@ -28,7 +29,7 @@ namespace tachyon void EmitField() { app.BeginRootWindow(); - app.ColorField(color, /*allowHDR*/false, + color::ColorField(app, colorContext, color, /*allowHDR*/false, tachyon::LayoutOverride{}.Size(120, 24)); app.EndRootWindow(); } @@ -56,8 +57,8 @@ namespace tachyon return FirstRectWithStyle(style).w > 0 || FirstRectWithStyle(style).h > 0; } - bool PickerOpen() const { return HasStyle(app.theme.colorPickerStyleRef); } - tachyon::IntRect Swatch() const { return FirstRectWithStyle(app.theme.colorSwatchStyleRef); } + bool PickerOpen() { return HasStyle(color::GetStyles(app, colorContext).colorPickerStyleRef); } + tachyon::IntRect Swatch() { return FirstRectWithStyle(color::GetStyles(app, colorContext).colorSwatchStyleRef); } void ClickSwatch() { @@ -103,7 +104,7 @@ namespace tachyon app.Frame([&] { EmitField(); }); app.Frame([&] { EmitField(); }); ASSERT_TRUE(PickerOpen()); - auto& cp = app.m_colorPickerSub->State(); + auto& cp = colorContext.picker; cp.activeSpace = tachyon::ColorSpace::HSL; app.Frame([&] { EmitField(); }); @@ -117,9 +118,9 @@ namespace tachyon app.Frame([&] { EmitField(); }); app.mouseWindow = tachyon::ID::Invalid(); }; - drag(FirstRectWithStyle(app.theme.colorPickerStripStyleRef), 0.5f, 1.0f / 3.0f); // green + drag(FirstRectWithStyle(color::GetStyles(app, colorContext).colorPickerStripStyleRef), 0.5f, 1.0f / 3.0f); // green EXPECT_NEAR(cp.spaceHue, 1.0f / 3.0f, 0.02f) << "kept though the color is still grey"; - drag(FirstRectWithStyle(app.theme.colorPickerSquareStyleRef), 0.9f, 0.5f); + drag(FirstRectWithStyle(color::GetStyles(app, colorContext).colorPickerSquareStyleRef), 0.9f, 0.5f); EXPECT_GT(cp.s, 0.3f) << "the square gave it color"; EXPECT_NEAR(cp.h, 1.0f / 3.0f, 0.03f) << "in the hue the strip set"; } @@ -177,7 +178,7 @@ namespace tachyon color = tachyon::color4f{ 2.0f, 1.0f, 0.5f, 1.0f }; auto emitHdr = [&] { app.BeginRootWindow(); - app.ColorField(color, /*allowHDR*/true, tachyon::LayoutOverride{}.Size(120, 24)); + color::ColorField(app, colorContext, color, /*allowHDR*/true, tachyon::LayoutOverride{}.Size(120, 24)); app.EndRootWindow(); }; app.Frame(emitHdr); @@ -197,6 +198,7 @@ namespace tachyon { protected: HeadlessGUIApp app; + color::Context colorContext; tachyon::Gradient a, b; void SetUp() override @@ -212,13 +214,13 @@ namespace tachyon void EmitFields() { app.BeginRootWindow(); - app.GradientField(a, tachyon::LayoutOverride{}.Size(120, 24)); - app.GradientField(b, tachyon::LayoutOverride{}.Size(120, 24)); + color::GradientField(app, colorContext, a, tachyon::LayoutOverride{}.Size(120, 24)); + color::GradientField(app, colorContext, b, tachyon::LayoutOverride{}.Size(120, 24)); app.EndRootWindow(); } // Swatch rects in emission order. - std::vector Swatches() const + std::vector Swatches() { std::vector out; for (uint32_t d = 0; d < app.elementStorage.NumberOfDepthLevels(); d++) @@ -226,7 +228,7 @@ namespace tachyon { tachyon::ElementRef ref{ d, i }; if (!app.elementStorage.IsValidRef(ref)) continue; - if (app.elementStorage.GetElementUnsafe(ref).styleRef != app.theme.gradientSwatchStyleRef) continue; + if (app.elementStorage.GetElementUnsafe(ref).styleRef != color::GetStyles(app, colorContext).gradientSwatchStyleRef) continue; if (const auto* rp = app.elementStorage.GetElementRectPtr(ref)) out.push_back(rp->rect); } return out; @@ -258,6 +260,7 @@ namespace tachyon { protected: HeadlessGUIApp app; + color::Context colorContext; tachyon::color4f a{ 1.0f, 0.0f, 0.0f, 1.0f }; tachyon::color4f b{ 0.0f, 0.0f, 1.0f, 1.0f }; tachyon::color4b bytes{ 200, 40, 10, 255 }; @@ -268,9 +271,9 @@ namespace tachyon void EmitFields() { app.BeginRootWindow(); - app.ColorField(a, /*allowHDR*/false, tachyon::LayoutOverride{}.Size(120, 24)); - app.ColorField(b, /*allowHDR*/false, tachyon::LayoutOverride{}.Size(120, 24)); - app.ColorField(bytes, tachyon::LayoutOverride{}.Size(120, 24)); + color::ColorField(app, colorContext, a, /*allowHDR*/false, tachyon::LayoutOverride{}.Size(120, 24)); + color::ColorField(app, colorContext, b, /*allowHDR*/false, tachyon::LayoutOverride{}.Size(120, 24)); + color::ColorField(app, colorContext, bytes, tachyon::LayoutOverride{}.Size(120, 24)); app.EndRootWindow(); } @@ -290,7 +293,7 @@ namespace tachyon void ClickSwatch(size_t index) { - const auto swatches = RectsWithStyle(app.theme.colorSwatchStyleRef); + const auto swatches = RectsWithStyle(color::GetStyles(app, colorContext).colorSwatchStyleRef); ASSERT_EQ(swatches.size(), 3u); const auto& s = swatches[index]; const tachyon::int2 c{ s.x + s.w / 2, s.y + s.h / 2 }; @@ -308,7 +311,7 @@ namespace tachyon app.Frame([&] { EmitFields(); }); ClickSwatch(0); - EXPECT_EQ(RectsWithStyle(app.theme.colorPickerStyleRef).size(), 1u) << "exactly one picker popup"; + EXPECT_EQ(RectsWithStyle(color::GetStyles(app, colorContext).colorPickerStyleRef).size(), 1u) << "exactly one picker popup"; EXPECT_TRUE(b == bBefore) << "the second field was overwritten by the first field's picker"; EXPECT_TRUE(a == aBefore) << "opening the picker must not change the edited color"; } @@ -321,7 +324,7 @@ namespace tachyon app.Frame([&] { EmitFields(); }); ClickSwatch(2); - EXPECT_EQ(RectsWithStyle(app.theme.colorPickerStyleRef).size(), 1u); + EXPECT_EQ(RectsWithStyle(color::GetStyles(app, colorContext).colorPickerStyleRef).size(), 1u); EXPECT_EQ(bytes.r, before.r); EXPECT_EQ(bytes.g, before.g); EXPECT_EQ(bytes.b, before.b); 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_grid_view_test.cpp b/tests/controls_grid_view_test.cpp index f891225f..b7cf5396 100644 --- a/tests/controls_grid_view_test.cpp +++ b/tests/controls_grid_view_test.cpp @@ -9,6 +9,7 @@ #include #include #include +#include namespace tachyon { @@ -20,6 +21,7 @@ namespace tachyon { protected: HeadlessGUIApp app; + views::Context viewsContext; ID gridID{}; void SetUp() override { @@ -42,16 +44,16 @@ namespace tachyon } app.Frame([&] { app.BeginRootWindow(); - if (app.BeginGridView(gridID, &selectedIndex, - app.theme.gridViewStyleRef, multi, + if (views::BeginGridView(app, viewsContext, gridID, &selectedIndex, + views::GetStyles(app, viewsContext).gridViewStyleRef, multi, /*dragDrop*/ nullptr, LayoutOverride{}.Size(400, 300))) { for (int i = 0; i < n; ++i) - app.GridViewItem(ids[i], "item", + views::GridViewItem(app, viewsContext, ids[i], "item", ElementState::None, nullptr, StyleRef{}, LayoutOverride{}.Size(80, 80)); - app.EndGridView(); + views::EndGridView(app, viewsContext); } app.EndRootWindow(); }); @@ -86,11 +88,11 @@ namespace tachyon }; auto draw = [&] { app.BeginRootWindow(); - if (app.BeginGridView(gridID, &sel, app.theme.gridViewStyleRef, nullptr, &dnd, LayoutOverride{}.Size(400, 300))) + if (views::BeginGridView(app, viewsContext, gridID, &sel, views::GetStyles(app, viewsContext).gridViewStyleRef, nullptr, &dnd, LayoutOverride{}.Size(400, 300))) { for (const ID id : ids) - app.GridViewItem(id, "item", ElementState::None, nullptr, StyleRef{}, LayoutOverride{}.Size(80, 80)); - app.EndGridView(); + views::GridViewItem(app, viewsContext, id, "item", ElementState::None, nullptr, StyleRef{}, LayoutOverride{}.Size(80, 80)); + views::EndGridView(app, viewsContext); } app.EndRootWindow(); }; @@ -155,11 +157,11 @@ namespace tachyon dnd.onDrop = [](uintptr_t, ID) {}; auto draw = [&] { app.BeginRootWindow(); - if (app.BeginGridView(gridID, &sel, app.theme.gridViewStyleRef, nullptr, &dnd, LayoutOverride{}.Size(400, 300))) + if (views::BeginGridView(app, viewsContext, gridID, &sel, views::GetStyles(app, viewsContext).gridViewStyleRef, nullptr, &dnd, LayoutOverride{}.Size(400, 300))) { for (const ID id : ids) - app.GridViewItem(id, "item", ElementState::None, nullptr, StyleRef{}, LayoutOverride{}.Size(80, 80)); - app.EndGridView(); + views::GridViewItem(app, viewsContext, id, "item", ElementState::None, nullptr, StyleRef{}, LayoutOverride{}.Size(80, 80)); + views::EndGridView(app, viewsContext); } app.EndRootWindow(); }; @@ -328,14 +330,14 @@ namespace tachyon { app.Frame([&] { app.BeginRootWindow(); - if (app.BeginGridView(gridID, nullptr, app.theme.gridViewStyleRef, &multi, + if (views::BeginGridView(app, viewsContext, gridID, nullptr, views::GetStyles(app, viewsContext).gridViewStyleRef, &multi, /*dragDrop*/ nullptr, LayoutOverride{}.Size(400, 300))) { for (int i = 0; i < 4; ++i) - app.GridViewItem(ids[i], names[i], + views::GridViewItem(app, viewsContext, ids[i], names[i], ElementState::None, &names[i], StyleRef{}, LayoutOverride{}.Size(80, 80)); - app.EndGridView(); + views::EndGridView(app, viewsContext); } app.EndRootWindow(); }); @@ -351,8 +353,8 @@ namespace tachyon ASSERT_EQ(multi.lastClickedID, ids[1]); app.InjectKey(KeyCode::F2); EmitFrame(); - ASSERT_TRUE(app.m_renameSub->isActive); - ASSERT_EQ(app.m_renameSub->targetID, ids[1]); + ASSERT_TRUE(viewsContext.rename.isActive); + ASSERT_EQ(viewsContext.rename.targetID, ids[1]); EmitFrame(); // editor emitted, takes focus ASSERT_EQ(app.guiStateManager.Interaction().GetFocusedID(), ids[1]); } @@ -364,17 +366,17 @@ namespace tachyon app.InjectText("x"); EmitFrame(); - EXPECT_TRUE(app.m_renameSub->isActive) + EXPECT_TRUE(viewsContext.rename.isActive) << "typing must not close the rename editor"; EXPECT_EQ(names[1], "beta") << "no commit yet — the name is unchanged"; app.InjectText("y"); EmitFrame(); - EXPECT_TRUE(app.m_renameSub->isActive); + EXPECT_TRUE(viewsContext.rename.isActive); app.InjectKey(KeyCode::Return); EmitFrame(); - EXPECT_FALSE(app.m_renameSub->isActive) << "Enter commits and ends the rename"; + EXPECT_FALSE(viewsContext.rename.isActive) << "Enter commits and ends the rename"; EXPECT_EQ(names[1], "betaxy"); } @@ -388,20 +390,20 @@ namespace tachyon auto emitBoth = [&] { app.Frame([&] { app.BeginRootWindow(); - if (app.BeginGridView(gridID, nullptr, app.theme.gridViewStyleRef, &multi, + if (views::BeginGridView(app, viewsContext, gridID, nullptr, views::GetStyles(app, viewsContext).gridViewStyleRef, &multi, /*dragDrop*/ nullptr, LayoutOverride{}.Size(400, 300))) { for (int i = 0; i < 4; ++i) - app.GridViewItem(ids[i], names[i], + views::GridViewItem(app, viewsContext, ids[i], names[i], ElementState::None, &names[i], StyleRef{}, LayoutOverride{}.Size(80, 80)); - app.EndGridView(); + views::EndGridView(app, viewsContext); } - if (app.BeginGridView(otherGrid, &otherSel, nullptr, nullptr, LayoutOverride{}.Size(400, 100))) + if (views::BeginGridView(app, viewsContext, otherGrid, &otherSel, nullptr, nullptr, LayoutOverride{}.Size(400, 100))) { - app.GridViewItem(otherItem, "other", + views::GridViewItem(app, viewsContext, otherItem, "other", ElementState::None, nullptr, StyleRef{}, LayoutOverride{}.Size(80, 80)); - app.EndGridView(); + views::EndGridView(app, viewsContext); } app.EndRootWindow(); }); @@ -413,8 +415,8 @@ namespace tachyon ASSERT_EQ(multi.lastClickedID, ids[1]); app.InjectKey(KeyCode::F2); emitBoth(); - EXPECT_TRUE(app.m_renameSub->isActive); - EXPECT_EQ(app.m_renameSub->targetID, ids[1]); + EXPECT_TRUE(viewsContext.rename.isActive); + EXPECT_EQ(viewsContext.rename.targetID, ids[1]); } TEST_F(GridViewRenameTest, EscapeCancelsWithoutCommit) @@ -423,11 +425,11 @@ namespace tachyon app.InjectText("x"); EmitFrame(); - ASSERT_TRUE(app.m_renameSub->isActive); + ASSERT_TRUE(viewsContext.rename.isActive); app.InjectKey(KeyCode::Escape); EmitFrame(); - EXPECT_FALSE(app.m_renameSub->isActive); + EXPECT_FALSE(viewsContext.rename.isActive); EXPECT_EQ(names[1], "beta") << "Escape must discard the edit"; } @@ -442,7 +444,8 @@ namespace tachyon { protected: HeadlessGUIApp app; - tachyon::GridViewVirtualState vstate{}; + views::Context viewsContext; + tachyon::views::GridViewVirtualState vstate{}; int paneW = 600; std::vector cellWidths; // the width each item was given, last frame @@ -481,12 +484,12 @@ namespace tachyon app.BeginVertical(app.idManager.AllocateDynamicID("gridPane"), app.theme.flexFillColStyleRef, LayoutOverride::Auto().FlexGrow(1).MinHeight(0)); - app.VirtualGridView(app.idManager.AllocateDynamicID("grid"), vstate, + views::VirtualGridView(app, viewsContext, app.idManager.AllocateDynamicID("grid"), vstate, /*itemCount*/5, tachyon::int2{ 80, 80 }, [&](int, tachyon::ID itemID) { const int w = std::max(80, int(vstate.cellStretchedW)); cellWidths.push_back(w); - app.GridViewItem(itemID, "file_with_a_long_name.txt", ElementState::None, + views::GridViewItem(app, viewsContext, itemID, "file_with_a_long_name.txt", ElementState::None, nullptr, StyleRef{}, LayoutOverride{}.Size(CssPx(w), 80)); }, @@ -542,12 +545,12 @@ namespace tachyon app.BeginRootWindow(); app.BeginArea(app.idManager.AllocateDynamicID("pane"), app.theme.emptyVertStyleRef, LayoutOverride{}.Size(401, 400)); - if (app.BeginGridView(gridID, &selected, nullptr, nullptr, LayoutOverride{}.FlexGrow(1))) + if (views::BeginGridView(app, viewsContext, gridID, &selected, nullptr, nullptr, LayoutOverride{}.FlexGrow(1))) { for (auto& id : items) - app.GridViewItem(id, "item", ElementState::None, nullptr, + views::GridViewItem(app, viewsContext, id, "item", ElementState::None, nullptr, StyleRef{}, LayoutOverride{}.Size(100, 40)); - app.EndGridView(); + views::EndGridView(app, viewsContext); } app.EndArea(); app.EndRootWindow(); @@ -594,10 +597,10 @@ namespace tachyon app.BeginRootWindow(); app.BeginArea(app.idManager.AllocateDynamicID("gridPane"), app.theme.emptyVertStyleRef, LayoutOverride{}.Size(420, 220)); - app.VirtualGridView(gridID, vstate, int(names.size()), tachyon::int2{ 100, 50 }, + views::VirtualGridView(app, viewsContext, gridID, vstate, int(names.size()), tachyon::int2{ 100, 50 }, [&](int idx, tachyon::ID itemID) { itemIDs[size_t(idx)] = itemID; - app.GridViewItem(itemID, names[size_t(idx)], ElementState::None, + views::GridViewItem(app, viewsContext, itemID, names[size_t(idx)], ElementState::None, &names[size_t(idx)], StyleRef{}, LayoutOverride{}.Size(100, 50)); }, nullptr, &multi, dragDrop, {}, {}, LayoutOverride{}.FlexGrow(1).MinHeight(0)); @@ -637,8 +640,8 @@ namespace tachyon app.ClickAt(app.CenterOf(itemIDs[1])); GridFrame(); GridFrame(); - EXPECT_TRUE(app.m_renameSub->isActive); - EXPECT_TRUE(app.IsRenaming()); + EXPECT_TRUE(viewsContext.rename.isActive); + EXPECT_TRUE(views::IsRenaming(viewsContext)); } // A double-click opens an item (onOpen), and doesn't rename it; a slow second click @@ -656,7 +659,7 @@ namespace tachyon GridFrame(); GridFrame(); EXPECT_EQ(opened, (std::vector{ itemIDs[2] })); - EXPECT_FALSE(app.IsRenaming()); + EXPECT_FALSE(views::IsRenaming(viewsContext)); app.ClickAt(app.CenterOf(itemIDs[2])); // a third: starts over GridFrame(); @@ -668,7 +671,7 @@ namespace tachyon GridFrame(); GridFrame(); EXPECT_TRUE(opened.empty()); - EXPECT_TRUE(app.IsRenaming()); + EXPECT_TRUE(views::IsRenaming(viewsContext)); } // Enter opens the selected item, the last one clicked; nothing with none selected. @@ -728,7 +731,7 @@ namespace tachyon app.InjectMouseUp(at); // dropped on itself GridFrame(); GridFrame(); - EXPECT_FALSE(app.m_renameSub->isActive); + EXPECT_FALSE(viewsContext.rename.isActive); } class VirtualGridKeyboardTest : public GridViewShrinkTest @@ -756,10 +759,10 @@ namespace tachyon app.BeginArea(app.idManager.AllocateDynamicID("gridPane"), app.theme.emptyVertStyleRef, LayoutOverride{}.Size(420, 220)); - app.VirtualGridView(gridID, vstate, kItems, tachyon::int2{ 100, 50 }, + views::VirtualGridView(app, viewsContext, gridID, vstate, kItems, tachyon::int2{ 100, 50 }, [&](int idx, tachyon::ID itemID) { itemIDs[size_t(idx)] = itemID; - app.GridViewItem(itemID, "item", + views::GridViewItem(app, viewsContext, itemID, "item", ElementState::None, nullptr, StyleRef{}, LayoutOverride{}.Size(100, 50)); }, diff --git a/tests/controls_menu_test.cpp b/tests/controls_menu_test.cpp index 45443c8c..8164cdab 100644 --- a/tests/controls_menu_test.cpp +++ b/tests/controls_menu_test.cpp @@ -1163,7 +1163,7 @@ namespace tachyon // Rows show they're hovered: the timeline's and the curve tree's. TEST_F(ControlsMenuTest, TheThemesRowsShowHover) { - for (const char* name : { "timeline-row", "curve-tree-row" }) + for (const char* name : { "curve-tree-row" }) { const StyleRef style = app.theme.GetStyle(name); auto background = [&](ElementState s) { 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/controls_settings_test.cpp b/tests/controls_settings_test.cpp index f0a8dc3a..db9436d6 100644 --- a/tests/controls_settings_test.cpp +++ b/tests/controls_settings_test.cpp @@ -6,6 +6,7 @@ #include "headless_gui_app.h" #include +#include #include #include @@ -16,18 +17,17 @@ namespace tachyon namespace { - // SettingsPanelState is protected on GUIApplication; reach it as an app does. class SettingsApp : public HeadlessGUIApp { public: - using SettingsState = GUIApplication::SettingsPanelState; - using GUIApplication::RenderSettingsPanel; + using SettingsState = views::SettingsPanelState; }; class ControlsSettingsTest : public ::testing::Test { protected: SettingsApp app; + views::Context viewsContext; void SetUp() override { ASSERT_TRUE(app.Initialize()); } void TearDown() override { app.Cleanup(); } @@ -55,7 +55,7 @@ namespace tachyon auto frame = [&] { app.Frame([&] { app.BeginRootWindow(); - app.RenderSettingsPanel(settings); + views::RenderSettingsPanel(app, viewsContext, settings); app.EndRootWindow(); }); }; diff --git a/tests/controls_table_cells_test.cpp b/tests/controls_table_cells_test.cpp index 47b7915c..4f923f30 100644 --- a/tests/controls_table_cells_test.cpp +++ b/tests/controls_table_cells_test.cpp @@ -1,4 +1,4 @@ -// Table-cell paths: Cell(lambda), TreeCell, TableSelectionMode::Cell, +// Table-cell paths: Cell(lambda), TreeCell, views::TableSelectionMode::Cell, // multi-select, scrollbars and column sizers. #include @@ -9,6 +9,7 @@ #include #include #include +#include #include #include @@ -23,9 +24,10 @@ namespace tachyon { protected: HeadlessGUIApp app; + views::Context viewsContext; // Three plain columns, wide enough that a click lands in exactly one. - tachyon::VirtualTableColumn kColumns[3] = { + tachyon::views::VirtualTableColumn kColumns[3] = { { { .header = "A", .initialWidth = 120, .minWidth = 40, .maxWidth = 400 } }, { { .header = "B", .initialWidth = 120, .minWidth = 40, .maxWidth = 400 } }, { { .header = "C", .initialWidth = 120, .minWidth = 40, .maxWidth = 400 } }, @@ -52,22 +54,22 @@ namespace tachyon TEST_F(TableCellsTest, CellLambdaEmitsLabelAsChildAndCellIsHittable) { // The label emitted by Cell(lambda) must lie inside the cell's rect. - tachyon::TableState state{}; + tachyon::views::TableState state{}; const tachyon::ID labelID = app.idManager.CreateStaticID(); auto build = [&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, kColumns, state, + if (views::BeginTable(app, viewsContext, tableID, kColumns, state, LayoutOverride{}.Size(400, 200))) { - app.BeginRow(); - app.Cell("first"); - app.Cell([&] { + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "first"); + views::Cell(app, viewsContext, [&] { app.Label(labelID, "embedded"); }); - app.Cell("third"); - app.EndRow(); - app.EndTable(); + views::Cell(app, viewsContext, "third"); + views::EndRow(app, viewsContext); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }; @@ -91,49 +93,49 @@ namespace tachyon TEST_F(TableCellsTest, TreeCellMetricsComeFromTheStylesheet) { auto layoutOf = [&](tachyon::StyleRef s) { return app.styleManager.GetLayoutStyle(s.layoutStyleIndex); }; - const auto* indent = layoutOf(app.theme.treeTableIndentStyleRef); - const auto* arrow = layoutOf(app.theme.treeTableArrowStyleRef); - const auto* icon = layoutOf(app.theme.treeTableIconStyleRef); - const auto* glyph = layoutOf(app.theme.treeTableArrowGlyphStyleRef); + const auto* indent = layoutOf(views::GetStyles(app, viewsContext).treeTableIndentStyleRef); + const auto* arrow = layoutOf(views::GetStyles(app, viewsContext).treeTableArrowStyleRef); + const auto* icon = layoutOf(views::GetStyles(app, viewsContext).treeTableIconStyleRef); + const auto* glyph = layoutOf(views::GetStyles(app, viewsContext).treeTableArrowGlyphStyleRef); ASSERT_TRUE(indent && arrow && icon && glyph); - EXPECT_EQ(app.theme.treeTableIndent, indent->layoutData.width); - EXPECT_EQ(app.theme.treeTableExpanderWidth, arrow->layoutData.width); - EXPECT_EQ(app.theme.treeTableIconSize, int32_t(icon->iconSize)); - EXPECT_EQ(app.theme.treeTableArrowGlyphSize, int32_t(glyph->iconSize)); - EXPECT_GT(app.theme.treeTableIndent, 0); - EXPECT_GT(app.theme.treeTableExpanderWidth, 0); + EXPECT_EQ(views::GetStyles(app, viewsContext).treeTableIndent, indent->layoutData.width); + EXPECT_EQ(views::GetStyles(app, viewsContext).treeTableExpanderWidth, arrow->layoutData.width); + EXPECT_EQ(views::GetStyles(app, viewsContext).treeTableIconSize, int32_t(icon->iconSize)); + EXPECT_EQ(views::GetStyles(app, viewsContext).treeTableArrowGlyphSize, int32_t(glyph->iconSize)); + EXPECT_GT(views::GetStyles(app, viewsContext).treeTableIndent, 0); + EXPECT_GT(views::GetStyles(app, viewsContext).treeTableExpanderWidth, 0); } // A table built inside a cell of another table must leave the outer table intact: // the cells emitted after it still land in the outer table. TEST_F(TableCellsTest, TableInsideACellDoesNotClobberTheOuterTable) { - tachyon::TableState outer{}, inner{}; + tachyon::views::TableState outer{}, inner{}; const tachyon::ID innerTableID = app.idManager.CreateStaticID(); const tachyon::ID afterID = app.idManager.CreateStaticID(); - tachyon::VirtualTableColumn innerCols[1] = { + tachyon::views::VirtualTableColumn innerCols[1] = { { { .header = "I", .initialWidth = 80, .minWidth = 40, .maxWidth = 200 } }, }; auto build = [&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, kColumns, outer, LayoutOverride{}.Size(400, 200))) + if (views::BeginTable(app, viewsContext, tableID, kColumns, outer, LayoutOverride{}.Size(400, 200))) { - app.BeginRow(); - app.Cell("first"); - app.Cell([&] { - if (app.BeginTable(innerTableID, innerCols, inner, LayoutOverride{}.Size(100, 60))) + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "first"); + views::Cell(app, viewsContext, [&] { + if (views::BeginTable(app, viewsContext, innerTableID, innerCols, inner, LayoutOverride{}.Size(100, 60))) { - app.BeginRow(); - app.Cell("x"); - app.EndRow(); - app.EndTable(); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "x"); + views::EndRow(app, viewsContext); + views::EndTable(app, viewsContext); } }); - app.Cell([&] { app.Label(afterID, "after"); }); - app.EndRow(); - app.EndTable(); + views::Cell(app, viewsContext, [&] { app.Label(afterID, "after"); }); + views::EndRow(app, viewsContext); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }; @@ -150,23 +152,23 @@ namespace tachyon // --------------------------------------------------------------------- TEST_F(TableCellsTest, SizerDoubleClickSnapsColumnToMaxContentWidth) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; // The stub text system measures 8px per char: 30 chars = 240 wide. - tachyon::VirtualTableColumn cols[3] = { + tachyon::views::VirtualTableColumn cols[3] = { { { .header = "A", .initialWidth = 80, .minWidth = 40, .maxWidth = 600, - .sizing = tachyon::ColumnSizing::Resizable } }, + .sizing = tachyon::views::ColumnSizing::Resizable } }, { { .header = "B", .initialWidth = 100, .minWidth = 40, .maxWidth = 400 } }, { { .header = "C", .initialWidth = 100, .minWidth = 40, .maxWidth = 400 } }, }; auto build = [&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, cols, state, LayoutOverride{}.Size(500, 200))) + if (views::BeginTable(app, viewsContext, tableID, cols, state, LayoutOverride{}.Size(500, 200))) { - app.BeginRow(); - app.Cell("very_long_thirty_char_cell_xyz"); - app.Cell("b"); app.Cell("c"); - app.EndRow(); - app.EndTable(); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "very_long_thirty_char_cell_xyz"); + views::Cell(app, viewsContext, "b"); views::Cell(app, viewsContext, "c"); + views::EndRow(app, viewsContext); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }; @@ -201,18 +203,18 @@ namespace tachyon // and left out, not written past the table's columns. TEST_F(TableCellsTest, ExtraCellsAreReportedAndLeftOut) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; GUITest::MisuseReports misuse; auto build = [&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, kColumns, state, LayoutOverride{}.Size(400, 200))) + if (views::BeginTable(app, viewsContext, tableID, kColumns, state, LayoutOverride{}.Size(400, 200))) { - app.Cell("before any row"); - app.BeginRow(); - app.Cell("a"); app.Cell("b"); app.Cell("c"); - app.Cell("one too many"); - app.EndRow(); - app.EndTable(); + views::Cell(app, viewsContext, "before any row"); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "a"); views::Cell(app, viewsContext, "b"); views::Cell(app, viewsContext, "c"); + views::Cell(app, viewsContext, "one too many"); + views::EndRow(app, viewsContext); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }; @@ -228,22 +230,22 @@ namespace tachyon // is gone: the snap must not read it. TEST_F(TableCellsTest, SizerDoubleClickDoesNotReadTheCallersColumnsAfterTheFrame) { - tachyon::TableState state{}; - tachyon::VirtualTableColumn cols[3] = { + tachyon::views::TableState state{}; + tachyon::views::VirtualTableColumn cols[3] = { { { .header = "A", .initialWidth = 80, .minWidth = 40, .maxWidth = 600, - .sizing = tachyon::ColumnSizing::Resizable } }, + .sizing = tachyon::views::ColumnSizing::Resizable } }, { { .header = "B", .initialWidth = 100, .minWidth = 40, .maxWidth = 400 } }, { { .header = "C", .initialWidth = 100, .minWidth = 40, .maxWidth = 400 } }, }; auto build = [&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, cols, state, LayoutOverride{}.Size(500, 200))) + if (views::BeginTable(app, viewsContext, tableID, cols, state, LayoutOverride{}.Size(500, 200))) { - app.BeginRow(); - app.Cell("very_long_thirty_char_cell_xyz"); - app.Cell("b"); app.Cell("c"); - app.EndRow(); - app.EndTable(); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "very_long_thirty_char_cell_xyz"); + views::Cell(app, viewsContext, "b"); views::Cell(app, viewsContext, "c"); + views::EndRow(app, viewsContext); + views::EndTable(app, viewsContext); } app.EndRootWindow(); // Stands in for the array going out of scope: its memory is reused. @@ -267,7 +269,7 @@ namespace tachyon } // --------------------------------------------------------------------- - // TreeCell - depth + isOpen registration on the user TableState + // TreeCell - depth + isOpen registration on the user views::TableState // --------------------------------------------------------------------- // --------------------------------------------------------------------- @@ -286,7 +288,7 @@ namespace tachyon // Rows live in the section grid. The tree cell shares rowID with the row // backdrop; only the tree cell has children, so filter on that. ChildRectSnapshot SnapshotTreeCellByRow(HeadlessGUIApp& app, - const tachyon::TableState& state, + const tachyon::views::TableState& state, tachyon::ID rowID) { ChildRectSnapshot s{}; @@ -318,9 +320,9 @@ namespace tachyon TEST_F(TableCellsTest, TreeCellInnerContentShiftsWithBodyHorizontalScroll) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; // Wide columns so the table overflows X inside the 300px viewport. - tachyon::VirtualTableColumn wideCols[3] = { + tachyon::views::VirtualTableColumn wideCols[3] = { { { .header = "Name", .initialWidth = 240, .minWidth = 80, .maxWidth = 600 } }, { { .header = "Size", .initialWidth = 100, .minWidth = 40, .maxWidth = 400 } }, { { .header = "Type", .initialWidth = 200, .minWidth = 40, .maxWidth = 400 } }, @@ -329,14 +331,14 @@ namespace tachyon auto build = [&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, wideCols, state, + if (views::BeginTable(app, viewsContext, tableID, wideCols, state, LayoutOverride{}.Size(300, 200))) { - app.BeginRow(); - app.TreeCell("a-folder", /*depth*/ 1, &branchOpen, IconID::Invalid); - app.Cell("12 KB"); app.Cell("Folder"); - app.EndRow(); - app.EndTable(); + views::BeginRow(app, viewsContext); + views::TreeCell(app, viewsContext, "a-folder", /*depth*/ 1, &branchOpen, IconID::Invalid); + views::Cell(app, viewsContext, "12 KB"); views::Cell(app, viewsContext, "Folder"); + views::EndRow(app, viewsContext); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }; @@ -384,8 +386,8 @@ namespace tachyon TEST_F(TableCellsTest, TreeCellInnerContentShiftsWithBodyVerticalScroll) { // Many rows so the body overflows Y inside the 100px viewport. - tachyon::TableState state{}; - tachyon::VirtualTableColumn cols[3] = { + tachyon::views::TableState state{}; + tachyon::views::VirtualTableColumn cols[3] = { { { .header = "Name", .initialWidth = 120, .minWidth = 40, .maxWidth = 400 } }, { { .header = "Size", .initialWidth = 100, .minWidth = 40, .maxWidth = 400 } }, { { .header = "Type", .initialWidth = 100, .minWidth = 40, .maxWidth = 400 } }, @@ -394,19 +396,19 @@ namespace tachyon auto build = [&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, cols, state, + if (views::BeginTable(app, viewsContext, tableID, cols, state, LayoutOverride{}.Size(400, 100))) { for (int r = 0; r < 30; ++r) { char rowName[32]; std::snprintf(rowName, sizeof(rowName), "vscroll_row_%d", r); - app.BeginRow(); - app.TreeCell(rowName, /*depth*/ 1, &branchOpen, IconID::Invalid); - app.Cell("12 KB"); app.Cell("Folder"); - app.EndRow(); + views::BeginRow(app, viewsContext); + views::TreeCell(app, viewsContext, rowName, /*depth*/ 1, &branchOpen, IconID::Invalid); + views::Cell(app, viewsContext, "12 KB"); views::Cell(app, viewsContext, "Folder"); + views::EndRow(app, viewsContext); } - app.EndTable(); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }; @@ -454,23 +456,23 @@ namespace tachyon TEST_F(TableCellsTest, TreeCellRegistersDepthAndIsOpenByRow) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; bool branchOpen = true; auto build = [&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, kColumns, state, + if (views::BeginTable(app, viewsContext, tableID, kColumns, state, LayoutOverride{}.Size(400, 200))) { - app.BeginRow(); - app.TreeCell("branch", /*depth*/ 1, &branchOpen); - app.Cell("b"); app.Cell("c"); - app.EndRow(); - app.BeginRow(); - app.TreeCell("leaf", /*depth*/ 2, /*isOpen*/ nullptr); - app.Cell("b"); app.Cell("c"); - app.EndRow(); - app.EndTable(); + views::BeginRow(app, viewsContext); + views::TreeCell(app, viewsContext, "branch", /*depth*/ 1, &branchOpen); + views::Cell(app, viewsContext, "b"); views::Cell(app, viewsContext, "c"); + views::EndRow(app, viewsContext); + views::BeginRow(app, viewsContext); + views::TreeCell(app, viewsContext, "leaf", /*depth*/ 2, /*isOpen*/ nullptr); + views::Cell(app, viewsContext, "b"); views::Cell(app, viewsContext, "c"); + views::EndRow(app, viewsContext); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }; @@ -501,20 +503,20 @@ namespace tachyon TEST_F(TableCellsTest, TreeCellDoubleClickTogglesIsOpenInRowMode) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; // Row mode is the default; keep selectionMode untouched. bool branchOpen = false; auto build = [&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, kColumns, state, + if (views::BeginTable(app, viewsContext, tableID, kColumns, state, LayoutOverride{}.Size(400, 200))) { - app.BeginRow(); - app.TreeCell("branch", /*depth*/ 1, &branchOpen); - app.Cell("b"); app.Cell("c"); - app.EndRow(); - app.EndTable(); + views::BeginRow(app, viewsContext); + views::TreeCell(app, viewsContext, "branch", /*depth*/ 1, &branchOpen); + views::Cell(app, viewsContext, "b"); views::Cell(app, viewsContext, "c"); + views::EndRow(app, viewsContext); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }; @@ -546,18 +548,18 @@ namespace tachyon TEST_F(TableCellsTest, CellModeClickingCellSelectsRowAndColumn) { - tachyon::TableState state{}; - state.selectionMode = tachyon::TableSelectionMode::Cell; + tachyon::views::TableState state{}; + state.selectionMode = tachyon::views::TableSelectionMode::Cell; auto build = [&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, kColumns, state, + if (views::BeginTable(app, viewsContext, tableID, kColumns, state, LayoutOverride{}.Size(400, 200))) { - app.BeginRow(); - app.Cell("col0"); app.Cell("col1"); app.Cell("col2"); - app.EndRow(); - app.EndTable(); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "col0"); views::Cell(app, viewsContext, "col1"); views::Cell(app, viewsContext, "col2"); + views::EndRow(app, viewsContext); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }; @@ -585,22 +587,22 @@ namespace tachyon TEST_F(TableCellsTest, MultiSelectCtrlClickTogglesIndividualRows) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; tachyon::MultiSelectState ms{}; state.multiSelect = &ms; auto build = [&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, kColumns, state, + if (views::BeginTable(app, viewsContext, tableID, kColumns, state, LayoutOverride{}.Size(400, 400))) { - app.BeginRow(); - app.Cell("a0"); app.Cell("b0"); app.Cell("c0"); app.EndRow(); - app.BeginRow(); - app.Cell("a1"); app.Cell("b1"); app.Cell("c1"); app.EndRow(); - app.BeginRow(); - app.Cell("a2"); app.Cell("b2"); app.Cell("c2"); app.EndRow(); - app.EndTable(); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "a0"); views::Cell(app, viewsContext, "b0"); views::Cell(app, viewsContext, "c0"); views::EndRow(app, viewsContext); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "a1"); views::Cell(app, viewsContext, "b1"); views::Cell(app, viewsContext, "c1"); views::EndRow(app, viewsContext); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "a2"); views::Cell(app, viewsContext, "b2"); views::Cell(app, viewsContext, "c2"); views::EndRow(app, viewsContext); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }; @@ -647,24 +649,24 @@ namespace tachyon TEST_F(TableCellsTest, MultiSelectShiftClickSelectsRange) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; tachyon::MultiSelectState ms{}; state.multiSelect = &ms; auto build = [&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, kColumns, state, + if (views::BeginTable(app, viewsContext, tableID, kColumns, state, LayoutOverride{}.Size(400, 400))) { - app.BeginRow(); - app.Cell("0a"); app.Cell("0b"); app.Cell("0c"); app.EndRow(); - app.BeginRow(); - app.Cell("1a"); app.Cell("1b"); app.Cell("1c"); app.EndRow(); - app.BeginRow(); - app.Cell("2a"); app.Cell("2b"); app.Cell("2c"); app.EndRow(); - app.BeginRow(); - app.Cell("3a"); app.Cell("3b"); app.Cell("3c"); app.EndRow(); - app.EndTable(); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "0a"); views::Cell(app, viewsContext, "0b"); views::Cell(app, viewsContext, "0c"); views::EndRow(app, viewsContext); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "1a"); views::Cell(app, viewsContext, "1b"); views::Cell(app, viewsContext, "1c"); views::EndRow(app, viewsContext); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "2a"); views::Cell(app, viewsContext, "2b"); views::Cell(app, viewsContext, "2c"); views::EndRow(app, viewsContext); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "3a"); views::Cell(app, viewsContext, "3b"); views::Cell(app, viewsContext, "3c"); views::EndRow(app, viewsContext); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }; @@ -703,22 +705,22 @@ namespace tachyon // the row last clicked (the end of the range), not from the anchor. TEST_F(TableCellsTest, ArrowAfterShiftClickMovesFromRangeEnd) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; tachyon::MultiSelectState ms{}; state.multiSelect = &ms; auto build = [&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, kColumns, state, + if (views::BeginTable(app, viewsContext, tableID, kColumns, state, LayoutOverride{}.Size(400, 400))) { for (int r = 0; r < 6; ++r) { - app.BeginRow(); - app.Cell("a"); app.Cell("b"); app.Cell("c"); - app.EndRow(); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "a"); views::Cell(app, viewsContext, "b"); views::Cell(app, viewsContext, "c"); + views::EndRow(app, viewsContext); } - app.EndTable(); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }; @@ -764,8 +766,8 @@ namespace tachyon // --------------------------------------------------------------------- TEST_F(TableCellsTest, StandardTableHeaderScrollsWithBodyX) { - tachyon::TableState state{}; - tachyon::VirtualTableColumn wideCols[3] = { + tachyon::views::TableState state{}; + tachyon::views::VirtualTableColumn wideCols[3] = { { { .header = "Name", .initialWidth = 240, .minWidth = 80, .maxWidth = 600 } }, { { .header = "Size", .initialWidth = 100, .minWidth = 40, .maxWidth = 400 } }, { { .header = "Type", .initialWidth = 200, .minWidth = 40, .maxWidth = 400 } }, @@ -773,12 +775,12 @@ namespace tachyon auto build = [&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, wideCols, state, + if (views::BeginTable(app, viewsContext, tableID, wideCols, state, LayoutOverride{}.Size(300, 200))) { - app.BeginRow(); - app.Cell("a"); app.Cell("b"); app.Cell("c"); app.EndRow(); - app.EndTable(); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "a"); views::Cell(app, viewsContext, "b"); views::Cell(app, viewsContext, "c"); views::EndRow(app, viewsContext); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }; @@ -813,8 +815,8 @@ namespace tachyon // --------------------------------------------------------------------- TEST_F(TableCellsTest, StandardTableHScrollbarDragWritesXOffset) { - tachyon::TableState state{}; - tachyon::VirtualTableColumn wideCols[3] = { + tachyon::views::TableState state{}; + tachyon::views::VirtualTableColumn wideCols[3] = { { { .header = "Name", .initialWidth = 240, .minWidth = 80, .maxWidth = 600 } }, { { .header = "Size", .initialWidth = 100, .minWidth = 40, .maxWidth = 400 } }, { { .header = "Type", .initialWidth = 200, .minWidth = 40, .maxWidth = 400 } }, @@ -827,12 +829,12 @@ namespace tachyon state.internal.lastViewportH = 200; state.internal.anyHorzOverflow = state.internal.anyVertOverflow = true; app.BeginRootWindow(); - if (app.BeginTable(tableID, wideCols, state, + if (views::BeginTable(app, viewsContext, tableID, wideCols, state, LayoutOverride{}.Size(300, 200))) { - app.BeginRow(); - app.Cell("a"); app.Cell("b"); app.Cell("c"); app.EndRow(); - app.EndTable(); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "a"); views::Cell(app, viewsContext, "b"); views::Cell(app, viewsContext, "c"); views::EndRow(app, viewsContext); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }; @@ -864,21 +866,21 @@ namespace tachyon // --------------------------------------------------------------------- TEST_F(TableCellsTest, StandardTableVScrollbarDragWritesYOffset) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; auto build = [&] { state.internal.lastViewportW = 400; state.internal.lastViewportH = 100; state.internal.anyHorzOverflow = state.internal.anyVertOverflow = true; app.BeginRootWindow(); - if (app.BeginTable(tableID, kColumns, state, + if (views::BeginTable(app, viewsContext, tableID, kColumns, state, LayoutOverride{}.Size(400, 100))) { for (int r = 0; r < 30; ++r) { - app.BeginRow(); - app.Cell("a"); app.Cell("b"); app.Cell("c"); app.EndRow(); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "a"); views::Cell(app, viewsContext, "b"); views::Cell(app, viewsContext, "c"); views::EndRow(app, viewsContext); } - app.EndTable(); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }; @@ -911,19 +913,19 @@ namespace tachyon // --------------------------------------------------------------------- TEST_F(TableCellsTest, StandardTableBothScrollbarsEmitCornerCap) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; auto build = [&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, kColumns, state, + if (views::BeginTable(app, viewsContext, tableID, kColumns, state, LayoutOverride{}.Size(200, 100))) { for (int r = 0; r < 5; ++r) { - app.BeginRow(); - app.Cell("a"); app.Cell("b"); app.Cell("c"); app.EndRow(); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "a"); views::Cell(app, viewsContext, "b"); views::Cell(app, viewsContext, "c"); views::EndRow(app, viewsContext); } - app.EndTable(); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }; @@ -959,25 +961,25 @@ namespace tachyon // --------------------------------------------------------------------- TEST_F(TableCellsTest, SizerXAlignsWithHeaderCellRightEdgeStandard) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; // The last column always stretches in standard mode, so only sizers before // it can be pinned: with 3 columns, just sizer 0. - tachyon::VirtualTableColumn cols[3] = { + tachyon::views::VirtualTableColumn cols[3] = { { { .header = "A", .initialWidth = 100, .minWidth = 40, - .sizing = tachyon::ColumnSizing::Resizable } }, + .sizing = tachyon::views::ColumnSizing::Resizable } }, { { .header = "B", .initialWidth = 100, .minWidth = 40, - .sizing = tachyon::ColumnSizing::Resizable } }, + .sizing = tachyon::views::ColumnSizing::Resizable } }, { { .header = "C", .initialWidth = 100, .minWidth = 40 } }, }; auto build = [&] { app.BeginRootWindow(); // Exactly the columns' total width, so the stretch on col 2 absorbs nothing. - if (app.BeginTable(tableID, cols, state, LayoutOverride{}.Size(300, 200))) + if (views::BeginTable(app, viewsContext, tableID, cols, state, LayoutOverride{}.Size(300, 200))) { - app.BeginRow(); - app.Cell("a"); app.Cell("b"); app.Cell("c"); - app.EndRow(); - app.EndTable(); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "a"); views::Cell(app, viewsContext, "b"); views::Cell(app, viewsContext, "c"); + views::EndRow(app, viewsContext); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }; @@ -997,21 +999,21 @@ namespace tachyon // The sizer is anchored to a header cell and must track its post-scroll rect. TEST_F(TableCellsTest, SizerXFollowsHorizontalScroll) { - tachyon::TableState state{}; - tachyon::VirtualTableColumn wideCols[3] = { + tachyon::views::TableState state{}; + tachyon::views::VirtualTableColumn wideCols[3] = { { { .header = "Name", .initialWidth = 240, .minWidth = 80, .maxWidth = 600, - .sizing = tachyon::ColumnSizing::Resizable } }, + .sizing = tachyon::views::ColumnSizing::Resizable } }, { { .header = "Size", .initialWidth = 100, .minWidth = 40, .maxWidth = 400, - .sizing = tachyon::ColumnSizing::Resizable } }, + .sizing = tachyon::views::ColumnSizing::Resizable } }, { { .header = "Type", .initialWidth = 200, .minWidth = 40, .maxWidth = 400 } }, }; auto build = [&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, wideCols, state, LayoutOverride{}.Size(300, 200))) + if (views::BeginTable(app, viewsContext, tableID, wideCols, state, LayoutOverride{}.Size(300, 200))) { - app.BeginRow(); - app.Cell("a"); app.Cell("b"); app.Cell("c"); app.EndRow(); - app.EndTable(); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "a"); views::Cell(app, viewsContext, "b"); views::Cell(app, viewsContext, "c"); views::EndRow(app, viewsContext); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }; @@ -1034,21 +1036,21 @@ namespace tachyon // Same invariant with a Stretch column left of the boundary. TEST_F(TableCellsTest, SizerXAlignsAfterStretchColumn) { - tachyon::TableState state{}; - tachyon::VirtualTableColumn cols[3] = { + tachyon::views::TableState state{}; + tachyon::views::VirtualTableColumn cols[3] = { { { .header = "A", .initialWidth = 100, .minWidth = 40, - .sizing = tachyon::ColumnSizing::Stretch } }, + .sizing = tachyon::views::ColumnSizing::Stretch } }, { { .header = "B", .initialWidth = 100, .minWidth = 40 } }, { { .header = "C", .initialWidth = 100, .minWidth = 40 } }, }; auto build = [&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, cols, state, LayoutOverride{}.Size(500, 200))) + if (views::BeginTable(app, viewsContext, tableID, cols, state, LayoutOverride{}.Size(500, 200))) { - app.BeginRow(); - app.Cell("a"); app.Cell("b"); app.Cell("c"); - app.EndRow(); - app.EndTable(); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "a"); views::Cell(app, viewsContext, "b"); views::Cell(app, viewsContext, "c"); + views::EndRow(app, viewsContext); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }; @@ -1063,19 +1065,19 @@ namespace tachyon // --------------------------------------------------------------------- // Standard-mode body section has a post-layout callback attached: it - // samples ElementInnerRect into TableState::internal.lastViewportH/W and the + // samples ElementInnerRect into views::TableState::internal.lastViewportH/W and the // overflow flags, which VirtualTable consumes on the next frame. // --------------------------------------------------------------------- TEST_F(TableCellsTest, StandardBodyHasViewportSamplingPostLayout) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; auto build = [&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, kColumns, state, LayoutOverride{}.Size(400, 200))) + if (views::BeginTable(app, viewsContext, tableID, kColumns, state, LayoutOverride{}.Size(400, 200))) { - app.BeginRow(); - app.Cell("a"); app.Cell("b"); app.Cell("c"); app.EndRow(); - app.EndTable(); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "a"); views::Cell(app, viewsContext, "b"); views::Cell(app, viewsContext, "c"); views::EndRow(app, viewsContext); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }; diff --git a/tests/controls_table_frozen_test.cpp b/tests/controls_table_frozen_test.cpp index a4f29174..fd6e9ff8 100644 --- a/tests/controls_table_frozen_test.cpp +++ b/tests/controls_table_frozen_test.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include @@ -24,12 +25,13 @@ namespace tachyon { protected: HeadlessGUIApp app; + views::Context viewsContext; // Five columns split into three sections via sectionId: // [#] | [Name] [Hex] [Multiple] | [Status] // sec 0 sec 1 sec 2 // The middle section (~308 wide) overflows its 240px area. - tachyon::VirtualTableColumn kColumns[5] = { + tachyon::views::VirtualTableColumn kColumns[5] = { { .column = { .header = "#", .initialWidth = 60, .minWidth = 30, .maxWidth = 200, .locked = true }, .sectionId = 0 }, { .column = { .header = "Name", .initialWidth = 100, .minWidth = 30, .maxWidth = 400 }, .sectionId = 1 }, { .column = { .header = "Hex", .initialWidth = 100, .minWidth = 30, .maxWidth = 400 }, .sectionId = 1 }, @@ -53,25 +55,25 @@ namespace tachyon // Render N rows of dummy data inside a container small enough that // both axes overflow. Width 400 is ~100 short of the columns' // intrinsic 480; height 200 with ~30 rows x 24px overflows Y. - void EmitFrozen(tachyon::TableState& state, int rowCount = 30, + void EmitFrozen(tachyon::views::TableState& state, int rowCount = 30, int width = 400, int height = 200) { app.BeginRootWindow(); - if (app.BeginTable(tableID, kColumns, state, + if (views::BeginTable(app, viewsContext, tableID, kColumns, state, LayoutOverride{}.Size(CssPx(width), CssPx(height)))) { for (int r = 0; r < rowCount; r++) { - app.BeginRow(); + views::BeginRow(app, viewsContext); char buf[24]; - std::snprintf(buf, sizeof(buf), "%d", r); app.Cell(buf); - std::snprintf(buf, sizeof(buf), "Row%05d", r); app.Cell(buf); - std::snprintf(buf, sizeof(buf), "0x%04X", r); app.Cell(buf); - std::snprintf(buf, sizeof(buf), "%d×7=%d", r, r*7); app.Cell(buf); - app.Cell(r % 7 == 0 ? "ALERT" : "ok"); - app.EndRow(); + std::snprintf(buf, sizeof(buf), "%d", r); views::Cell(app, viewsContext, buf); + std::snprintf(buf, sizeof(buf), "Row%05d", r); views::Cell(app, viewsContext, buf); + std::snprintf(buf, sizeof(buf), "0x%04X", r); views::Cell(app, viewsContext, buf); + std::snprintf(buf, sizeof(buf), "%d×7=%d", r, r*7); views::Cell(app, viewsContext, buf); + views::Cell(app, viewsContext, r % 7 == 0 ? "ALERT" : "ok"); + views::EndRow(app, viewsContext); } - app.EndTable(); + views::EndTable(app, viewsContext); } app.EndRootWindow(); } @@ -85,9 +87,9 @@ namespace tachyon } // Read section[s]'s body scroll offset. - int2 SectionBodyScroll(const tachyon::TableState& state, size_t s) + int2 SectionBodyScroll(const tachyon::views::TableState& state, size_t s) { - if (s >= size_t(tachyon::TableState::kMaxTableSections)) return int2{0, 0}; + if (s >= size_t(tachyon::views::TableState::kMaxTableSections)) return int2{0, 0}; const tachyon::ID id = state.SectionBodyID(int(s)); if (id == tachyon::ID::Invalid()) return int2{0, 0}; auto& sm = app.guiStateManager.GetScrollManagement(); @@ -103,7 +105,7 @@ namespace tachyon TEST_F(FrozenTableTest, FrozenModeCreatesThreeBodySections) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; app.Frame([&] { EmitFrozen(state); }); ASSERT_EQ(state.internal.sectionCount, 3); @@ -119,9 +121,9 @@ namespace tachyon // Count elements in storage whose styleRef matches the table separator. // Walks every (depth, index) since separators sit at varying depths // inside header-row vs body-row scopes. - int CountSeparators(const HeadlessGUIApp& a) + int CountSeparators(HeadlessGUIApp& a, views::Context& viewsContext) { - const StyleRef sep = a.theme.tableSeparatorStyleRef; + const StyleRef sep = views::GetStyles(a, viewsContext).tableSeparatorStyleRef; int count = 0; for (uint32_t d = 0; d < a.elementStorage.NumberOfDepthLevels(); d++) { @@ -144,61 +146,61 @@ namespace tachyon // Reassign sectionIds so there are exactly two sections: // [Name Hex Multiple] | [Status] (cols 1..3 then col 4; // col 0 also lives in the leading section). - tachyon::VirtualTableColumn cols[5] = { + tachyon::views::VirtualTableColumn cols[5] = { { .column = { .header = "#", .initialWidth = 60 }, .sectionId = 0 }, { .column = { .header = "Name", .initialWidth = 100 }, .sectionId = 0 }, { .column = { .header = "Hex", .initialWidth = 100 }, .sectionId = 0 }, { .column = { .header = "Multiple", .initialWidth = 100 }, .sectionId = 0 }, { .column = { .header = "Status", .initialWidth = 60 }, .sectionId = 1 }, }; - tachyon::TableState state{}; + tachyon::views::TableState state{}; app.Frame([&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, cols, state, LayoutOverride{}.Size(400, 200))) + if (views::BeginTable(app, viewsContext, tableID, cols, state, LayoutOverride{}.Size(400, 200))) { - app.BeginRow(); - for (int c = 0; c < 5; c++) app.Cell("x"); - app.EndRow(); - app.EndTable(); + views::BeginRow(app, viewsContext); + for (int c = 0; c < 5; c++) views::Cell(app, viewsContext, "x"); + views::EndRow(app, viewsContext); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }); - EXPECT_EQ(CountSeparators(app), 1) + EXPECT_EQ(CountSeparators(app, viewsContext), 1) << "One boundary between section 0 and section 1 → 1 separator."; } // Mirror: leading single-column section + everything else. TEST_F(FrozenTableTest, NoSeparatorWhenRightFrozenIsZero) { - tachyon::VirtualTableColumn cols[5] = { + tachyon::views::VirtualTableColumn cols[5] = { { .column = { .header = "#", .initialWidth = 60 }, .sectionId = 0 }, { .column = { .header = "Name", .initialWidth = 100 }, .sectionId = 0 }, { .column = { .header = "Hex", .initialWidth = 100 }, .sectionId = 1 }, { .column = { .header = "Multiple", .initialWidth = 100 }, .sectionId = 1 }, { .column = { .header = "Status", .initialWidth = 60 }, .sectionId = 1 }, }; - tachyon::TableState state{}; + tachyon::views::TableState state{}; app.Frame([&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, cols, state, LayoutOverride{}.Size(400, 200))) + if (views::BeginTable(app, viewsContext, tableID, cols, state, LayoutOverride{}.Size(400, 200))) { - app.BeginRow(); - for (int c = 0; c < 5; c++) app.Cell("x"); - app.EndRow(); - app.EndTable(); + views::BeginRow(app, viewsContext); + for (int c = 0; c < 5; c++) views::Cell(app, viewsContext, "x"); + views::EndRow(app, viewsContext); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }); - EXPECT_EQ(CountSeparators(app), 1) + EXPECT_EQ(CountSeparators(app, viewsContext), 1) << "One boundary → 1 separator (header lives inside the section grid)."; } // Three sections (default kColumns layout) - both boundaries non-empty. TEST_F(FrozenTableTest, BothSeparatorsEmittedWhenAllSectionsNonEmpty) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; app.Frame([&] { EmitFrozen(state, /*rowCount*/3); }); - EXPECT_EQ(CountSeparators(app), 2) + EXPECT_EQ(CountSeparators(app, viewsContext), 2) << "Two boundaries → 2 separators."; } @@ -209,7 +211,7 @@ namespace tachyon TEST_F(FrozenTableTest, SizerIdsAreDeterministicPerColumn) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; app.Frame([&] { EmitFrozen(state); }); // Section 1 (cols 1..3) has two interior boundaries, between @@ -222,7 +224,7 @@ namespace tachyon // header cell right edge - same invariant in every section. TEST_F(FrozenTableTest, SizerXAlignsWithHeaderCellRightEdge) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; app.Frame([&] { EmitFrozen(state); }); // Boundaries between section-1 cols (1|2 and 2|3). @@ -244,7 +246,7 @@ namespace tachyon TEST_F(FrozenTableTest, VerticalWheelOverMiddleScrollsY) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; app.Frame([&] { EmitFrozen(state); }); // Center of the middle section's body grid. @@ -262,7 +264,7 @@ namespace tachyon TEST_F(FrozenTableTest, VerticalWheelOverLeftFrozenScrollsY) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; app.Frame([&] { EmitFrozen(state); }); const auto leftRect = app.GetElementRect(state.SectionBodyID(0)); @@ -281,24 +283,24 @@ namespace tachyon // when it is the one that changed. TEST_F(FrozenTableTest, VerticalWheelOverFirstOfTwoSectionsScrollsY) { - tachyon::VirtualTableColumn cols[4] = { + tachyon::views::VirtualTableColumn cols[4] = { { .column = { .header = "#", .initialWidth = 60, .locked = true }, .sectionId = 0 }, { .column = { .header = "Name", .initialWidth = 100 }, .sectionId = 1 }, { .column = { .header = "Hex", .initialWidth = 100 }, .sectionId = 1 }, { .column = { .header = "Val", .initialWidth = 100 }, .sectionId = 1 }, }; - tachyon::TableState state{}; + tachyon::views::TableState state{}; auto emit = [&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, cols, state, LayoutOverride{}.Size(400, 200))) + if (views::BeginTable(app, viewsContext, tableID, cols, state, LayoutOverride{}.Size(400, 200))) { for (int r = 0; r < 30; r++) { - app.BeginRow(); - for (int c = 0; c < 4; c++) app.Cell("x"); - app.EndRow(); + views::BeginRow(app, viewsContext); + for (int c = 0; c < 4; c++) views::Cell(app, viewsContext, "x"); + views::EndRow(app, viewsContext); } - app.EndTable(); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }; @@ -318,7 +320,7 @@ namespace tachyon TEST_F(FrozenTableTest, VerticalWheelOverRightFrozenScrollsY) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; app.Frame([&] { EmitFrozen(state); }); const auto rightRect = app.GetElementRect(state.SectionBodyID(2)); @@ -335,7 +337,7 @@ namespace tachyon TEST_F(FrozenTableTest, HorizontalWheelOverMiddleScrollsX) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; app.Frame([&] { EmitFrozen(state); }); const auto midRect = app.GetElementRect(state.SectionBodyID(1)); @@ -353,7 +355,7 @@ namespace tachyon { // The wheel scrolls the leading section under the cursor, which fits its // content, so X clamps to 0 and must stay valid. - tachyon::TableState state{}; + tachyon::views::TableState state{}; app.Frame([&] { EmitFrozen(state); }); const auto leftRect = app.GetElementRect(state.SectionBodyID(0)); @@ -372,7 +374,7 @@ namespace tachyon TEST_F(FrozenTableTest, VerticalScrollIsMirroredToFrozenSides) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; app.Frame([&] { EmitFrozen(state); }); const auto midRect = app.GetElementRect(state.SectionBodyID(1)); @@ -396,7 +398,7 @@ namespace tachyon // body section scrolls on a horizontal wheel. TEST_F(FrozenTableTest, MiddleSectionScrollsHorizontally) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; app.Frame([&] { EmitFrozen(state); }); const auto midRect = app.GetElementRect(state.SectionBodyID(1)); @@ -420,7 +422,7 @@ namespace tachyon // Frame N: Move(from) + Down(from) - activeID := sizer // Frame N+1: Move(to, Left held) - handler updates width // Frame N+2: Up(to) - drag teardown - static void DragSizer(HeadlessGUIApp& app, tachyon::TableState& state, + static void DragSizer(HeadlessGUIApp& app, tachyon::views::TableState& state, tachyon::int2 from, tachyon::int2 to, std::function emitFn) { @@ -438,7 +440,7 @@ namespace tachyon TEST_F(FrozenTableTest, SizerDragFromHeaderResizesColumn) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; app.Frame([&] { EmitFrozen(state); }); const tachyon::ID sizerID = SizerID(1); @@ -460,7 +462,7 @@ namespace tachyon TEST_F(FrozenTableTest, SizerDragFromBodyResizesColumn) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; app.Frame([&] { EmitFrozen(state); }); // Same ID as the header copy; a body-level Y hits the body copy. @@ -482,7 +484,7 @@ namespace tachyon // scrolls vertically, so it remains clickable. TEST_F(FrozenTableTest, SizerStaysHittableAfterVerticalScroll) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; app.Frame([&] { EmitFrozen(state); }); // Scroll ~half the content height directly, independent of wheel geometry. @@ -522,30 +524,30 @@ namespace tachyon // 3 sections: [L0 L1] | [M0 M1] | [R0]. Boundary 0 (between // cols 0 and 1) lives ENTIRELY inside the leading section // and should be a draggable sizer. - tachyon::VirtualTableColumn cols[5] = { + tachyon::views::VirtualTableColumn cols[5] = { { .column = { .header = "L0", .initialWidth = 60, .minWidth = 30, .maxWidth = 200, .locked = true }, .sectionId = 0 }, { .column = { .header = "L1", .initialWidth = 60, .minWidth = 30, .maxWidth = 200, .locked = true }, .sectionId = 0 }, { .column = { .header = "M0", .initialWidth = 100, .minWidth = 30, .maxWidth = 400 }, .sectionId = 1 }, { .column = { .header = "M1", .initialWidth = 100, .minWidth = 30, .maxWidth = 400 }, .sectionId = 1 }, { .column = { .header = "R0", .initialWidth = 60, .minWidth = 30, .maxWidth = 200, .locked = true }, .sectionId = 2 }, }; - tachyon::TableState state{}; + tachyon::views::TableState state{}; auto emit = [&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, cols, state, LayoutOverride{}.Size(500, 200))) + if (views::BeginTable(app, viewsContext, tableID, cols, state, LayoutOverride{}.Size(500, 200))) { for (int r = 0; r < 5; r++) { - app.BeginRow(); + views::BeginRow(app, viewsContext); for (int c = 0; c < 5; c++) { char cb[8]; std::snprintf(cb, sizeof(cb), "%d-%d", r, c); - app.Cell(cb); + views::Cell(app, viewsContext, cb); } - app.EndRow(); + views::EndRow(app, viewsContext); } - app.EndTable(); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }; @@ -571,24 +573,24 @@ namespace tachyon { // 3 sections where the leading [L0 L1] section's L0 is Stretch, so the // L0|L1 boundary is a 1px separator, not a sizer. - tachyon::VirtualTableColumn cols[5] = { + tachyon::views::VirtualTableColumn cols[5] = { { .column = { .header = "L0", .initialWidth = 60, .minWidth = 30, .maxWidth = 200, - .locked = true, .sizing = tachyon::ColumnSizing::Stretch }, .sectionId = 0 }, + .locked = true, .sizing = tachyon::views::ColumnSizing::Stretch }, .sectionId = 0 }, { .column = { .header = "L1", .initialWidth = 60, .minWidth = 30, .maxWidth = 200, .locked = true }, .sectionId = 0 }, { .column = { .header = "M0", .initialWidth = 100, .minWidth = 30, .maxWidth = 400 }, .sectionId = 1 }, { .column = { .header = "M1", .initialWidth = 100, .minWidth = 30, .maxWidth = 400 }, .sectionId = 1 }, { .column = { .header = "R0", .initialWidth = 60, .minWidth = 30, .maxWidth = 200, .locked = true }, .sectionId = 2 }, }; - tachyon::TableState state{}; + tachyon::views::TableState state{}; app.Frame([&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, cols, state, LayoutOverride{}.Size(500, 200))) + if (views::BeginTable(app, viewsContext, tableID, cols, state, LayoutOverride{}.Size(500, 200))) { - app.BeginRow(); - for (int c = 0; c < 5; c++) app.Cell("x"); - app.EndRow(); - app.EndTable(); + views::BeginRow(app, viewsContext); + for (int c = 0; c < 5; c++) views::Cell(app, viewsContext, "x"); + views::EndRow(app, viewsContext); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }); @@ -606,7 +608,7 @@ namespace tachyon // stop at the corner, so neither bar nor thumb extends into it. TEST_F(FrozenTableTest, BothScrollbarsEndAtCornerWithoutOverlap) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; // Run an unprimed frame so the section bodies get laid out. app.Frame([&] { EmitFrozen(state); }); // Headless skips render, so feed the rightmost section's real size into @@ -642,7 +644,7 @@ namespace tachyon // emitted at the bottom-right (rightmost section). TEST_F(FrozenTableTest, ScrollbarCornerMaskExistsWhenBothScrollbarsVisible) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; // Headless skips render, so force both overflow flags. auto build = [&] { state.internal.anyHorzOverflow = state.internal.anyVertOverflow = true; @@ -674,7 +676,7 @@ namespace tachyon TEST_F(FrozenTableTest, VerticalScrollbarDragWritesYOffset) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; // Headless skips render: set _lastViewport{W,H} and the overflow flags each // build (the prologue resets them). auto build = [&] { @@ -706,7 +708,7 @@ namespace tachyon TEST_F(FrozenTableTest, HorizontalScrollbarDragWritesXOffset) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; auto build = [&] { state.internal.lastViewportW = 200; state.internal.lastViewportH = 150; @@ -752,23 +754,24 @@ namespace tachyon static constexpr bool kTableFillsPanel = true; GUITest::HeadlessGUIApp app; - tachyon::TableState state{}; - std::vector cols; + views::Context viewsContext; + tachyon::views::TableState state{}; + std::vector cols; static constexpr int kPaneW = 530, kPaneH = 400; static constexpr int kRows = 50; // taller than the panel, within 16-bit layout coordinates void SetUp() override { ASSERT_TRUE(app.Initialize()); - auto cell = [this](const char* t) { return [this, t](int) { app.Cell(t); }; }; + auto cell = [this](const char* t) { return [this, t](int) { views::Cell(app, viewsContext, t); }; }; cols = { - { .column = { .header = "#", .initialWidth = 60, .minWidth = 40, .maxWidth = 160, .locked = true }, .generateCell = cell("0"), .sectionId = 0, .sectionSizing = SectionSizing::FitContent }, + { .column = { .header = "#", .initialWidth = 60, .minWidth = 40, .maxWidth = 160, .locked = true }, .generateCell = cell("0"), .sectionId = 0, .sectionSizing = views::SectionSizing::FitContent }, { .column = { .header = "Type", .initialWidth = 80, .minWidth = 40, .maxWidth = 200, .locked = true }, .generateCell = cell("int"), .sectionId = 0 }, { .column = { .header = "Name", .initialWidth = 160, .minWidth = 60, .maxWidth = 400 }, .generateCell = cell("Row"), .sectionId = 1 }, { .column = { .header = "Hex", .initialWidth = 120, .minWidth = 60, .maxWidth = 200 }, .generateCell = cell("0x"), .sectionId = 1 }, { .column = { .header = "Multiple", .initialWidth = 140, .minWidth = 60, .maxWidth = 400 }, .generateCell = cell("m"), .sectionId = 1 }, - { .column = { .header = "Tag", .initialWidth = 60, .minWidth = 40, .maxWidth = 200, .locked = true, .sizing = ColumnSizing::Stretch }, .generateCell = cell("A"), .sectionId = 2, - .sectionSizing = kTagStatusFitContent ? SectionSizing::FitContent : SectionSizing::Scrollable }, + { .column = { .header = "Tag", .initialWidth = 60, .minWidth = 40, .maxWidth = 200, .locked = true, .sizing = views::ColumnSizing::Stretch }, .generateCell = cell("A"), .sectionId = 2, + .sectionSizing = kTagStatusFitContent ? views::SectionSizing::FitContent : views::SectionSizing::Scrollable }, { .column = { .header = "Status", .initialWidth = 80, .minWidth = 60, .maxWidth = 200, .locked = true }, .generateCell = cell("ok"), .sectionId = 2 }, }; } @@ -780,17 +783,17 @@ namespace tachyon app.BeginRootWindow(); app.BeginArea(app.idManager.AllocateDynamicID("pane"), app.theme.emptyVertStyleRef, LayoutOverride{}.Size(kPaneW, kPaneH)); - std::span sp(cols.data(), cols.size()); + std::span sp(cols.data(), cols.size()); const tachyon::ID tableID = app.idManager.AllocateDynamicID("multiSectionTable"); if (kTableFillsPanel) { app.BeginHorizontal(app.idManager.AllocateDynamicID("splitScrollFill"), app.theme.flexFillRowStyleRef, LayoutOverride::Auto().FlexGrow(1)); - app.VirtualTable(tableID, state, sp, kRows, 0, app.theme.tableFillStyleRef, LayoutOverride{}); + views::VirtualTable(app, viewsContext, tableID, state, sp, kRows, 0, views::GetStyles(app, viewsContext).tableFillStyleRef, LayoutOverride{}); app.EndHorizontal(); } else - app.VirtualTable(tableID, state, sp, kRows, 0, app.theme.tableStyleRef, LayoutOverride{}.NoGrow().NoShrink()); + views::VirtualTable(app, viewsContext, tableID, state, sp, kRows, 0, views::GetStyles(app, viewsContext).tableStyleRef, LayoutOverride{}.NoGrow().NoShrink()); app.EndArea(); app.EndRootWindow(); }); diff --git a/tests/controls_table_virtual_test.cpp b/tests/controls_table_virtual_test.cpp index 5541f029..cfd72e3f 100644 --- a/tests/controls_table_virtual_test.cpp +++ b/tests/controls_table_virtual_test.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include @@ -25,10 +26,11 @@ namespace tachyon { protected: HeadlessGUIApp app; + views::Context viewsContext; tachyon::ID tableID{}; // 4 columns wider than the body so the H-scrollbar shows up. - std::vector columns; + std::vector columns; void SetUp() override { @@ -37,32 +39,32 @@ namespace tachyon columns.clear(); columns.push_back({ { .header = "A", .initialWidth = 200, .minWidth = 60, .maxWidth = 400 }, - [this](int r) { char b[16]; std::snprintf(b, sizeof(b), "A%05d", r); app.Cell(b); } }); + [this](int r) { char b[16]; std::snprintf(b, sizeof(b), "A%05d", r); views::Cell(app, viewsContext, b); } }); columns.push_back({ { .header = "B", .initialWidth = 200, .minWidth = 60, .maxWidth = 400 }, - [this](int r) { char b[16]; std::snprintf(b, sizeof(b), "B%05d", r); app.Cell(b); } }); + [this](int r) { char b[16]; std::snprintf(b, sizeof(b), "B%05d", r); views::Cell(app, viewsContext, b); } }); columns.push_back({ { .header = "C", .initialWidth = 200, .minWidth = 60, .maxWidth = 400 }, - [this](int r) { char b[16]; std::snprintf(b, sizeof(b), "C%05d", r); app.Cell(b); } }); + [this](int r) { char b[16]; std::snprintf(b, sizeof(b), "C%05d", r); views::Cell(app, viewsContext, b); } }); columns.push_back({ { .header = "D", .initialWidth = 200, .minWidth = 60, .maxWidth = 400 }, - [this](int r) { char b[16]; std::snprintf(b, sizeof(b), "D%05d", r); app.Cell(b); } }); + [this](int r) { char b[16]; std::snprintf(b, sizeof(b), "D%05d", r); views::Cell(app, viewsContext, b); } }); } void TearDown() override { app.Cleanup(); } // Body container 400x300; columns total ~800 -> overflow X. // 200 rows x ~24 px -> overflow Y. - void Emit(tachyon::TableState& state, int rowCount = 200, + void Emit(tachyon::views::TableState& state, int rowCount = 200, int width = 400, int height = 300) { app.BeginRootWindow(); - std::span span(columns.data(), columns.size()); - app.VirtualTable(tableID, state, span, rowCount, /*rowHeight*/0, - app.theme.tableStyleRef, + std::span span(columns.data(), columns.size()); + views::VirtualTable(app, viewsContext, tableID, state, span, rowCount, /*rowHeight*/0, + views::GetStyles(app, viewsContext).tableStyleRef, LayoutOverride{}.Size(CssPx(width), CssPx(height))); app.EndRootWindow(); } // A panel-sized pane holding a mode bar and a 50k-row table, like the showcase's Table panel. tachyon::ID paneID = tachyon::ID::Invalid(); - IntRect EmitInPane(tachyon::TableState& state, StyleRef tableStyle, LayoutOverride&& tableLayout) + IntRect EmitInPane(tachyon::views::TableState& state, StyleRef tableStyle, LayoutOverride&& tableLayout) { if (paneID == tachyon::ID::Invalid()) paneID = app.idManager.CreateStaticID(); @@ -70,15 +72,15 @@ namespace tachyon app.BeginRootWindow(); app.BeginArea(paneID, app.theme.emptyVertStyleRef, LayoutOverride{}.Size(530, 400)); app.Button(app.idManager.AllocateDynamicID("mode"), "Row", [] {}, LayoutOverride{}.NoGrow().NoShrink()); - std::span span(columns.data(), columns.size()); - app.VirtualTable(tableID, state, span, 50000, 0, tableStyle, std::move(tableLayout)); + std::span span(columns.data(), columns.size()); + views::VirtualTable(app, viewsContext, tableID, state, span, 50000, 0, tableStyle, std::move(tableLayout)); app.EndArea(); app.EndRootWindow(); }); return app.GetElementRect(tableID); } - int2 SectionScroll(tachyon::TableState& state, int sectionIdx = 0) + int2 SectionScroll(tachyon::views::TableState& state, int sectionIdx = 0) { auto& sm = app.guiStateManager.GetScrollManagement(); const tachyon::ID id = state.SectionBodyID(sectionIdx); @@ -90,7 +92,7 @@ namespace tachyon // Headless skips render, so pin internal.lastViewportH/W and the overflow flags // that its custom-draw would set. - void PinViewport(tachyon::TableState& state, + void PinViewport(tachyon::views::TableState& state, bool xOverflow = true, bool yOverflow = true) { state.internal.lastViewportH = 298; @@ -106,7 +108,7 @@ namespace tachyon // --------------------------------------------------------------- TEST_F(TableVirtualScrollTest, WheelAtBottomDoesNotOscillate) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; auto pin = [&]{ PinViewport(state); }; pin(); app.Frame([&]{ Emit(state); pin(); }); @@ -144,7 +146,7 @@ namespace tachyon // --------------------------------------------------------------- TEST_F(TableVirtualScrollTest, ScrollbarJumpUpdatesRowWindowSameFrame) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; auto pin = [&]{ PinViewport(state); }; pin(); app.Frame([&]{ Emit(state); pin(); }); @@ -180,7 +182,7 @@ namespace tachyon // --------------------------------------------------------------- TEST_F(TableVirtualScrollTest, LastRowClearsHorizontalScrollbarAtMaxScroll) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; auto pin = [&]{ PinViewport(state); }; pin(); app.Frame([&]{ Emit(state); pin(); }); @@ -230,16 +232,16 @@ namespace tachyon columns.push_back({ { .header = "Name", .initialWidth = 240, .minWidth = 80, .maxWidth = 600, .locked = true }, [this](int r) { char b[24]; std::snprintf(b, sizeof(b), "Item%05d", r); - app.TreeCell(b, /*depth*/0, /*isOpen*/nullptr, + views::TreeCell(app, viewsContext, b, /*depth*/0, /*isOpen*/nullptr, IconID::Invalid, /*ancestorMask*/0, /*isLastSibling*/true, /*renameBuffer*/nullptr); } }); columns.push_back({ { .header = "Size", .initialWidth = 100, .minWidth = 40, .maxWidth = 200 }, - [this](int r) { char b[16]; std::snprintf(b, sizeof(b), "%dKB", r); app.Cell(b); } }); + [this](int r) { char b[16]; std::snprintf(b, sizeof(b), "%dKB", r); views::Cell(app, viewsContext, b); } }); columns.push_back({ { .header = "Type", .initialWidth = 120, .minWidth = 40, .maxWidth = 200 }, - [this](int r) { app.Cell((r % 2) ? "File" : "Folder"); } }); + [this](int r) { views::Cell(app, viewsContext, (r % 2) ? "File" : "Folder"); } }); - tachyon::TableState state{}; + tachyon::views::TableState state{}; auto pin = [&]{ PinViewport(state); }; pin(); app.Frame([&]{ Emit(state); pin(); }); @@ -273,7 +275,7 @@ namespace tachyon TEST_F(TableVirtualScrollTest, PlainAndTreeCellsRenderAtSameHeight) { // Plain table. - tachyon::TableState state{}; + tachyon::views::TableState state{}; auto pin = [&]{ PinViewport(state); }; pin(); app.Frame([&]{ Emit(state); pin(); }); @@ -286,14 +288,14 @@ namespace tachyon columns.push_back({ { .header = "Name", .initialWidth = 240, .minWidth = 80, .maxWidth = 600, .locked = true }, [this](int r) { char b[24]; std::snprintf(b, sizeof(b), "Item%05d", r); - app.TreeCell(b, /*depth*/0, /*isOpen*/nullptr, + views::TreeCell(app, viewsContext, b, /*depth*/0, /*isOpen*/nullptr, IconID::Invalid, /*ancestorMask*/0, /*isLastSibling*/true, /*renameBuffer*/nullptr); } }); columns.push_back({ { .header = "Size", .initialWidth = 100, .minWidth = 40, .maxWidth = 200 }, - [this](int r) { char b[16]; std::snprintf(b, sizeof(b), "%d", r); app.Cell(b); } }); + [this](int r) { char b[16]; std::snprintf(b, sizeof(b), "%d", r); views::Cell(app, viewsContext, b); } }); - tachyon::TableState state2{}; + tachyon::views::TableState state2{}; auto pin2 = [&]{ PinViewport(state2); }; pin2(); app.Frame([&]{ Emit(state2); pin2(); }); @@ -306,11 +308,11 @@ namespace tachyon << " px — mixing cell types in one table requires uniform row height"; } - // A table's context menu (TableState::contextMenu) opens on a right-click on a row, for + // A table's context menu (views::TableState::contextMenu) opens on a right-click on a row, for // that row, and on the empty space below the rows, for none (-1). TEST_F(TableVirtualScrollTest, ARightClickOpensTheTablesContextMenuForTheRowUnderIt) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; int menuRow = -2; state.contextMenu = [this, &menuRow](int row) { menuRow = row; @@ -339,7 +341,7 @@ namespace tachyon EXPECT_EQ(menuRow, -1) << "below the rows: no row"; } - // A table's command mode (TableState::commandMode) is the command manager's while the + // A table's command mode (views::TableState::commandMode) is the command manager's while the // focus is in the table: its shortcuts (Delete) work there and nowhere else. TEST_F(TableVirtualScrollTest, ATablesCommandModeIsOnWhileItHasTheFocus) { @@ -347,7 +349,7 @@ namespace tachyon const CommandMode mode = app.commandManager.RegisterMode("Table"); int deletes = 0; app.commandManager.RegisterCommand(mode, KeyCode::Delete, KeyModifier::None, [&deletes] { ++deletes; }, "Delete rows"); - tachyon::TableState state{}; + tachyon::views::TableState state{}; state.commandMode = mode; auto frame = [&] { app.Frame([&] { Emit(state, 3); }); }; frame(); @@ -376,7 +378,7 @@ namespace tachyon // row is as tall as a plain one and the button's text sits where plain text does. TEST_F(TableVirtualScrollTest, AFlatButtonCellLinesUpWithPlainCells) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; auto pin = [&]{ PinViewport(state); }; pin(); app.Frame([&]{ Emit(state); pin(); }); @@ -388,7 +390,7 @@ namespace tachyon std::function findCell = [&](ElementRef ref) { if (!app.elementStorage.IsValidRef(ref)) return; const ElementRect& r = app.elementStorage.GetElementRectUnsafe(ref); - if (app.elementStorage.GetElementUnsafe(ref).styleRef == app.theme.tableCellStyleRef && + if (app.elementStorage.GetElementUnsafe(ref).styleRef == views::GetStyles(app, viewsContext).tableCellStyleRef && r.rect.y == plainRow.y && plainTextY < 0) plainTextY = r.innerRect.y - plainRow.y; const auto children = app.elementStorage.GetChildRange(ref); @@ -400,12 +402,12 @@ namespace tachyon const ID buttonID = app.idManager.CreateStaticID(); columns[0].generateCell = [this, buttonID](int r) { - app.Cell([this, buttonID, r]() { + views::Cell(app, viewsContext, [this, buttonID, r]() { app.Button(r == 0 ? buttonID : app.idManager.AllocateDynamicID("btn"), "Ctrl S", []() {}, app.theme.flatButtonStyleRef); }); }; - tachyon::TableState state2{}; + tachyon::views::TableState state2{}; auto pin2 = [&]{ PinViewport(state2); }; pin2(); app.Frame([&]{ Emit(state2); pin2(); }); @@ -436,7 +438,7 @@ namespace tachyon TEST_F(TableVirtualScrollTest, VScrollbarOnlyEmittedWhenContentOverflowsY) { // No-Y-overflow: pin yOverflow=false. Bar must NOT exist. - tachyon::TableState stateA{}; + tachyon::views::TableState stateA{}; auto pinA = [&]{ PinViewport(stateA, /*xOverflow*/true, /*yOverflow*/false); }; pinA(); app.Frame([&]{ Emit(stateA); pinA(); }); @@ -445,7 +447,7 @@ namespace tachyon << "V-scrollbar must not be emitted when content fits vertically"; // Y-overflow: pin yOverflow=true. Bar must exist. - tachyon::TableState stateB{}; + tachyon::views::TableState stateB{}; auto pinB = [&]{ PinViewport(stateB, /*xOverflow*/true, /*yOverflow*/true); }; pinB(); app.Frame([&]{ Emit(stateB); pinB(); }); @@ -459,7 +461,7 @@ namespace tachyon TEST_F(TableVirtualScrollTest, HScrollbarOnlyEmittedWhenAnySectionOverflows) { // No-overflow: pin xOverflow=false. Bar must NOT exist. - tachyon::TableState stateA{}; + tachyon::views::TableState stateA{}; auto pinA = [&]{ PinViewport(stateA, /*xOverflow*/false); }; pinA(); app.Frame([&]{ Emit(stateA); pinA(); }); @@ -468,7 +470,7 @@ namespace tachyon << "H-scrollbar must not be emitted when no section overflows X"; // Overflow: pin xOverflow=true. Bar must exist. - tachyon::TableState stateB{}; + tachyon::views::TableState stateB{}; auto pinB = [&]{ PinViewport(stateB, /*xOverflow*/true); }; pinB(); app.Frame([&]{ Emit(stateB); pinB(); }); @@ -482,7 +484,7 @@ namespace tachyon // Same table with and without X overflow. // Scenario A: NO X-overflow - flag false, no pad expected. - tachyon::TableState stateA{}; + tachyon::views::TableState stateA{}; auto pinA = [&]{ PinViewport(stateA, /*xOverflow*/false); }; pinA(); app.Frame([&]{ Emit(stateA); pinA(); }); @@ -491,7 +493,7 @@ namespace tachyon ASSERT_GT(rangeNoOverflow, 0); // Scenario B: X-overflow - flag true, pad expected. - tachyon::TableState stateB{}; + tachyon::views::TableState stateB{}; auto pinB = [&]{ PinViewport(stateB, /*xOverflow*/true); }; pinB(); app.Frame([&]{ Emit(stateB); pinB(); }); @@ -512,7 +514,7 @@ namespace tachyon // --------------------------------------------------------------- TEST_F(TableVirtualScrollTest, HeadersEmittedAfterBodyRowsForCorrectPaintOrder) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; auto pin = [&]{ PinViewport(state); }; pin(); app.Frame([&]{ Emit(state); pin(); }); @@ -549,7 +551,7 @@ namespace tachyon { // Render a normal (non-virtual) cell so layout produces a // real row height, then compare against theme.tableRowHeight. - tachyon::TableState state{}; + tachyon::views::TableState state{}; auto pin = [&]{ PinViewport(state); }; pin(); app.Frame([&]{ Emit(state); pin(); }); @@ -558,10 +560,10 @@ namespace tachyon ASSERT_GT(state.internal.totalRowCount, 0); const auto rowRect = app.GetElementRect(state.RowIDForIndex(0)); - EXPECT_GT(app.theme.tableRowHeight, 0) + EXPECT_GT(views::GetStyles(app, viewsContext).tableRowHeight, 0) << "theme.tableRowHeight must be initialized by ComputeRowMetrics"; - EXPECT_EQ(app.theme.tableRowHeight, rowRect.h) - << "theme.tableRowHeight (" << app.theme.tableRowHeight + EXPECT_EQ(views::GetStyles(app, viewsContext).tableRowHeight, rowRect.h) + << "theme.tableRowHeight (" << views::GetStyles(app, viewsContext).tableRowHeight << ") must match the actual rendered row height (" << rowRect.h << ") — drift here is what causes scroll " << "oscillation"; @@ -574,7 +576,7 @@ namespace tachyon TEST_F(TableVirtualScrollTest, ColumnReorderRespectsHorizontalScroll) { int reorderFrom = -1, reorderTo = -1; - tachyon::TableState state{}; + tachyon::views::TableState state{}; state.onReorderColumns = [&](int f, int t){ reorderFrom = f; reorderTo = t; }; auto pin = [&]{ PinViewport(state); }; pin(); @@ -640,7 +642,7 @@ namespace tachyon return int(app.elementStorage.GetChildrenSpan(ref).size()); }; - tachyon::TableState state{}; + tachyon::views::TableState state{}; state.onReorderColumns = [](int, int){}; auto pin = [&]{ PinViewport(state); }; pin(); @@ -692,7 +694,7 @@ namespace tachyon // --------------------------------------------------------------- TEST_F(TableVirtualScrollTest, DraggedColumnPaintsOnTopOfSizers) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; state.onReorderColumns = [](int, int){}; auto pin = [&]{ PinViewport(state); }; pin(); @@ -738,7 +740,7 @@ namespace tachyon // --------------------------------------------------------------- TEST_F(TableVirtualScrollTest, ColumnDragAutoScrollsNearEdges) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; state.onReorderColumns = [](int, int){}; auto pin = [&]{ PinViewport(state); }; pin(); @@ -801,7 +803,7 @@ namespace tachyon // --------------------------------------------------------------- TEST_F(TableVirtualScrollTest, KeyboardHomeEndJumpToDatasetBoundsNotVisibleWindow) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; auto pin = [&]{ PinViewport(state); }; pin(); app.Frame([&]{ Emit(state); pin(); }); @@ -850,7 +852,7 @@ namespace tachyon // virtualized window. TEST_F(TableVirtualScrollTest, KeyboardUpStepsBeyondVirtualizedTopBuffer) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; auto pin = [&]{ PinViewport(state); }; pin(); app.Frame([&]{ Emit(state); pin(); }); @@ -891,7 +893,7 @@ namespace tachyon // --------------------------------------------------------------- TEST_F(TableVirtualScrollTest, SizersStayPresentWhenScrolling) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; auto pin = [&]{ PinViewport(state); }; pin(); app.Frame([&]{ Emit(state); pin(); }); @@ -929,17 +931,17 @@ namespace tachyon { columns[0].sortAscending = [](int a, int b) { return a < b; }; // a sortable header, with its chevron columns[0].column.locked = true; // a landmark that doesn't move - tachyon::TableState state{}; + tachyon::views::TableState state{}; state.sortColumn = 0; state.selectionBar = true; state.onReorderColumns = [](int, int) {}; for (size_t c = 1; c < columns.size(); ++c) - columns[c].column.cellStyle = app.theme.tableCellNumberStyleRef; // numbers, as a data table's + columns[c].column.cellStyle = views::GetStyles(app, viewsContext).tableCellNumberStyleRef; // numbers, as a data table's auto emit = [&] { app.BeginRootWindow(); app.BeginVertical(app.idManager.AllocateDynamicID("pane"), app.theme.emptyVertStyleRef, LayoutOverride{}.Size(500, 400)); - std::span span(columns.data(), columns.size()); - app.VirtualTable(tableID, state, span, 200, 0, app.theme.tableFillStyleRef, + std::span span(columns.data(), columns.size()); + views::VirtualTable(app, viewsContext, tableID, state, span, 200, 0, views::GetStyles(app, viewsContext).tableFillStyleRef, LayoutOverride::Auto().FlexGrow(1).MinHeight(0)); app.EndVertical(); app.EndRootWindow(); @@ -958,26 +960,26 @@ namespace tachyon // the header sits over its values; a text column's header stays at the start. TEST_F(TableVirtualScrollTest, AHeaderIsAlignedAsItsColumnsCells) { - columns[1].column.cellStyle = app.theme.tableCellNumberStyleRef; // right-aligned numbers + columns[1].column.cellStyle = views::GetStyles(app, viewsContext).tableCellNumberStyleRef; // right-aligned numbers columns[2].sortAscending = [](int a, int b) { return a < b; }; // sortable - columns[2].column.cellStyle = app.theme.tableCellNumberStyleRef; - tachyon::TableState state{}; + columns[2].column.cellStyle = views::GetStyles(app, viewsContext).tableCellNumberStyleRef; + tachyon::views::TableState state{}; app.Frame([&] { Emit(state); }); app.Frame([&] { Emit(state); }); auto headerStyle = [&](size_t c) { return app.elementStorage.GetElementUnsafe(columns[c].internal.headerRef).styleRef; }; - EXPECT_EQ(headerStyle(0), app.theme.tableHeaderLockedStyleRef) << "text: at the start"; - EXPECT_EQ(headerStyle(1), app.theme.tableHeaderLockedEndStyleRef) << "numbers: at the end"; - EXPECT_EQ(headerStyle(2), app.theme.tableHeaderEndStyleRef) << "numbers, sortable: at the end"; + EXPECT_EQ(headerStyle(0), views::GetStyles(app, viewsContext).tableHeaderLockedStyleRef) << "text: at the start"; + EXPECT_EQ(headerStyle(1), views::GetStyles(app, viewsContext).tableHeaderLockedEndStyleRef) << "numbers: at the end"; + EXPECT_EQ(headerStyle(2), views::GetStyles(app, viewsContext).tableHeaderEndStyleRef) << "numbers, sortable: at the end"; } // With columnSeparators off, a table with headers draws no line between columns that // can't be resized; a column that can keeps its sizer, to drag. TEST_F(TableVirtualScrollTest, NoSeparatorsLeaveOnlyTheSizersToDrag) { - columns[0].column.sizing = ColumnSizing::Resizable; - columns[1].column.sizing = ColumnSizing::Fixed; - columns[2].column.sizing = ColumnSizing::Fixed; - tachyon::TableState state{}; + columns[0].column.sizing = views::ColumnSizing::Resizable; + columns[1].column.sizing = views::ColumnSizing::Fixed; + columns[2].column.sizing = views::ColumnSizing::Fixed; + tachyon::views::TableState state{}; auto frames = [&] { app.Frame([&] { Emit(state); }); app.Frame([&] { Emit(state); }); }; frames(); EXPECT_TRUE(app.HasElement(columns[1].internal.sizerID)) << "separators are on by default"; @@ -995,7 +997,7 @@ namespace tachyon // --------------------------------------------------------------- TEST_F(TableVirtualScrollTest, KeyboardEndFullyShowsLastRowAboveHScrollbar) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; auto pin = [&]{ PinViewport(state); }; pin(); app.Frame([&]{ Emit(state); pin(); }); @@ -1043,7 +1045,7 @@ namespace tachyon // --------------------------------------------------------------- TEST_F(TableVirtualScrollTest, KeyboardUpScrollsSelectedRowBelowStickyHeader) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; auto pin = [&]{ PinViewport(state); }; pin(); app.Frame([&]{ Emit(state); pin(); }); @@ -1098,7 +1100,7 @@ namespace tachyon // --------------------------------------------------------------- TEST_F(TableVirtualScrollTest, KeyboardDownScrollsLastVisibleRowAboveHScrollbar) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; auto pin = [&]{ PinViewport(state); }; pin(); app.Frame([&]{ Emit(state); pin(); }); @@ -1140,7 +1142,7 @@ namespace tachyon // --------------------------------------------------------------- TEST_F(TableVirtualScrollTest, KeyboardPageDownLandsAboveHScrollbar) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; auto pin = [&]{ PinViewport(state); }; pin(); app.Frame([&]{ Emit(state); pin(); }); @@ -1183,7 +1185,7 @@ namespace tachyon // --------------------------------------------------------------- TEST_F(TableVirtualScrollTest, KeyboardPageDownClearsHScrollbarWithoutPinningOverflowFlag) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; // Pin only the viewport size; the overflow flag stays false as at dispatch. auto pin = [&]{ state.internal.lastViewportH = 298; @@ -1238,7 +1240,7 @@ namespace tachyon TEST_F(TableVirtualScrollTest, SortIndicatorFollowsDraggedColumn) { int reorderFrom = -1, reorderTo = -1; - tachyon::TableState state{}; + tachyon::views::TableState state{}; // The caller rotates its columns vector on reorder. state.onReorderColumns = [&](int f, int t){ reorderFrom = f; reorderTo = t; @@ -1292,7 +1294,7 @@ namespace tachyon TEST_F(TableVirtualScrollTest, TheKeyboardSortsAndMovesColumns) { for (auto& c : columns) c.column.sortable = true; - tachyon::TableState state{}; + tachyon::views::TableState state{}; int reorderFrom = -1, reorderTo = -1; state.onReorderColumns = [&](int f, int t) { reorderFrom = f; reorderTo = t; @@ -1336,7 +1338,7 @@ namespace tachyon // --------------------------------------------------------------- TEST_F(TableVirtualScrollTest, ColumnWidthsFollowDraggedColumn) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; state.onReorderColumns = [&](int f, int t){ if (f == t) return; if (f < t) std::rotate(columns.begin() + f, columns.begin() + f + 1, columns.begin() + t + 1); @@ -1384,7 +1386,7 @@ namespace tachyon // land in the multi-select set (that is what row highlighting reads). TEST_F(TableVirtualScrollTest, FollowTailSelectsTheBottomRowWhenSortedAndMultiSelect) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; tachyon::MultiSelectState multi{}; state.multiSelect = &multi; state.followTail = true; @@ -1394,17 +1396,17 @@ namespace tachyon // Keys ascending by dataset index, sorted descending: the bottom // visual row holds dataset row 0. const int kRows = 50; - std::vector cols; + std::vector cols; cols.push_back({ .column = { .header = "V", .initialWidth = 200, .minWidth = 60, .maxWidth = 400 }, - .generateCell = [this](int r) { char b[16]; std::snprintf(b, sizeof(b), "%d", r); app.Cell(b); }, + .generateCell = [this](int r) { char b[16]; std::snprintf(b, sizeof(b), "%d", r); views::Cell(app, viewsContext, b); }, .sortAscending = [](int a, int b) { return a < b; }, }); auto frame = [&] { app.Frame([&] { app.BeginRootWindow(); - std::span sp(cols.data(), cols.size()); - app.VirtualTable(tableID, state, sp, kRows, 0, app.theme.tableStyleRef, + std::span sp(cols.data(), cols.size()); + views::VirtualTable(app, viewsContext, tableID, state, sp, kRows, 0, views::GetStyles(app, viewsContext).tableStyleRef, LayoutOverride{}.Size(400, 300)); app.EndRootWindow(); }); @@ -1435,7 +1437,7 @@ namespace tachyon // (onto whatever data row then sits there) when rows are added again. TEST_F(TableVirtualScrollTest, SelectionPastTheEndIsDroppedWhenRowsShrink) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; tachyon::MultiSelectState multi{}; auto pin = [&]{ PinViewport(state); }; app.Frame([&]{ Emit(state, 50); pin(); }); @@ -1452,8 +1454,8 @@ namespace tachyon } // Begin a column drag on column `col` (press + move past the threshold). - static void BeginColumnDrag(HeadlessGUIApp& app, tachyon::TableState& state, - std::vector& columns, int col, + static void BeginColumnDrag(HeadlessGUIApp& app, tachyon::views::TableState& state, + std::vector& columns, int col, const std::function& emit) { const auto r = app.elementStorage.GetElementRectUnsafe(columns[size_t(col)].internal.headerRef).rect; @@ -1468,30 +1470,30 @@ namespace tachyon TEST_F(TableVirtualScrollTest, ColumnDragIsCancelledWhenItsColumnDisappears) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; state.onReorderColumns = [](int, int) {}; auto pin = [&]{ PinViewport(state); }; auto emit = [&]{ Emit(state); pin(); }; app.Frame(emit); app.Frame(emit); BeginColumnDrag(app, state, columns, 1, emit); - ASSERT_TRUE(app.m_columnDrag.IsDragging()); + ASSERT_TRUE(viewsContext.columnDrag.IsDragging()); columns.resize(1); // the dragged column (and the ones after it) went away app.Frame(emit); - EXPECT_FALSE(app.m_columnDrag.IsDragging()); + EXPECT_FALSE(viewsContext.columnDrag.IsDragging()); } TEST_F(TableVirtualScrollTest, ColumnDragIsCancelledAfterTheTableWasHidden) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; state.onReorderColumns = [](int, int) {}; auto pin = [&]{ PinViewport(state); }; auto emit = [&]{ Emit(state); pin(); }; app.Frame(emit); app.Frame(emit); BeginColumnDrag(app, state, columns, 1, emit); - ASSERT_TRUE(app.m_columnDrag.IsDragging()); + ASSERT_TRUE(viewsContext.columnDrag.IsDragging()); // The table is not emitted while the button is released elsewhere. auto empty = [&]{ app.BeginRootWindow(); app.EndRootWindow(); }; @@ -1500,30 +1502,30 @@ namespace tachyon app.Frame(empty); app.Frame(emit); - EXPECT_FALSE(app.m_columnDrag.IsDragging()); + EXPECT_FALSE(viewsContext.columnDrag.IsDragging()); } TEST_F(TableVirtualScrollTest, SortAscendingBuildsPermutationAndKeepsSelection) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; // Dataset whose index order isn't its sorted order. std::vector data = { 30, 10, 50, 20, 40 }; - std::vector sortedColumns; + std::vector sortedColumns; sortedColumns.push_back({ .column = { .header = "V", .initialWidth = 200, .minWidth = 60, .maxWidth = 400 }, .generateCell = [this, &data](int r) { - char b[16]; std::snprintf(b, sizeof(b), "%d", data[r]); app.Cell(b); + char b[16]; std::snprintf(b, sizeof(b), "%d", data[r]); views::Cell(app, viewsContext, b); }, .sortAscending = [&data](int a, int b) { return data[a] < data[b]; }, }); auto emitSorted = [&]{ app.BeginRootWindow(); - std::span sp(sortedColumns.data(), sortedColumns.size()); - app.VirtualTable(tableID, state, sp, int(data.size()), 0, - app.theme.tableStyleRef, + std::span sp(sortedColumns.data(), sortedColumns.size()); + views::VirtualTable(app, viewsContext, tableID, state, sp, int(data.size()), 0, + views::GetStyles(app, viewsContext).tableStyleRef, LayoutOverride{}.Size(400, 300)); app.EndRootWindow(); }; @@ -1577,12 +1579,12 @@ namespace tachyon // --------------------------------------------------------------- TEST_F(TableVirtualScrollTest, ColumnWithoutSortLambdaDoesNotBuildPermutation) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; - std::vector noLambdaCols; + std::vector noLambdaCols; noLambdaCols.push_back({ .column = { .header = "X", .initialWidth = 200, .minWidth = 60, .maxWidth = 400, .sortable = true }, - .generateCell = [this](int r) { char b[16]; std::snprintf(b, sizeof(b), "%d", r); app.Cell(b); }, + .generateCell = [this](int r) { char b[16]; std::snprintf(b, sizeof(b), "%d", r); views::Cell(app, viewsContext, b); }, // sortAscending intentionally omitted }); @@ -1590,9 +1592,9 @@ namespace tachyon state.sortDescending = true; app.Frame([&]{ app.BeginRootWindow(); - std::span sp(noLambdaCols.data(), noLambdaCols.size()); - app.VirtualTable(tableID, state, sp, 10, 0, - app.theme.tableStyleRef, + std::span sp(noLambdaCols.data(), noLambdaCols.size()); + views::VirtualTable(app, viewsContext, tableID, state, sp, 10, 0, + views::GetStyles(app, viewsContext).tableStyleRef, LayoutOverride{}.Size(400, 300)); app.EndRootWindow(); }); @@ -1610,24 +1612,24 @@ namespace tachyon TEST_F(TableVirtualScrollTest, TreeCellPopulatesHasChildrenForBranches) { bool branchOpen = true; - std::vector cols; + std::vector cols; cols.push_back({ { .header = "Name", .initialWidth = 240, .minWidth = 80, .maxWidth = 600 }, [&](int r) { if (r == 0) - app.TreeCell("Branch", /*depth*/0, &branchOpen, + views::TreeCell(app, viewsContext, "Branch", /*depth*/0, &branchOpen, IconID::Invalid, 0, true, nullptr); else - app.TreeCell("Leaf", /*depth*/1, /*isOpen*/nullptr, + views::TreeCell(app, viewsContext, "Leaf", /*depth*/1, /*isOpen*/nullptr, IconID::Invalid, 0, true, nullptr); } }); - tachyon::TableState state{}; + tachyon::views::TableState state{}; auto pin = [&]{ PinViewport(state, /*xOverflow*/false, /*yOverflow*/false); }; auto emit = [&]{ app.BeginRootWindow(); - std::span sp(cols.data(), cols.size()); - app.VirtualTable(tableID, state, sp, 2, 0, - app.theme.tableStyleRef, + std::span sp(cols.data(), cols.size()); + views::VirtualTable(app, viewsContext, tableID, state, sp, 2, 0, + views::GetStyles(app, viewsContext).tableStyleRef, LayoutOverride{}.Size(400, 200)); app.EndRootWindow(); }; @@ -1648,22 +1650,22 @@ namespace tachyon TEST_F(TableVirtualScrollTest, TreeCellIconDoubleClickTogglesBranch) { bool branchOpen = false; - std::vector cols; + std::vector cols; cols.push_back({ { .header = "Name", .initialWidth = 240, .minWidth = 80, .maxWidth = 600 }, [&](int r) { (void)r; // A valid icon so the hittable icon element is emitted. - app.TreeCell("Branch", /*depth*/0, &branchOpen, - app.theme.sortArrowDownIcon, 0, true, nullptr); + views::TreeCell(app, viewsContext, "Branch", /*depth*/0, &branchOpen, + views::GetStyles(app, viewsContext).sortArrowDownIcon, 0, true, nullptr); } }); - tachyon::TableState state{}; + tachyon::views::TableState state{}; auto pin = [&]{ PinViewport(state, false, false); }; auto emit = [&]{ app.BeginRootWindow(); - std::span sp(cols.data(), cols.size()); - app.VirtualTable(tableID, state, sp, 1, 0, - app.theme.tableStyleRef, + std::span sp(cols.data(), cols.size()); + views::VirtualTable(app, viewsContext, tableID, state, sp, 1, 0, + views::GetStyles(app, viewsContext).tableStyleRef, LayoutOverride{}.Size(400, 200)); app.EndRootWindow(); }; @@ -1689,14 +1691,14 @@ namespace tachyon // A resizable column's sizer takes the hover (it highlights like other dividers), // rather than the header cell under it. - std::vector SelectionBars(const HeadlessGUIApp& app) + std::vector SelectionBars(HeadlessGUIApp& app, views::Context& viewsContext) { std::vector bars; const auto& storage = app.elementStorage; for (auto it = storage.TopDownDepthScanBegin(); it != storage.TopDownDepthScanEnd(); ++it) for (const tachyon::Element& e : it->GetChildren(storage)) - if (e.styleRef.visualBoxStyleIndex == app.theme.tableRowBarStyleRef.visualBoxStyleIndex - && e.styleRef.layoutStyleIndex == app.theme.tableRowBarStyleRef.layoutStyleIndex) + if (e.styleRef.visualBoxStyleIndex == views::GetStyles(app, viewsContext).tableRowBarStyleRef.visualBoxStyleIndex + && e.styleRef.layoutStyleIndex == views::GetStyles(app, viewsContext).tableRowBarStyleRef.layoutStyleIndex) bars.push_back(e.id); return bars; } @@ -1704,14 +1706,14 @@ namespace tachyon // With selectionBar on, a selected row has an accent bar on its left, over its cells. TEST_F(TableVirtualScrollTest, ASelectedRowHasAnAccentBar) { - tachyon::TableState state; + tachyon::views::TableState state; state.selectionBar = true; app.Frame([&] { Emit(state); }); state.selectedRowID = state.RowIDInRange(3); ASSERT_NE(state.selectedRowID, tachyon::ID::Invalid()); app.Frame([&] { Emit(state); }); - const std::vector bars = SelectionBars(app); + const std::vector bars = SelectionBars(app, viewsContext); ASSERT_EQ(bars.size(), 1u) << "one bar, on the selected row"; const IntRect bar = app.GetElementRect(bars[0]); @@ -1724,31 +1726,31 @@ namespace tachyon TEST_F(TableVirtualScrollTest, TablesHaveNoSelectionBarByDefault) { - tachyon::TableState state; + tachyon::views::TableState state; app.Frame([&] { Emit(state); }); state.selectedRowID = state.RowIDInRange(3); app.Frame([&] { Emit(state); }); - EXPECT_TRUE(SelectionBars(app).empty()); + EXPECT_TRUE(SelectionBars(app, viewsContext).empty()); } // A table's own row style replaces the striped pair on every row. TEST_F(TableVirtualScrollTest, ARowStyleReplacesTheStripes) { - tachyon::TableState state; - state.rowStyle = app.theme.tableRowBarStyleRef; // any style will do + tachyon::views::TableState state; + state.rowStyle = views::GetStyles(app, viewsContext).tableRowBarStyleRef; // any style will do app.Frame([&] { Emit(state); }); for (int row : { 0, 1 }) { const auto ref = app.elementStorage.FindElementRefByID(state.RowIDInRange(row)); ASSERT_TRUE(ref.IsValid()); EXPECT_EQ(app.elementStorage.GetElementUnsafe(ref).styleRef.visualBoxStyleIndex, - app.theme.tableRowBarStyleRef.visualBoxStyleIndex) << row; + views::GetStyles(app, viewsContext).tableRowBarStyleRef.visualBoxStyleIndex) << row; } } TEST_F(TableVirtualScrollTest, AColumnSizerTakesTheHover) { - tachyon::TableState state; + tachyon::views::TableState state; app.Frame([&] { Emit(state); }); const tachyon::ID sizer = columns[0].internal.sizerID; ASSERT_TRUE(app.HasElement(sizer)); @@ -1763,7 +1765,7 @@ namespace tachyon // A column sizer runs the table's full height, not a sliver at its top. TEST_F(TableVirtualScrollTest, AColumnSizerRunsTheTablesHeight) { - tachyon::TableState state; + tachyon::views::TableState state; app.Frame([&] { Emit(state); }); app.Frame([&] { Emit(state); }); const tachyon::ID sizer = columns[0].internal.sizerID; @@ -1780,8 +1782,8 @@ namespace tachyon // Filling its panel, the table stays inside it and scrolls. TEST_F(TableVirtualScrollTest, AManyRowTableFillingItsPanelStaysInsideIt) { - tachyon::TableState state; - const IntRect table = EmitInPane(state, app.theme.tableFillStyleRef, LayoutOverride::Auto().FlexGrow(1).MinHeight(0)); + tachyon::views::TableState state; + const IntRect table = EmitInPane(state, views::GetStyles(app, viewsContext).tableFillStyleRef, LayoutOverride::Auto().FlexGrow(1).MinHeight(0)); const IntRect pane = app.GetElementRect(paneID); EXPECT_GT(table.h, 100); EXPECT_GE(table.y, pane.y); @@ -1793,26 +1795,26 @@ namespace tachyon // own ID and gets its clicks. No element shares an ID by accident. TEST_F(TableVirtualScrollTest, AWidgetInARowKeepsTheRowHoveredAndGetsItsClicks) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; std::vector buttonIDs(5); for (ID& id : buttonIDs) id = app.idManager.CreateStaticID(); int clicked = -1; - std::vector cols; + std::vector cols; cols.push_back({ .column = { .header = "Eye", .initialWidth = 60, .minWidth = 60, .maxWidth = 60, .interactiveContent = true }, .generateCell = [&](int r) { - app.Cell([&, r] { app.Button(buttonIDs[size_t(r)], "o", [&clicked, r] { clicked = r; }); }); + views::Cell(app, viewsContext, [&, r] { app.Button(buttonIDs[size_t(r)], "o", [&clicked, r] { clicked = r; }); }); }, }); cols.push_back({ .column = { .header = "Name", .initialWidth = 200, .minWidth = 60, .maxWidth = 400 }, - .generateCell = [this](int r) { char b[16]; std::snprintf(b, sizeof(b), "Row %d", r); app.Cell(b); }, + .generateCell = [this](int r) { char b[16]; std::snprintf(b, sizeof(b), "Row %d", r); views::Cell(app, viewsContext, b); }, }); auto frame = [&] { app.Frame([&] { app.BeginRootWindow(); - std::span sp(cols.data(), cols.size()); - app.VirtualTable(tableID, state, sp, int(buttonIDs.size()), 0, app.theme.tableStyleRef, + std::span sp(cols.data(), cols.size()); + views::VirtualTable(app, viewsContext, tableID, state, sp, int(buttonIDs.size()), 0, views::GetStyles(app, viewsContext).tableStyleRef, LayoutOverride{}.Size(400, 300)); app.EndRootWindow(); }); 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/controls_tooltip_test.cpp b/tests/controls_tooltip_test.cpp index e9ad8232..7fed6500 100644 --- a/tests/controls_tooltip_test.cpp +++ b/tests/controls_tooltip_test.cpp @@ -9,6 +9,8 @@ #include #include #include +#include +#include #include #include @@ -25,6 +27,8 @@ namespace tachyon { protected: HeadlessGUIApp app; + views::Context viewsContext; + color::Context colorContext; void SetUp() override { ASSERT_TRUE(app.Initialize()); } void TearDown() override { app.Cleanup(); } }; @@ -615,7 +619,7 @@ namespace tachyon color4f color{ 0.2f, 0.4f, 0.6f, 1.0f }; auto draw = [&] { app.BeginRootWindow(); - app.ColorField(fieldID, color); + color::ColorField(app, colorContext, fieldID, color); app.SetTooltip("Help text"); app.EndRootWindow(); }; @@ -678,7 +682,7 @@ namespace tachyon color4f color{ 0.2f, 0.4f, 0.6f, 1.0f }; auto draw = [&] { app.BeginRootWindow(); - app.ColorField(fieldID, color); + color::ColorField(app, colorContext, fieldID, color); if (app.BeginContextMenu()) app.MenuItem("Reset", [] {}); app.EndContextMenu(); @@ -872,15 +876,15 @@ namespace tachyon app.BeginHorizontal(app.idManager.AllocateDynamicID("indent"), app.theme.emptyHorzStyleRef, LayoutOverride{}.Width(Pixels{ 300 })); app.EndHorizontal(); gridID = app.idManager.AllocateDynamicID("grid"); - app.BeginGridView(gridID); + views::BeginGridView(app, viewsContext, gridID); cut = app.idManager.AllocateDynamicID("item"); // An icon drawn larger than it is, and a gap under it, as the showcase's files. Style item = app.styleManager.ToPixels(app.theme.gridViewItemBaseStyle); item.iconSize = 34; item.iconTextGap = 6; - app.GridViewItem(cut, GUIContent{ icon, kLongName }, ElementState::None, nullptr, + views::GridViewItem(app, viewsContext, cut, GUIContent{ icon, kLongName }, ElementState::None, nullptr, app.styleManager.Register(item, StyleUnits::Pixels), LayoutOverride{}.Size(80, 86)); - app.EndGridView(); + views::EndGridView(app, viewsContext); app.EndHorizontal(); at = itemID = cut; }); diff --git a/tests/controls_tree_list_test.cpp b/tests/controls_tree_list_test.cpp index 4335eec7..89ad2724 100644 --- a/tests/controls_tree_list_test.cpp +++ b/tests/controls_tree_list_test.cpp @@ -1,6 +1,6 @@ // Integration tests for VirtualTreeView (the flat-data tree-view widget, // backed by VirtualTable + TreeCell). Selection and scroll live on -// TableState; the widget exposes sub-range row IDs as TableState.selectedRowID +// views::TableState; the widget exposes sub-range row IDs as views::TableState.selectedRowID // - translate to the dataset (flat) index via visibleIdx. #include @@ -11,6 +11,7 @@ #include #include #include +#include namespace tachyon { @@ -22,11 +23,12 @@ namespace tachyon { protected: HeadlessGUIApp app; + views::Context viewsContext; ID treeID{}; - std::vector rows; + std::vector rows; std::vector visibleIdx; - tachyon::TableState state; + tachyon::views::TableState state; void SetUp() override { @@ -51,7 +53,7 @@ namespace tachyon }; for (int i = 0; i < n; ++i) { - tachyon::TreeViewRow row{}; + tachyon::views::TreeViewRow row{}; row.id = makeID(); row.name = "Branch"; row.depth = 0; @@ -60,21 +62,21 @@ namespace tachyon state.openRows.insert(rows.back().id); for (int c = 0; c < childrenPerNode; ++c) { - tachyon::TreeViewRow child{}; + tachyon::views::TreeViewRow child{}; child.id = makeID(); child.name = "Leaf"; child.depth = 1; rows.push_back(std::move(child)); } } - app.RebuildTreeViewIndex(rows); + views::RebuildTreeViewIndex(rows); } void RenderFrame() { app.Frame([&] { app.BeginRootWindow(); - app.VirtualTreeView( + views::VirtualTreeView(app, viewsContext, treeID, rows, visibleIdx, state, StyleRef{}, LayoutOverride{}.Size(400, 300)); app.EndRootWindow(); @@ -82,11 +84,11 @@ namespace tachyon } // Whether this view has flat row lat open, and opening or closing it. - bool IsOpen(size_t flat) const { return state.openRows.contains(TreeViewRowKey(rows[flat], flat)); } + bool IsOpen(size_t flat) const { return state.openRows.contains(views::TreeViewRowKey(rows[flat], flat)); } void SetOpen(size_t flat, bool open) { - if (open) state.openRows.insert(TreeViewRowKey(rows[flat], flat)); - else state.openRows.erase(TreeViewRowKey(rows[flat], flat)); + if (open) state.openRows.insert(views::TreeViewRowKey(rows[flat], flat)); + else state.openRows.erase(views::TreeViewRowKey(rows[flat], flat)); } // Row backdrop ID for a visible row index (usable outside a frame). @@ -165,18 +167,18 @@ namespace tachyon state.selectedRowID = RowIDAt(2); rows.erase(rows.begin()); - app.RebuildTreeViewIndex(rows); + views::RebuildTreeViewIndex(rows); RenderFrame(); EXPECT_EQ(state.selectedRowID, RowIDAt(1)) << "the row moved up one"; ASSERT_EQ(rows[1].id, third); std::swap(rows[0], rows[1]); // same positions shown, other rows in them - app.RebuildTreeViewIndex(rows); + views::RebuildTreeViewIndex(rows); RenderFrame(); EXPECT_EQ(state.selectedRowID, RowIDAt(0)); rows.erase(rows.begin()); // the selected row itself - app.RebuildTreeViewIndex(rows); + views::RebuildTreeViewIndex(rows); RenderFrame(); EXPECT_EQ(state.selectedRowID, ID::Invalid()); } @@ -199,14 +201,14 @@ namespace tachyon auto frame = [&] { app.Frame([&] { app.BeginRootWindow(); - GUIApplication::WalkTreeViewVisibility(rows, visibleIdx, state); - VirtualTableColumn cols[1]; - cols[0].column = TableColumn{ .header = {} }; + views::WalkTreeViewVisibility(rows, visibleIdx, state); + views::VirtualTableColumn cols[1]; + cols[0].column = views::TableColumn{ .header = {} }; cols[0].generateCell = [&](int row) { const size_t flat = size_t(visibleIdx[row]); - app.TreeCell(rows[flat].name, rows[flat].depth, GUIApplication::TreeViewOpenRef(rows, flat, state)); + views::TreeCell(app, viewsContext, rows[flat].name, rows[flat].depth, views::TreeViewOpenRef(rows, flat, state)); }; - app.VirtualTable(treeID, state, std::span(cols, 1), int(visibleIdx.size()), 0, + views::VirtualTable(app, viewsContext, treeID, state, std::span(cols, 1), int(visibleIdx.size()), 0, StyleRef{}, LayoutOverride{}.Size(400, 300)); app.EndRootWindow(); }); @@ -281,7 +283,7 @@ namespace tachyon { tachyon::ElementRef ref{ d, i }; if (!app.elementStorage.IsValidRef(ref)) continue; - if (app.elementStorage.GetElementUnsafe(ref).styleRef != app.theme.treeTableIconStyleRef) continue; + if (app.elementStorage.GetElementUnsafe(ref).styleRef != views::GetStyles(app, viewsContext).treeTableIconStyleRef) continue; if (const auto* rp = app.elementStorage.GetElementRectPtr(ref)) { iconRect = rp->rect; } } ASSERT_GT(iconRect.w, 0); @@ -307,11 +309,11 @@ namespace tachyon state = {}; ItemDragDropConfig dd{ .payloadType = 1 }; state.rowDragDrop = dragDrop ? &dd : nullptr; - app.m_renameSub->Cancel(); + viewsContext.rename.Cancel(); auto render = [&] { app.BeginRootWindow(); - app.VirtualTreeView(treeID, rows, visibleIdx, state, StyleRef{}, LayoutOverride{}.Size(400, 150)); + views::VirtualTreeView(app, viewsContext, treeID, rows, visibleIdx, state, StyleRef{}, LayoutOverride{}.Size(400, 150)); app.EndRootWindow(); }; app.Frame(render); @@ -326,8 +328,8 @@ namespace tachyon app.ClickAt(pt); app.Frame(render); app.Frame(render); - const bool renaming = app.m_renameSub->isActive; - app.m_renameSub->Cancel(); + const bool renaming = viewsContext.rename.isActive; + viewsContext.rename.Cancel(); return renaming; }; EXPECT_TRUE(slowReClickStartsRename(false)); @@ -364,7 +366,7 @@ namespace tachyon RenderFrame(); app.InjectMouseMove(end, MouseButtons::Left); RenderFrame(); - const TreeDropState over = app.m_treeDropState; + const views::TreeDropState over = viewsContext.treeDrop; app.InjectMouseUp(end); RenderFrame(); RenderFrame(); @@ -373,7 +375,7 @@ namespace tachyon const int h = app.GetElementRect(RowIDAt(0)).h; // An open branch's bottom: its first child's top. - TreeDropState over = dragTo(0, h - 2); + views::TreeDropState over = dragTo(0, h - 2); EXPECT_EQ(over.targetRowID, RowIDAt(1)); EXPECT_EQ(over.position, TreeDropPosition::Before); EXPECT_EQ(over.targetDepth, 1); @@ -398,11 +400,11 @@ namespace tachyon BuildFlatTree(/*n*/1, /*children*/2, /*open*/true); const ID treeIDB = app.idManager.CreateStaticID(); std::vector visibleIdxB; - TableState stateB; // nothing open + views::TableState stateB; // nothing open auto renderBoth = [&] { app.BeginRootWindow(); - app.VirtualTreeView(treeID, rows, visibleIdx, state, StyleRef{}, LayoutOverride{}.Size(400, 150)); - app.VirtualTreeView(treeIDB, rows, visibleIdxB, stateB, StyleRef{}, LayoutOverride{}.Size(400, 150)); + views::VirtualTreeView(app, viewsContext, treeID, rows, visibleIdx, state, StyleRef{}, LayoutOverride{}.Size(400, 150)); + views::VirtualTreeView(app, viewsContext, treeIDB, rows, visibleIdxB, stateB, StyleRef{}, LayoutOverride{}.Size(400, 150)); app.EndRootWindow(); }; app.Frame(renderBoth); @@ -430,7 +432,7 @@ namespace tachyon TEST_F(VirtualTreeViewTest, ARowWithoutAnIDOpensByPosition) { BuildFlatTree(/*n*/2, /*children*/1, /*open*/false); - for (TreeViewRow& r : rows) r.id = ID::Invalid(); + for (views::TreeViewRow& r : rows) r.id = ID::Invalid(); SetOpen(2, true); RenderFrame(); EXPECT_EQ(visibleIdx, (std::vector{ 0, 2, 3 })); @@ -443,9 +445,9 @@ namespace tachyon // Tree B = an independent tree view (own id / rows / state). const tachyon::ID treeIDB = app.idManager.CreateStaticID(); - std::vector rowsB; + std::vector rowsB; std::vector visibleIdxB; - tachyon::TableState stateB{}; + tachyon::views::TableState stateB{}; { int idc = 6000; auto makeID = [&] { @@ -454,21 +456,21 @@ namespace tachyon id.value.dynamicParts.hashValue = ++idc; return id; }; - tachyon::TreeViewRow branch{}; + tachyon::views::TreeViewRow branch{}; branch.id = makeID(); branch.name = "Branch"; branch.depth = 0; stateB.openRows.insert(branch.id); rowsB.push_back(std::move(branch)); - tachyon::TreeViewRow leaf{}; + tachyon::views::TreeViewRow leaf{}; leaf.id = makeID(); leaf.name = "Leaf"; leaf.depth = 1; rowsB.push_back(std::move(leaf)); - app.RebuildTreeViewIndex(rowsB); + views::RebuildTreeViewIndex(rowsB); } auto renderBoth = [&] { app.BeginRootWindow(); - app.VirtualTreeView(treeID, rows, visibleIdx, state, + views::VirtualTreeView(app, viewsContext, treeID, rows, visibleIdx, state, StyleRef{}, LayoutOverride{}.Size(400, 150)); - app.VirtualTreeView(treeIDB, rowsB, visibleIdxB, stateB, + views::VirtualTreeView(app, viewsContext, treeIDB, rowsB, visibleIdxB, stateB, StyleRef{}, LayoutOverride{}.Size(400, 150)); app.EndRootWindow(); }; diff --git a/tests/curve_editor_test.cpp b/tests/curve_editor_test.cpp index 6e6a9c4a..5f1fa937 100644 --- a/tests/curve_editor_test.cpp +++ b/tests/curve_editor_test.cpp @@ -2,6 +2,7 @@ // its playhead, the interpolation and tangent toggles, keys on frames, and no presets. #include +#include #include "headless_gui_app.h" @@ -17,8 +18,9 @@ namespace tachyon { protected: HeadlessGUIApp app; - CurveView view; - std::vector edits; + curves::Context curvesContext; + curves::CurveView view; + std::vector edits; std::vector playheads; int32_t width = 1000; // the editor's, as a panel sizes it @@ -29,15 +31,15 @@ namespace tachyon const float2 rise[] = { { 0.0f, 0.0f }, { 1.0f, 2.0f }, { 2.0f, 1.0f } }; const float2 flat[] = { { 0.0f, 0.5f }, { 2.0f, 0.5f } }; view.channels = { - CurveChannel{ .name = "X", .path = "Sphere/Position", .color = CurveChannelColor::Red, .curve = MakeCurve(rise) }, - CurveChannel{ .name = "Y", .path = "Sphere/Position", .color = CurveChannelColor::Green, .curve = MakeCurve(flat) }, - CurveChannel{ .name = "Y", .path = "Sphere/Rotation", .color = CurveChannelColor::Blue, .curve = MakeCurve(flat) } }; - for (CurveChannel& channel : view.channels) - for (CurveKey& k : channel.curve.keys) + curves::CurveChannel{ .name = "X", .path = "Sphere/Position", .color = curves::CurveChannelColor::Red, .curve = curves::MakeCurve(rise) }, + curves::CurveChannel{ .name = "Y", .path = "Sphere/Position", .color = curves::CurveChannelColor::Green, .curve = curves::MakeCurve(flat) }, + curves::CurveChannel{ .name = "Y", .path = "Sphere/Rotation", .color = curves::CurveChannelColor::Blue, .curve = curves::MakeCurve(flat) } }; + for (curves::CurveChannel& channel : view.channels) + for (curves::CurveKey& k : channel.curve.keys) k.stableID = app.idManager.CreateStaticID(); - view.range = CurveRange{ 0.0f, 2.0f, 0.0f, 2.0f }; + view.range = curves::CurveRange{ 0.0f, 2.0f, 0.0f, 2.0f }; view.fps = 24.0f; - view.onEdit = [this](const CurveEdit& edit) { edits.push_back(edit); }; + view.onEdit = [this](const curves::CurveEdit& edit) { edits.push_back(edit); }; view.onPlayheadChanged = [this](float time) { playheads.push_back(time); }; } void TearDown() override { app.Cleanup(); } @@ -46,7 +48,7 @@ namespace tachyon { app.Frame([&] { app.BeginRootWindow({ 2000, 600 }); - app.CurveEditor(view, LayoutOverride::FixedSize(Pixels{ width }, Pixels{ 600 })); // as a panel sizes it + curves::CurveEditor(app, curvesContext, view, LayoutOverride::FixedSize(Pixels{ width }, Pixels{ 600 })); // as a panel sizes it app.EndRootWindow(); }); } @@ -68,18 +70,18 @@ namespace tachyon ids.push_back(e.id); return ids; } - size_t Rows() { return AllWithStyle(app.theme.curveTreeRowStyleRef).size() + AllWithStyle(app.theme.curveTreeRowHiddenStyleRef).size(); } + size_t Rows() { return AllWithStyle(curves::GetStyles(app, curvesContext).curveTreeRowStyleRef).size() + AllWithStyle(curves::GetStyles(app, curvesContext).curveTreeRowHiddenStyleRef).size(); } - CurveRange Shown() const { return view.shownSet ? view.shown : view.range; } + curves::CurveRange Shown() const { return view.shownSet ? view.shown : view.range; } int XAt(float time) const { - const CurveRange s = Shown(); + const curves::CurveRange s = Shown(); return int(std::lround(float(view.plotRect.x) + (time - s.timeMin) / (s.timeMax - s.timeMin) * float(view.plotRect.w))); } int2 KeyAt(int k, int channel = 0) const { - const CurveRange s = Shown(); - const CurveKey& key = view.channels[size_t(channel)].curve.keys[size_t(k)]; + const curves::CurveRange s = Shown(); + const curves::CurveKey& key = view.channels[size_t(channel)].curve.keys[size_t(k)]; return { XAt(key.time), int(std::lround(float(view.plotRect.y + view.plotRect.h) - (key.value - s.valueMin) / (s.valueMax - s.valueMin) * float(view.plotRect.h))) }; } @@ -93,22 +95,22 @@ namespace tachyon TEST_F(CurveEditorTest, TheTreeGroupsTheChannelsByPath) { Frames(); - EXPECT_EQ(AllWithStyle(app.theme.curveTreeGroupStyleRef).size(), 3u) << "Sphere, Position, Rotation"; + EXPECT_EQ(AllWithStyle(curves::GetStyles(app, curvesContext).curveTreeGroupStyleRef).size(), 3u) << "Sphere, Position, Rotation"; EXPECT_EQ(app.CountByText("Sphere"), 1); EXPECT_EQ(Rows(), 3u); - EXPECT_TRUE(AllWithStyle(app.theme.curveChannelStyleRef).empty()) << "the tree in place of the chips"; + EXPECT_TRUE(AllWithStyle(curves::GetStyles(app, curvesContext).curveChannelStyleRef).empty()) << "the tree in place of the chips"; // A group's row closes it, and the channels in it go; again opens it. - const ID position = AllWithStyle(app.theme.curveTreeGroupStyleRef)[1]; + const ID position = AllWithStyle(curves::GetStyles(app, curvesContext).curveTreeGroupStyleRef)[1]; app.ClickAt(app.CenterOf(position)); Frames(); EXPECT_TRUE(view.collapsedGroups.contains("Sphere/Position")); EXPECT_EQ(Rows(), 1u); - app.ClickAt(app.CenterOf(AllWithStyle(app.theme.curveTreeGroupStyleRef)[0])); + app.ClickAt(app.CenterOf(AllWithStyle(curves::GetStyles(app, curvesContext).curveTreeGroupStyleRef)[0])); Frames(); EXPECT_EQ(Rows(), 0u) << "all under Sphere"; - EXPECT_EQ(AllWithStyle(app.theme.curveTreeGroupStyleRef).size(), 1u); - app.ClickAt(app.CenterOf(AllWithStyle(app.theme.curveTreeGroupStyleRef)[0])); + EXPECT_EQ(AllWithStyle(curves::GetStyles(app, curvesContext).curveTreeGroupStyleRef).size(), 1u); + app.ClickAt(app.CenterOf(AllWithStyle(curves::GetStyles(app, curvesContext).curveTreeGroupStyleRef)[0])); Frames(); EXPECT_EQ(Rows(), 1u) << "Position stays closed"; } @@ -116,7 +118,7 @@ namespace tachyon TEST_F(CurveEditorTest, ARowPicksItsChannelAndItsEyeHidesIt) { Frames(); - app.ClickAt(app.CenterOf(AllWithStyle(app.theme.curveTreeRowStyleRef)[2])); + app.ClickAt(app.CenterOf(AllWithStyle(curves::GetStyles(app, curvesContext).curveTreeRowStyleRef)[2])); Frames(); EXPECT_EQ(view.activeChannel, 2); @@ -130,7 +132,7 @@ namespace tachyon EXPECT_FALSE(view.channels[1].visible); EXPECT_EQ(view.activeChannel, 2) << "the eye, not its row"; EXPECT_TRUE(view.selectedKeys.empty()); - EXPECT_EQ(AllWithStyle(app.theme.curveTreeRowHiddenStyleRef).size(), 1u); + EXPECT_EQ(AllWithStyle(curves::GetStyles(app, curvesContext).curveTreeRowHiddenStyleRef).size(), 1u); } TEST_F(CurveEditorTest, TheTreeShowsTheValuesAtThePlayhead) @@ -149,7 +151,7 @@ namespace tachyon TEST_F(CurveEditorTest, TheRulerMovesThePlayheadOntoFrames) { Frames(); - const std::vector rulers = AllWithStyle(app.theme.curveRulerStyleRef); + const std::vector rulers = AllWithStyle(curves::GetStyles(app, curvesContext).curveRulerStyleRef); ASSERT_EQ(rulers.size(), 1u); const IntRect ruler = app.GetElementRect(rulers[0]); const int y = ruler.y + ruler.h / 2; @@ -215,16 +217,16 @@ namespace tachyon std::vector icons; for (const ID id : AllWithStyle(app.theme.menuItemIconStyleRef)) icons.push_back(app.ownedTextSystem.IconOf(app.elementStorage.GetElementUnsafe(app.elementStorage.FindElementRefByID(id)).textID)); - EXPECT_NE(std::find(icons.begin(), icons.end(), app.theme.curveConstantIcon), icons.end()); - EXPECT_NE(std::find(icons.begin(), icons.end(), app.theme.curveLinearIcon), icons.end()); + EXPECT_NE(std::find(icons.begin(), icons.end(), curves::GetStyles(app, curvesContext).curveConstantIcon), icons.end()); + EXPECT_NE(std::find(icons.begin(), icons.end(), curves::GetStyles(app, curvesContext).curveLinearIcon), icons.end()); clickItem("Constant"); - EXPECT_EQ(view.channels[0].curve.keys[1].interpolation, CurveInterpolation::Constant); - EXPECT_EQ(EvaluateCurve(view.channels[0].curve, 1.5f), 2.0f) << "held"; + EXPECT_EQ(view.channels[0].curve.keys[1].interpolation, curves::CurveInterpolation::Constant); + EXPECT_EQ(curves::EvaluateCurve(view.channels[0].curve, 1.5f), 2.0f) << "held"; rightClick(KeyAt(1)); clickItem("Flat"); - EXPECT_EQ(view.channels[0].curve.keys[1].tangents, CurveTangentMode::Flat); - EXPECT_EQ(view.channels[0].curve.keys[0].tangents, CurveTangentMode::Auto) << "only the selected"; + EXPECT_EQ(view.channels[0].curve.keys[1].tangents, curves::CurveTangentMode::Flat); + EXPECT_EQ(view.channels[0].curve.keys[0].tangents, curves::CurveTangentMode::Auto) << "only the selected"; EXPECT_EQ(edits.size(), 2u); } @@ -268,9 +270,9 @@ namespace tachyon TEST_F(CurveEditorTest, NoPresetsAndNoTimesUnderThePlot) { Frames(); - EXPECT_TRUE(AllWithStyle(app.theme.curvePresetStyleRef).empty()); - EXPECT_EQ(AllWithStyle(app.theme.curvePlotFramesStyleRef).size(), 1u); - EXPECT_TRUE(AllWithStyle(app.theme.curvePlotStyleRef).empty()); + EXPECT_TRUE(AllWithStyle(curves::GetStyles(app, curvesContext).curvePresetStyleRef).empty()); + EXPECT_EQ(AllWithStyle(curves::GetStyles(app, curvesContext).curvePlotFramesStyleRef).size(), 1u); + EXPECT_TRUE(AllWithStyle(curves::GetStyles(app, curvesContext).curvePlotStyleRef).empty()); } // Frame all sizes to its icon and text, whatever room the toolbar has. @@ -290,7 +292,7 @@ namespace tachyon TEST_F(CurveEditorTest, FrameAllIsAFlatButton) { Frames(); - const std::vector buttons = AllWithStyle(app.theme.curveFrameAllStyleRef); + const std::vector buttons = AllWithStyle(curves::GetStyles(app, curvesContext).curveFrameAllStyleRef); ASSERT_EQ(buttons.size(), 1u); EXPECT_EQ(buttons[0], app.FindByText("Frame all")); EXPECT_EQ(app.FindByText("A"), ID::Invalid()) << "no shortcut on the toolbar"; @@ -299,7 +301,7 @@ namespace tachyon ASSERT_NE(visual, nullptr); EXPECT_EQ(visual->iconTextGap, app.styleManager.Px(6)); - view.shown = CurveRange{ 0.5f, 1.0f, 0.5f, 1.0f }; + view.shown = curves::CurveRange{ 0.5f, 1.0f, 0.5f, 1.0f }; view.shownSet = true; app.ClickAt(app.CenterOf(buttons[0])); Frames(); @@ -311,7 +313,7 @@ namespace tachyon TEST_F(CurveEditorTest, TheBarKeepsItsHeightWithAKeySelected) { Frames(); - const std::vector bars = AllWithStyle(app.theme.curveToolbarStyleRef); + const std::vector bars = AllWithStyle(curves::GetStyles(app, curvesContext).curveToolbarStyleRef); ASSERT_FALSE(bars.empty()); const int32_t empty = app.GetElementRect(bars[0]).h; view.selectedKeys = { KeyID(1) }; @@ -328,16 +330,16 @@ namespace tachyon { view.fps = 0.0f; Frames(); - EXPECT_FALSE(AllWithStyle(app.theme.curveTreeStyleRef).empty()); - EXPECT_TRUE(AllWithStyle(app.theme.curveChannelStyleRef).empty()); - EXPECT_TRUE(AllWithStyle(app.theme.curveRulerStyleRef).empty()); + EXPECT_FALSE(AllWithStyle(curves::GetStyles(app, curvesContext).curveTreeStyleRef).empty()); + EXPECT_TRUE(AllWithStyle(curves::GetStyles(app, curvesContext).curveChannelStyleRef).empty()); + EXPECT_TRUE(AllWithStyle(curves::GetStyles(app, curvesContext).curveRulerStyleRef).empty()); } // A row stays hovered over all of it: its name, value and eye too, not only between them. TEST_F(CurveEditorTest, ARowIsHoveredOverItsLabels) { Frames(); - const ID row = AllWithStyle(app.theme.curveTreeRowStyleRef)[0]; + const ID row = AllWithStyle(curves::GetStyles(app, curvesContext).curveTreeRowStyleRef)[0]; const IntRect r = app.GetElementRect(row); for (int x = r.x + 4; x < r.x + r.w; x += 16) { @@ -352,13 +354,13 @@ namespace tachyon TEST_F(CurveEditorTest, WithoutFpsOrPathsItsTheFieldsEditor) { view.fps = 0.0f; - for (CurveChannel& channel : view.channels) + for (curves::CurveChannel& channel : view.channels) channel.path.clear(); Frames(); - EXPECT_TRUE(AllWithStyle(app.theme.curveTreeStyleRef).empty()); - EXPECT_TRUE(AllWithStyle(app.theme.curveRulerStyleRef).empty()); - EXPECT_EQ(AllWithStyle(app.theme.curveChannelStyleRef).size(), 3u); - EXPECT_FALSE(AllWithStyle(app.theme.curvePresetStyleRef).empty()); + EXPECT_TRUE(AllWithStyle(curves::GetStyles(app, curvesContext).curveTreeStyleRef).empty()); + EXPECT_TRUE(AllWithStyle(curves::GetStyles(app, curvesContext).curveRulerStyleRef).empty()); + EXPECT_EQ(AllWithStyle(curves::GetStyles(app, curvesContext).curveChannelStyleRef).size(), 3u); + EXPECT_FALSE(AllWithStyle(curves::GetStyles(app, curvesContext).curvePresetStyleRef).empty()); } } } diff --git a/tests/curve_field_test.cpp b/tests/curve_field_test.cpp index b273bc3c..ba4b26e3 100644 --- a/tests/curve_field_test.cpp +++ b/tests/curve_field_test.cpp @@ -2,6 +2,7 @@ // tangent handles, the keys, the wheel, the channels, the presets and the menu. #include +#include #include "gpu/allocation_count.h" #include "headless_gui_app.h" @@ -19,9 +20,10 @@ namespace tachyon { protected: HeadlessGUIApp app; - CurveView view; + curves::Context curvesContext; + curves::CurveView view; ID fieldID {}; - std::vector edits; + std::vector edits; bool returned = false; void SetUp() override @@ -30,10 +32,10 @@ namespace tachyon app.runPostLayoutCallbacks = true; // the editor keeps where its plot is fieldID = app.idManager.CreateStaticID(); const float2 points[] = { { 0.0f, 0.0f }, { 0.5f, 0.5f }, { 1.0f, 1.0f } }; - view.channels = { CurveChannel{ .name = "Value", .curve = MakeCurve(points) } }; - for (CurveKey& k : view.channels[0].curve.keys) + view.channels = { curves::CurveChannel{ .name = "Value", .curve = curves::MakeCurve(points) } }; + for (curves::CurveKey& k : view.channels[0].curve.keys) k.stableID = app.idManager.CreateStaticID(); - view.onEdit = [this](const CurveEdit& edit) { edits.push_back(edit); }; + view.onEdit = [this](const curves::CurveEdit& edit) { edits.push_back(edit); }; } void TearDown() override { app.Cleanup(); } @@ -41,7 +43,7 @@ namespace tachyon { app.Frame([&] { app.BeginRootWindow({ 1000, 800 }); - returned = app.CurveField(fieldID, view, LayoutOverride::FixedWidth(200)); + returned = curves::CurveField(app, curvesContext, fieldID, view, LayoutOverride::FixedWidth(200)); app.EndRootWindow(); }); } @@ -79,31 +81,31 @@ namespace tachyon return ids; } - CurveRange Shown() const { return view.shownSet ? view.shown : view.range; } + curves::CurveRange Shown() const { return view.shownSet ? view.shown : view.range; } // Where a time and value are on the plot, in pixels. int2 At(float time, float value) const { - const CurveRange s = Shown(); + const curves::CurveRange s = Shown(); const IntRect r = view.plotRect; return { int32_t(std::lround(float(r.x) + (time - s.timeMin) / (s.timeMax - s.timeMin) * float(r.w))), int32_t(std::lround(float(r.y + r.h) - (value - s.valueMin) / (s.valueMax - s.valueMin) * float(r.h))) }; } int2 KeyAt(int k, int channel = 0) const { - const CurveKey& key = view.channels[size_t(channel)].curve.keys[size_t(k)]; + const curves::CurveKey& key = view.channels[size_t(channel)].curve.keys[size_t(k)]; return At(key.time, key.value); } float TimeAt(int x) const { - const CurveRange s = Shown(); + const curves::CurveRange s = Shown(); return s.timeMin + float(x - view.plotRect.x) / float(view.plotRect.w) * (s.timeMax - s.timeMin); } // The end of a key's handle on a side. int2 HandleAt(int k, bool out) { - const CurveKey& key = view.channels[0].curve.keys[size_t(k)]; - const CurveRange s = Shown(); + const curves::CurveKey& key = view.channels[0].curve.keys[size_t(k)]; + const curves::CurveRange s = Shown(); const float sx = float(view.plotRect.w) / (s.timeMax - s.timeMin), sy = float(view.plotRect.h) / (s.valueMax - s.valueMin); const float slope = out ? key.outSlope : key.inSlope; float dx = 1.0f, dy = -slope * sy / sx; @@ -170,17 +172,17 @@ namespace tachyon TEST_F(CurveFieldTest, AClickOpensTheEditorAndAnotherClosesIt) { Frame(); - EXPECT_EQ(FindByStyle(app.theme.curvePlotStyleRef), ID::Invalid()); + EXPECT_EQ(FindByStyle(curves::GetStyles(app, curvesContext).curvePlotStyleRef), ID::Invalid()); app.ClickAt(app.CenterOf(fieldID)); Frame(); Frame(); EXPECT_TRUE(view.popupOpen); - EXPECT_NE(FindByStyle(app.theme.curvePlotStyleRef), ID::Invalid()); + EXPECT_NE(FindByStyle(curves::GetStyles(app, curvesContext).curvePlotStyleRef), ID::Invalid()); app.ClickAt(app.CenterOf(fieldID)); Frame(); Frame(); EXPECT_FALSE(view.popupOpen); - EXPECT_EQ(FindByStyle(app.theme.curvePlotStyleRef), ID::Invalid()); + EXPECT_EQ(FindByStyle(curves::GetStyles(app, curvesContext).curvePlotStyleRef), ID::Invalid()); } TEST_F(CurveFieldTest, EscapeClosesTheEditor) @@ -198,7 +200,7 @@ namespace tachyon { Frame(); EXPECT_FALSE(returned); - CommitCurveEdit(view, SetCurveWrapEdit(view, 0, CurveWrapMode::Loop, CurveWrapMode::Loop)); + curves::CommitCurveEdit(view, curves::SetCurveWrapEdit(view, 0, curves::CurveWrapMode::Loop, curves::CurveWrapMode::Loop)); Frame(); EXPECT_TRUE(returned); Frame(); @@ -211,7 +213,7 @@ namespace tachyon app.Frame([&] { app.BeginRootWindow({ 1000, 800 }); app.BeginDisabled(); - app.CurveField(fieldID, view, LayoutOverride::FixedWidth(200)); + curves::CurveField(app, curvesContext, fieldID, view, LayoutOverride::FixedWidth(200)); app.EndDisabled(); app.EndRootWindow(); }); @@ -255,7 +257,7 @@ namespace tachyon { Open(); Drag(KeyAt(1), At(0.6f, 0.3f)); - const CurveKey& k = view.channels[0].curve.keys[1]; + const curves::CurveKey& k = view.channels[0].curve.keys[1]; EXPECT_NEAR(k.time, 0.6f, 0.02f); EXPECT_NEAR(k.value, 0.3f, 0.02f); ASSERT_EQ(edits.size(), 1u); @@ -279,8 +281,8 @@ namespace tachyon TEST_F(CurveFieldTest, TheActiveChannelsKeyComesFirst) { const float2 points[] = { { 0.0f, 0.2f }, { 0.5f, 0.5f }, { 1.0f, 0.2f } }; - view.channels.push_back(CurveChannel{ .name = "G", .color = CurveChannelColor::Green, .curve = MakeCurve(points) }); - for (CurveKey& k : view.channels[1].curve.keys) + view.channels.push_back(curves::CurveChannel{ .name = "G", .color = curves::CurveChannelColor::Green, .curve = curves::MakeCurve(points) }); + for (curves::CurveKey& k : view.channels[1].curve.keys) k.stableID = app.idManager.CreateStaticID(); view.activeChannel = 1; Open(); @@ -302,7 +304,7 @@ namespace tachyon const ID dragged = KeyID(1); Drag(KeyAt(1), { view.plotRect.x + view.plotRect.w + 200, view.plotRect.y - 200 }); const auto& keys = view.channels[0].curve.keys; - const auto k = std::find_if(keys.begin(), keys.end(), [dragged](const CurveKey& key) { return key.stableID == dragged; }); + const auto k = std::find_if(keys.begin(), keys.end(), [dragged](const curves::CurveKey& key) { return key.stableID == dragged; }); ASSERT_NE(k, keys.end()); EXPECT_EQ(k->time, 1.0f); EXPECT_EQ(k->value, 1.0f); @@ -311,7 +313,7 @@ namespace tachyon TEST_F(CurveFieldTest, EscapePutsADraggedKeyBack) { Open(); - const Curve before = view.channels[0].curve; + const curves::Curve before = view.channels[0].curve; const int2 from = KeyAt(1), to = At(0.7f, 0.1f); app.InjectMouseMove(from); app.InjectMouseDown(from); @@ -354,23 +356,23 @@ namespace tachyon app.ClickAt(at); Frame(); ASSERT_EQ(view.channels[0].curve.keys.size(), 4u); - const CurveKey& added = view.channels[0].curve.keys[1]; + const curves::CurveKey& added = view.channels[0].curve.keys[1]; EXPECT_NEAR(added.time, 0.25f, 0.01f); EXPECT_NEAR(added.value, 0.8f, 0.01f); EXPECT_EQ(view.selectedKeys, std::unordered_set{ added.stableID }); EXPECT_EQ(edits.size(), 1u); // Near the curve: on it. - const Curve before = view.channels[0].curve; - const float onCurve = EvaluateCurve(before, 0.8f); + const curves::Curve before = view.channels[0].curve; + const float onCurve = curves::EvaluateCurve(before, 0.8f); const int2 near = At(0.8f, onCurve); app.ClickAt({ near.x, near.y + 3 }); Frame(); app.ClickAt({ near.x, near.y + 3 }); Frame(); ASSERT_EQ(view.channels[0].curve.keys.size(), 5u); - const CurveKey& onIt = view.channels[0].curve.keys[3]; - EXPECT_NEAR(onIt.value, EvaluateCurve(before, onIt.time), 1e-5f); + const curves::CurveKey& onIt = view.channels[0].curve.keys[3]; + EXPECT_NEAR(onIt.value, curves::EvaluateCurve(before, onIt.time), 1e-5f); } TEST_F(CurveFieldTest, ABoxSelects) @@ -421,19 +423,19 @@ namespace tachyon Frame(); const int2 handle = HandleAt(1, true); Drag(handle, { handle.x, handle.y - 40 }); - const CurveKey& k = view.channels[0].curve.keys[1]; - EXPECT_EQ(k.tangents, CurveTangentMode::Aligned); + const curves::CurveKey& k = view.channels[0].curve.keys[1]; + EXPECT_EQ(k.tangents, curves::CurveTangentMode::Aligned); EXPECT_GT(k.outSlope, 1.5f); EXPECT_EQ(k.inSlope, k.outSlope); ASSERT_EQ(edits.size(), 1u); - view.channels[0].curve.keys[1].tangents = CurveTangentMode::Free; + view.channels[0].curve.keys[1].tangents = curves::CurveTangentMode::Free; const float out = k.outSlope; const int2 in = HandleAt(1, false); Drag(in, { in.x, in.y + 30 }); EXPECT_EQ(view.channels[0].curve.keys[1].outSlope, out) << "the other side stays"; EXPECT_NE(view.channels[0].curve.keys[1].inSlope, out); - EXPECT_EQ(view.channels[0].curve.keys[1].tangents, CurveTangentMode::Free); + EXPECT_EQ(view.channels[0].curve.keys[1].tangents, curves::CurveTangentMode::Free); } // The key or handle under the pointer is the hovered one, for its hover look; none over @@ -463,15 +465,15 @@ namespace tachyon TEST_F(CurveFieldTest, TheCurveUnderThePointerIsHovered) { const float2 flat[] = { { 0.0f, 0.2f }, { 1.0f, 0.2f } }; - view.channels.push_back(CurveChannel{ .name = "G", .color = CurveChannelColor::Green, .curve = MakeCurve(flat) }); - for (CurveKey& k : view.channels[1].curve.keys) + view.channels.push_back(curves::CurveChannel{ .name = "G", .color = curves::CurveChannelColor::Green, .curve = curves::MakeCurve(flat) }); + for (curves::CurveKey& k : view.channels[1].curve.keys) k.stableID = app.idManager.CreateStaticID(); view.activeChannel = 0; Open(); app.InjectMouseMove(At(0.7f, 0.2f)); Frame(); EXPECT_EQ(view.hover.part.channel, 1); - app.InjectMouseMove(At(0.3f, EvaluateCurve(view.channels[0].curve, 0.3f))); + app.InjectMouseMove(At(0.3f, curves::EvaluateCurve(view.channels[0].curve, 0.3f))); Frame(); EXPECT_EQ(view.hover.part.channel, 0) << "the diagonal"; app.InjectMouseMove(At(0.2f, 0.9f)); @@ -491,8 +493,8 @@ namespace tachyon // Constant one. TEST_F(CurveFieldTest, NoHandlesOnStraightOrSteppedSides) { - view.channels[0].curve.keys[1].interpolation = CurveInterpolation::Linear; - view.channels[0].curve.keys[0].interpolation = CurveInterpolation::Constant; + view.channels[0].curve.keys[1].interpolation = curves::CurveInterpolation::Linear; + view.channels[0].curve.keys[0].interpolation = curves::CurveInterpolation::Constant; Open(); for (const bool out : { true, false }) { @@ -501,7 +503,7 @@ namespace tachyon ASSERT_TRUE(view.selectedKeys.contains(KeyID(1))); const int2 handle = HandleAt(1, out); Drag(handle, { handle.x, handle.y - 40 }); - EXPECT_EQ(view.channels[0].curve.keys[1].tangents, CurveTangentMode::Auto) << (out ? "out" : "in"); + EXPECT_EQ(view.channels[0].curve.keys[1].tangents, curves::CurveTangentMode::Auto) << (out ? "out" : "in"); } } @@ -524,26 +526,26 @@ namespace tachyon Frame(); EXPECT_GT(view.shown.timeMax - view.shown.timeMin, 1.0f) << "out"; - const CurveRange before = view.shown; + const curves::CurveRange before = view.shown; app.InjectMouseScroll(center, { 0, 1 }, KeyModifier::Alt); Frame(); EXPECT_EQ(view.shown.valueMin, before.valueMin) << "Alt: the time only"; EXPECT_LT(view.shown.timeMax - view.shown.timeMin, before.timeMax - before.timeMin); - const CurveRange zoomed = view.shown; + const curves::CurveRange zoomed = view.shown; app.InjectMouseScroll(center, { 0, -1 }, KeyModifier::Shift); Frame(); EXPECT_GT(view.shown.timeMin, zoomed.timeMin) << "Shift scrolls along the time"; EXPECT_FLOAT_EQ(view.shown.timeMax - view.shown.timeMin, zoomed.timeMax - zoomed.timeMin) << "no zoom"; - const CurveRange panned = view.shown; + const curves::CurveRange panned = view.shown; Drag(center, { center.x - 50, center.y + 40 }, MouseButtons::Middle); EXPECT_GT(view.shown.timeMin, panned.timeMin) << "dragged left: later times"; EXPECT_GT(view.shown.valueMin, panned.valueMin) << "dragged down: higher values"; EXPECT_TRUE(edits.empty()); // Alt + left drags it too, and leaves the keys alone. - const CurveRange again = view.shown; + const curves::CurveRange again = view.shown; app.InjectMouseMove(center, MouseButtons::None, KeyModifier::Alt); app.InjectMouseDown(center, MouseButtons::Left, KeyModifier::Alt); Frame(); @@ -583,11 +585,11 @@ namespace tachyon TEST_F(CurveFieldTest, ChannelsPickAndHide) { const float2 flat[] = { { 0.0f, 0.2f }, { 1.0f, 0.2f } }; - view.channels.push_back(CurveChannel{ .name = "G", .color = CurveChannelColor::Green, .curve = MakeCurve(flat) }); - for (CurveKey& k : view.channels[1].curve.keys) + view.channels.push_back(curves::CurveChannel{ .name = "G", .color = curves::CurveChannelColor::Green, .curve = curves::MakeCurve(flat) }); + for (curves::CurveKey& k : view.channels[1].curve.keys) k.stableID = app.idManager.CreateStaticID(); Open(); - const std::vector chips = AllWithStyle(app.theme.curveChannelStyleRef); + const std::vector chips = AllWithStyle(curves::GetStyles(app, curvesContext).curveChannelStyleRef); ASSERT_EQ(chips.size(), 2u); app.ClickAt(app.CenterOf(chips[1])); Frame(); @@ -611,28 +613,28 @@ namespace tachyon app.ClickAt(KeyAt(0, 1)); Frame(); EXPECT_FALSE(view.selectedKeys.contains(KeyID(0, 1))); - EXPECT_TRUE(AddCurveKeyEdit(view, 1, 0.5f, 0.5f, app.idManager.CreateStaticID()).empty()); + EXPECT_TRUE(curves::AddCurveKeyEdit(view, 1, 0.5f, 0.5f, app.idManager.CreateStaticID()).empty()); } TEST_F(CurveFieldTest, APresetReplacesTheActiveCurve) { Open(); - const std::vector presets = AllWithStyle(app.theme.curvePresetStyleRef); - ASSERT_EQ(presets.size(), DefaultCurvePresets().size()); + const std::vector presets = AllWithStyle(curves::GetStyles(app, curvesContext).curvePresetStyleRef); + ASSERT_EQ(presets.size(), curves::DefaultCurvePresets().size()); app.ClickAt(app.CenterOf(presets[0])); // constant Frame(); ASSERT_EQ(edits.size(), 1u); EXPECT_EQ(view.channels[0].curve.keys.size(), 2u); - EXPECT_EQ(EvaluateCurve(view.channels[0].curve, 0.3f), 1.0f); + EXPECT_EQ(curves::EvaluateCurve(view.channels[0].curve, 0.3f), 1.0f); - view.presets = { CurvePreset{ .name = "Mine", .curve = DefaultCurvePresets()[2].curve } }; + view.presets = { curves::CurvePreset{ .name = "Mine", .curve = curves::DefaultCurvePresets()[2].curve } }; Frame(); Frame(); - const std::vector own = AllWithStyle(app.theme.curvePresetStyleRef); + const std::vector own = AllWithStyle(curves::GetStyles(app, curvesContext).curvePresetStyleRef); ASSERT_EQ(own.size(), 1u) << "the app's own in place of the built-in ones"; app.ClickAt(app.CenterOf(own[0])); Frame(); - EXPECT_FLOAT_EQ(EvaluateCurve(view.channels[0].curve, 0.25f), 0.75f); + EXPECT_FLOAT_EQ(curves::EvaluateCurve(view.channels[0].curve, 0.25f), 0.75f); } // The presets are drawn from the view's list each frame, not copied (names and keys) @@ -645,8 +647,8 @@ namespace tachyon const auto allocationsAFrame = [&](int count) { view.presets.clear(); for (int p = 0; p < count; ++p) - view.presets.push_back(CurvePreset{ .name = "A preset with a long name " + std::to_string(p), - .curve = DefaultCurvePresets()[size_t(p) % DefaultCurvePresets().size()].curve }); + view.presets.push_back(curves::CurvePreset{ .name = "A preset with a long name " + std::to_string(p), + .curve = curves::DefaultCurvePresets()[size_t(p) % curves::DefaultCurvePresets().size()].curve }); for (int i = 0; i < 4; ++i) Frame(); AllocationCount::ScopedAllocationCount allocations; @@ -667,12 +669,12 @@ namespace tachyon EXPECT_EQ(view.menuKey, KeyID(1)); EXPECT_EQ(view.selectedKeys, std::unordered_set{ KeyID(1) }); ClickMenuItem("Flat"); - EXPECT_EQ(view.channels[0].curve.keys[1].tangents, CurveTangentMode::Flat); + EXPECT_EQ(view.channels[0].curve.keys[1].tangents, curves::CurveTangentMode::Flat); EXPECT_EQ(view.channels[0].curve.keys[1].outSlope, 0.0f); RightClick(key); ClickMenuItem("Linear"); - EXPECT_EQ(view.channels[0].curve.keys[1].interpolation, CurveInterpolation::Linear) << "to the next key, straight"; + EXPECT_EQ(view.channels[0].curve.keys[1].interpolation, curves::CurveInterpolation::Linear) << "to the next key, straight"; RightClick(key); ClickMenuItem("Delete key"); @@ -731,7 +733,7 @@ namespace tachyon Frame(); Frame(); const auto& keys = view.channels[0].curve.keys; - const auto it = std::find_if(keys.begin(), keys.end(), [key](const CurveKey& k) { return k.stableID == key; }); + const auto it = std::find_if(keys.begin(), keys.end(), [key](const curves::CurveKey& k) { return k.stableID == key; }); ASSERT_NE(it, keys.end()); EXPECT_GT(it->time, 0.0f) << "moved"; EXPECT_LE(it->time, 1.0f) << "in the range"; diff --git a/tests/curve_plot_two_views_test.cpp b/tests/curve_plot_two_views_test.cpp index a7b9335e..f1a75ddc 100644 --- a/tests/curve_plot_two_views_test.cpp +++ b/tests/curve_plot_two_views_test.cpp @@ -1,5 +1,5 @@ -// Curves and a plot, each shown in two places: a CurveData (PlotData) and a CurveViewState -// (PlotViewState) for each view of it. Each view zooms, selects and opens its editor on its +// Curves and a plot, each shown in two places: a curves::CurveData (curves::PlotData) and a curves::CurveViewState +// (curves::PlotViewState) for each view of it. Each view zooms, selects and opens its editor on its // own; an edit made in one shows in both. #include @@ -7,7 +7,8 @@ #include "headless_gui_app.h" #include "misuse_reports.h" -#include +#include +#include namespace tachyon { @@ -19,8 +20,9 @@ namespace tachyon { protected: HeadlessGUIApp app; - CurveData data; - CurveViewState left, right; + curves::Context curvesContext; + curves::CurveData data; + curves::CurveViewState left, right; ID middleKey{}, leftField{}, rightField{}; void SetUp() override @@ -28,8 +30,8 @@ namespace tachyon ASSERT_TRUE(app.Initialize()); app.runPostLayoutCallbacks = true; // the editors keep where their plots are const float2 rise[] = { { 0.0f, 0.0f }, { 0.5f, 1.0f }, { 1.0f, 0.5f } }; - data.channels = { CurveChannel{ .name = "X", .curve = MakeCurve(rise) } }; - for (CurveKey& k : data.channels[0].curve.keys) + data.channels = { curves::CurveChannel{ .name = "X", .curve = curves::MakeCurve(rise) } }; + for (curves::CurveKey& k : data.channels[0].curve.keys) k.stableID = app.idManager.CreateStaticID(); middleKey = data.channels[0].curve.keys[1].stableID; leftField = app.idManager.CreateStaticID(); @@ -46,13 +48,13 @@ namespace tachyon LayoutOverride::Auto().FlexGrow(1)); if (fields) { - app.CurveField(leftField, { data, left }, LayoutOverride::FixedSize(Pixels{ 200 }, Pixels{ 40 })); - app.CurveField(rightField, { data, right }, LayoutOverride::FixedSize(Pixels{ 200 }, Pixels{ 40 })); + curves::CurveField(app, curvesContext, leftField, { data, left }, LayoutOverride::FixedSize(Pixels{ 200 }, Pixels{ 40 })); + curves::CurveField(app, curvesContext, rightField, { data, right }, LayoutOverride::FixedSize(Pixels{ 200 }, Pixels{ 40 })); } else { - app.CurveEditor({ data, left }, LayoutOverride::FixedSize(Pixels{ 900 }, Pixels{ 600 })); - app.CurveEditor({ data, right }, LayoutOverride::FixedSize(Pixels{ 900 }, Pixels{ 600 })); + curves::CurveEditor(app, curvesContext, { data, left }, LayoutOverride::FixedSize(Pixels{ 900 }, Pixels{ 600 })); + curves::CurveEditor(app, curvesContext, { data, right }, LayoutOverride::FixedSize(Pixels{ 900 }, Pixels{ 600 })); } app.EndHorizontal(); app.EndRootWindow(); @@ -78,7 +80,7 @@ namespace tachyon TEST_F(CurveTwoViewsTest, EachEditorZoomsOnItsOwn) { Frames(); - const CurveRange leftBefore = left.shown, rightBefore = right.shown; + const curves::CurveRange leftBefore = left.shown, rightBefore = right.shown; app.InjectMouseScroll(Middle(left.plotRect), { 0, 2 }); Frames(); EXPECT_NE(left.shown, leftBefore) << "zoomed"; @@ -90,7 +92,7 @@ namespace tachyon { left.selectedKeys = right.selectedKeys = { middleKey }; Frames(); - CommitCurveEdit({ data, left }, DeleteSelectedCurveKeysEdit({ data, left })); + curves::CommitCurveEdit({ data, left }, curves::DeleteSelectedCurveKeysEdit({ data, left })); EXPECT_TRUE(left.selectedKeys.empty()) << "the view it was made through, at once"; EXPECT_EQ(right.selectedKeys.size(), 1u) << "the other, not before it builds"; Frames(); @@ -114,15 +116,16 @@ namespace tachyon { protected: HeadlessGUIApp app; - PlotData data; - PlotViewState left, right; + curves::Context curvesContext; + curves::PlotData data; + curves::PlotViewState left, right; void SetUp() override { ASSERT_TRUE(app.Initialize()); app.runPostLayoutCallbacks = true; // the plots keep where they are - data.series = { PlotSeries{ .name = "R", .values = { 1, 4, 2, 8, 5, 7, 3, 6 } }, - PlotSeries{ .name = "G", .values = { 2, 1, 6, 3, 7, 2, 5, 4 } } }; + data.series = { curves::PlotSeries{ .name = "R", .values = { 1, 4, 2, 8, 5, 7, 3, 6 } }, + curves::PlotSeries{ .name = "G", .values = { 2, 1, 6, 3, 7, 2, 5, 4 } } }; data.handles = { { "Black", 0.0f }, { "White", 1.0f } }; } void TearDown() override { app.Cleanup(); } @@ -133,8 +136,8 @@ namespace tachyon app.BeginRootWindow({ 2000, 700 }); app.BeginHorizontal(app.idManager.AllocateDynamicID("views"), app.theme.flexFillRowStyleRef, LayoutOverride::Auto().FlexGrow(1)); - app.Plot({ data, left }, LayoutOverride::FixedSize(Pixels{ 900 }, Pixels{ 400 })); - app.Plot({ data, right }, LayoutOverride::FixedSize(Pixels{ 900 }, Pixels{ 400 })); + curves::Plot(app, curvesContext, { data, left }, LayoutOverride::FixedSize(Pixels{ 900 }, Pixels{ 400 })); + curves::Plot(app, curvesContext, { data, right }, LayoutOverride::FixedSize(Pixels{ 900 }, Pixels{ 400 })); app.EndHorizontal(); app.EndRootWindow(); }); @@ -161,15 +164,15 @@ namespace tachyon TEST_F(PlotTwoViewsTest, AHandleMovedInOneIsMovedInBoth) { Frames(); - CommitPlotEdit({ data, left }, MovePlotHandleEdit(data, 0, 0.25f)); + curves::CommitPlotEdit({ data, left }, curves::MovePlotHandleEdit(data, 0, 0.25f)); EXPECT_FLOAT_EQ(data.handles[0].x, 0.25f); bool leftReports = false, rightReports = false; app.Frame([&] { app.BeginRootWindow({ 2000, 700 }); app.BeginHorizontal(app.idManager.AllocateDynamicID("views"), app.theme.flexFillRowStyleRef, LayoutOverride::Auto().FlexGrow(1)); - leftReports = app.Plot({ data, left }, LayoutOverride::FixedSize(Pixels{ 900 }, Pixels{ 400 })); - rightReports = app.Plot({ data, right }, LayoutOverride::FixedSize(Pixels{ 900 }, Pixels{ 400 })); + leftReports = curves::Plot(app, curvesContext, { data, left }, LayoutOverride::FixedSize(Pixels{ 900 }, Pixels{ 400 })); + rightReports = curves::Plot(app, curvesContext, { data, right }, LayoutOverride::FixedSize(Pixels{ 900 }, Pixels{ 400 })); app.EndHorizontal(); app.EndRootWindow(); }); diff --git a/tests/curve_test.cpp b/tests/curve_test.cpp index 9384e358..803f8596 100644 --- a/tests/curve_test.cpp +++ b/tests/curve_test.cpp @@ -3,7 +3,8 @@ #include -#include +#include +#include #include #include @@ -20,20 +21,20 @@ namespace tachyon return id; } - CurveKey Key(float time, float value, CurveTangentMode mode = CurveTangentMode::Auto, uint32_t id = 0) + curves::CurveKey Key(float time, float value, curves::CurveTangentMode mode = curves::CurveTangentMode::Auto, uint32_t id = 0) { - return CurveKey{ .stableID = id ? Id(id) : ID::Invalid(), .time = time, .value = value, .tangents = mode }; + return curves::CurveKey{ .stableID = id ? Id(id) : ID::Invalid(), .time = time, .value = value, .tangents = mode }; } - CurveKey Linear(float time, float value) + curves::CurveKey Linear(float time, float value) { - return CurveKey{ .time = time, .value = value, .interpolation = CurveInterpolation::Linear }; + return curves::CurveKey{ .time = time, .value = value, .interpolation = curves::CurveInterpolation::Linear }; } - Curve Updated(std::vector keys) + curves::Curve Updated(std::vector keys) { - Curve curve{ .keys = std::move(keys) }; - UpdateCurveTangents(curve); + curves::Curve curve{ .keys = std::move(keys) }; + curves::UpdateCurveTangents(curve); return curve; } @@ -43,89 +44,89 @@ namespace tachyon TEST(Curve, NoKeysIsZeroAndOneKeyIsItsValue) { - EXPECT_EQ(EvaluateCurve(Curve{}, 0.5f), 0.0f); - const Curve one = Updated({ Key(0.3f, 0.7f) }); - EXPECT_EQ(EvaluateCurve(one, -10.0f), 0.7f); - EXPECT_EQ(EvaluateCurve(one, 0.3f), 0.7f); - EXPECT_EQ(EvaluateCurve(one, 10.0f), 0.7f); + EXPECT_EQ(curves::EvaluateCurve(curves::Curve{}, 0.5f), 0.0f); + const curves::Curve one = Updated({ Key(0.3f, 0.7f) }); + EXPECT_EQ(curves::EvaluateCurve(one, -10.0f), 0.7f); + EXPECT_EQ(curves::EvaluateCurve(one, 0.3f), 0.7f); + EXPECT_EQ(curves::EvaluateCurve(one, 10.0f), 0.7f); } // Linear goes straight to the next key, whatever the keys' slopes; the keys' own values // are hit exactly. TEST(Curve, LinearIsStraight) { - CurveKey a = Linear(0.0f, 0.0f); - a.tangents = CurveTangentMode::Free; + curves::CurveKey a = Linear(0.0f, 0.0f); + a.tangents = curves::CurveTangentMode::Free; a.outSlope = 9.0f; - const Curve curve = Updated({ a, Linear(1.0f, 2.0f), Linear(3.0f, 0.0f) }); - EXPECT_FLOAT_EQ(EvaluateCurve(curve, 0.0f), 0.0f); - EXPECT_FLOAT_EQ(EvaluateCurve(curve, 0.25f), 0.5f) << "the slope doesn't bend it"; - EXPECT_FLOAT_EQ(EvaluateCurve(curve, 1.0f), 2.0f); - EXPECT_FLOAT_EQ(EvaluateCurve(curve, 2.0f), 1.0f); - EXPECT_FLOAT_EQ(EvaluateCurve(curve, 3.0f), 0.0f); + const curves::Curve curve = Updated({ a, Linear(1.0f, 2.0f), Linear(3.0f, 0.0f) }); + EXPECT_FLOAT_EQ(curves::EvaluateCurve(curve, 0.0f), 0.0f); + EXPECT_FLOAT_EQ(curves::EvaluateCurve(curve, 0.25f), 0.5f) << "the slope doesn't bend it"; + EXPECT_FLOAT_EQ(curves::EvaluateCurve(curve, 1.0f), 2.0f); + EXPECT_FLOAT_EQ(curves::EvaluateCurve(curve, 2.0f), 1.0f); + EXPECT_FLOAT_EQ(curves::EvaluateCurve(curve, 3.0f), 0.0f); } // Constant holds the key's value up to the next key: a step. TEST(Curve, ConstantStepsHold) { - CurveKey a = Key(0.0f, 1.0f); - a.interpolation = CurveInterpolation::Constant; - const Curve curve = Updated({ a, Key(1.0f, 3.0f), Key(2.0f, 5.0f) }); - EXPECT_EQ(EvaluateCurve(curve, 0.5f), 1.0f); - EXPECT_EQ(EvaluateCurve(curve, 0.999f), 1.0f); - EXPECT_EQ(EvaluateCurve(curve, 1.0f), 3.0f); - EXPECT_GT(EvaluateCurve(curve, 1.5f), 3.0f) << "the next key's own interpolation after it"; + curves::CurveKey a = Key(0.0f, 1.0f); + a.interpolation = curves::CurveInterpolation::Constant; + const curves::Curve curve = Updated({ a, Key(1.0f, 3.0f), Key(2.0f, 5.0f) }); + EXPECT_EQ(curves::EvaluateCurve(curve, 0.5f), 1.0f); + EXPECT_EQ(curves::EvaluateCurve(curve, 0.999f), 1.0f); + EXPECT_EQ(curves::EvaluateCurve(curve, 1.0f), 3.0f); + EXPECT_GT(curves::EvaluateCurve(curve, 1.5f), 3.0f) << "the next key's own interpolation after it"; } // Flat keys ease in and out: halfway at the middle, slow at the ends. TEST(Curve, FlatKeysEaseInAndOut) { - const Curve curve = Updated({ Key(0.0f, 0.0f, CurveTangentMode::Flat), Key(1.0f, 1.0f, CurveTangentMode::Flat) }); - EXPECT_FLOAT_EQ(EvaluateCurve(curve, 0.5f), 0.5f); - EXPECT_NEAR(EvaluateCurve(curve, 0.25f), 0.15625f, 1e-5f); // 3t^2 - 2t^3 - EXPECT_LT(EvaluateCurve(curve, 0.1f), 0.1f); + const curves::Curve curve = Updated({ Key(0.0f, 0.0f, curves::CurveTangentMode::Flat), Key(1.0f, 1.0f, curves::CurveTangentMode::Flat) }); + EXPECT_FLOAT_EQ(curves::EvaluateCurve(curve, 0.5f), 0.5f); + EXPECT_NEAR(curves::EvaluateCurve(curve, 0.25f), 0.15625f, 1e-5f); // 3t^2 - 2t^3 + EXPECT_LT(curves::EvaluateCurve(curve, 0.1f), 0.1f); } // Each slope sets its own side: a steep start, a level end. TEST(Curve, SlopesShapeTheSegment) { - CurveKey a = Key(0.0f, 0.0f, CurveTangentMode::Aligned); + curves::CurveKey a = Key(0.0f, 0.0f, curves::CurveTangentMode::Aligned); a.outSlope = 2.0f; - CurveKey b = Key(1.0f, 1.0f, CurveTangentMode::Aligned); - const Curve curve = Updated({ a, b }); - EXPECT_NEAR(EvaluateCurve(curve, 0.5f), 0.75f, 1e-5f); // h10 * 2 + h01 = 0.25 + 0.5 - EXPECT_NEAR(EvaluateCurve(curve, 0.01f), 0.02f, 1e-3f); + curves::CurveKey b = Key(1.0f, 1.0f, curves::CurveTangentMode::Aligned); + const curves::Curve curve = Updated({ a, b }); + EXPECT_NEAR(curves::EvaluateCurve(curve, 0.5f), 0.75f, 1e-5f); // h10 * 2 + h01 = 0.25 + 0.5 + EXPECT_NEAR(curves::EvaluateCurve(curve, 0.01f), 0.02f, 1e-3f); } TEST(Curve, WrapModes) { - Curve curve = Updated({ Linear(1.0f, 0.0f), Linear(2.0f, 1.0f) }); - EXPECT_EQ(EvaluateCurve(curve, 0.0f), 0.0f) << "clamp before"; - EXPECT_EQ(EvaluateCurve(curve, 5.0f), 1.0f) << "clamp after"; - - curve.preWrap = curve.postWrap = CurveWrapMode::Loop; - EXPECT_NEAR(EvaluateCurve(curve, 2.25f), 0.25f, 1e-5f); - EXPECT_NEAR(EvaluateCurve(curve, 3.75f), 0.75f, 1e-5f); - EXPECT_NEAR(EvaluateCurve(curve, 0.25f), 0.25f, 1e-5f); - EXPECT_NEAR(EvaluateCurve(curve, -0.5f), 0.5f, 1e-5f); - - curve.preWrap = curve.postWrap = CurveWrapMode::PingPong; - EXPECT_NEAR(EvaluateCurve(curve, 2.25f), 0.75f, 1e-5f) << "back down"; - EXPECT_NEAR(EvaluateCurve(curve, 3.25f), 0.25f, 1e-5f) << "up again"; - EXPECT_NEAR(EvaluateCurve(curve, 0.75f), 0.25f, 1e-5f) << "mirrored before"; - EXPECT_NEAR(EvaluateCurve(curve, -0.25f), 0.75f, 1e-5f); - - curve.postWrap = CurveWrapMode::Clamp; - curve.preWrap = CurveWrapMode::Loop; - EXPECT_EQ(EvaluateCurve(curve, 9.0f), 1.0f) << "each end its own"; - EXPECT_NEAR(EvaluateCurve(curve, 0.25f), 0.25f, 1e-5f); + curves::Curve curve = Updated({ Linear(1.0f, 0.0f), Linear(2.0f, 1.0f) }); + EXPECT_EQ(curves::EvaluateCurve(curve, 0.0f), 0.0f) << "clamp before"; + EXPECT_EQ(curves::EvaluateCurve(curve, 5.0f), 1.0f) << "clamp after"; + + curve.preWrap = curve.postWrap = curves::CurveWrapMode::Loop; + EXPECT_NEAR(curves::EvaluateCurve(curve, 2.25f), 0.25f, 1e-5f); + EXPECT_NEAR(curves::EvaluateCurve(curve, 3.75f), 0.75f, 1e-5f); + EXPECT_NEAR(curves::EvaluateCurve(curve, 0.25f), 0.25f, 1e-5f); + EXPECT_NEAR(curves::EvaluateCurve(curve, -0.5f), 0.5f, 1e-5f); + + curve.preWrap = curve.postWrap = curves::CurveWrapMode::PingPong; + EXPECT_NEAR(curves::EvaluateCurve(curve, 2.25f), 0.75f, 1e-5f) << "back down"; + EXPECT_NEAR(curves::EvaluateCurve(curve, 3.25f), 0.25f, 1e-5f) << "up again"; + EXPECT_NEAR(curves::EvaluateCurve(curve, 0.75f), 0.25f, 1e-5f) << "mirrored before"; + EXPECT_NEAR(curves::EvaluateCurve(curve, -0.25f), 0.75f, 1e-5f); + + curve.postWrap = curves::CurveWrapMode::Clamp; + curve.preWrap = curves::CurveWrapMode::Loop; + EXPECT_EQ(curves::EvaluateCurve(curve, 9.0f), 1.0f) << "each end its own"; + EXPECT_NEAR(curves::EvaluateCurve(curve, 0.25f), 0.25f, 1e-5f); } TEST(Curve, BadTimesCountAsZero) { - const Curve curve = Updated({ Linear(0.0f, 2.0f), Linear(1.0f, 4.0f) }); - EXPECT_EQ(EvaluateCurve(curve, std::numeric_limits::quiet_NaN()), 2.0f); - EXPECT_EQ(EvaluateCurve(curve, std::numeric_limits::infinity()), 2.0f); + const curves::Curve curve = Updated({ Linear(0.0f, 2.0f), Linear(1.0f, 4.0f) }); + EXPECT_EQ(curves::EvaluateCurve(curve, std::numeric_limits::quiet_NaN()), 2.0f); + EXPECT_EQ(curves::EvaluateCurve(curve, std::numeric_limits::infinity()), 2.0f); } // --------------------------------------------------------------------- @@ -134,7 +135,7 @@ namespace tachyon TEST(Curve, AutoIsTheSlopeBetweenTheNeighbors) { - const Curve curve = Updated({ Key(0.0f, 0.0f), Key(1.0f, 1.0f), Key(3.0f, 5.0f) }); + const curves::Curve curve = Updated({ Key(0.0f, 0.0f), Key(1.0f, 1.0f), Key(3.0f, 5.0f) }); EXPECT_FLOAT_EQ(curve.keys[1].inSlope, 5.0f / 3.0f); EXPECT_FLOAT_EQ(curve.keys[1].outSlope, 5.0f / 3.0f); EXPECT_EQ(curve.keys[0].outSlope, 0.0f) << "an end key is level"; @@ -146,20 +147,20 @@ namespace tachyon TEST(Curve, AutoDoesntOvershoot) { // Lopsided, so the slope between the neighbors isn't level by itself. - const Curve peak = Updated({ Key(0.0f, 0.0f), Key(1.0f, 1.0f), Key(3.0f, 0.5f) }); + const curves::Curve peak = Updated({ Key(0.0f, 0.0f), Key(1.0f, 1.0f), Key(3.0f, 0.5f) }); EXPECT_EQ(peak.keys[1].outSlope, 0.0f); - const Curve trough = Updated({ Key(0.0f, 1.0f), Key(1.0f, 0.0f), Key(3.0f, 0.5f) }); + const curves::Curve trough = Updated({ Key(0.0f, 1.0f), Key(1.0f, 0.0f), Key(3.0f, 0.5f) }); EXPECT_EQ(trough.keys[1].inSlope, 0.0f); // Rising steeply then barely: the auto slope (5.05) is held to 3 x 0.1. - const Curve held = Updated({ Key(0.0f, 0.0f), Key(1.0f, 10.0f), Key(2.0f, 10.1f) }); + const curves::Curve held = Updated({ Key(0.0f, 0.0f), Key(1.0f, 10.0f), Key(2.0f, 10.1f) }); EXPECT_NEAR(held.keys[1].outSlope, 0.3f, 1e-5f); EXPECT_EQ(held.keys[1].inSlope, held.keys[1].outSlope); // Gently: the plain auto slope. - const Curve gentle = Updated({ Key(0.0f, 0.0f), Key(1.0f, 1.0f), Key(2.0f, 2.5f) }); + const curves::Curve gentle = Updated({ Key(0.0f, 0.0f), Key(1.0f, 1.0f), Key(2.0f, 2.5f) }); EXPECT_NEAR(gentle.keys[1].outSlope, 1.25f, 1e-5f); // Falling: held the same way. - const Curve falling = Updated({ Key(0.0f, 10.1f), Key(1.0f, 10.0f), Key(2.0f, 0.0f) }); + const curves::Curve falling = Updated({ Key(0.0f, 10.1f), Key(1.0f, 10.0f), Key(2.0f, 0.0f) }); EXPECT_NEAR(falling.keys[1].outSlope, -0.3f, 1e-5f); } @@ -167,15 +168,15 @@ namespace tachyon // side's own. TEST(Curve, FlatAlignedAndFree) { - CurveKey flat = Key(1.0f, 1.0f, CurveTangentMode::Flat); + curves::CurveKey flat = Key(1.0f, 1.0f, curves::CurveTangentMode::Flat); flat.inSlope = 4.0f; - CurveKey aligned = Key(2.0f, 0.0f, CurveTangentMode::Aligned); + curves::CurveKey aligned = Key(2.0f, 0.0f, curves::CurveTangentMode::Aligned); aligned.inSlope = 1.0f; aligned.outSlope = -3.0f; - CurveKey free = Key(3.0f, 2.0f, CurveTangentMode::Free); + curves::CurveKey free = Key(3.0f, 2.0f, curves::CurveTangentMode::Free); free.inSlope = 7.0f; free.outSlope = -2.0f; - const Curve curve = Updated({ Key(0.0f, 0.0f), flat, aligned, free, Key(4.0f, 0.0f) }); + const curves::Curve curve = Updated({ Key(0.0f, 0.0f), flat, aligned, free, Key(4.0f, 0.0f) }); EXPECT_EQ(curve.keys[1].inSlope, 0.0f); EXPECT_EQ(curve.keys[1].outSlope, 0.0f); EXPECT_EQ(curve.keys[2].inSlope, -3.0f) << "one slope, the leaving one"; @@ -187,7 +188,7 @@ namespace tachyon TEST(Curve, MakeCurveSortsAndWorksOutTheSlopes) { const float2 points[] = { { 1.0f, 1.0f }, { 0.0f, 0.0f }, { 2.0f, 4.0f } }; - const Curve curve = MakeCurve(points); + const curves::Curve curve = curves::MakeCurve(points); ASSERT_EQ(curve.keys.size(), 3u); EXPECT_EQ(curve.keys[0].time, 0.0f); EXPECT_EQ(curve.keys[2].time, 2.0f); @@ -196,17 +197,17 @@ namespace tachyon TEST(Curve, ThePresets) { - const auto presets = DefaultCurvePresets(); + const auto presets = curves::DefaultCurvePresets(); ASSERT_EQ(presets.size(), 7u); EXPECT_EQ(presets[0].name, "Constant"); - EXPECT_EQ(EvaluateCurve(presets[0].curve, 0.5f), 1.0f); - EXPECT_FLOAT_EQ(EvaluateCurve(presets[1].curve, 0.3f), 0.3f) << "linear"; - EXPECT_FLOAT_EQ(EvaluateCurve(presets[2].curve, 0.3f), 0.7f) << "linear, falling"; - EXPECT_LT(EvaluateCurve(presets[3].curve, 0.5f), 0.5f) << "ease in starts slow"; - EXPECT_GT(EvaluateCurve(presets[4].curve, 0.5f), 0.5f) << "ease out starts fast"; - EXPECT_FLOAT_EQ(EvaluateCurve(presets[5].curve, 0.5f), 0.5f); - EXPECT_FLOAT_EQ(EvaluateCurve(presets[6].curve, 0.25f), 1.0f - 0.15625f); - for (const CurvePreset& preset : presets) + EXPECT_EQ(curves::EvaluateCurve(presets[0].curve, 0.5f), 1.0f); + EXPECT_FLOAT_EQ(curves::EvaluateCurve(presets[1].curve, 0.3f), 0.3f) << "linear"; + EXPECT_FLOAT_EQ(curves::EvaluateCurve(presets[2].curve, 0.3f), 0.7f) << "linear, falling"; + EXPECT_LT(curves::EvaluateCurve(presets[3].curve, 0.5f), 0.5f) << "ease in starts slow"; + EXPECT_GT(curves::EvaluateCurve(presets[4].curve, 0.5f), 0.5f) << "ease out starts fast"; + EXPECT_FLOAT_EQ(curves::EvaluateCurve(presets[5].curve, 0.5f), 0.5f); + EXPECT_FLOAT_EQ(curves::EvaluateCurve(presets[6].curve, 0.25f), 1.0f - 0.15625f); + for (const curves::CurvePreset& preset : presets) { EXPECT_EQ(preset.curve.keys.front().time, 0.0f) << preset.name; EXPECT_EQ(preset.curve.keys.back().time, 1.0f) << preset.name; @@ -220,20 +221,20 @@ namespace tachyon class CurveEdits : public ::testing::Test { protected: - CurveView view; - std::vector edits; + curves::CurveView view; + std::vector edits; uint32_t nextID = 100; void SetUp() override { - view.channels = { CurveChannel{ .name = "R", .color = CurveChannelColor::Red, - .curve = Updated({ Key(0.0f, 0.0f, CurveTangentMode::Auto, 1), - Key(0.5f, 0.8f, CurveTangentMode::Auto, 2), - Key(1.0f, 1.0f, CurveTangentMode::Auto, 3) }) }, - CurveChannel{ .name = "G", .color = CurveChannelColor::Green, - .curve = Updated({ Key(0.0f, 1.0f, CurveTangentMode::Auto, 4), - Key(1.0f, 0.0f, CurveTangentMode::Auto, 5) }) } }; - view.onEdit = [this](const CurveEdit& edit) { edits.push_back(edit); }; + view.channels = { curves::CurveChannel{ .name = "R", .color = curves::CurveChannelColor::Red, + .curve = Updated({ Key(0.0f, 0.0f, curves::CurveTangentMode::Auto, 1), + Key(0.5f, 0.8f, curves::CurveTangentMode::Auto, 2), + Key(1.0f, 1.0f, curves::CurveTangentMode::Auto, 3) }) }, + curves::CurveChannel{ .name = "G", .color = curves::CurveChannelColor::Green, + .curve = Updated({ Key(0.0f, 1.0f, curves::CurveTangentMode::Auto, 4), + Key(1.0f, 0.0f, curves::CurveTangentMode::Auto, 5) }) } }; + view.onEdit = [this](const curves::CurveEdit& edit) { edits.push_back(edit); }; } ID Make() { return Id(nextID++); } }; @@ -241,10 +242,10 @@ namespace tachyon TEST_F(CurveEdits, AddingAKey) { const ID key = Make(); - const CurveEdit add = AddCurveKeyEdit(view, 1, 0.25f, 0.6f, key); + const curves::CurveEdit add = curves::AddCurveKeyEdit(view, 1, 0.25f, 0.6f, key); ASSERT_EQ(add.changes.size(), 1u); EXPECT_EQ(add.changes[0].channel, 1); - CommitCurveEdit(view, add); + curves::CommitCurveEdit(view, add); ASSERT_EQ(edits.size(), 1u); EXPECT_EQ(view.revision, 1u); const auto& keys = view.channels[1].curve.keys; @@ -252,72 +253,72 @@ namespace tachyon EXPECT_EQ(keys[1].stableID, key) << "in time order"; EXPECT_EQ(keys[1].value, 0.6f); - ApplyCurveEdit(view, add, /*undo*/ true); + curves::ApplyCurveEdit(view, add, /*undo*/ true); EXPECT_EQ(view.channels[1].curve.keys.size(), 2u); - ApplyCurveEdit(view, add); + curves::ApplyCurveEdit(view, add); EXPECT_EQ(view.channels[1].curve.keys.size(), 3u); - EXPECT_TRUE(AddCurveKeyEdit(view, 1, 0.25f + 1e-6f, 0.1f, Make()).empty()) << "one there already"; - EXPECT_TRUE(AddCurveKeyEdit(view, 5, 0.3f, 0.1f, Make()).empty()); - EXPECT_TRUE(AddCurveKeyEdit(view, -1, 0.3f, 0.1f, Make()).empty()); + EXPECT_TRUE(curves::AddCurveKeyEdit(view, 1, 0.25f + 1e-6f, 0.1f, Make()).empty()) << "one there already"; + EXPECT_TRUE(curves::AddCurveKeyEdit(view, 5, 0.3f, 0.1f, Make()).empty()); + EXPECT_TRUE(curves::AddCurveKeyEdit(view, -1, 0.3f, 0.1f, Make()).empty()); view.channels[0].visible = false; - EXPECT_TRUE(AddCurveKeyEdit(view, 0, 0.3f, 0.1f, Make()).empty()) << "a hidden channel"; + EXPECT_TRUE(curves::AddCurveKeyEdit(view, 0, 0.3f, 0.1f, Make()).empty()) << "a hidden channel"; } // A key is kept in the range's time; in its values too with clampValues. TEST_F(CurveEdits, AddedKeysStayInTheRange) { - EXPECT_TRUE(AddCurveKeyEdit(view, 1, 3.0f, 5.0f, Make()).empty()) << "held to 1, where there's a key"; - EXPECT_EQ(AddCurveKeyEdit(view, 1, 0.75f, 5.0f, Make()).changes[0].to.keys[1].value, 5.0f) << "values free"; + EXPECT_TRUE(curves::AddCurveKeyEdit(view, 1, 3.0f, 5.0f, Make()).empty()) << "held to 1, where there's a key"; + EXPECT_EQ(curves::AddCurveKeyEdit(view, 1, 0.75f, 5.0f, Make()).changes[0].to.keys[1].value, 5.0f) << "values free"; view.clampValues = true; - EXPECT_EQ(AddCurveKeyEdit(view, 1, 0.75f, 5.0f, Make()).changes[0].to.keys[1].value, 1.0f); - EXPECT_EQ(AddCurveKeyEdit(view, 1, 0.75f, -5.0f, Make()).changes[0].to.keys[1].value, 0.0f); + EXPECT_EQ(curves::AddCurveKeyEdit(view, 1, 0.75f, 5.0f, Make()).changes[0].to.keys[1].value, 1.0f); + EXPECT_EQ(curves::AddCurveKeyEdit(view, 1, 0.75f, -5.0f, Make()).changes[0].to.keys[1].value, 0.0f); view.range = { -2.0f, 2.0f, -1.0f, 3.0f }; - EXPECT_EQ(AddCurveKeyEdit(view, 1, -3.0f, 0.5f, Make()).changes[0].to.keys.front().time, -2.0f); - EXPECT_EQ(AddCurveKeyEdit(view, 1, 3.0f, 0.5f, Make()).changes[0].to.keys.back().time, 2.0f); - EXPECT_EQ(AddCurveKeyEdit(view, 1, 0.25f, 5.0f, Make()).changes[0].to.keys[1].value, 3.0f); + EXPECT_EQ(curves::AddCurveKeyEdit(view, 1, -3.0f, 0.5f, Make()).changes[0].to.keys.front().time, -2.0f); + EXPECT_EQ(curves::AddCurveKeyEdit(view, 1, 3.0f, 0.5f, Make()).changes[0].to.keys.back().time, 2.0f); + EXPECT_EQ(curves::AddCurveKeyEdit(view, 1, 0.25f, 5.0f, Make()).changes[0].to.keys[1].value, 3.0f); } // With fps set, an added key lands on the frame nearest. TEST_F(CurveEdits, AddedKeysLandOnFrames) { view.fps = 10.0f; - EXPECT_FLOAT_EQ(AddCurveKeyEdit(view, 1, 0.43f, 0.5f, Make()).changes[0].to.keys[1].time, 0.4f); - EXPECT_FLOAT_EQ(SnapToFrame(view, 0.46f), 0.5f); - EXPECT_TRUE(AddCurveKeyEdit(view, 1, 0.04f, 0.5f, Make()).empty()) << "frame 0, where there's a key"; + EXPECT_FLOAT_EQ(curves::AddCurveKeyEdit(view, 1, 0.43f, 0.5f, Make()).changes[0].to.keys[1].time, 0.4f); + EXPECT_FLOAT_EQ(curves::SnapToFrame(view, 0.46f), 0.5f); + EXPECT_TRUE(curves::AddCurveKeyEdit(view, 1, 0.04f, 0.5f, Make()).empty()) << "frame 0, where there's a key"; view.fps = 0.0f; - EXPECT_EQ(SnapToFrame(view, 0.46f), 0.46f); + EXPECT_EQ(curves::SnapToFrame(view, 0.46f), 0.46f); } // The selected keys go from every channel; what's gone isn't selected any more. TEST_F(CurveEdits, DeletingTheSelectedKeys) { view.selectedKeys = { Id(2), Id(5) }; - const CurveEdit edit = DeleteSelectedCurveKeysEdit(view); + const curves::CurveEdit edit = curves::DeleteSelectedCurveKeysEdit(view); ASSERT_EQ(edit.changes.size(), 2u); - CommitCurveEdit(view, edit); + curves::CommitCurveEdit(view, edit); EXPECT_EQ(view.channels[0].curve.keys.size(), 2u); EXPECT_EQ(view.channels[1].curve.keys.size(), 1u); EXPECT_TRUE(view.selectedKeys.empty()); - ApplyCurveEdit(view, edit, true); + curves::ApplyCurveEdit(view, edit, true); EXPECT_EQ(view.channels[0].curve.keys.size(), 3u); - EXPECT_TRUE(DeleteSelectedCurveKeysEdit(view).empty()) << "nothing selected"; + EXPECT_TRUE(curves::DeleteSelectedCurveKeysEdit(view).empty()) << "nothing selected"; } TEST_F(CurveEdits, TangentModes) { view.selectedKeys = { Id(2) }; - CommitCurveEdit(view, SetCurveTangentModeEdit(view, CurveTangentMode::Flat)); - EXPECT_EQ(view.channels[0].curve.keys[1].tangents, CurveTangentMode::Flat); + curves::CommitCurveEdit(view, curves::SetCurveTangentModeEdit(view, curves::CurveTangentMode::Flat)); + EXPECT_EQ(view.channels[0].curve.keys[1].tangents, curves::CurveTangentMode::Flat); EXPECT_EQ(view.channels[0].curve.keys[1].outSlope, 0.0f); - EXPECT_EQ(view.channels[0].curve.keys[0].tangents, CurveTangentMode::Auto) << "only the selected"; - EXPECT_TRUE(SetCurveTangentModeEdit(view, CurveTangentMode::Flat).empty()) << "already"; + EXPECT_EQ(view.channels[0].curve.keys[0].tangents, curves::CurveTangentMode::Auto) << "only the selected"; + EXPECT_TRUE(curves::SetCurveTangentModeEdit(view, curves::CurveTangentMode::Flat).empty()) << "already"; // Free from another mode: each side keeps the slope it had. - CommitCurveEdit(view, SetCurveTangentModeEdit(view, CurveTangentMode::Auto)); + curves::CommitCurveEdit(view, curves::SetCurveTangentModeEdit(view, curves::CurveTangentMode::Auto)); const float slope = view.channels[0].curve.keys[1].outSlope; - CommitCurveEdit(view, SetCurveTangentModeEdit(view, CurveTangentMode::Free)); - EXPECT_EQ(view.channels[0].curve.keys[1].tangents, CurveTangentMode::Free); + curves::CommitCurveEdit(view, curves::SetCurveTangentModeEdit(view, curves::CurveTangentMode::Free)); + EXPECT_EQ(view.channels[0].curve.keys[1].tangents, curves::CurveTangentMode::Free); EXPECT_EQ(view.channels[0].curve.keys[1].inSlope, slope); EXPECT_EQ(view.channels[0].curve.keys[1].outSlope, slope); } @@ -326,26 +327,26 @@ namespace tachyon TEST_F(CurveEdits, Interpolation) { view.selectedKeys = { Id(1), Id(4) }; - CommitCurveEdit(view, SetCurveInterpolationEdit(view, CurveInterpolation::Constant)); - EXPECT_EQ(view.channels[0].curve.keys[0].interpolation, CurveInterpolation::Constant); - EXPECT_EQ(view.channels[1].curve.keys[0].interpolation, CurveInterpolation::Constant) << "on every channel"; - EXPECT_EQ(view.channels[0].curve.keys[1].interpolation, CurveInterpolation::Bezier) << "only the selected"; - EXPECT_EQ(EvaluateCurve(view.channels[0].curve, 0.4f), 0.0f) << "a step"; - EXPECT_TRUE(SetCurveInterpolationEdit(view, CurveInterpolation::Constant).empty()) << "already"; + curves::CommitCurveEdit(view, curves::SetCurveInterpolationEdit(view, curves::CurveInterpolation::Constant)); + EXPECT_EQ(view.channels[0].curve.keys[0].interpolation, curves::CurveInterpolation::Constant); + EXPECT_EQ(view.channels[1].curve.keys[0].interpolation, curves::CurveInterpolation::Constant) << "on every channel"; + EXPECT_EQ(view.channels[0].curve.keys[1].interpolation, curves::CurveInterpolation::Bezier) << "only the selected"; + EXPECT_EQ(curves::EvaluateCurve(view.channels[0].curve, 0.4f), 0.0f) << "a step"; + EXPECT_TRUE(curves::SetCurveInterpolationEdit(view, curves::CurveInterpolation::Constant).empty()) << "already"; ASSERT_EQ(edits.size(), 1u); - ApplyCurveEdit(view, edits[0], /*undo*/ true); - EXPECT_EQ(view.channels[0].curve.keys[0].interpolation, CurveInterpolation::Bezier); + curves::ApplyCurveEdit(view, edits[0], /*undo*/ true); + EXPECT_EQ(view.channels[0].curve.keys[0].interpolation, curves::CurveInterpolation::Bezier); } // A preset is stretched over the range, its slopes with it, with new keys. TEST_F(CurveEdits, APresetStretchedOverTheRange) { view.range = { 0.0f, 2.0f, 10.0f, 14.0f }; - view.channels[1].curve.postWrap = CurveWrapMode::Loop; - const CurvePreset& easeOut = DefaultCurvePresets()[4]; - const CurveEdit edit = ApplyCurvePresetEdit(view, 1, easeOut, [this] { return Make(); }); + view.channels[1].curve.postWrap = curves::CurveWrapMode::Loop; + const curves::CurvePreset& easeOut = curves::DefaultCurvePresets()[4]; + const curves::CurveEdit edit = curves::ApplyCurvePresetEdit(view, 1, easeOut, [this] { return Make(); }); ASSERT_EQ(edit.changes.size(), 1u); - const Curve& to = edit.changes[0].to; + const curves::Curve& to = edit.changes[0].to; ASSERT_EQ(to.keys.size(), 2u); EXPECT_EQ(to.keys[0].time, 0.0f); EXPECT_EQ(to.keys[1].time, 2.0f); @@ -354,23 +355,23 @@ namespace tachyon EXPECT_FLOAT_EQ(to.keys[0].outSlope, 2.0f * 4.0f / 2.0f) << "the slope stretched too"; EXPECT_EQ(to.keys[0].stableID, Id(100)); EXPECT_EQ(to.keys[1].stableID, Id(101)); - EXPECT_EQ(to.postWrap, CurveWrapMode::Loop) << "the wrap modes stay"; - EXPECT_TRUE(ApplyCurvePresetEdit(view, 7, easeOut, [this] { return Make(); }).empty()); + EXPECT_EQ(to.postWrap, curves::CurveWrapMode::Loop) << "the wrap modes stay"; + EXPECT_TRUE(curves::ApplyCurvePresetEdit(view, 7, easeOut, [this] { return Make(); }).empty()); } TEST_F(CurveEdits, WrapModes) { - CommitCurveEdit(view, SetCurveWrapEdit(view, 0, CurveWrapMode::PingPong, CurveWrapMode::Loop)); - EXPECT_EQ(view.channels[0].curve.preWrap, CurveWrapMode::PingPong); - EXPECT_EQ(view.channels[0].curve.postWrap, CurveWrapMode::Loop); - EXPECT_EQ(view.channels[1].curve.preWrap, CurveWrapMode::Clamp); - EXPECT_TRUE(SetCurveWrapEdit(view, 0, CurveWrapMode::PingPong, CurveWrapMode::Loop).empty()); - EXPECT_TRUE(SetCurveWrapEdit(view, 2, CurveWrapMode::Loop, CurveWrapMode::Loop).empty()); + curves::CommitCurveEdit(view, curves::SetCurveWrapEdit(view, 0, curves::CurveWrapMode::PingPong, curves::CurveWrapMode::Loop)); + EXPECT_EQ(view.channels[0].curve.preWrap, curves::CurveWrapMode::PingPong); + EXPECT_EQ(view.channels[0].curve.postWrap, curves::CurveWrapMode::Loop); + EXPECT_EQ(view.channels[1].curve.preWrap, curves::CurveWrapMode::Clamp); + EXPECT_TRUE(curves::SetCurveWrapEdit(view, 0, curves::CurveWrapMode::PingPong, curves::CurveWrapMode::Loop).empty()); + EXPECT_TRUE(curves::SetCurveWrapEdit(view, 2, curves::CurveWrapMode::Loop, curves::CurveWrapMode::Loop).empty()); } TEST_F(CurveEdits, AnEmptyEditIsntCommitted) { - CommitCurveEdit(view, CurveEdit{}); + curves::CommitCurveEdit(view, curves::CurveEdit{}); EXPECT_TRUE(edits.empty()); EXPECT_EQ(view.revision, 0u); } 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/edit_id_release_test.cpp b/tests/edit_id_release_test.cpp index 59dcbc01..0200cdca 100644 --- a/tests/edit_id_release_test.cpp +++ b/tests/edit_id_release_test.cpp @@ -4,10 +4,11 @@ #include -#include -#include -#include +#include +#include #include +#include +#include #include @@ -15,66 +16,9 @@ namespace tachyon { namespace { - TimelineTrack Track(ID id, std::vector keys, std::vector events = {}) + curves::Curve KeysCurve(std::vector keys) { - TimelineTrack track; - track.stableID = id; - for (ID key : keys) track.keys.push_back({ .stableID = key }); - for (ID event : events) track.events.push_back({ .stableID = event }); - return track; - } - - // Deletes key b from a track, removes a whole track, and moves a third one: removed - // from one place and added at another, so both sides hold it. - struct TimelineDeletion - { - IDManager ids; - ID kept = ids.CreateStaticID(), a = ids.CreateStaticID(), b = ids.CreateStaticID(); - ID gone = ids.CreateStaticID(), goneKey = ids.CreateStaticID(), goneEvent = ids.CreateStaticID(); - ID moved = ids.CreateStaticID(), movedKey = ids.CreateStaticID(); - TimelineEdit edit; - - TimelineDeletion() - { - edit.changes.push_back({ .track = 0, .from = Track(kept, { a, b }), .to = Track(kept, { a }) }); - edit.tracks.push_back({ .index = 1, .added = false, .track = Track(gone, { goneKey }, { goneEvent }) }); - edit.tracks.push_back({ .index = 2, .added = false, .track = Track(moved, { movedKey }) }); - edit.tracks.push_back({ .index = 0, .added = true, .track = Track(moved, { movedKey }) }); - } - }; - - TEST(EditIDRelease, ADoneTimelineEditGivesBackWhatItsUndoWouldBringBack) - { - TimelineDeletion t; - ReleaseTimelineEditIDs(t.ids, t.edit, /*undone*/ false); - EXPECT_FALSE(t.ids.IsStaticIDValid(t.b)); - EXPECT_FALSE(t.ids.IsStaticIDValid(t.gone)); - EXPECT_FALSE(t.ids.IsStaticIDValid(t.goneKey)); - EXPECT_FALSE(t.ids.IsStaticIDValid(t.goneEvent)); - for (ID id : { t.kept, t.a, t.moved, t.movedKey }) - EXPECT_TRUE(t.ids.IsStaticIDValid(id)) << "both sides hold it"; - EXPECT_EQ(t.ids.GetStaticIDCount(), 4u); - } - - TEST(EditIDRelease, AnUndoneTimelineEditGivesBackWhatItsRedoWouldAdd) - { - TimelineDeletion t; - ReleaseTimelineEditIDs(t.ids, t.edit, /*undone*/ true); - EXPECT_EQ(t.ids.GetStaticIDCount(), 8u) << "a deletion's redo adds nothing"; - - IDManager ids; - const ID key = ids.CreateStaticID(), added = ids.CreateStaticID(), track = ids.CreateStaticID(); - TimelineEdit add; - add.changes.push_back({ .track = 0, .from = Track(track, { key }), .to = Track(track, { key, added }) }); - ReleaseTimelineEditIDs(ids, add, /*undone*/ true); - EXPECT_FALSE(ids.IsStaticIDValid(added)); - EXPECT_TRUE(ids.IsStaticIDValid(key)); - EXPECT_TRUE(ids.IsStaticIDValid(track)); - } - - Curve KeysCurve(std::vector keys) - { - Curve curve; + curves::Curve curve; for (ID key : keys) curve.keys.push_back({ .stableID = key }); return curve; } @@ -84,16 +28,16 @@ namespace tachyon { IDManager ids; const ID before = ids.CreateStaticID(), after = ids.CreateStaticID(), both = ids.CreateStaticID(); - CurveEdit edit; + curves::CurveEdit edit; edit.changes.push_back({ .channel = 0, .from = KeysCurve({ before, both }), .to = KeysCurve({ after, both }) }); IDManager undoneIDs = ids; - ReleaseCurveEditIDs(ids, edit, /*undone*/ false); + curves::ReleaseCurveEditIDs(ids, edit, /*undone*/ false); EXPECT_FALSE(ids.IsStaticIDValid(before)); EXPECT_TRUE(ids.IsStaticIDValid(after)); EXPECT_TRUE(ids.IsStaticIDValid(both)); - ReleaseCurveEditIDs(undoneIDs, edit, /*undone*/ true); + curves::ReleaseCurveEditIDs(undoneIDs, edit, /*undone*/ true); EXPECT_TRUE(undoneIDs.IsStaticIDValid(before)); EXPECT_FALSE(undoneIDs.IsStaticIDValid(after)); EXPECT_TRUE(undoneIDs.IsStaticIDValid(both)); @@ -104,39 +48,25 @@ namespace tachyon IDManager ids; const ID node = ids.CreateStaticID(), frame = ids.CreateStaticID(), transition = ids.CreateStaticID(); const ID addedNode = ids.CreateStaticID(); - NodeViewEdit edit; - NodeModel removed; removed.stableID = node; - NodeModel added; added.stableID = addedNode; + nodes::NodeViewEdit edit; + nodes::NodeModel removed; removed.stableID = node; + nodes::NodeModel added; added.stableID = addedNode; edit.nodes.push_back({ .index = 0, .added = false, .node = removed }); edit.nodes.push_back({ .index = 3, .added = true, .node = added }); - edit.frames.push_back({ .index = 0, .added = false, .frame = NodeFrame{ .stableID = frame } }); - edit.transitions.push_back({ .index = 0, .added = false, .transition = StateTransition{ .stableID = transition } }); - edit.initial = NodeViewEdit::Initial{ .from = node, .to = ID::Invalid() }; // names a state, holds nothing + edit.frames.push_back({ .index = 0, .added = false, .frame = nodes::NodeFrame{ .stableID = frame } }); + edit.transitions.push_back({ .index = 0, .added = false, .transition = nodes::StateTransition{ .stableID = transition } }); + edit.initial = nodes::NodeViewEdit::Initial{ .from = node, .to = ID::Invalid() }; // names a state, holds nothing IDManager undoneIDs = ids; - ReleaseNodeViewEditIDs(ids, edit, /*undone*/ false); + nodes::ReleaseNodeViewEditIDs(ids, edit, /*undone*/ false); EXPECT_FALSE(ids.IsStaticIDValid(node)); EXPECT_FALSE(ids.IsStaticIDValid(frame)); EXPECT_FALSE(ids.IsStaticIDValid(transition)); EXPECT_TRUE(ids.IsStaticIDValid(addedNode)); - ReleaseNodeViewEditIDs(undoneIDs, edit, /*undone*/ true); + nodes::ReleaseNodeViewEditIDs(undoneIDs, edit, /*undone*/ true); EXPECT_EQ(undoneIDs.GetStaticIDCount(), 3u); EXPECT_FALSE(undoneIDs.IsStaticIDValid(addedNode)); } - - // An edit that neither adds nor removes anything gives nothing back. - TEST(EditIDRelease, AMoveGivesNothingBack) - { - IDManager ids; - const ID track = ids.CreateStaticID(), key = ids.CreateStaticID(); - TimelineEdit edit; - TimelineTrack later = Track(track, { key }); - later.keys[0].time = 1.0f; - edit.changes.push_back({ .track = 0, .from = Track(track, { key }), .to = later }); - ReleaseTimelineEditIDs(ids, edit, false); - ReleaseTimelineEditIDs(ids, edit, true); - EXPECT_EQ(ids.GetStaticIDCount(), 2u); - } } } diff --git a/tests/file_drop_test.cpp b/tests/file_drop_test.cpp index d6c5ecd4..5798a4f7 100644 --- a/tests/file_drop_test.cpp +++ b/tests/file_drop_test.cpp @@ -6,6 +6,8 @@ #include "headless_gui_app.h" #include +#include +#include #include #include @@ -179,6 +181,8 @@ namespace tachyon } HeadlessGUIApp app; + views::Context viewsContext; + color::Context colorContext; ID takerID, childID, otherID, disabledID, cornerID; bool takesOther = false; std::vector seen; @@ -296,22 +300,23 @@ namespace tachyon TEST(FileDrop, AGridOrTreeInAPaneLetsItTakeTheDrop) { HeadlessGUIApp app; + views::Context viewsContext; ASSERT_TRUE(app.Initialize()); const ID paneID = app.idManager.CreateStaticID(), gridID = app.idManager.CreateStaticID(), treeID = app.idManager.CreateStaticID(); std::vector taken; std::vector appDrops; app.SetFileDropHandler([&](const FileDrop& drop) { appDrops.push_back(drop); }); - GridViewVirtualState vstate; + views::GridViewVirtualState vstate; MultiSelectState multi; std::vector itemIDs(3); - std::vector rows(2); + std::vector rows(2); rows[0].name = "Root"; rows[1].name = "Child"; rows[1].depth = 1; - GUIApplication::RebuildTreeViewIndex(rows); + views::RebuildTreeViewIndex(rows); std::vector visibleIdx; - TableState treeState; - treeState.openRows.insert(TreeViewRowKey(rows[0], 0)); + views::TableState treeState; + treeState.openRows.insert(views::TreeViewRowKey(rows[0], 0)); auto frame = [&] { app.Frame([&] { app.BeginRootWindow(); @@ -324,11 +329,11 @@ namespace tachyon }; app.RegisterElement(std::move(pane), LayoutOverride{}.Size(600, 500)); VERIFY(app.elementStorage.BeginChildren()); - app.VirtualTreeView(treeID, rows, visibleIdx, treeState, StyleRef{}, LayoutOverride{}.Size(200, 100)); - app.VirtualGridView(gridID, vstate, 3, int2{ 100, 50 }, + views::VirtualTreeView(app, viewsContext, treeID, rows, visibleIdx, treeState, StyleRef{}, LayoutOverride{}.Size(200, 100)); + views::VirtualGridView(app, viewsContext, gridID, vstate, 3, int2{ 100, 50 }, [&](int i, ID itemID) { itemIDs[size_t(i)] = itemID; - app.GridViewItem(itemID, "item", ElementState::None, nullptr, StyleRef{}, LayoutOverride{}.Size(100, 50)); + views::GridViewItem(app, viewsContext, itemID, "item", ElementState::None, nullptr, StyleRef{}, LayoutOverride{}.Size(100, 50)); }, nullptr, &multi, nullptr, {}, {}, LayoutOverride{}.Size(400, 300)); VERIFY(app.elementStorage.EndChildren()); @@ -452,6 +457,8 @@ namespace tachyon TEST(FileDrop, NoControlTakesADropOfItsOwn) { HeadlessGUIApp app; + views::Context viewsContext; + color::Context colorContext; ASSERT_TRUE(app.Initialize()); std::vector drops; app.SetFileDropHandler([&](const FileDrop& drop) { drops.push_back(drop); }); @@ -463,10 +470,10 @@ namespace tachyon color4f color { 1.0f, 0.5f, 0.0f, 1.0f }; Gradient gradient; std::vector list { "one", "two" }, crumbs { "Graphs", "Terrain" }; - TableState tableState; - std::vector tableColumns; + views::TableState tableState; + std::vector tableColumns; tableColumns.push_back({ .column = { .header = "Name", .initialWidth = 120, .minWidth = 60, .maxWidth = 300 }, - .generateCell = [&app](int r) { app.Cell(r == 0 ? "First" : "Second"); } }); + .generateCell = [&app, &viewsContext](int r) { views::Cell(app, viewsContext, r == 0 ? "First" : "Second"); } }); std::vector ids; for (int i = 0; i < 20; ++i) ids.push_back(app.idManager.CreateStaticID()); @@ -483,8 +490,8 @@ namespace tachyon app.SliderField(ids[n++], volume, 0.0f, 100.0f, "Volume"); app.SliderField(ids[n++], count, 0, 10, "Count"); app.Slider(ids[n++], level, 0, 10); - app.ColorField(ids[n++], color); - app.GradientField(ids[n++], gradient); + color::ColorField(app, colorContext, ids[n++], color); + color::GradientField(app, colorContext, ids[n++], gradient); app.Field(ids[n++], list); app.BeginToolbar(); app.Button(ids[n++], "Tool", [] {}); @@ -494,14 +501,14 @@ namespace tachyon app.EndToolbar(); app.Breadcrumb(ids[n++], crumbs, [](int) {}); app.TypedField(ids[n++], typed); - if (app.BeginListView(ids[n++], &listSelection, 2)) + if (views::BeginListView(app, viewsContext, ids[n++], &listSelection, 2)) { - app.ListItem("First"); - app.ListItem("Second"); + views::ListItem(app, viewsContext, "First"); + views::ListItem(app, viewsContext, "Second"); } - app.EndListView(); - app.VirtualTable(ids[n++], tableState, std::span(tableColumns), 2, 0, - app.theme.tableStyleRef, LayoutOverride{}.Size(200, 80)); + views::EndListView(app, viewsContext); + views::VirtualTable(app, viewsContext, ids[n++], tableState, std::span(tableColumns), 2, 0, + views::GetStyles(app, viewsContext).tableStyleRef, LayoutOverride{}.Size(200, 80)); app.Dropdown(ids[n++], quality, { "Low", "High" }); app.EndRootWindow(); }); diff --git a/tests/focus_ring_test.cpp b/tests/focus_ring_test.cpp index c578f2e9..651e6b24 100644 --- a/tests/focus_ring_test.cpp +++ b/tests/focus_ring_test.cpp @@ -1,6 +1,7 @@ // The focus ring (:focus-visible) shows while focus came from the keyboard: Tab // shows it, a mouse press hides it. #include +#include #include "headless_gui_app.h" namespace tachyon @@ -13,6 +14,7 @@ namespace tachyon { protected: HeadlessGUIApp app; + views::Context viewsContext; ID first, second; void SetUp() override @@ -126,7 +128,7 @@ namespace tachyon // List rows take an outline inside them instead. TEST_F(FocusRingTest, TheThemeGivesFocusedRowsAnInsetOutline) { - const VisualBoxStyleIndex row = app.theme.listItemStyleRef.visualBoxStyleIndex; + const VisualBoxStyleIndex row = views::GetStyles(app, viewsContext).listItemStyleRef.visualBoxStyleIndex; const VisualShadowStyle* focused = app.styleManager.GetVisualShadowStyle(ComputeGPUStyleIndex(row, ElementState::Focused)); ASSERT_NE(focused, nullptr); EXPECT_NE(focused->insetRing, 0u); diff --git a/tests/fuzz_test.cpp b/tests/fuzz_test.cpp index 677feafe..9e41b5f4 100644 --- a/tests/fuzz_test.cpp +++ b/tests/fuzz_test.cpp @@ -9,9 +9,11 @@ #include "misuse_reports.h" #include "skribidi_test_fixture.h" -#include +#include #include #include +#include +#include #include #include @@ -143,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); @@ -170,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. @@ -186,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()); } } @@ -211,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()); } @@ -327,6 +329,7 @@ namespace TEST(FuzzTest, BadGradientsAndColors) { HeadlessGUIApp app; + color::Context colorContext; ASSERT_TRUE(app.Initialize()); Gradient tooMany = Gradient::Solid(color4b{ 255, 0, 0, 255 }); tooMany.stopCount = 200; // past the stop array @@ -341,9 +344,9 @@ namespace auto draw = [&] { app.BeginRootWindow(); for (Gradient* g : gradients) - app.GradientField(*g); - app.ColorField(nanColor, true); - app.ColorField(byteColor); + color::GradientField(app, colorContext, *g); + color::ColorField(app, colorContext, nanColor, true); + color::ColorField(app, colorContext, byteColor); app.EndRootWindow(); }; MisuseReports reports; diff --git a/tests/gpu/gpu_cut_text_test.cpp b/tests/gpu/gpu_cut_text_test.cpp index ec2ee945..c4792ac9 100644 --- a/tests/gpu/gpu_cut_text_test.cpp +++ b/tests/gpu/gpu_cut_text_test.cpp @@ -6,6 +6,7 @@ #include #include +#include #include "gpu_injected_input.h" @@ -77,6 +78,7 @@ namespace IconID icon = IconID::Invalid; bool drawn = false; int frame = 0; + views::Context viewsContext; void OnGUI() override { @@ -86,13 +88,13 @@ namespace BeginVertical(LayoutOverride{}.FlexGrow(1)); if (gridItem) { - BeginGridView(idManager.AllocateDynamicID("grid")); + views::BeginGridView(*this, viewsContext, idManager.AllocateDynamicID("grid")); Style item = styleManager.ToPixels(theme.gridViewItemBaseStyle); item.iconSize = static_cast(styleManager.Px(34)); - GridViewItem(labelID, GUIContent{ icon, kText }, ElementState::None, nullptr, - styleManager.Register(item, StyleUnits::Pixels), - LayoutOverride{}.Size(Pixels{ styleManager.Px(96) }, Pixels{ styleManager.Px(86) })); - EndGridView(); + views::GridViewItem(*this, viewsContext, labelID, GUIContent{ icon, kText }, ElementState::None, nullptr, + styleManager.Register(item, StyleUnits::Pixels), + LayoutOverride{}.Size(Pixels{ styleManager.Px(96) }, Pixels{ styleManager.Px(86) })); + views::EndGridView(*this, viewsContext); } else Label(labelID, kText, LayoutOverride{}.Width(90)); diff --git a/tests/gpu/gpu_inspector_fields_test.cpp b/tests/gpu/gpu_inspector_fields_test.cpp index b95f1df2..bf6613c9 100644 --- a/tests/gpu/gpu_inspector_fields_test.cpp +++ b/tests/gpu/gpu_inspector_fields_test.cpp @@ -6,6 +6,8 @@ #include #include +#include +#include #include "gpu_injected_input.h" @@ -24,6 +26,8 @@ namespace class InspectorFieldsApp : public GUIApplicationInternals { public: + curves::Context curvesContext; + color::Context colorContext; ID windowID = ID::Invalid(); ID gradientID = ID::Invalid(); ID curveID = ID::Invalid(); @@ -31,7 +35,7 @@ namespace ID fadeID = ID::Invalid(); ID fadeInID = ID::Invalid(); GradientF gradient, fade, fadeIn; - CurveView curve, colors; + curves::CurveView curve, colors; void OnGUI() override { @@ -44,11 +48,11 @@ namespace field(); EndHorizontal(); }; - row("gradientRow", [this] { GradientField(gradientID, gradient); }); - row("fadeRow", [this] { GradientField(fadeID, fade); }); - row("fadeInRow", [this] { GradientField(fadeInID, fadeIn); }); - row("curveRow", [this] { CurveField(curveID, curve); }); - row("colorsRow", [this] { CurveField(colorsID, colors); }); + row("gradientRow", [this] { color::GradientField(*this, colorContext, gradientID, gradient); }); + row("fadeRow", [this] { color::GradientField(*this, colorContext, fadeID, fade); }); + row("fadeInRow", [this] { color::GradientField(*this, colorContext, fadeInID, fadeIn); }); + row("curveRow", [this] { curves::CurveField(*this, curvesContext, curveID, curve); }); + row("colorsRow", [this] { curves::CurveField(*this, curvesContext, colorsID, colors); }); } EndWindow(); } @@ -79,9 +83,9 @@ namespace // One value, level at a half; and a color's R, G, B, all at 0. static constexpr float2 kHalf[] = { { 0.0f, 0.5f }, { 1.0f, 0.5f } }; static constexpr float2 kZero[] = { { 0.0f, 0.0f }, { 1.0f, 0.0f } }; - curve.channels = { CurveChannel{ .name = "Value", .curve = MakeCurve(kHalf) } }; - for (CurveChannelColor c : { CurveChannelColor::Red, CurveChannelColor::Green, CurveChannelColor::Blue }) - colors.channels.push_back(CurveChannel{ .name = "C", .color = c, .curve = MakeCurve(kZero) }); + curve.channels = { curves::CurveChannel{ .name = "Value", .curve = curves::MakeCurve(kHalf) } }; + for (curves::CurveChannelColor c : { curves::CurveChannelColor::Red, curves::CurveChannelColor::Green, curves::CurveChannelColor::Blue }) + colors.channels.push_back(curves::CurveChannel{ .name = "C", .color = c, .curve = curves::MakeCurve(kZero) }); SetRedrawMode(RedrawMode::Always); return true; } 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_node_look_test.cpp b/tests/gpu/gpu_node_look_test.cpp index ea6641fc..b4283d61 100644 --- a/tests/gpu/gpu_node_look_test.cpp +++ b/tests/gpu/gpu_node_look_test.cpp @@ -5,7 +5,8 @@ #include #include -#include +#include +#include #include "gpu_injected_input.h" @@ -30,7 +31,8 @@ namespace { public: ID windowID = ID::Invalid(); - NodeView view; + nodes::NodeView view; + nodes::Context nodesContext; const color4f red { 0.88f, 0.44f, 0.42f, 1.0f }; const color4f teal { 0.20f, 0.82f, 0.75f, 1.0f }; @@ -38,11 +40,11 @@ namespace { if (BeginWindow(windowID, "Nodes", theme.mainWindowStyleRef, LayoutOverride{}.Size(900, 600), ElementFlags::WindowRenderToImage)) - RenderNodeView(view); + nodes::RenderNodeView(*this, nodesContext, view); EndWindow(); } - bool Start(NodeViewKind kind) + bool Start(nodes::NodeViewKind kind) { UseInjectedInputOnly(*this); if (!Initialize()) @@ -50,16 +52,16 @@ namespace windowID = idManager.CreateStaticID(); view.kind = kind; view.showMinimap = false; - NodeModel node; + nodes::NodeModel node; node.stableID = idManager.CreateStaticID(); node.title = "N"; // short: the header's middle is clear of it node.pos = { -100, -60 }; node.categoryColor = red; - if (kind == NodeViewKind::Graph) - node.properties.push_back(NodeProperty{ .output = true }); + if (kind == nodes::NodeViewKind::Graph) + node.properties.push_back(nodes::NodeProperty{ .output = true }); view.nodes.push_back(std::move(node)); - if (kind == NodeViewKind::Graph) - view.frames.push_back(NodeFrame{ .stableID = idManager.CreateStaticID(), .title = "F", .color = teal, + if (kind == nodes::NodeViewKind::Graph) + view.frames.push_back(nodes::NodeFrame{ .stableID = idManager.CreateStaticID(), .title = "F", .color = teal, .pos = { -380, -160 }, .size = { 200, 240 } }); SetRedrawMode(RedrawMode::Always); return true; @@ -107,10 +109,10 @@ namespace TEST(GpuNodeLook, ANodesHeaderIsTintedWithItsColor) { NodeLookApp app; - if (!app.Start(NodeViewKind::Graph)) { app.Cleanup(); GTEST_SKIP() << "no GPU device available"; } + if (!app.Start(nodes::NodeViewKind::Graph)) { app.Cleanup(); GTEST_SKIP() << "no GPU device available"; } ASSERT_TRUE(app.Frames(4)); ASSERT_TRUE(app.Read()); - const ElementRef node = app.elementStorage.FindElementRefByID(NodeElementID(app.view, app.view.nodes[0].stableID)); + const ElementRef node = app.elementStorage.FindElementRefByID(nodes::NodeElementID(app.view, app.view.nodes[0].stableID)); ASSERT_TRUE(node.IsValid()); const ElementRef header = app.elementStorage.GetChildrenSpan(node).empty() ? ElementRef{} : app.elementStorage.FindElementRefByID(app.elementStorage.GetChildrenSpan(node)[0].id); @@ -118,8 +120,8 @@ namespace const IntRect h = app.OnScreen(header); const IntRect n = app.OnScreen(node); const color4f body = app.theme.GetColor("--node-bg"); - const Rgb tint = Mix(body, app.red, app.theme.nodeTints.header); - const Rgb line = Mix(body, app.red, app.theme.nodeTints.headerLine); + const Rgb tint = Mix(body, app.red, nodes::GetStyles(app, app.nodesContext).nodeTints.header); + const Rgb line = Mix(body, app.red, nodes::GetStyles(app, app.nodesContext).nodeTints.headerLine); EXPECT_LT(Distance(app.At(h.x + h.w * 3 / 4, h.y + h.h / 2), tint), 12) << Show(app.At(h.x + h.w * 3 / 4, h.y + h.h / 2)); EXPECT_LT(Distance(app.At(h.x + h.w * 3 / 4, h.y + h.h - 1), line), 12) << "the line under it, stronger"; EXPECT_LT(Distance(app.At(n.x + n.w / 2, n.y + n.h - 3), Mix(body, body, 0.0f)), 12) << "the body is the node's own color"; @@ -129,15 +131,15 @@ namespace TEST(GpuNodeLook, AStateIsFilledAndEdgedInItsColor) { NodeLookApp app; - if (!app.Start(NodeViewKind::StateMachine)) { app.Cleanup(); GTEST_SKIP() << "no GPU device available"; } + if (!app.Start(nodes::NodeViewKind::StateMachine)) { app.Cleanup(); GTEST_SKIP() << "no GPU device available"; } ASSERT_TRUE(app.Frames(4)); ASSERT_TRUE(app.Read()); - const ElementRef state = app.elementStorage.FindElementRefByID(NodeElementID(app.view, app.view.nodes[0].stableID)); + const ElementRef state = app.elementStorage.FindElementRefByID(nodes::NodeElementID(app.view, app.view.nodes[0].stableID)); ASSERT_TRUE(state.IsValid()); const IntRect s = app.OnScreen(state); const color4f body = app.theme.GetColor("--node-bg"); - const Rgb fill = Mix(body, app.red, app.theme.nodeTints.state); - const Rgb edge = Mix(body, app.red, app.theme.nodeTints.stateBorder); + const Rgb fill = Mix(body, app.red, nodes::GetStyles(app, app.nodesContext).nodeTints.state); + const Rgb edge = Mix(body, app.red, nodes::GetStyles(app, app.nodesContext).nodeTints.stateBorder); EXPECT_LT(Distance(app.At(s.x + s.w * 3 / 4, s.y + s.h / 2), fill), 12) << Show(app.At(s.x + s.w * 3 / 4, s.y + s.h / 2)); EXPECT_LT(Distance(app.At(s.x + s.w / 2, s.y), edge), 12) << "edged in its color: " << Show(app.At(s.x + s.w / 2, s.y)); app.Cleanup(); @@ -148,12 +150,12 @@ namespace TEST(GpuNodeLook, AnActiveStateIsRingedWithItsTimeUnderIt) { NodeLookApp app; - if (!app.Start(NodeViewKind::StateMachine)) { app.Cleanup(); GTEST_SKIP() << "no GPU device available"; } + if (!app.Start(nodes::NodeViewKind::StateMachine)) { app.Cleanup(); GTEST_SKIP() << "no GPU device available"; } app.view.activeState = app.view.nodes[0].stableID; app.view.activeStateTime = 1.24f; ASSERT_TRUE(app.Frames(4)); ASSERT_TRUE(app.Read()); - const IntRect s = app.OnScreen(app.elementStorage.FindElementRefByID(NodeElementID(app.view, app.view.nodes[0].stableID))); + const IntRect s = app.OnScreen(app.elementStorage.FindElementRefByID(nodes::NodeElementID(app.view, app.view.nodes[0].stableID))); const color4f ok = app.theme.GetColor("--ok"); const Rgb okRgb = Mix(ok, ok, 0.0f); const int ring = app.styleManager.Px(3); @@ -179,11 +181,11 @@ namespace TEST(GpuNodeLook, ANestedStateHasABoxStackedBehindIt) { NodeLookApp app; - if (!app.Start(NodeViewKind::StateMachine)) { app.Cleanup(); GTEST_SKIP() << "no GPU device available"; } + if (!app.Start(nodes::NodeViewKind::StateMachine)) { app.Cleanup(); GTEST_SKIP() << "no GPU device available"; } app.view.nodes[0].subMachine = true; ASSERT_TRUE(app.Frames(4)); ASSERT_TRUE(app.Read()); - const IntRect s = app.OnScreen(app.elementStorage.FindElementRefByID(NodeElementID(app.view, app.view.nodes[0].stableID))); + const IntRect s = app.OnScreen(app.elementStorage.FindElementRefByID(nodes::NodeElementID(app.view, app.view.nodes[0].stableID))); // In the state's shadow, so darker than the state, but red where the canvas is grey. const int o = app.styleManager.Px(4); const Rgb behind = app.At(s.x - o / 2, s.y + s.h / 2); @@ -198,28 +200,28 @@ namespace TEST(GpuNodeLook, AFrameIsFaintWithItsColorItsTitleBarStronger) { NodeLookApp app; - if (!app.Start(NodeViewKind::Graph)) { app.Cleanup(); GTEST_SKIP() << "no GPU device available"; } + if (!app.Start(nodes::NodeViewKind::Graph)) { app.Cleanup(); GTEST_SKIP() << "no GPU device available"; } ASSERT_TRUE(app.Frames(4)); ASSERT_TRUE(app.Read()); // The frame where it is from the node, at 100%: its title bar a row pitch tall (two grid // cells), the box going on below it. - const ElementRef node = app.elementStorage.FindElementRefByID(NodeElementID(app.view, app.view.nodes[0].stableID)); + const ElementRef node = app.elementStorage.FindElementRefByID(nodes::NodeElementID(app.view, app.view.nodes[0].stableID)); ASSERT_TRUE(node.IsValid()); const IntRect n = app.OnScreen(node); - const NodeFrame& frame = app.view.frames[0]; + const nodes::NodeFrame& frame = app.view.frames[0]; const IntRect t{ n.x + frame.pos.x - app.view.nodes[0].pos.x, n.y + frame.pos.y - app.view.nodes[0].pos.y, - frame.size.x, 2 * app.theme.nodeGridSize }; + frame.size.x, 2 * nodes::GetStyles(app, app.nodesContext).nodeGridSize }; const IntRect window = app.windowManager->GetWindowRect(app.windowID); ASSERT_TRUE(t.x >= 3 && t.y >= 3 && t.x + t.w + 3 <= window.w && t.y + t.h + 83 <= window.h) << "in the window: " << t.x << "," << t.y; const color4f canvas = app.theme.GetColor("--bg-canvas"); - const Rgb fill = Mix(canvas, app.teal, app.theme.nodeTints.frameFill); + const Rgb fill = Mix(canvas, app.teal, nodes::GetStyles(app, app.nodesContext).nodeTints.frameFill); // The title bar is over the box's fill. - const float boxA = app.theme.nodeTints.frameFill; + const float boxA = nodes::GetStyles(app, app.nodesContext).nodeTints.frameFill; const color4f boxColor{ canvas.r + (app.teal.r - canvas.r) * boxA, canvas.g + (app.teal.g - canvas.g) * boxA, canvas.b + (app.teal.b - canvas.b) * boxA, 1.0f }; - const Rgb band = Mix(boxColor, app.teal, app.theme.nodeTints.frameBand); - const Rgb border = Mix(canvas, app.teal, app.theme.nodeTints.frameBorder); + const Rgb band = Mix(boxColor, app.teal, nodes::GetStyles(app, app.nodesContext).nodeTints.frameBand); + const Rgb border = Mix(canvas, app.teal, nodes::GetStyles(app, app.nodesContext).nodeTints.frameBorder); const Rgb inBox = app.Nearest(t.x + t.w / 2, t.y + t.h + 80, fill); EXPECT_LT(Distance(inBox, fill), 12) << "faint: " << Show(inBox); const Rgb inBand = app.Nearest(t.x + t.w * 3 / 4, t.y + t.h / 2, band); diff --git a/tests/gpu/gpu_node_view_test.cpp b/tests/gpu/gpu_node_view_test.cpp index ac36d1e4..685fba6c 100644 --- a/tests/gpu/gpu_node_view_test.cpp +++ b/tests/gpu/gpu_node_view_test.cpp @@ -4,7 +4,8 @@ #include #include -#include +#include +#include #include "gpu_injected_input.h" @@ -16,19 +17,20 @@ namespace { public: ID windowID = ID::Invalid(); - NodeView view; + nodes::NodeView view; + nodes::Context nodesContext; int frame = 0; int added = 0; bool addAfterRender = false; // the app adds a node later in its frame, after the view - NodeModel Node(int2 pos, bool input, bool output) + nodes::NodeModel Node(int2 pos, bool input, bool output) { - NodeModel node; + nodes::NodeModel node; node.stableID = idManager.CreateStaticID(); node.title = "Node"; node.pos = pos; - node.properties.push_back(NodeProperty{ - .input = input ? std::optional(PropertyEndpoint{}) : std::nullopt, + node.properties.push_back(nodes::NodeProperty{ + .input = input ? std::optional(nodes::PropertyEndpoint{}) : std::nullopt, .output = output }); return node; } @@ -37,11 +39,11 @@ namespace { if (BeginWindow(windowID, "Nodes", theme.mainWindowStyleRef, LayoutOverride{}.Size(900, 600), ElementFlags::WindowRenderToImage)) - RenderNodeView(view); + nodes::RenderNodeView(*this, nodesContext, view); EndWindow(); if (addAfterRender && frame == 5) { - CommitNodeViewEdit(view, RerouteWireEdit(view, WireKey(1, 0), idManager.CreateStaticID(), { -100, -20 })); + nodes::CommitNodeViewEdit(view, nodes::RerouteWireEdit(view, nodes::WireKey(1, 0), idManager.CreateStaticID(), { -100, -20 })); ++added; } @@ -64,10 +66,10 @@ namespace windowID = idManager.CreateStaticID(); view.nodes.push_back(Node({ -300, -100 }, false, true)); view.nodes.push_back(Node({ 100, 60 }, true, false)); - view.nodes[1].properties[0].input = PropertyEndpoint{ 0, 0 }; + view.nodes[1].properties[0].input = nodes::PropertyEndpoint{ 0, 0 }; view.onCanvasContextMenu = [this](float2) { MenuItem("Add reroute", [this] { - CommitNodeViewEdit(view, RerouteWireEdit(view, WireKey(1, 0), idManager.CreateStaticID(), { -100, -20 })); + nodes::CommitNodeViewEdit(view, nodes::RerouteWireEdit(view, nodes::WireKey(1, 0), idManager.CreateStaticID(), { -100, -20 })); ++added; }); }; @@ -88,7 +90,7 @@ namespace EXPECT_EQ(app.added, 1) << "the menu item was chosen"; ASSERT_EQ(app.view.nodes.size(), 3u); EXPECT_TRUE(app.view.nodes[2].reroute); - EXPECT_EQ(*app.view.nodes[1].properties[0].input, (PropertyEndpoint{ 2, 0 })); + EXPECT_EQ(*app.view.nodes[1].properties[0].input, (nodes::PropertyEndpoint{ 2, 0 })); app.Cleanup(); } @@ -116,14 +118,15 @@ namespace { public: ID windowID = ID::Invalid(); - NodeView view; + nodes::NodeView view; + nodes::Context nodesContext; size_t handles = 0; // lane handles the draw found, with the wire on void OnGUI() override { if (BeginWindow(windowID, "Nodes", theme.mainWindowStyleRef, LayoutOverride{}.Size(900, 600), ElementFlags::WindowRenderToImage)) - RenderNodeView(view); + nodes::RenderNodeView(*this, nodesContext, view); EndWindow(); } @@ -147,25 +150,25 @@ namespace // Where, a quarter of the way along the wire, it crosses: the middle row of the // changed pixels in that column, or -1. - int QuarterRow(NodeWireShape shape) + int QuarterRow(nodes::NodeWireShape shape) { if (!Initialize()) return -2; windowID = idManager.CreateStaticID(); - NodeModel a, b; + nodes::NodeModel a, b; a.stableID = idManager.CreateStaticID(); a.pos = { -300, -200 }; - a.properties.push_back(NodeProperty{ .output = true }); + a.properties.push_back(nodes::NodeProperty{ .output = true }); b.stableID = idManager.CreateStaticID(); b.pos = { 100, 200 }; - b.properties.push_back(NodeProperty{ .input = PropertyEndpoint{ 0, 0 } }); + b.properties.push_back(nodes::NodeProperty{ .input = nodes::PropertyEndpoint{ 0, 0 } }); view.nodes = { std::move(a), std::move(b) }; view.showMinimap = view.showZoomControls = false; view.wireShape = shape; if (!Frames(6)) return -1; handles = view.wireHandleCache.size(); const std::vector with = Pixels(); - view.nodes[1].properties[0].input = PropertyEndpoint{}; + view.nodes[1].properties[0].input = nodes::PropertyEndpoint{}; if (!Frames(4)) return -1; const std::vector without = Pixels(); const IntRect rect = windowManager->GetWindowRect(windowID); @@ -188,7 +191,7 @@ namespace if (top < 0) return -1; // Wired again, with the mouse there: the view finds the wire under it. - view.nodes[1].properties[0].input = PropertyEndpoint{ 0, 0 }; + view.nodes[1].properties[0].input = nodes::PropertyEndpoint{ 0, 0 }; if (!Frames(2)) return -1; InjectMouseMove(windowID, { column, (top + bottom) / 2 }); if (!Frames(3)) return -1; @@ -209,7 +212,7 @@ namespace std::optional gridHovered, curveHovered; { WireShapeApp app; - grid = app.QuarterRow(NodeWireShape::Orthogonal); + grid = app.QuarterRow(nodes::NodeWireShape::Orthogonal); gridHandles = app.handles; gridHovered = app.hovered; app.Cleanup(); @@ -218,7 +221,7 @@ namespace GTEST_SKIP() << "no GPU device available"; { WireShapeApp app; - curve = app.QuarterRow(NodeWireShape::Curved); + curve = app.QuarterRow(nodes::NodeWireShape::Curved); curveHandles = app.handles; curveHovered = app.hovered; app.Cleanup(); @@ -228,7 +231,7 @@ namespace EXPECT_GT(curve, grid + 8) << "the curve is below the output's row there"; EXPECT_GT(gridHandles, 0u); EXPECT_EQ(curveHandles, 0u); - EXPECT_EQ(gridHovered, WireKey(1, 0)); - EXPECT_EQ(curveHovered, WireKey(1, 0)) << "hovered along the curve it's drawn as"; + EXPECT_EQ(gridHovered, nodes::WireKey(1, 0)); + EXPECT_EQ(curveHovered, nodes::WireKey(1, 0)) << "hovered along the curve it's drawn as"; } } diff --git a/tests/gpu/gpu_table_header_test.cpp b/tests/gpu/gpu_table_header_test.cpp index 7cb2724a..ed3259f7 100644 --- a/tests/gpu/gpu_table_header_test.cpp +++ b/tests/gpu/gpu_table_header_test.cpp @@ -5,6 +5,7 @@ #include #include +#include #include "gpu_injected_input.h" @@ -20,19 +21,22 @@ namespace public: ID windowID = ID::Invalid(); ID tableID = ID::Invalid(); - TableState state; - std::vector columns; + views::TableState state; + std::vector columns; + views::Context viewsContext; void OnGUI() override { if (BeginWindow(windowID, "Table", theme.mainWindowStyleRef, LayoutOverride{}.Size(500, 300), ElementFlags::WindowRenderToImage)) { - std::span span(columns.data(), columns.size()); + std::span span(columns.data(), columns.size()); // Few enough rows to fit: no scrollbar over the last column's cells. - VirtualTable(tableID, state, span, 5, 0, theme.tableFillStyleRef, LayoutOverride::Auto().FlexGrow(1).MinHeight(0)); + views::VirtualTable(*this, viewsContext, tableID, state, span, 5, 0, views::GetStyles(*this, viewsContext).tableFillStyleRef, + LayoutOverride::Auto().FlexGrow(1).MinHeight(0)); } EndWindow(); + views::EndGUI(*this, viewsContext); } bool Start() @@ -44,12 +48,12 @@ namespace tableID = idManager.CreateStaticID(); columns.resize(3); columns[0].column = { .header = "#", .initialWidth = 60 }; - columns[0].generateCell = [this](int) { Cell("1"); }; + columns[0].generateCell = [this](int) { views::Cell(*this, viewsContext, "1"); }; columns[0].sortAscending = [](int a, int b) { return a < b; }; // sorted: its header has the chevron columns[1].column = { .header = "Name", .initialWidth = 160 }; - columns[1].generateCell = [this](int) { Cell("Row"); }; - columns[2].column = { .header = "Value", .initialWidth = 120, .cellStyle = theme.tableCellNumberStyleRef }; // right-aligned - columns[2].generateCell = [this](int) { Cell("1234"); }; + columns[1].generateCell = [this](int) { views::Cell(*this, viewsContext, "Row"); }; + columns[2].column = { .header = "Value", .initialWidth = 120, .cellStyle = views::GetStyles(*this, viewsContext).tableCellNumberStyleRef }; // right-aligned + columns[2].generateCell = [this](int) { views::Cell(*this, viewsContext, "1234"); }; state.sortColumn = 0; return true; } 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/gpu/gpu_tree_drop_line_test.cpp b/tests/gpu/gpu_tree_drop_line_test.cpp index e4b98516..c8c359ca 100644 --- a/tests/gpu/gpu_tree_drop_line_test.cpp +++ b/tests/gpu/gpu_tree_drop_line_test.cpp @@ -5,6 +5,7 @@ #include #include +#include #include "gpu_injected_input.h" @@ -24,7 +25,8 @@ namespace public: ID windowID = ID::Invalid(); ID tableID = ID::Invalid(); - TableState state; + views::Context viewsContext; + views::TableState state; ItemDragDropConfig dragDrop; std::vector names{ "Alpha", "Beta", "Gamma", "Delta" }; @@ -33,18 +35,19 @@ namespace if (BeginWindow(windowID, "Tree", theme.mainWindowStyleRef, LayoutOverride{}.Size(500, 300), ElementFlags::WindowRenderToImage)) { - VirtualTableColumn cols[2]; - cols[0].column = TableColumn{ .header = {}, .initialWidth = kFirstColumnWidth, .minWidth = kFirstColumnWidth, - .maxWidth = kFirstColumnWidth, .sizing = ColumnSizing::Fixed }; - cols[0].generateCell = [this](int) { Cell(""); }; - cols[1].column = TableColumn{ .header = {} }; - cols[1].generateCell = [this](int row) { TreeCell(names[size_t(row)], 0, nullptr); }; + views::VirtualTableColumn cols[2]; + cols[0].column = views::TableColumn{ .header = {}, .initialWidth = kFirstColumnWidth, .minWidth = kFirstColumnWidth, + .maxWidth = kFirstColumnWidth, .sizing = views::ColumnSizing::Fixed }; + cols[0].generateCell = [this](int) { views::Cell(*this, viewsContext, ""); }; + cols[1].column = views::TableColumn{ .header = {} }; + cols[1].generateCell = [this](int row) { views::TreeCell(*this, viewsContext, names[size_t(row)], 0, nullptr); }; state.showHeaders = false; state.rowDragDrop = &dragDrop; - VirtualTable(tableID, state, std::span(cols, 2), int(names.size()), 0, {}, + views::VirtualTable(*this, viewsContext, tableID, state, std::span(cols, 2), int(names.size()), 0, {}, LayoutOverride{}.FlexGrow(1)); } EndWindow(); + views::EndGUI(*this, viewsContext); } bool Start() @@ -113,8 +116,8 @@ namespace ASSERT_TRUE(app.Frames(1)); } ASSERT_TRUE(app.Frames(2)); - ASSERT_EQ(app.m_treeDropState.targetRowID, app.state.RowIDForIndex(2)); - ASSERT_EQ(app.m_treeDropState.position, TreeDropPosition::Before); + ASSERT_EQ(app.viewsContext.treeDrop.targetRowID, app.state.RowIDForIndex(2)); + ASSERT_EQ(app.viewsContext.treeDrop.position, TreeDropPosition::Before); const std::vector during = app.Pixels(); app.InjectMouseButton(app.windowID, { x, to.y + 3 }, MouseButtons::Left, false); ASSERT_TRUE(app.Frames(1)); @@ -134,7 +137,7 @@ namespace { firstX = px; break; } } // The items' icons come after the first column and the tree's arrow column. - const int itemsX = to.x + kFirstColumnWidth + app.theme.treeTableExpanderWidth; + const int itemsX = to.x + kFirstColumnWidth + views::GetStyles(app, app.viewsContext).treeTableExpanderWidth; ASSERT_GE(firstX, 0) << "the drop line is drawn"; EXPECT_GE(firstX, itemsX) << "it starts at the items' icons; the row starts at " << to.x; EXPECT_LE(firstX, itemsX + 16) << "at the items' icons, not further in"; diff --git a/tests/gradient_editor_dialog_test.cpp b/tests/gradient_editor_dialog_test.cpp index 919b5c76..2765fece 100644 --- a/tests/gradient_editor_dialog_test.cpp +++ b/tests/gradient_editor_dialog_test.cpp @@ -10,7 +10,7 @@ #include #include -#include +#include namespace { @@ -32,7 +32,7 @@ namespace { app.Frame([&] { app.BeginRootWindow({ 1200, 900 }); - app.GradientField(gradient, LayoutOverride{}.Width(300)); + color::GradientField(app, colorContext, gradient, LayoutOverride{}.Width(300)); app.EndRootWindow(); }); } @@ -51,7 +51,7 @@ namespace void Open() { Emit(); - app.ClickAt(app.CenterOf(FindByStyle(app.theme.gradientSwatchStyleRef))); + app.ClickAt(app.CenterOf(FindByStyle(color::GetStyles(app, colorContext).gradientSwatchStyleRef))); Emit(); Emit(); } @@ -66,13 +66,14 @@ namespace // A point on the dialog's gradient bar, `t` across it (the bar is inset 24 px at the sides). int2 OnTheBar(float t) { - const IntRect r = app.GetElementRect(FindByStyle(app.theme.gradientEditorBarStyleRef)); + const IntRect r = app.GetElementRect(FindByStyle(color::GetStyles(app, colorContext).gradientEditorBarStyleRef)); const int inset = app.styleManager.Px(24); const int barTop = r.y + (r.h - app.styleManager.Px(44 + 6 + 18)) / 2; return { r.x + inset + int(t * float(r.w - 2 * inset)), barTop + app.styleManager.Px(20) }; } HeadlessGUIApp app; + color::Context colorContext; Gradient gradient; }; @@ -88,7 +89,7 @@ namespace app.Frame([&] { app.BeginRootWindow({ 1200, 900 }); for (int i = 0; i < count; ++i) - app.GradientField(gradients[size_t(i)], LayoutOverride{}.Width(300)); + color::GradientField(app, colorContext, gradients[size_t(i)], LayoutOverride{}.Width(300)); app.EndRootWindow(); }); }; @@ -106,7 +107,7 @@ namespace TEST_F(GradientEditorDialog, TheFieldOpensIt) { Open(); - EXPECT_NE(FindByStyle(app.theme.gradientEditorBarStyleRef), ID::Invalid()); + EXPECT_NE(FindByStyle(color::GetStyles(app, colorContext).gradientEditorBarStyleRef), ID::Invalid()); EXPECT_NE(FindByStyle(app.theme.dialogPrimaryButtonStyleRef), ID::Invalid()) << "with an OK button"; } @@ -145,7 +146,7 @@ namespace const auto& storage = app.elementStorage; for (auto it = storage.TopDownDepthScanBegin(); it != storage.TopDownDepthScanEnd(); ++it) for (const Element& e : it->GetChildren(storage)) - if (e.styleRef == app.theme.gradientEditorPresetStyleRef) + if (e.styleRef == color::GetStyles(app, colorContext).gradientEditorPresetStyleRef) { GUITest::StubGUIRenderer renderer; const ElementRef ref = storage.FindElementRefByID(e.id); @@ -168,7 +169,7 @@ namespace EXPECT_EQ(gradient.stopCount, 3) << "a click on the bar added a stop"; ClickAt(app.CenterOf(FindByStyle(app.theme.dialogButtonStyleRef))); EXPECT_EQ(gradient.stopCount, 2); - EXPECT_EQ(FindByStyle(app.theme.gradientEditorBarStyleRef), ID::Invalid()) << "and closed the dialog"; + EXPECT_EQ(FindByStyle(color::GetStyles(app, colorContext).gradientEditorBarStyleRef), ID::Invalid()) << "and closed the dialog"; } TEST_F(GradientEditorDialog, OkKeepsTheGradient) @@ -177,7 +178,7 @@ namespace ClickAt(OnTheBar(0.5f)); ClickAt(app.CenterOf(FindByStyle(app.theme.dialogPrimaryButtonStyleRef))); EXPECT_EQ(gradient.stopCount, 3); - EXPECT_EQ(FindByStyle(app.theme.gradientEditorBarStyleRef), ID::Invalid()) << "and closed the dialog"; + EXPECT_EQ(FindByStyle(color::GetStyles(app, colorContext).gradientEditorBarStyleRef), ID::Invalid()) << "and closed the dialog"; } // Escape in the dialog is Cancel, and the keyboard goes back to the swatch. @@ -186,15 +187,15 @@ namespace Open(); ClickAt(OnTheBar(0.5f)); ASSERT_EQ(gradient.stopCount, 3); - app.activeWindow = GUIApplicationInternals::GradientEditor(app).State().windowID; // the dialog has the keyboard + app.activeWindow = colorContext.gradientEditor.windowID; // the dialog has the keyboard Emit(); app.InjectKey(KeyCode::Escape); Emit(); Emit(); app.activeWindow = ID::Invalid(); EXPECT_EQ(gradient.stopCount, 2); - EXPECT_EQ(FindByStyle(app.theme.gradientEditorBarStyleRef), ID::Invalid()) << "closed"; - EXPECT_EQ(app.guiStateManager.Interaction().GetFocusedID(), FindByStyle(app.theme.gradientSwatchStyleRef)); + EXPECT_EQ(FindByStyle(color::GetStyles(app, colorContext).gradientEditorBarStyleRef), ID::Invalid()) << "closed"; + EXPECT_EQ(app.guiStateManager.Interaction().GetFocusedID(), FindByStyle(color::GetStyles(app, colorContext).gradientSwatchStyleRef)); } // Opened and closed with OK, untouched, the gradient is exactly as it was: no edit reported. @@ -207,21 +208,21 @@ namespace auto emit = [&] { app.Frame([&] { app.BeginRootWindow({ 1200, 900 }); - changed |= app.GradientField(gradient, LayoutOverride{}.Width(300)); + changed |= color::GradientField(app, colorContext, gradient, LayoutOverride{}.Width(300)); app.EndRootWindow(); }); }; emit(); - app.ClickAt(app.CenterOf(FindByStyle(app.theme.gradientSwatchStyleRef))); + app.ClickAt(app.CenterOf(FindByStyle(color::GetStyles(app, colorContext).gradientSwatchStyleRef))); emit(); emit(); - ASSERT_NE(FindByStyle(app.theme.gradientEditorBarStyleRef), ID::Invalid()); + ASSERT_NE(FindByStyle(color::GetStyles(app, colorContext).gradientEditorBarStyleRef), ID::Invalid()); app.ClickAt(app.CenterOf(FindByStyle(app.theme.dialogPrimaryButtonStyleRef))); emit(); emit(); EXPECT_FALSE(changed); EXPECT_EQ(gradient, before); - EXPECT_EQ(FindByStyle(app.theme.gradientEditorBarStyleRef), ID::Invalid()) << "closed"; + EXPECT_EQ(FindByStyle(color::GetStyles(app, colorContext).gradientEditorBarStyleRef), ID::Invalid()) << "closed"; } // A Gradient field's editor stops at the Gradient's 8 stops, and has no per-stop blend. @@ -244,14 +245,14 @@ namespace { app.Frame([&] { app.BeginRootWindow({ 1200, 900 }); - app.GradientField(floatGradient, LayoutOverride{}.Width(300)); + color::GradientField(app, colorContext, floatGradient, LayoutOverride{}.Width(300)); app.EndRootWindow(); }); } void OpenF() { EmitF(); - app.ClickAt(app.CenterOf(FindByStyle(app.theme.gradientSwatchStyleRef))); + app.ClickAt(app.CenterOf(FindByStyle(color::GetStyles(app, colorContext).gradientSwatchStyleRef))); EmitF(); EmitF(); } @@ -294,26 +295,26 @@ namespace } // In a row 300 wide, as in an inspector. - void EmitInARow(HeadlessGUIApp& app, GradientF& gradient) + void EmitInARow(HeadlessGUIApp& app, color::Context& colorContext, GradientF& gradient) { for (int i = 0; i < 2; ++i) app.Frame([&] { app.BeginRootWindow({ 1200, 900 }); app.BeginHorizontal(app.idManager.AllocateDynamicID("row"), app.theme.emptyHorzStyleRef, LayoutOverride::FixedWidth(300)); - app.GradientField(gradient); + color::GradientField(app, colorContext, gradient); app.EndHorizontal(); app.EndRootWindow(); }); } // Points at the swatch and waits past the tooltip's delay. - void HoverTheSwatch(HeadlessGUIApp& app, GradientF& gradient, ID swatch) + void HoverTheSwatch(HeadlessGUIApp& app, color::Context& colorContext, GradientF& gradient, ID swatch) { app.InjectMouseMove(app.CenterOf(swatch)); for (int i = 0; i < 8; ++i) { app.AdvanceTime(100); - EmitInARow(app, gradient); + EmitInARow(app, colorContext, gradient); } } @@ -323,10 +324,10 @@ namespace { floatGradient.AddStop(color4f{ 0.0f, 0.0f, 0.0f, 1.0f }, 0.0f); floatGradient.AddStop(color4f{ 8.0f, 6.0f, 2.0f, 1.0f }, 1.0f); - EmitInARow(app, floatGradient); - const ID swatch = FindByStyle(app.theme.gradientSwatchStyleRef); + EmitInARow(app, colorContext, floatGradient); + const ID swatch = FindByStyle(color::GetStyles(app, colorContext).gradientSwatchStyleRef); EXPECT_EQ(app.GetElementRect(swatch).w, app.styleManager.Px(300)) << "the bar is the whole field"; - HoverTheSwatch(app, floatGradient, swatch); + HoverTheSwatch(app, colorContext, floatGradient, swatch); EXPECT_NE(app.FindByText("Up to 8.0 \xC3\x97 white"), ID::Invalid()); } @@ -334,8 +335,8 @@ namespace { floatGradient.AddStop(color4f{ 0.0f, 0.0f, 0.0f, 1.0f }, 0.0f); floatGradient.AddStop(color4f{ 1.0f, 1.0f, 1.0f, 1.0f }, 1.0f); - EmitInARow(app, floatGradient); - HoverTheSwatch(app, floatGradient, FindByStyle(app.theme.gradientSwatchStyleRef)); + EmitInARow(app, colorContext, floatGradient); + HoverTheSwatch(app, colorContext, floatGradient, FindByStyle(color::GetStyles(app, colorContext).gradientSwatchStyleRef)); EXPECT_EQ(app.FindByText("Up to 1.0 \xC3\x97 white"), ID::Invalid()); } @@ -359,7 +360,7 @@ namespace TEST_F(GradientEditorDialog, TheHeaderDragsTheDialog) { Open(); - const ID window = GUIApplicationInternals::GradientEditor(app).State().windowID; + const ID window = colorContext.gradientEditor.windowID; const IntRect header = app.GetElementRect(FindByStyle(app.theme.dialogHeaderStyleRef)); EXPECT_EQ(app.TitleBarHitTest(window, { header.x + header.w / 2, header.y + header.h / 2 }), WindowHitArea::Caption); EXPECT_EQ(app.TitleBarHitTest(window, app.CenterOf(FindByStyle(app.theme.dialogCloseStyleRef))), WindowHitArea::Client); @@ -369,7 +370,7 @@ namespace TEST_F(GradientEditorDialog, AThemeReloadRecreatesItsStyles) { Open(); - auto& ge = GUIApplicationInternals::GradientEditor(app).State(); + auto& ge = colorContext.gradientEditor; ge.stopHaloColor = app.theme.accentColor; GUIApplicationInternals::ReloadThemeNextFrame(app); Emit(); @@ -381,7 +382,7 @@ namespace TEST_F(GradientEditorDialog, AGrabbedStopMovesFromWhereItWasAndEscapePutsItBack) { Open(); - const auto& working = GUIApplicationInternals::GradientEditor(app).State().workingCopy; + const auto& working = colorContext.gradientEditor.workingCopy; ASSERT_EQ(working.stops.size(), 2u); const int2 bar = OnTheBar(0.0f); // The stops' handles hang under the bar (44 px), past its pointer (6 px), 18 px tall. @@ -402,7 +403,7 @@ namespace Emit(); EXPECT_FLOAT_EQ(working.stops[0].offset, 0.0f); EXPECT_EQ(working.stops.size(), 2u); - EXPECT_NE(FindByStyle(app.theme.gradientEditorBarStyleRef), ID::Invalid()) << "only the drag was cancelled"; + EXPECT_NE(FindByStyle(color::GetStyles(app, colorContext).gradientEditorBarStyleRef), ID::Invalid()) << "only the drag was cancelled"; app.InjectMouseMove({ to.x + 30, to.y }, MouseButtons::Left); app.InjectMouseUp({ to.x + 30, to.y }); diff --git a/tests/headless_gui_app.cpp b/tests/headless_gui_app.cpp index 30d8d572..bd99625a 100644 --- a/tests/headless_gui_app.cpp +++ b/tests/headless_gui_app.cpp @@ -83,11 +83,7 @@ tachyon::Result HeadlessGUIApp::Initialize(const InitializeOptions& option m_menuRects = std::make_unique(); m_labelGroup = std::make_unique(m_frame, elementStorage, guiStateManager, theme); m_buttonGroup = std::make_unique(m_frame, elementStorage, styleManager); - m_colorPickerSub = std::make_unique(m_frame); - m_gradientEditorSub = std::make_unique(m_frame); - m_renameSub = std::make_unique(); m_reorderable = std::make_unique(m_frame); - m_dockTabDragSub = std::make_unique(); m_uiCache = std::make_unique(m_frame, elementStorage, guiStateManager); RegisterFrameBalanceChecks(); @@ -151,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(); @@ -162,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. @@ -190,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. @@ -217,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); @@ -233,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. @@ -267,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); @@ -286,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/keyboard_focus_test.cpp b/tests/keyboard_focus_test.cpp index 8c811ac6..2edd9a93 100644 --- a/tests/keyboard_focus_test.cpp +++ b/tests/keyboard_focus_test.cpp @@ -8,6 +8,9 @@ #include "headless_gui_app.h" #include +#include +#include +#include #include #include @@ -31,11 +34,11 @@ namespace tachyon for (ID* id : { &buttonID, &toggleID, &checkboxID, &switchID, &textID, &numberID, &sliderFieldID, &intSliderFieldID, &sliderID, &colorID, &gradientID, &listID, &disabledID, &toolbarButtonID, &toolbarToggleID, &toolbarMenuID, &breadcrumbID, &typedID, - &listViewID, &tableID, &dropdownID, &timelineID, &editorID, &edgesID, &cornersID, &shadowID, &curveID, &plotID }) + &listViewID, &tableID, &dropdownID, &edgesID, &cornersID, &shadowID, &curveID, &plotID }) *id = app.idManager.CreateStaticID(); tableColumns.push_back({ .column = { .header = "Name", .initialWidth = 120, .minWidth = 60, .maxWidth = 300 }, - .generateCell = [this](int r) { app.Cell(r == 0 ? "First" : "Second"); } }); + .generateCell = [this](int r) { views::Cell(app, viewsContext, r == 0 ? "First" : "Second"); } }); } void TearDown() override { app.Cleanup(); } @@ -52,8 +55,8 @@ namespace tachyon app.SliderField(sliderFieldID, volume, 0.0f, 100.0f, "Volume"); app.SliderField(intSliderFieldID, count, 0, 10, "Count"); app.Slider(sliderID, level, 0, 10); - app.ColorField(colorID, color); - app.GradientField(gradientID, gradient); + color::ColorField(app, colorContext, colorID, color); + color::GradientField(app, colorContext, gradientID, gradient); app.Field(listID, list); app.BeginToolbar(); app.Button(toolbarButtonID, "Tool", [] {}); @@ -63,22 +66,20 @@ namespace tachyon app.EndToolbar(); app.Breadcrumb(breadcrumbID, crumbs, [](int) {}); app.TypedField(typedID, typed); - if (app.BeginListView(listViewID, &listSelection, 2)) + if (views::BeginListView(app, viewsContext, listViewID, &listSelection, 2)) { - app.ListItem("First"); - app.ListItem("Second"); + views::ListItem(app, viewsContext, "First"); + views::ListItem(app, viewsContext, "Second"); } - app.EndListView(); - app.VirtualTable(tableID, tableState, std::span(tableColumns), 2, 0, - app.theme.tableStyleRef, LayoutOverride{}.Size(200, 80)); + views::EndListView(app, viewsContext); + views::VirtualTable(app, viewsContext, tableID, tableState, std::span(tableColumns), 2, 0, + views::GetStyles(app, viewsContext).tableStyleRef, LayoutOverride{}.Size(200, 80)); app.Dropdown(dropdownID, quality, { "Low", "High" }); - app.Timeline(timelineID, playback, TimelineOptions{ .duration = 4.0f }); - app.TimelineEditor(editorID, animation, LayoutOverride{}.Height(240)); app.EdgesField(edgesID, edges); app.CornersField(cornersID, corners); - app.ShadowField(shadowID, shadow); - app.CurveField(curveID, curve, LayoutOverride::FixedWidth(120)); - app.Plot(plotID, plot, LayoutOverride{}.Size(200, 140)); + color::ShadowField(app, colorContext, shadowID, shadow); + curves::CurveField(app, curvesContext, curveID, curve, LayoutOverride::FixedWidth(120)); + curves::Plot(app, curvesContext, plotID, plot, LayoutOverride{}.Size(200, 140)); app.BeginDisabled(); app.Button(disabledID, "Disabled", [] {}); app.EndDisabled(); @@ -123,7 +124,7 @@ namespace tachyon { gradientID, "GradientField" }, { listID, "Field(list)" }, { toolbarButtonID, "toolbar Button" }, { toolbarToggleID, "toolbar Toggle" }, { toolbarMenuID, "toolbar BeginMenu" }, { breadcrumbID, "Breadcrumb" }, { typedID, "TypedField" }, { listViewID, "ListView" }, { tableID, "VirtualTable" }, { dropdownID, "Dropdown" }, - { timelineID, "Timeline" }, { editorID, "TimelineEditor" }, { edgesID, "EdgesField" }, + { edgesID, "EdgesField" }, { cornersID, "CornersField" }, { shadowID, "ShadowField" }, { curveID, "CurveField" }, { plotID, "Plot" } }; const auto& storage = app.elementStorage; @@ -141,16 +142,17 @@ namespace tachyon } HeadlessGUIApp app; + views::Context viewsContext; + color::Context colorContext; + curves::Context curvesContext; ID buttonID, toggleID, checkboxID, switchID, textID, numberID, sliderFieldID, intSliderFieldID, sliderID, colorID, gradientID, listID, disabledID, toolbarButtonID, toolbarToggleID, toolbarMenuID, - breadcrumbID, typedID, listViewID, tableID, dropdownID, timelineID, editorID, edgesID, cornersID, shadowID, curveID, plotID; - TimelineState playback; - TimelineView animation; + breadcrumbID, typedID, listViewID, tableID, dropdownID, edgesID, cornersID, shadowID, curveID, plotID; bool toolbarToggle = false; std::vector crumbs { "Graphs", "Terrain" }; int typed = 7, listSelection = 0, quality = 0; - TableState tableState; - std::vector tableColumns; + views::TableState tableState; + std::vector tableColumns; bool toggle = false, checkbox = false, switchOn = false; std::string text = "text"; float number = 1.0f, volume = 50.0f; @@ -161,8 +163,8 @@ namespace tachyon BoxEdges edges = BoxEdges(1, 2, 3, 4); // four sides of their own BoxCorners corners = BoxCorners(4); // linked BoxShadow shadow { .y = 4, .blur = 12, .color = { 0, 0, 0, 90 } }; - CurveView curve; - PlotView plot { PlotData{ .series = { PlotSeries{ .name = "R", .values = { 1, 2 } }, PlotSeries{ .name = "G", .values = { 2, 1 } } }, + curves::CurveView curve; + curves::PlotView plot { curves::PlotData{ .series = { curves::PlotSeries{ .name = "R", .values = { 1, 2 } }, curves::PlotSeries{ .name = "G", .values = { 2, 1 } } }, .handles = { { "Black", 0.0f }, { "White", 1.0f } } } }; }; @@ -189,12 +191,6 @@ namespace tachyon sliderFieldID, intSliderFieldID, sliderID, toolbarButtonID, toolbarToggleID, toolbarMenuID, typedID, listViewID, tableID, dropdownID, curveID }) EXPECT_TRUE(reached.contains(id)) << "Tab skips a control: " << Describe(id); - // The Timeline's buttons and scrubber: its six buttons and the scrubber. - EXPECT_EQ(std::count_if(visited.begin(), visited.end(), - [this](ID id) { return Describe(id).starts_with("a part of Timeline ") || Describe(id) == "a part of Timeline"; }), 7); - // The editor's: its toolbar, its filter and its lanes at least. - EXPECT_GE(std::count_if(visited.begin(), visited.end(), - [this](ID id) { return Describe(id).starts_with("a part of TimelineEditor"); }), 10); // The link toggle and a number a side; linked, the toggle and the one number. auto partsOf = [&](const char* control) { return std::count_if(visited.begin(), visited.end(), @@ -255,6 +251,7 @@ namespace tachyon TEST(ControlIDs, PartsDontDependOnWhatCameBefore) { HeadlessGUIApp app; + color::Context colorContext; ASSERT_TRUE(app.Initialize()); const ID firstID = app.idManager.CreateStaticID(); const ID secondID = app.idManager.CreateStaticID(); @@ -269,7 +266,7 @@ namespace tachyon { "Switch", [&](ID id) { app.Switch(id, on, "On"); } }, { "SliderField", [&](ID id) { app.SliderField(id, volume, 0.0f, 1.0f, "Volume"); } }, { "SliderField(int)", [&](ID id) { app.SliderField(id, count, 0, 10, "Count"); } }, - { "ColorField", [&](ID id) { app.ColorField(id, color); } }, + { "ColorField", [&](ID id) { color::ColorField(app, colorContext, id, color); } }, { "SearchField", [&](ID id) { app.SearchField(id, search, app.theme.searchIcon); } }, { "TypedField", [&](ID id) { app.TypedField(id, volume); } }, }; @@ -308,6 +305,7 @@ namespace tachyon TEST(ControlOverloads, EveryFormBuildsAndTakesTheStyle) { HeadlessGUIApp app; + color::Context colorContext; ASSERT_TRUE(app.Initialize()); const StyleRef style = app.theme.emptyHorzStyleRef; // any style, to look for bool on = false; @@ -335,9 +333,9 @@ namespace tachyon app.SliderField(id("SliderField"), f, 0.0f, 1.0f, "F", style); app.SliderField(id("SliderField(int)"), i, 0, 10, "I", style); app.Slider(id("Slider"), i, 0, 10, style); - app.ColorField(id("ColorField"), c4f, false, style); - app.ColorField(id("ColorField(4b)"), c4b, style); - app.GradientField(id("GradientField"), gradient, style); + color::ColorField(app, colorContext, id("ColorField"), c4f, false, style); + color::ColorField(app, colorContext, id("ColorField(4b)"), c4b, style); + color::GradientField(app, colorContext, id("GradientField"), gradient, style); app.SearchField(id("SearchField"), search, app.theme.searchIcon, TextEditBehavior::ContinuousUpdate, style); app.AutocompleteField(id("AutocompleteField"), text, suggestions, style); app.Dropdown(id("Dropdown"), pick, { "One", "Two" }, style); @@ -355,9 +353,9 @@ namespace tachyon app.Switch(on, "On", style); app.SliderField(f, 0.0f, 1.0f, "F", style); app.Slider(i, 0, 10, style); - app.ColorField(c4f, false, style); - app.ColorField(c4b, style); - app.GradientField(gradient, style); + color::ColorField(app, colorContext, c4f, false, style); + color::ColorField(app, colorContext, c4b, style); + color::GradientField(app, colorContext, gradient, style); app.SearchField(search, app.theme.searchIcon, TextEditBehavior::ContinuousUpdate, style); app.AutocompleteField(text, suggestions, style); app.Dropdown(pick, { "One", "Two" }, style); 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/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/misuse_test.cpp b/tests/misuse_test.cpp index 637a2b75..a3a1c3cd 100644 --- a/tests/misuse_test.cpp +++ b/tests/misuse_test.cpp @@ -8,7 +8,10 @@ #include "scoped_temp_dir.h" #include "misuse_reports.h" -#include +#include +#include +#include +#include #include #include @@ -24,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; } @@ -50,15 +60,19 @@ namespace void RunMisuse(const MisuseCase& c) { HeadlessGUIApp app; + Contexts contexts; ASSERT_TRUE(app.Initialize()); + docking::Install(app, contexts.docking); MisuseReports reports; app.Frame([&] { app.BeginRootWindow(); - c.misuse(app); + c.misuse(app, contexts); app.EndRootWindow(); + views::EndGUI(app, contexts.views); }); EXPECT_GE(reports.Count(), 1u) << c.name << " wasn't reported"; ExpectTheNextFrameWorks(app); + docking::Cleanup(app, contexts.docking); app.Cleanup(); } @@ -69,37 +83,37 @@ namespace TEST_P(EndWithoutBeginTest, IsReportedAndIgnored) { RunMisuse(GetParam()); } INSTANTIATE_TEST_SUITE_P(Misuse, EndWithoutBeginTest, ::testing::Values( - MisuseCase{ "EndArea", [](HeadlessGUIApp& a) { a.EndArea(); } }, - MisuseCase{ "EndHorizontal", [](HeadlessGUIApp& a) { a.EndHorizontal(); } }, - MisuseCase{ "EndHorizontalWrap", [](HeadlessGUIApp& a) { a.EndHorizontalWrap(); } }, - MisuseCase{ "EndVertical", [](HeadlessGUIApp& a) { a.EndVertical(); } }, - MisuseCase{ "EndVerticalWrap", [](HeadlessGUIApp& a) { a.EndVerticalWrap(); } }, - MisuseCase{ "EndCached", [](HeadlessGUIApp& a) { a.EndCached(); } }, - MisuseCase{ "EndMenu", [](HeadlessGUIApp& a) { a.EndMenu(); } }, - MisuseCase{ "EndMenuBar", [](HeadlessGUIApp& a) { a.EndMenuBar(); } }, - MisuseCase{ "EndTitleBar", [](HeadlessGUIApp& a) { a.EndTitleBar(); } }, - MisuseCase{ "EndTooltip", [](HeadlessGUIApp& a) { a.EndTooltip(); } }, - MisuseCase{ "EndContextMenu", [](HeadlessGUIApp& a) { a.EndContextMenu(); } }, - MisuseCase{ "EndLabelGroup", [](HeadlessGUIApp& a) { a.EndLabelGroup(); } }, - MisuseCase{ "EndButtonGroup", [](HeadlessGUIApp& a) { a.EndButtonGroup(); } }, - MisuseCase{ "EndToggleGroup", [](HeadlessGUIApp& a) { a.EndToggleGroup(); } }, - MisuseCase{ "EndToolbar", [](HeadlessGUIApp& a) { a.EndToolbar(); } }, - MisuseCase{ "EndReorderableGroup", [](HeadlessGUIApp& a) { a.EndReorderableGroup(); } }, - MisuseCase{ "EndReorderableItem", [](HeadlessGUIApp& a) { a.EndReorderableItem(); } }, - MisuseCase{ "EndListView", [](HeadlessGUIApp& a) { a.EndListView(); } }, - MisuseCase{ "EndGridView", [](HeadlessGUIApp& a) { a.EndGridView(); } }, - MisuseCase{ "EndTable", [](HeadlessGUIApp& a) { a.EndTable(); } }, - MisuseCase{ "EndRow", [](HeadlessGUIApp& a) { a.EndRow(); } }, - MisuseCase{ "EndTabBar", [](HeadlessGUIApp& a) { a.EndTabBar(); } }, - MisuseCase{ "EndStatusBar", [](HeadlessGUIApp& a) { a.EndStatusBar(); } }, - MisuseCase{ "EndDockingContainer", [](HeadlessGUIApp& a) { a.EndDockingContainer(); } }, - MisuseCase{ "EndWindow", [](HeadlessGUIApp& a) { a.EndWindow(); } }, - MisuseCase{ "EndGhostWindow", [](HeadlessGUIApp& a) { a.EndGhostWindow(); } }, - MisuseCase{ "EndDisabled", [](HeadlessGUIApp& a) { a.EndDisabled(); } }, - MisuseCase{ "EndInvalid", [](HeadlessGUIApp& a) { a.EndInvalid(); } }, - MisuseCase{ "EndSelected", [](HeadlessGUIApp& a) { a.EndSelected(); } }, - MisuseCase{ "EndIndeterminate", [](HeadlessGUIApp& a) { a.EndIndeterminate(); } }, - MisuseCase{ "PopParent", [](HeadlessGUIApp& a) { (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 ---- @@ -109,35 +123,35 @@ namespace TEST_P(BeginLeftOpenTest, IsReportedAndClosed) { RunMisuse(GetParam()); } int g_selected = 0; - TableState g_tableState; - VirtualTableColumn g_columns[1]; - DockingLayout g_dockingLayout; + views::TableState g_tableState; + views::VirtualTableColumn g_columns[1]; + docking::DockingLayout g_dockingLayout; INSTANTIATE_TEST_SUITE_P(Misuse, BeginLeftOpenTest, ::testing::Values( - MisuseCase{ "BeginArea", [](HeadlessGUIApp& a) { a.BeginArea(a.idManager.CreateStaticID()); } }, - MisuseCase{ "BeginHorizontal", [](HeadlessGUIApp& a) { a.BeginHorizontal(a.idManager.CreateStaticID()); } }, - MisuseCase{ "BeginHorizontalWrap", [](HeadlessGUIApp& a) { a.BeginHorizontalWrap(a.idManager.CreateStaticID()); } }, - MisuseCase{ "BeginVertical", [](HeadlessGUIApp& a) { a.BeginVertical(a.idManager.CreateStaticID()); } }, - MisuseCase{ "BeginVerticalWrap", [](HeadlessGUIApp& a) { a.BeginVerticalWrap(a.idManager.CreateStaticID()); } }, - MisuseCase{ "BeginCached", [](HeadlessGUIApp& a) { a.BeginCached(a.idManager.CreateStaticID()); } }, - MisuseCase{ "BeginMenuBar", [](HeadlessGUIApp& a) { a.BeginMenuBar(a.idManager.CreateStaticID()); } }, - MisuseCase{ "BeginTitleBar", [](HeadlessGUIApp& a) { a.BeginTitleBar(a.idManager.CreateStaticID()); } }, - MisuseCase{ "BeginStatusBar", [](HeadlessGUIApp& a) { a.BeginStatusBar(a.idManager.CreateStaticID()); } }, - MisuseCase{ "BeginLabelGroup", [](HeadlessGUIApp& a) { a.BeginLabelGroup(a.idManager.CreateStaticID()); } }, - MisuseCase{ "BeginButtonGroup", [](HeadlessGUIApp& a) { a.BeginButtonGroup(); } }, - MisuseCase{ "BeginToggleGroup", [](HeadlessGUIApp& a) { a.BeginToggleGroup(); } }, - MisuseCase{ "BeginToolbar", [](HeadlessGUIApp& a) { a.BeginToolbar(); } }, - MisuseCase{ "BeginReorderableGroup", [](HeadlessGUIApp& a) { a.BeginReorderableGroup(a.idManager.CreateStaticID(), ReorderDirection::Vertical, [](int, int) {}); } }, - MisuseCase{ "BeginListView", [](HeadlessGUIApp& a) { a.BeginListView(a.idManager.CreateStaticID(), &g_selected, 0); } }, - MisuseCase{ "BeginGridView", [](HeadlessGUIApp& a) { a.BeginGridView(a.idManager.CreateStaticID(), &g_selected); } }, - MisuseCase{ "BeginTable", [](HeadlessGUIApp& a) { a.BeginTable(a.idManager.CreateStaticID(), g_columns, g_tableState); } }, - MisuseCase{ "BeginTabBar", [](HeadlessGUIApp& a) { a.BeginTabBar(a.idManager.CreateStaticID(), &g_selected, [](int, int) {}); } }, - MisuseCase{ "BeginDockingContainer", [](HeadlessGUIApp& a) { a.BeginDockingContainer(a.idManager.CreateStaticID(), &g_dockingLayout); } }, - MisuseCase{ "BeginDisabled", [](HeadlessGUIApp& a) { a.BeginDisabled(); } }, - MisuseCase{ "BeginInvalid", [](HeadlessGUIApp& a) { a.BeginInvalid(); } }, - MisuseCase{ "BeginSelected", [](HeadlessGUIApp& a) { a.BeginSelected(); } }, - MisuseCase{ "BeginIndeterminate", [](HeadlessGUIApp& a) { a.BeginIndeterminate(); } }, - MisuseCase{ "PushParent", [](HeadlessGUIApp& a) { (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. @@ -214,12 +228,12 @@ namespace } INSTANTIATE_TEST_SUITE_P(MisuseIDs, BeginLeftOpenTest, ::testing::Values( - MisuseCase{ "TheSameIDTwice", [](HeadlessGUIApp& a) { + MisuseCase{ "TheSameIDTwice", [](HeadlessGUIApp& a, Contexts&) { const ID id = a.idManager.CreateStaticID(); a.Button(id, "One", [] {}); a.Button(id, "Two", [] {}); } }, - MisuseCase{ "AnInvalidID", [](HeadlessGUIApp& a) { a.Button(ID::Invalid(), "Invalid", [] {}); } }, - MisuseCase{ "AnInvalidStyle", [](HeadlessGUIApp& a) { 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. @@ -320,14 +334,18 @@ namespace TEST_P(OddValueTest, LaysOut) { HeadlessGUIApp app; + 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); + GetParam().misuse(app, contexts); app.EndRootWindow(); + views::EndGUI(app, contexts.views); }); ExpectTheNextFrameWorks(app); + docking::Cleanup(app, contexts.docking); app.Cleanup(); } @@ -336,26 +354,26 @@ namespace std::string g_string; INSTANTIATE_TEST_SUITE_P(Misuse, OddValueTest, ::testing::Values( - MisuseCase{ "NaNField", [](HeadlessGUIApp& a) { g_float = std::numeric_limits::quiet_NaN(); a.Field(g_float); } }, - MisuseCase{ "InfinityField", [](HeadlessGUIApp& a) { g_float = std::numeric_limits::infinity(); a.Field(g_float); } }, - MisuseCase{ "NaNSlider", [](HeadlessGUIApp& a) { g_float = std::numeric_limits::quiet_NaN(); a.SliderField(a.idManager.CreateStaticID(), g_float, 0.0f, 1.0f, "NaN"); } }, - MisuseCase{ "SliderMinAboveMax", [](HeadlessGUIApp& a) { g_float = 0.5f; a.SliderField(a.idManager.CreateStaticID(), g_float, 1.0f, 0.0f, "Backwards"); } }, - MisuseCase{ "SliderEmptyRange", [](HeadlessGUIApp& a) { g_int = 3; a.Slider(a.idManager.CreateStaticID(), g_int, 5, 5); } }, - MisuseCase{ "IntSliderOutOfRange",[](HeadlessGUIApp& a) { g_int = 1000; a.Slider(a.idManager.CreateStaticID(), g_int, 0, 10); } }, - MisuseCase{ "EmptyLabel", [](HeadlessGUIApp& a) { a.Label(a.idManager.CreateStaticID(), ""); } }, - MisuseCase{ "HugeLabel", [](HeadlessGUIApp& a) { a.Label(a.idManager.CreateStaticID(), std::string(200000, 'x')); } }, - MisuseCase{ "InvalidUtf8Label", [](HeadlessGUIApp& a) { a.Label(a.idManager.CreateStaticID(), "\xff\xfe\xc3 \xe2\x82 \xf0\x9f"); } }, - MisuseCase{ "InvalidUtf8Field", [](HeadlessGUIApp& a) { g_string = "\xc3\x28\xa0\xa1"; a.Field(a.idManager.CreateStaticID(), g_string); } }, - MisuseCase{ "NegativeSize", [](HeadlessGUIApp& a) { a.Button(a.idManager.CreateStaticID(), "Negative", [] {}, LayoutOverride{}.Size(-50, -20)); } }, - MisuseCase{ "ZeroSize", [](HeadlessGUIApp& a) { a.Button(a.idManager.CreateStaticID(), "Zero", [] {}, LayoutOverride{}.Size(0, 0)); } }, - MisuseCase{ "HugeSize", [](HeadlessGUIApp& a) { a.Button(a.idManager.CreateStaticID(), "Huge", [] {}, LayoutOverride{}.Size(1000000, 1000000)); } }, - MisuseCase{ "ListPastSixteenBits",[](HeadlessGUIApp& a) { + 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 (a.BeginListView(a.idManager.CreateStaticID(), &selected, 70000)) + if (views::BeginListView(a, contexts.views, a.idManager.CreateStaticID(), &selected, 70000)) { for (int i = 0; i < 70000; i++) - a.ListItem(std::string_view("row")); - a.EndListView(); + views::ListItem(a, contexts.views, std::string_view("row")); + views::EndListView(a, contexts.views); } } } ), CaseName); @@ -488,60 +506,60 @@ namespace // ---- Parts of a container used outside it ---- INSTANTIATE_TEST_SUITE_P(MisuseParts, EndWithoutBeginTest, ::testing::Values( - MisuseCase{ "MenuItemOutsideAMenu", [](HeadlessGUIApp& a) { a.MenuItem(a.idManager.CreateStaticID(), "Stray"); } }, - MisuseCase{ "ListItemOutsideAList", [](HeadlessGUIApp& a) { a.ListItem(a.idManager.CreateStaticID(), std::string_view("Stray"), LayoutOverride{}); } }, - MisuseCase{ "TabOutsideATabBar", [](HeadlessGUIApp& a) { a.Tab(a.idManager.CreateStaticID(), "Stray"); } }, - MisuseCase{ "TreeCellOutsideATable", [](HeadlessGUIApp& a) { bool open = true; a.TreeCell("Stray", 0, &open); } }, - MisuseCase{ "CellOutsideATable", [](HeadlessGUIApp& a) { a.Cell("Stray"); } }, - MisuseCase{ "ReorderableItemOutsideAGroup",[](HeadlessGUIApp& a) { 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 ---- - std::vector g_bigTableColumns; - TableState g_bigTableState; - NodeView g_badNodeView; + std::vector g_bigTableColumns; + views::TableState g_bigTableState; + nodes::NodeView g_badNodeView; INSTANTIATE_TEST_SUITE_P(MisuseScale, OddValueTest, ::testing::Values( - MisuseCase{ "DeepNesting", [](HeadlessGUIApp& a) { + 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) { + MisuseCase{ "FortyThousandLabels", [](HeadlessGUIApp& a, Contexts&) { for (int i = 0; i < 40000; i++) a.Label(std::string_view("row")); } }, - MisuseCase{ "ATableOfAHundredThousandRows", [](HeadlessGUIApp& a) { + 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](int row) { a.Cell(std::to_string(row)); }; + for (auto& c : g_bigTableColumns) c.generateCell = [&a, &contexts](int row) { views::Cell(a, contexts.views, std::to_string(row)); }; } - a.VirtualTable(a.idManager.CreateStaticID(), g_bigTableState, g_bigTableColumns, 100000, 0, {}, LayoutOverride{}.Size(400, 300)); } }, - MisuseCase{ "ATableWithNoColumns", [](HeadlessGUIApp& a) { - static TableState state; - a.VirtualTable(a.idManager.CreateStaticID(), state, std::span{}, 10, 0, {}, LayoutOverride{}.Size(400, 300)); } }, - MisuseCase{ "ATableWithNegativeRows", [](HeadlessGUIApp& a) { - static TableState state; - static VirtualTableColumn column[1]; - a.VirtualTable(a.idManager.CreateStaticID(), state, column, -5, -10, {}, LayoutOverride{}.Size(400, 300)); } }, - MisuseCase{ "NodeWiresToNodesThatDontExist", [](HeadlessGUIApp& a) { + 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, 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, 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); g_badNodeView.nodes[0].stableID = a.idManager.CreateStaticID(); g_badNodeView.nodes[0].properties.resize(2); - g_badNodeView.nodes[0].properties[0].input = PropertyEndpoint{ 99, 0 }; // no node 99 - g_badNodeView.nodes[0].properties[1].input = PropertyEndpoint{ 1, 7 }; // node 1 has no property 7 + g_badNodeView.nodes[0].properties[0].input = nodes::PropertyEndpoint{ 99, 0 }; // no node 99 + g_badNodeView.nodes[0].properties[1].input = nodes::PropertyEndpoint{ 1, 7 }; // node 1 has no property 7 g_badNodeView.nodes[1].stableID = a.idManager.CreateStaticID(); g_badNodeView.nodes[1].pos = { 2000000000, -2000000000 }; g_badNodeView.nodes[1].properties.resize(1); - g_badNodeView.nodes[1].properties[0].input = PropertyEndpoint{ 1, 0 }; // wired to itself + g_badNodeView.nodes[1].properties[0].input = nodes::PropertyEndpoint{ 1, 0 }; // wired to itself g_badNodeView.ordering = { 5, -1, 0 }; // bad z-order } - a.RenderNodeView(g_badNodeView); } }, - MisuseCase{ "AnEmptyNodeView", [](HeadlessGUIApp& a) { static NodeView view; a.RenderNodeView(view); } }, - MisuseCase{ "ATooltipForNoElement", [](HeadlessGUIApp& a) { a.SetTooltip(ID::Invalid(), "for nothing"); } } + nodes::RenderNodeView(a, nodesContext, g_badNodeView); } }, + 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. @@ -661,8 +679,9 @@ namespace TEST(MisuseTest, NodesRemovedDuringANodeDrag) { HeadlessGUIApp app; + nodes::Context nodesContext; ASSERT_TRUE(app.Initialize()); - NodeView view; + nodes::NodeView view; view.nodes.resize(2); for (int i = 0; i < 2; i++) { @@ -673,16 +692,16 @@ namespace view.nodes[size_t(i)].properties[0].output = true; } int edits = 0; - view.onEdit = [&](const NodeViewEdit&) { edits++; }; + view.onEdit = [&](const nodes::NodeViewEdit&) { edits++; }; auto draw = [&] { app.BeginRootWindow({ 1920, 1080 }, ElementFlags::None, app.theme.mainWindowStyleRef); - app.RenderNodeView(view); + nodes::RenderNodeView(app, nodesContext, view); app.EndRootWindow(); }; app.Frame(draw); app.Frame(draw); - const IntRect n = app.GetElementRect(NodeElementID(view, view.nodes[1].stableID)); - const int2 from{ n.x + n.w / 2, n.y + app.theme.nodeGridSize }; + const IntRect n = app.GetElementRect(nodes::NodeElementID(view, view.nodes[1].stableID)); + const int2 from{ n.x + n.w / 2, n.y + nodes::GetStyles(app, nodesContext).nodeGridSize }; app.InjectMouseMove(from); app.InjectMouseDown(from); app.Frame(draw); diff --git a/tests/node_view_control_test.cpp b/tests/node_view_control_test.cpp index df625a56..d0bd1a28 100644 --- a/tests/node_view_control_test.cpp +++ b/tests/node_view_control_test.cpp @@ -10,7 +10,8 @@ #include "headless_gui_app.h" #include -#include +#include +#include #include #include @@ -27,7 +28,8 @@ namespace tachyon { protected: HeadlessGUIApp app; - NodeView view; + nodes::Context nodesContext; + nodes::NodeView view; tachyon::ID nodeA{}; tachyon::ID nodeB{}; @@ -37,17 +39,17 @@ namespace tachyon nodeA = app.idManager.CreateStaticID(); nodeB = app.idManager.CreateStaticID(); - NodeModel a{}; + nodes::NodeModel a{}; a.stableID = nodeA; a.title = "A"; a.pos = { 100, 80 }; - a.properties.push_back(NodeProperty{ .output = true }); + a.properties.push_back(nodes::NodeProperty{ .output = true }); - NodeModel b{}; + nodes::NodeModel b{}; b.stableID = nodeB; b.title = "B"; b.pos = { 520, 320 }; - b.properties.push_back(NodeProperty{ .input = PropertyEndpoint{} }); + b.properties.push_back(nodes::NodeProperty{ .input = nodes::PropertyEndpoint{} }); view = {}; view.transform = tachyon::float3x2::Scale(1.0f); // identity @@ -60,7 +62,7 @@ namespace tachyon { app.Frame([&] { app.BeginRootWindow({ 1920, 1080 }, ElementFlags::None, app.theme.mainWindowStyleRef); - app.RenderNodeView(view); + nodes::RenderNodeView(app, nodesContext, view); app.EndRootWindow(); }); } @@ -68,9 +70,9 @@ namespace tachyon void Settle() { Frame(); Frame(); } // The canvas's inner rect (the node-view style is unique to it). - tachyon::IntRect CanvasInner() const + tachyon::IntRect CanvasInner() { - const auto style = app.theme.nodeViewStyleRef; + const auto style = nodes::GetStyles(app, nodesContext).nodeViewStyleRef; for (uint32_t d = 0; d < app.elementStorage.NumberOfDepthLevels(); d++) { const uint32_t count = app.elementStorage.DepthSizeOf(d); @@ -87,7 +89,7 @@ namespace tachyon } // A point on the canvas background, clear of the nodes and the overlays. - tachyon::int2 CanvasPoint() const + tachyon::int2 CanvasPoint() { const auto inner = CanvasInner(); return { inner.x + inner.w * 3 / 4, inner.y + inner.h / 2 }; @@ -109,10 +111,10 @@ namespace tachyon } // The centre of the first socket inside `node`'s rect. - tachyon::int2 SocketOf(tachyon::ID node) const + tachyon::int2 SocketOf(tachyon::ID node) { - const auto n = app.GetElementRect(NodeElementID(view, node)); - for (const auto& r : RectsWithStyle(app.theme.nodeSocketStyleRef)) + const auto n = app.GetElementRect(nodes::NodeElementID(view, node)); + for (const auto& r : RectsWithStyle(nodes::GetStyles(app, nodesContext).nodeSocketStyleRef)) { const tachyon::int2 c{ r.x + r.w / 2, r.y + r.h / 2 }; if (c.x >= n.x - r.w && c.x <= n.x + n.w + r.w && c.y >= n.y && c.y < n.y + n.h) @@ -164,10 +166,10 @@ namespace tachyon } // A point on `node`'s header, clear of its sockets. - tachyon::int2 HeaderOf(tachyon::ID node) const + tachyon::int2 HeaderOf(tachyon::ID node) { - const auto n = app.GetElementRect(NodeElementID(view, node)); - return { n.x + n.w / 2, n.y + app.theme.nodeGridSize }; + const auto n = app.GetElementRect(nodes::NodeElementID(view, node)); + return { n.x + n.w / 2, n.y + nodes::GetStyles(app, nodesContext).nodeGridSize }; } }; @@ -193,7 +195,7 @@ namespace tachyon // box style table doesn't grow by one a frame either. TEST_F(NodeViewControlTest, AnimatedEdgeColorsDoNotGrowTheBoxStyleTable) { - view.frames.push_back(NodeFrame{ .stableID = app.idManager.CreateStaticID(), .title = "Frame", + view.frames.push_back(nodes::NodeFrame{ .stableID = app.idManager.CreateStaticID(), .title = "Frame", .color = tachyon::color4f{ 0.2f, 0.4f, 0.8f, 1.0f }, .pos = { 60, 40 }, .size = { 400, 300 } }); Settle(); @@ -206,7 +208,7 @@ namespace tachyon EXPECT_LE(app.styleManager.VisualBoxStyleCount(), before + 2) << "a frame's edge"; view.frames.clear(); - view.kind = NodeViewKind::StateMachine; + view.kind = nodes::NodeViewKind::StateMachine; Settle(); before = app.styleManager.VisualBoxStyleCount(); for (int i = 0; i < 60; ++i) @@ -233,15 +235,15 @@ namespace tachyon } return out; }; - const auto nodeRect = app.GetElementRect(NodeElementID(view, nodeA)); + const auto nodeRect = app.GetElementRect(nodes::NodeElementID(view, nodeA)); tachyon::IntRect header{}, socket{}; - for (const auto& r : rectsWithStyle(app.theme.nodeHeaderStyleRef)) + for (const auto& r : rectsWithStyle(nodes::GetStyles(app, nodesContext).nodeHeaderStyleRef)) if (r.x >= nodeRect.x && r.x < nodeRect.x + nodeRect.w && r.y >= nodeRect.y && r.y < nodeRect.y + nodeRect.h) header = r; - for (const auto& r : rectsWithStyle(app.theme.nodeSocketStyleRef)) + for (const auto& r : rectsWithStyle(nodes::GetStyles(app, nodesContext).nodeSocketStyleRef)) if (std::abs(r.y - nodeRect.y) < nodeRect.h) socket = r; ASSERT_GT(header.h, 0); ASSERT_GT(socket.h, 0); - const int rowPitch = 2 * app.theme.nodeGridSize; + const int rowPitch = 2 * nodes::GetStyles(app, nodesContext).nodeGridSize; EXPECT_EQ(socket.y + socket.h / 2, nodeRect.y + rowPitch / 2) << "on the header slot's centre (a grid line), not a fixed offset"; } @@ -267,27 +269,27 @@ namespace tachyon { Settle(); int edits = 0; - view.onEdit = [&](const NodeViewEdit& edit) { edits++; EXPECT_EQ(edit.moves.size(), 1u); }; + view.onEdit = [&](const nodes::NodeViewEdit& edit) { edits++; EXPECT_EQ(edit.moves.size(), 1u); }; const tachyon::int2 before = view.nodes[1].pos; const tachyon::int2 from = HeaderOf(nodeB); - Drag(from, { from.x + 5 * app.theme.nodeGridSize, from.y + 3 * app.theme.nodeGridSize }); + Drag(from, { from.x + 5 * nodes::GetStyles(app, nodesContext).nodeGridSize, from.y + 3 * nodes::GetStyles(app, nodesContext).nodeGridSize }); Settle(); EXPECT_GT(view.nodes[1].pos.x, before.x); EXPECT_GT(view.nodes[1].pos.y, before.y); - EXPECT_EQ(view.nodes[1].pos.x % app.theme.nodeGridSize, 0) << "positions snap to the grid"; + EXPECT_EQ(view.nodes[1].pos.x % nodes::GetStyles(app, nodesContext).nodeGridSize, 0) << "positions snap to the grid"; EXPECT_EQ(edits, 1); } // A position off the grid moves onto it while snapping, and stays put without. TEST_F(NodeViewControlTest, PositionsSnapToTheGridOnlyWhileSnapping) { - const int32_t grid = app.theme.nodeGridSize; + const int32_t grid = nodes::GetStyles(app, nodesContext).nodeGridSize; ASSERT_GT(grid, 1); view.snapToGrid = false; view.nodes[1].pos = { 10 * grid + 1, 6 * grid + 1 }; Settle(); EXPECT_EQ(view.nodes[1].pos, (tachyon::int2{ 10 * grid + 1, 6 * grid + 1 })); - EXPECT_EQ(app.GetElementRect(NodeElementID(view, nodeB)).x - app.GetElementRect(NodeElementID(view, nodeA)).x, 10 * grid + 1 - view.nodes[0].pos.x) << "laid out there"; + EXPECT_EQ(app.GetElementRect(nodes::NodeElementID(view, nodeB)).x - app.GetElementRect(nodes::NodeElementID(view, nodeA)).x, 10 * grid + 1 - view.nodes[0].pos.x) << "laid out there"; view.snapToGrid = true; Settle(); @@ -299,9 +301,9 @@ namespace tachyon { view.snapToGrid = false; Settle(); - std::vector edits; - view.onEdit = [&](const NodeViewEdit& edit) { edits.push_back(edit); }; - const int32_t grid = app.theme.nodeGridSize; + std::vector edits; + view.onEdit = [&](const nodes::NodeViewEdit& edit) { edits.push_back(edit); }; + const int32_t grid = nodes::GetStyles(app, nodesContext).nodeGridSize; const tachyon::int2 before = view.nodes[1].pos; const tachyon::int2 by{ 5 * grid + 3, 3 * grid + 7 }; const tachyon::int2 from = HeaderOf(nodeB); @@ -318,19 +320,19 @@ namespace tachyon { view.nodes.resize(2); view.ordering.clear(); - view.nodes[1].properties[0].input = PropertyEndpoint{ 0, 0 }; + view.nodes[1].properties[0].input = nodes::PropertyEndpoint{ 0, 0 }; Settle(); auto wired = [&] { return view.nodes[1].properties[0].input && view.nodes[1].properties[0].input->valid(); }; const tachyon::int2 at = CanvasPoint() + tachyon::int2{ 3, 5 }; app.InjectMouseMove(at); Frame(); - view.hoveredWire.part = WireKey(1, 0); + view.hoveredWire.part = nodes::WireKey(1, 0); app.DragFrom(at, { at.x + 40, at.y }, MouseButtons::Middle); Frame(); EXPECT_TRUE(wired()) << "a drag pans"; app.InjectMouseMove(at); Frame(); - view.hoveredWire.part = WireKey(1, 0); + view.hoveredWire.part = nodes::WireKey(1, 0); app.ClickAt(at, MouseButtons::Middle); Frame(); EXPECT_FALSE(wired()) << "a click removes it"; @@ -340,27 +342,27 @@ namespace tachyon // where the wire was clicked without. TEST_F(NodeViewControlTest, AddRerouteHereSnapsOnlyWhileSnapping) { - const int32_t grid = app.theme.nodeGridSize; + const int32_t grid = nodes::GetStyles(app, nodesContext).nodeGridSize; for (const bool snap : { true, false }) { SCOPED_TRACE(snap ? "snapping" : "not snapping"); view.snapToGrid = snap; view.nodes.resize(2); view.ordering.clear(); - view.nodes[1].properties[0].input = PropertyEndpoint{ 0, 0 }; + view.nodes[1].properties[0].input = nodes::PropertyEndpoint{ 0, 0 }; Settle(); const tachyon::int2 at = CanvasPoint() + tachyon::int2{ 3, 5 }; app.InjectMouseMove(at); Frame(); - view.hoveredWire.part = WireKey(1, 0); + view.hoveredWire.part = nodes::WireKey(1, 0); app.ClickAt(at, MouseButtons::Right); Frame(); Frame(); ASSERT_TRUE(view.wireMenuWire); ASSERT_NE(app.FindByText("Add reroute here"), tachyon::ID::Invalid()); const tachyon::int2 clicked{ int32_t(std::lround(view.wireMenuPos.x)), int32_t(std::lround(view.wireMenuPos.y)) }; - std::vector edits; - view.onEdit = [&](const NodeViewEdit& edit) { edits.push_back(edit); }; + std::vector edits; + view.onEdit = [&](const nodes::NodeViewEdit& edit) { edits.push_back(edit); }; app.InjectKey(KeyCode::Down); // past "Delete wire", the first Frame(); app.InjectKey(KeyCode::Return); @@ -406,12 +408,12 @@ namespace tachyon void Settle() { NodeViewControlTest::Settle(); - for (NodeModel& node : view.nodes) - node.lastSize = app.GetElementRect(NodeElementID(view, node.stableID)).size; + for (nodes::NodeModel& node : view.nodes) + node.lastSize = app.GetElementRect(nodes::NodeElementID(view, node.stableID)).size; } }; - struct CanvasDrop { PropertyEndpoint from; bool fromOutput; float2 at; }; + struct CanvasDrop { nodes::PropertyEndpoint from; bool fromOutput; float2 at; }; // A new wire from an output, released over the empty canvas: the app hears where. TEST_F(NodeViewWireDropTest, ANewWireFromAnOutputDroppedOnTheCanvasIsReported) @@ -420,22 +422,22 @@ namespace tachyon std::vector drops; int edits = 0; bool stillDragging = true; - view.onWireDroppedOnCanvas = [&](PropertyEndpoint from, bool fromOutput, float2 at) { + view.onWireDroppedOnCanvas = [&](nodes::PropertyEndpoint from, bool fromOutput, float2 at) { drops.push_back({ from, fromOutput, at }); stillDragging = view.pendingConnection.IsActive(); }; - view.onEdit = [&](const NodeViewEdit&) { edits++; }; + view.onEdit = [&](const nodes::NodeViewEdit&) { edits++; }; const tachyon::int2 to = CanvasPoint(); Drag(SocketOf(nodeA), to); Settle(); ASSERT_EQ(drops.size(), 1u); - EXPECT_EQ(drops[0].from, (PropertyEndpoint{ 0, 0 })); + EXPECT_EQ(drops[0].from, (nodes::PropertyEndpoint{ 0, 0 })); EXPECT_TRUE(drops[0].fromOutput); // Through the transform the canvas was drawn with: centred for view.lastInnerSize. - const float2 expected = NodeViewScreenToCanvas(view.transform, IntRect{ .position = CanvasInner().position, .size = view.lastInnerSize }, to); + const float2 expected = nodes::NodeViewScreenToCanvas(view.transform, IntRect{ .position = CanvasInner().position, .size = view.lastInnerSize }, to); EXPECT_FLOAT_EQ(drops[0].at.x, expected.x); EXPECT_FLOAT_EQ(drops[0].at.y, expected.y); - EXPECT_EQ(NodeAtCanvasPos(view, drops[0].at), -1); + EXPECT_EQ(nodes::NodeAtCanvasPos(view, drops[0].at), -1); EXPECT_FALSE(stillDragging) << "the wire is done with when the app hears of it"; EXPECT_EQ(edits, 0) << "nothing changed"; EXPECT_FALSE(view.pendingConnection.IsActive()); @@ -447,11 +449,11 @@ namespace tachyon { Settle(); std::vector drops; - view.onWireDroppedOnCanvas = [&](PropertyEndpoint from, bool fromOutput, float2 at) { drops.push_back({ from, fromOutput, at }); }; + view.onWireDroppedOnCanvas = [&](nodes::PropertyEndpoint from, bool fromOutput, float2 at) { drops.push_back({ from, fromOutput, at }); }; Drag(SocketOf(nodeB), CanvasPoint()); Settle(); ASSERT_EQ(drops.size(), 1u); - EXPECT_EQ(drops[0].from, (PropertyEndpoint{ 1, 0 })); + EXPECT_EQ(drops[0].from, (nodes::PropertyEndpoint{ 1, 0 })); EXPECT_FALSE(drops[0].fromOutput); EXPECT_FALSE(view.nodes[1].properties[0].input->valid()); } @@ -461,8 +463,8 @@ namespace tachyon TEST_F(NodeViewWireDropTest, DraggingFromAnInputToAnOutputConnects) { Settle(); - std::vector edits; - view.onEdit = [&](const NodeViewEdit& e) { edits.push_back(e); }; + std::vector edits; + view.onEdit = [&](const nodes::NodeViewEdit& e) { edits.push_back(e); }; const tachyon::int2 in = SocketOf(nodeB), out = SocketOf(nodeA); app.InjectMouseMove(in); app.InjectMouseDown(in); @@ -471,19 +473,19 @@ namespace tachyon Frame(); EXPECT_TRUE(view.pendingConnection.IsActive()); EXPECT_TRUE(view.pendingConnection.fromInput); - EXPECT_EQ(view.pendingConnection.source, (PropertyEndpoint{ 1, 0 })); + EXPECT_EQ(view.pendingConnection.source, (nodes::PropertyEndpoint{ 1, 0 })); app.InjectMouseMove(out, MouseButtons::Left); Frame(); Frame(); - EXPECT_EQ(view.pendingConnection.target, (PropertyEndpoint{ 0, 0 })) << "over the output"; + EXPECT_EQ(view.pendingConnection.target, (nodes::PropertyEndpoint{ 0, 0 })) << "over the output"; app.InjectMouseUp(out); Frame(); Settle(); - EXPECT_EQ(*view.nodes[1].properties[0].input, (PropertyEndpoint{ 0, 0 })); + EXPECT_EQ(*view.nodes[1].properties[0].input, (nodes::PropertyEndpoint{ 0, 0 })); ASSERT_EQ(edits.size(), 1u); ASSERT_EQ(edits[0].rewires.size(), 1u); - EXPECT_EQ(edits[0].rewires[0].input, (PropertyEndpoint{ 1, 0 })); - EXPECT_EQ(edits[0].rewires[0].to, (PropertyEndpoint{ 0, 0 })); + EXPECT_EQ(edits[0].rewires[0].input, (nodes::PropertyEndpoint{ 1, 0 })); + EXPECT_EQ(edits[0].rewires[0].to, (nodes::PropertyEndpoint{ 0, 0 })); EXPECT_FALSE(view.pendingConnection.IsActive()); } @@ -492,10 +494,10 @@ namespace tachyon { Settle(); int drops = 0; - view.onWireDroppedOnCanvas = [&](PropertyEndpoint, bool, float2) { drops++; }; + view.onWireDroppedOnCanvas = [&](nodes::PropertyEndpoint, bool, float2) { drops++; }; Drag(SocketOf(nodeB), HeaderOf(nodeA)); Settle(); - EXPECT_EQ(*view.nodes[1].properties[0].input, (PropertyEndpoint{ 0, 0 })); + EXPECT_EQ(*view.nodes[1].properties[0].input, (nodes::PropertyEndpoint{ 0, 0 })); EXPECT_EQ(drops, 0) << "a node isn't the empty canvas"; } @@ -505,8 +507,8 @@ namespace tachyon { Settle(); int drops = 0; - view.onWireDroppedOnCanvas = [&](PropertyEndpoint, bool, float2) { drops++; }; - view.canConnect = [](const NodeGraph&, PropertyEndpoint, PropertyEndpoint) { return false; }; + view.onWireDroppedOnCanvas = [&](nodes::PropertyEndpoint, bool, float2) { drops++; }; + view.canConnect = [](const nodes::NodeGraph&, nodes::PropertyEndpoint, nodes::PropertyEndpoint) { return false; }; Drag(SocketOf(nodeB), SocketOf(nodeA)); Settle(); Drag(SocketOf(nodeA), HeaderOf(nodeB)); @@ -518,11 +520,11 @@ namespace tachyon // A wire pulled off an input and dropped on the canvas is a disconnect, not a new wire. TEST_F(NodeViewWireDropTest, AWirePulledOffAnInputOntoTheCanvasDisconnects) { - view.nodes[1].properties[0].input = PropertyEndpoint{ 0, 0 }; + view.nodes[1].properties[0].input = nodes::PropertyEndpoint{ 0, 0 }; Settle(); int drops = 0, edits = 0; - view.onWireDroppedOnCanvas = [&](PropertyEndpoint, bool, float2) { drops++; }; - view.onEdit = [&](const NodeViewEdit&) { edits++; }; + view.onWireDroppedOnCanvas = [&](nodes::PropertyEndpoint, bool, float2) { drops++; }; + view.onEdit = [&](const nodes::NodeViewEdit&) { edits++; }; Drag(SocketOf(nodeB), CanvasPoint()); Settle(); EXPECT_FALSE(view.nodes[1].properties[0].input->valid()); @@ -535,7 +537,7 @@ namespace tachyon TEST_F(NodeViewWireDropTest, AnOutputThatMayNotTakeAWireRefusesIt) { Settle(); - view.canConnect = [](const NodeGraph&, PropertyEndpoint, PropertyEndpoint) { return false; }; + view.canConnect = [](const nodes::NodeGraph&, nodes::PropertyEndpoint, nodes::PropertyEndpoint) { return false; }; const tachyon::int2 in = SocketOf(nodeB), out = SocketOf(nodeA); app.InjectMouseMove(in); app.InjectMouseDown(in); @@ -555,20 +557,20 @@ namespace tachyon // A wire pulled off one input and let go over another moves there: one edit. TEST_F(NodeViewWireDropTest, AWirePulledOffAnInputMovesToAnother) { - NodeModel c{}; + nodes::NodeModel c{}; c.stableID = app.idManager.CreateStaticID(); c.title = "C"; c.pos = { 520, 80 }; - c.properties.push_back(NodeProperty{ .input = PropertyEndpoint{} }); + c.properties.push_back(nodes::NodeProperty{ .input = nodes::PropertyEndpoint{} }); view.nodes.push_back(std::move(c)); - view.nodes[1].properties[0].input = PropertyEndpoint{ 0, 0 }; + view.nodes[1].properties[0].input = nodes::PropertyEndpoint{ 0, 0 }; Settle(); - std::vector edits; - view.onEdit = [&](const NodeViewEdit& e) { edits.push_back(e); }; + std::vector edits; + view.onEdit = [&](const nodes::NodeViewEdit& e) { edits.push_back(e); }; Drag(SocketOf(nodeB), SocketOf(view.nodes[2].stableID)); Settle(); EXPECT_FALSE(view.nodes[1].properties[0].input->valid()); - EXPECT_EQ(*view.nodes[2].properties[0].input, (PropertyEndpoint{ 0, 0 })); + EXPECT_EQ(*view.nodes[2].properties[0].input, (nodes::PropertyEndpoint{ 0, 0 })); ASSERT_EQ(edits.size(), 1u); EXPECT_EQ(edits[0].rewires.size(), 2u) << "the detach and the connect"; } @@ -578,7 +580,7 @@ namespace tachyon { Settle(); int drops = 0; - view.onWireDroppedOnCanvas = [&](PropertyEndpoint, bool, float2) { drops++; }; + view.onWireDroppedOnCanvas = [&](nodes::PropertyEndpoint, bool, float2) { drops++; }; const tachyon::int2 at = CanvasPoint(), to{ at.x + 40, at.y }; app.InjectMouseMove(at); Frame(); @@ -603,7 +605,7 @@ namespace tachyon { Settle(); int edits = 0; - view.onEdit = [&](const NodeViewEdit&) { edits++; }; + view.onEdit = [&](const nodes::NodeViewEdit&) { edits++; }; Drag(SocketOf(nodeB), CanvasPoint()); Settle(); EXPECT_FALSE(view.pendingConnection.IsActive()); @@ -623,13 +625,13 @@ namespace tachyon view.lastCanvasRect = CanvasInner(); } // The canvas element: the node-view style is unique to it. - tachyon::ID CanvasID() const + tachyon::ID CanvasID() { for (uint32_t d = 0; d < app.elementStorage.NumberOfDepthLevels(); d++) for (uint32_t i = 0; i < app.elementStorage.DepthSizeOf(d); i++) { const tachyon::ElementRef ref{ d, i }; - if (app.elementStorage.IsValidRef(ref) && app.elementStorage.GetElementUnsafe(ref).styleRef == app.theme.nodeViewStyleRef) + if (app.elementStorage.IsValidRef(ref) && app.elementStorage.GetElementUnsafe(ref).styleRef == nodes::GetStyles(app, nodesContext).nodeViewStyleRef) return app.elementStorage.GetElementUnsafe(ref).id; } return tachyon::ID::Invalid(); @@ -656,7 +658,7 @@ namespace tachyon const tachyon::int2 at = CanvasPoint(); RightClick(at); ASSERT_FALSE(built.empty()); - const float2 expected = NodeViewScreenToCanvas(view, at); + const float2 expected = nodes::NodeViewScreenToCanvas(view, at); EXPECT_FLOAT_EQ(built.back().x, expected.x); EXPECT_FLOAT_EQ(built.back().y, expected.y); EXPECT_TRUE(app.menuManager.IsOpen()); @@ -760,7 +762,7 @@ namespace tachyon press(KeyCode::Application); ASSERT_FALSE(canvasMenus.empty()); const tachyon::IntRect inner = CanvasInner(); - const float2 centre = NodeViewScreenToCanvas(view, inner.position + tachyon::int2{ inner.w / 2, inner.h / 2 }); + const float2 centre = nodes::NodeViewScreenToCanvas(view, inner.position + tachyon::int2{ inner.w / 2, inner.h / 2 }); EXPECT_FLOAT_EQ(canvasMenus.back().x, centre.x); EXPECT_FLOAT_EQ(canvasMenus.back().y, centre.y); EXPECT_TRUE(nodeMenus.empty()); @@ -770,8 +772,8 @@ namespace tachyon press(KeyCode::F10, KeyModifier::Shift); ASSERT_FALSE(nodeMenus.empty()); EXPECT_EQ(nodeMenus.back(), 1) << "the one clicked last"; - const NodeModel& b = view.nodes[1]; - const float2 below = NodeViewCanvasToScreen(view, float2{ float(b.pos.x), float(b.pos.y + b.lastSize.y) }); + const nodes::NodeModel& b = view.nodes[1]; + const float2 below = nodes::NodeViewCanvasToScreen(view, float2{ float(b.pos.x), float(b.pos.y + b.lastSize.y) }); ASSERT_TRUE(app.menuManager.IsOpen()); EXPECT_EQ(app.GetElementRect(app.menuManager.levels[0].windowID).position, (tachyon::int2{ int32_t(below.x), int32_t(below.y) })) << "the menu just below it"; @@ -803,20 +805,20 @@ namespace tachyon { NodeViewWireDropTest::SetUp(); reroute = app.idManager.CreateStaticID(); - NodeModel r{}; + nodes::NodeModel r{}; r.stableID = reroute; r.reroute = true; r.pos = { 360, 192 }; - r.properties.push_back(NodeProperty{ .input = PropertyEndpoint{ 0, 0 }, .output = true }); + r.properties.push_back(nodes::NodeProperty{ .input = nodes::PropertyEndpoint{ 0, 0 }, .output = true }); view.nodes.push_back(std::move(r)); - view.nodes[1].properties[0].input = PropertyEndpoint{ 2, 0 }; + view.nodes[1].properties[0].input = nodes::PropertyEndpoint{ 2, 0 }; } // The reroute's two sockets: its input (left edge) and output (right edge). - std::vector RerouteSockets() const + std::vector RerouteSockets() { - const auto square = app.GetElementRect(NodeElementID(view, reroute)); + const auto square = app.GetElementRect(nodes::NodeElementID(view, reroute)); std::vector out; - for (const auto& r : RectsWithStyle(app.theme.nodeSocketStyleRef)) + for (const auto& r : RectsWithStyle(nodes::GetStyles(app, nodesContext).nodeSocketStyleRef)) if (r.y >= square.y && r.y < square.y + square.h && r.x >= square.x - r.w && r.x < square.x + square.w) out.push_back(r); std::sort(out.begin(), out.end(), [](const auto& a, const auto& b) { return a.x < b.x; }); @@ -828,8 +830,8 @@ namespace tachyon TEST_F(NodeViewRerouteTest, ARerouteIsADotWithASocketOnEachEdge) { Settle(); - const int pitch = 2 * app.theme.nodeGridSize; - const auto square = app.GetElementRect(NodeElementID(view, reroute)); + const int pitch = 2 * nodes::GetStyles(app, nodesContext).nodeGridSize; + const auto square = app.GetElementRect(nodes::NodeElementID(view, reroute)); EXPECT_EQ(square.w, pitch); EXPECT_EQ(square.h, pitch); const auto sockets = RerouteSockets(); @@ -837,8 +839,8 @@ namespace tachyon EXPECT_EQ(sockets[0].x + sockets[0].w / 2, square.x) << "the input on the left edge"; EXPECT_EQ(sockets[1].x + sockets[1].w / 2, square.x + pitch) << "the output on the right"; EXPECT_EQ(sockets[0].y + sockets[0].h / 2, square.y + pitch / 2); - EXPECT_EQ(RectsWithStyle(app.theme.nodeHeaderStyleRef).size(), 2u) << "a header for A and B, none for the reroute"; - EXPECT_EQ(RectsWithStyle(app.theme.nodeRowStyleRef).size(), 2u) << "and no rows"; + EXPECT_EQ(RectsWithStyle(nodes::GetStyles(app, nodesContext).nodeHeaderStyleRef).size(), 2u) << "a header for A and B, none for the reroute"; + EXPECT_EQ(RectsWithStyle(nodes::GetStyles(app, nodesContext).nodeRowStyleRef).size(), 2u) << "and no rows"; } // Dragging its middle moves it, one edit; double-clicking doesn't collapse it. @@ -846,16 +848,16 @@ namespace tachyon { Settle(); int edits = 0; - view.onEdit = [&](const NodeViewEdit&) { edits++; }; - const auto square = app.GetElementRect(NodeElementID(view, reroute)); + view.onEdit = [&](const nodes::NodeViewEdit&) { edits++; }; + const auto square = app.GetElementRect(nodes::NodeElementID(view, reroute)); const tachyon::int2 start = view.nodes[2].pos; // on the grid const tachyon::int2 middle{ square.x + square.w / 2, square.y + square.h / 2 }; - Drag(middle, { middle.x + 4 * app.theme.nodeGridSize, middle.y + 2 * app.theme.nodeGridSize }); + Drag(middle, { middle.x + 4 * nodes::GetStyles(app, nodesContext).nodeGridSize, middle.y + 2 * nodes::GetStyles(app, nodesContext).nodeGridSize }); Settle(); - EXPECT_EQ(view.nodes[2].pos, (tachyon::int2{ start.x + 4 * app.theme.nodeGridSize, start.y + 2 * app.theme.nodeGridSize })); + EXPECT_EQ(view.nodes[2].pos, (tachyon::int2{ start.x + 4 * nodes::GetStyles(app, nodesContext).nodeGridSize, start.y + 2 * nodes::GetStyles(app, nodesContext).nodeGridSize })); EXPECT_EQ(edits, 1); - const auto moved = app.GetElementRect(NodeElementID(view, reroute)); + const auto moved = app.GetElementRect(nodes::NodeElementID(view, reroute)); const tachyon::int2 at{ moved.x + moved.w / 2, moved.y + moved.h / 2 }; app.ClickAt(at); Frame(); @@ -868,10 +870,10 @@ namespace tachyon // A wire drags out of its right edge into another input, and its left edge takes one. TEST_F(NodeViewRerouteTest, WiresDragOutOfAndIntoARerouteAtItsEdges) { - NodeModel c{}; + nodes::NodeModel c{}; c.stableID = app.idManager.CreateStaticID(); c.pos = { 520, 520 }; - c.properties.push_back(NodeProperty{ .input = PropertyEndpoint{} }); + c.properties.push_back(nodes::NodeProperty{ .input = nodes::PropertyEndpoint{} }); view.nodes.push_back(std::move(c)); Settle(); const auto sockets = RerouteSockets(); @@ -879,16 +881,16 @@ namespace tachyon const tachyon::int2 out{ sockets[1].x + sockets[1].w / 2, sockets[1].y + sockets[1].h / 2 }; Drag(out, SocketOf(view.nodes[3].stableID)); Settle(); - EXPECT_EQ(*view.nodes[3].properties[0].input, (PropertyEndpoint{ 2, 0 })) << "one output feeds many"; - EXPECT_EQ(*view.nodes[1].properties[0].input, (PropertyEndpoint{ 2, 0 })); + EXPECT_EQ(*view.nodes[3].properties[0].input, (nodes::PropertyEndpoint{ 2, 0 })) << "one output feeds many"; + EXPECT_EQ(*view.nodes[1].properties[0].input, (nodes::PropertyEndpoint{ 2, 0 })); - view.nodes[2].properties[0].input = PropertyEndpoint{}; + view.nodes[2].properties[0].input = nodes::PropertyEndpoint{}; Settle(); const auto again = RerouteSockets(); const tachyon::int2 in{ again[0].x + again[0].w / 2, again[0].y + again[0].h / 2 }; Drag(SocketOf(nodeA), in); Settle(); - EXPECT_EQ(*view.nodes[2].properties[0].input, (PropertyEndpoint{ 0, 0 })); + EXPECT_EQ(*view.nodes[2].properties[0].input, (nodes::PropertyEndpoint{ 0, 0 })); } // A right click on a reroute opens its menu, even with a wire hovered last that reaches @@ -896,11 +898,11 @@ namespace tachyon TEST_F(NodeViewRerouteTest, ARightClickOnARerouteOpensItsMenuNotAWires) { Settle(); - const auto square = app.GetElementRect(NodeElementID(view, reroute)); + const auto square = app.GetElementRect(nodes::NodeElementID(view, reroute)); const tachyon::int2 middle{ square.x + square.w / 2, square.y + square.h / 2 }; app.InjectMouseMove(middle); Frame(); - view.hoveredWire.part = WireKey(2, 0); + view.hoveredWire.part = nodes::WireKey(2, 0); app.ClickAt(middle, MouseButtons::Right); Frame(); Frame(); @@ -942,8 +944,8 @@ namespace tachyon app.ClickAt(CanvasPoint()); // focuses the canvas Frame(); view.selectedNodeIDs = { reroute, nodeA }; - std::vector edits; - view.onEdit = [&](const NodeViewEdit& e) { edits.push_back(e); }; + std::vector edits; + view.onEdit = [&](const nodes::NodeViewEdit& e) { edits.push_back(e); }; app.InjectKey(KeyCode::Return); Frame(); EXPECT_TRUE(view.nodes[0].collapsed) << "A"; @@ -956,7 +958,7 @@ namespace tachyon TEST_F(NodeViewRerouteTest, RemoveRerouteFromItsMenu) { Settle(); - const auto square = app.GetElementRect(NodeElementID(view, reroute)); + const auto square = app.GetElementRect(nodes::NodeElementID(view, reroute)); const tachyon::int2 middle{ square.x + square.w / 2, square.y + square.h / 2 }; app.InjectMouseMove(middle); Frame(); @@ -970,20 +972,20 @@ namespace tachyon Frame(); Frame(); ASSERT_EQ(view.nodes.size(), 2u); - EXPECT_EQ(*view.nodes[1].properties[0].input, (PropertyEndpoint{ 0, 0 })); + EXPECT_EQ(*view.nodes[1].properties[0].input, (nodes::PropertyEndpoint{ 0, 0 })); } // Its pins show while it's hovered or selected, else only the dot. TEST_F(NodeViewRerouteTest, ARerouteShowsItsPinsWhileHoveredOrSelected) { auto pinsDrawn = [&] { - const auto square = app.GetElementRect(NodeElementID(view, reroute)); + const auto square = app.GetElementRect(nodes::NodeElementID(view, reroute)); int drawn = 0; for (uint32_t d = 0; d < app.elementStorage.NumberOfDepthLevels(); d++) for (uint32_t i = 0; i < app.elementStorage.DepthSizeOf(d); i++) { const tachyon::ElementRef ref{ d, i }; - if (!app.elementStorage.IsValidRef(ref) || app.elementStorage.GetElementUnsafe(ref).styleRef != app.theme.nodeSocketStyleRef) + if (!app.elementStorage.IsValidRef(ref) || app.elementStorage.GetElementUnsafe(ref).styleRef != nodes::GetStyles(app, nodesContext).nodeSocketStyleRef) continue; const auto& r = app.elementStorage.GetElementRectPtr(ref)->rect; if (r.y >= square.y && r.y < square.y + square.h && r.x >= square.x - r.w && r.x < square.x + square.w @@ -998,7 +1000,7 @@ namespace tachyon Settle(); EXPECT_EQ(pinsDrawn(), 2) << "selected"; view.selectedNodeIDs.clear(); - const auto square = app.GetElementRect(NodeElementID(view, reroute)); + const auto square = app.GetElementRect(nodes::NodeElementID(view, reroute)); app.InjectMouseMove({ square.x + square.w / 2, square.y + square.h / 2 }); Settle(); EXPECT_EQ(pinsDrawn(), 2) << "hovered"; @@ -1011,16 +1013,16 @@ namespace tachyon app.runPostLayoutCallbacks = true; view.nodes[0].title = "A node with a much longer title than B"; Settle(); - const tachyon::int2 sizeB = app.GetElementRect(NodeElementID(view, nodeB)).size; - ASSERT_NE(app.GetElementRect(NodeElementID(view, nodeA)).size, sizeB); + const tachyon::int2 sizeB = app.GetElementRect(nodes::NodeElementID(view, nodeB)).size; + ASSERT_NE(app.GetElementRect(nodes::NodeElementID(view, nodeA)).size, sizeB); view.nodes[1].lastSize = {}; app.Frame([&] { app.BeginRootWindow({ 1920, 1080 }, ElementFlags::None, app.theme.mainWindowStyleRef); - app.RenderNodeView(view); + nodes::RenderNodeView(app, nodesContext, view); app.EndRootWindow(); const int first[] = { 0 }; - ApplyNodeViewEdit(view, RemoveNodesEdit(view, first)); + nodes::ApplyNodeViewEdit(view, nodes::RemoveNodesEdit(view, first)); }); ASSERT_EQ(view.nodes.size(), 1u); EXPECT_EQ(view.nodes[0].stableID, nodeB); @@ -1049,12 +1051,12 @@ namespace tachyon EXPECT_EQ(built.back(), 1); const int first[] = { 0 }; - ApplyNodeViewEdit(view, RemoveNodesEdit(view, first)); + nodes::ApplyNodeViewEdit(view, nodes::RemoveNodesEdit(view, first)); Frame(); EXPECT_EQ(built.back(), 0) << "B is node 0 now"; const int last[] = { 0 }; - ApplyNodeViewEdit(view, RemoveNodesEdit(view, last)); + nodes::ApplyNodeViewEdit(view, nodes::RemoveNodesEdit(view, last)); const size_t count = built.size(); Frame(); Frame(); @@ -1116,7 +1118,7 @@ namespace tachyon EXPECT_EQ(reported, 1) << "nothing changed since"; const int first[] = { 0 }; - ApplyNodeViewEdit(view, RemoveNodesEdit(view, first)); + nodes::ApplyNodeViewEdit(view, nodes::RemoveNodesEdit(view, first)); Frame(); EXPECT_EQ(reported, 2) << "a selected node went"; EXPECT_EQ(view.selectedNodeIDs, std::unordered_set{ nodeB }); @@ -1145,21 +1147,21 @@ namespace tachyon view.nodes[0].properties[0].renderBody = [this] { app.Field(a); }; view.nodes[1].properties[0].renderBody = [this] { app.Field(b); }; far = app.idManager.CreateStaticID(); - NodeModel node{}; + nodes::NodeModel node{}; node.stableID = far; node.title = "F"; node.pos = { 40000, 0 }; - node.properties.push_back(NodeProperty{ .input = PropertyEndpoint{ 0, 0 }, .renderBody = [this] { ++farBodies; app.Field(f1); } }); - node.properties.push_back(NodeProperty{ .output = true, .renderBody = [this] { ++farBodies; app.Field(f2); }, .rowSpan = 2 }); + node.properties.push_back(nodes::NodeProperty{ .input = nodes::PropertyEndpoint{ 0, 0 }, .renderBody = [this] { ++farBodies; app.Field(f1); } }); + node.properties.push_back(nodes::NodeProperty{ .output = true, .renderBody = [this] { ++farBodies; app.Field(f2); }, .rowSpan = 2 }); view.nodes.push_back(std::move(node)); } tachyon::ID FocusedID() const { return app.guiStateManager.Interaction().GetFocusedID(); } // The socket rects inside `node`'s rect, relative to it, left to right then top down. - std::vector SocketsOf(tachyon::ID node) const + std::vector SocketsOf(tachyon::ID node) { - const auto n = app.GetElementRect(NodeElementID(view, node)); + const auto n = app.GetElementRect(nodes::NodeElementID(view, node)); std::vector out; - for (auto r : RectsWithStyle(app.theme.nodeSocketStyleRef)) + for (auto r : RectsWithStyle(nodes::GetStyles(app, nodesContext).nodeSocketStyleRef)) if (r.y >= n.y && r.y < n.y + n.h && r.x >= n.x - r.w && r.x < n.x + n.w + r.w) out.push_back({ r.x - n.x, r.y - n.y, r.w, r.h }); std::sort(out.begin(), out.end(), [](const auto& p, const auto& q) { return p.x != q.x ? p.x < q.x : p.y < q.y; }); @@ -1174,7 +1176,7 @@ namespace tachyon view.virtualizeLayout = false; Settle(); Settle(); - const tachyon::IntRect whole = app.GetElementRect(NodeElementID(view, far)); + const tachyon::IntRect whole = app.GetElementRect(nodes::NodeElementID(view, far)); const auto wholeSockets = SocketsOf(far); ASSERT_EQ(wholeSockets.size(), 2u); ASSERT_GT(farBodies, 0); @@ -1184,7 +1186,7 @@ namespace tachyon farBodies = 0; Settle(); EXPECT_EQ(farBodies, 0) << "no renderBody for it"; - EXPECT_EQ(app.GetElementRect(NodeElementID(view, far)).size, whole.size) << "its last size"; + EXPECT_EQ(app.GetElementRect(nodes::NodeElementID(view, far)).size, whole.size) << "its last size"; EXPECT_EQ(SocketsOf(far), wholeSockets) << "its sockets where they'd be"; EXPECT_EQ(view.nodes[2].lastSize, whole.size); EXPECT_FALSE(app.HasElement(app.FindByText("F"))) << "no header"; @@ -1237,10 +1239,10 @@ namespace tachyon for (int y = 0; y < 30; ++y) for (int x = 0; x < 30; ++x) { - NodeModel node{}; + nodes::NodeModel node{}; node.stableID = app.idManager.CreateStaticID(); node.pos = { (x - 15) * 600, (y - 15) * 400 }; - node.properties.push_back(NodeProperty{ .output = true, .renderBody = [&bodies] { ++bodies; } }); + node.properties.push_back(nodes::NodeProperty{ .output = true, .renderBody = [&bodies] { ++bodies; } }); view.nodes.push_back(std::move(node)); } Settle(); // each laid out once, to learn its size @@ -1273,11 +1275,11 @@ namespace tachyon TEST_F(NodeViewVirtualTest, ANewNodeFarAwayIsLaidOutOnce) { Settle(); - NodeModel node{}; + nodes::NodeModel node{}; node.stableID = app.idManager.CreateStaticID(); node.title = "G"; node.pos = { 0, 40000 }; - node.properties.push_back(NodeProperty{ .output = true, .renderBody = [this] { app.Field(f1); } }); + node.properties.push_back(nodes::NodeProperty{ .output = true, .renderBody = [this] { app.Field(f1); } }); view.nodes.push_back(std::move(node)); Settle(); EXPECT_GT(view.nodes[3].lastSize.x, 0); @@ -1289,11 +1291,11 @@ namespace tachyon TEST_F(NodeViewVirtualTest, CollapsedNodesAndReroutesNeverStandIn) { view.nodes[2].collapsed = true; - NodeModel dot{}; + nodes::NodeModel dot{}; dot.stableID = app.idManager.CreateStaticID(); dot.reroute = true; dot.pos = { 0, 40000 }; - dot.properties.push_back(NodeProperty{ .input = PropertyEndpoint{}, .output = true }); + dot.properties.push_back(nodes::NodeProperty{ .input = nodes::PropertyEndpoint{}, .output = true }); view.nodes.push_back(std::move(dot)); const tachyon::ID dotID = view.nodes[3].stableID; @@ -1355,10 +1357,10 @@ namespace tachyon TEST_F(NodeViewControlTest, NodesLayOutAtTheirPositions) { Settle(); - ASSERT_TRUE(app.HasElement(NodeElementID(view, nodeA))); - ASSERT_TRUE(app.HasElement(NodeElementID(view, nodeB))); - const auto a = app.GetElementRect(NodeElementID(view, nodeA)); - const auto b = app.GetElementRect(NodeElementID(view, nodeB)); + ASSERT_TRUE(app.HasElement(nodes::NodeElementID(view, nodeA))); + ASSERT_TRUE(app.HasElement(nodes::NodeElementID(view, nodeB))); + const auto a = app.GetElementRect(nodes::NodeElementID(view, nodeA)); + const auto b = app.GetElementRect(nodes::NodeElementID(view, nodeB)); EXPECT_GT(a.w, 0); EXPECT_GT(b.w, 0); // B sits below-right of A (pos {100,80} vs {520,320}). @@ -1372,8 +1374,8 @@ namespace tachyon // every frame; running several proves RenderNodeView opens and // closes its element scopes correctly each time. for (int i = 0; i < 4; ++i) Frame(); - EXPECT_TRUE(app.HasElement(NodeElementID(view, nodeA))); - EXPECT_TRUE(app.HasElement(NodeElementID(view, nodeB))); + EXPECT_TRUE(app.HasElement(nodes::NodeElementID(view, nodeA))); + EXPECT_TRUE(app.HasElement(nodes::NodeElementID(view, nodeB))); } TEST_F(NodeViewControlTest, BareClickOnEmptyCanvasClearsSelection) @@ -1506,18 +1508,18 @@ namespace tachyon EXPECT_LT(view.transform.r0.z, panBefore) << "Right with nothing selected pans"; press(KeyCode::Equals); - EXPECT_GT(NodeViewZoom(view), 0.99f); + EXPECT_GT(nodes::NodeViewZoom(view), 0.99f); view.transform = tachyon::float3x2::Scale(0.5f); press(KeyCode::Equals); - EXPECT_NEAR(NodeViewZoom(view), 0.55f, 1e-3f) << "+ zooms in"; + EXPECT_NEAR(nodes::NodeViewZoom(view), 0.55f, 1e-3f) << "+ zooms in"; press(KeyCode::Minus); - EXPECT_NEAR(NodeViewZoom(view), 0.5f, 1e-3f) << "- zooms out"; + EXPECT_NEAR(nodes::NodeViewZoom(view), 0.5f, 1e-3f) << "- zooms out"; press(KeyCode::KeyA, KeyModifier::Control); EXPECT_EQ(view.selectedNodeIDs.size(), 2u) << "Ctrl+A selects every node"; const int2 a = view.nodes[0].pos, b = view.nodes[1].pos; - const int32_t grid = app.theme.nodeGridSize; + const int32_t grid = nodes::GetStyles(app, nodesContext).nodeGridSize; press(KeyCode::Down); EXPECT_EQ(view.nodes[0].pos, (int2{ a.x, a.y + grid })) << "Down moves the selected nodes a grid step"; EXPECT_EQ(view.nodes[1].pos, (int2{ b.x, b.y + grid })); @@ -1538,11 +1540,11 @@ namespace tachyon { app.runPostLayoutCallbacks = true; // the view learns its size and the nodes theirs there const ID farID = app.idManager.CreateStaticID(); - NodeModel far{}; + nodes::NodeModel far{}; far.stableID = farID; far.title = "Far"; far.pos = { 4000, 80 }; - far.properties.push_back(NodeProperty{ .renderBody = [this] { app.Button("Go", [] {}); } }); + far.properties.push_back(nodes::NodeProperty{ .renderBody = [this] { app.Button("Go", [] {}); } }); view.nodes.push_back(std::move(far)); Settle(); @@ -1550,7 +1552,7 @@ namespace tachyon // canvas position. const tachyon::IntRect inner = CanvasInner(); auto onScreen = [&] { - const NodeModel& node = view.nodes[2]; + const nodes::NodeModel& node = view.nodes[2]; const float2 a = view.transform.TransformPoint(float2{ (float)node.pos.x, (float)node.pos.y }); const float2 b = view.transform.TransformPoint(float2{ (float)(node.pos.x + node.lastSize.x), (float)(node.pos.y + node.lastSize.y) }); @@ -1561,7 +1563,7 @@ namespace tachyon ASSERT_GT(onScreen().x, inner.x + inner.w) << "test setup: the node starts out of view"; auto focusInFar = [&] { - return (app.guiStateManager.GetCurrentState(NodeElementID(view, farID)) & ElementState::Focused) != ElementState::None; + return (app.guiStateManager.GetCurrentState(nodes::NodeElementID(view, farID)) & ElementState::Focused) != ElementState::None; }; for (int i = 0; i < 8 && !focusInFar(); ++i) { @@ -1582,11 +1584,11 @@ namespace tachyon TEST_F(NodeViewControlTest, PanningAwayFromTheFocusedNodeStays) { app.runPostLayoutCallbacks = true; - view.nodes[0].properties.push_back(NodeProperty{ .renderBody = [this] { app.Button("Go", [] {}); } }); + view.nodes[0].properties.push_back(nodes::NodeProperty{ .renderBody = [this] { app.Button("Go", [] {}); } }); Settle(); app.InjectKey(KeyCode::Tab); Settle(); - ASSERT_TRUE((app.guiStateManager.GetCurrentState(NodeElementID(view, nodeA)) & ElementState::Focused) != ElementState::None); + ASSERT_TRUE((app.guiStateManager.GetCurrentState(nodes::NodeElementID(view, nodeA)) & ElementState::Focused) != ElementState::None); view.transform = tachyon::float3x2::Translate(tachyon::float2{ -5000.0f, 0.0f }); Settle(); @@ -1601,7 +1603,7 @@ namespace tachyon { Settle(); int edits = 0; - view.onEdit = [&](const NodeViewEdit&) { edits++; }; + view.onEdit = [&](const nodes::NodeViewEdit&) { edits++; }; const tachyon::int2 before = view.nodes[1].pos; const tachyon::int2 from = HeaderOf(nodeB); app.InjectMouseMove(from); @@ -1609,7 +1611,7 @@ namespace tachyon Frame(); app.InjectMouseMove({ from.x + 2, from.y + 1 }, MouseButtons::Left); Frame(); - EXPECT_TRUE(view.nodeDrag.IsPressed(NodeElementID(view, nodeB))); + EXPECT_TRUE(view.nodeDrag.IsPressed(nodes::NodeElementID(view, nodeB))); EXPECT_EQ(view.nodeDrag.Phase(), GesturePhase::Pressed) << "under the drag distance it isn't a move yet"; app.InjectMouseUp({ from.x + 2, from.y + 1 }); Settle(); @@ -1622,10 +1624,10 @@ namespace tachyon { Settle(); int edits = 0; - view.onEdit = [&](const NodeViewEdit&) { edits++; }; + view.onEdit = [&](const nodes::NodeViewEdit&) { edits++; }; const tachyon::int2 before = view.nodes[1].pos; const tachyon::int2 from = HeaderOf(nodeB); - const tachyon::int2 to{ from.x + 6 * app.theme.nodeGridSize, from.y + 2 * app.theme.nodeGridSize }; + const tachyon::int2 to{ from.x + 6 * nodes::GetStyles(app, nodesContext).nodeGridSize, from.y + 2 * nodes::GetStyles(app, nodesContext).nodeGridSize }; app.InjectMouseMove(from); app.InjectMouseDown(from); Frame(); @@ -1648,7 +1650,7 @@ namespace tachyon { view.transform = tachyon::float3x2::Scale(2.0f); Settle(); - const int32_t grid = app.theme.nodeGridSize; + const int32_t grid = nodes::GetStyles(app, nodesContext).nodeGridSize; const tachyon::int2 before = view.nodes[0].pos; // The canvas scales its content around its inner rect's top-left. const tachyon::int2 pivot = CanvasInner().position; @@ -1709,7 +1711,7 @@ namespace tachyon TEST_F(NodeViewControlTest, TheMinimapFollowsOnlyItsOwnPress) { Settle(); - const auto minimaps = RectsWithStyle(app.theme.nodeViewMinimapStyleRef); + const auto minimaps = RectsWithStyle(nodes::GetStyles(app, nodesContext).nodeViewMinimapStyleRef); ASSERT_EQ(minimaps.size(), 1u); const tachyon::IntRect m = minimaps[0]; const tachyon::int2 inMinimap{ m.x + m.w / 4, m.y + m.h / 4 }; @@ -1747,19 +1749,19 @@ namespace tachyon // Dragging a wire's lane moves it; Escape puts it back and records nothing. TEST_F(NodeViewControlTest, EscapeDuringALaneDragPutsTheLaneBack) { - view.nodes[1].properties[0].input = PropertyEndpoint{ 0, 0 }; + view.nodes[1].properties[0].input = nodes::PropertyEndpoint{ 0, 0 }; Settle(); int edits = 0; - view.onEdit = [&](const NodeViewEdit&) { edits++; }; - const uint32_t key = WireKey(1, 0); + view.onEdit = [&](const nodes::NodeViewEdit&) { edits++; }; + const uint32_t key = nodes::WireKey(1, 0); // Each frame's route pass caches the wires' draggable segments for the next one; this // wire is straight, so the test gives it a vertical segment before every frame. - const CachedWireHandle handle{ .wireKey = key, .role = WireHandle::LaneX, .vertical = true, + const nodes::CachedWireHandle handle{ .wireKey = key, .role = nodes::WireHandle::LaneX, .vertical = true, .a = { 300, 100 }, .b = { 300, 300 } }; auto frame = [&] { view.wireHandleCache = { handle }; Frame(); }; frame(); // Node A's laid-out rect against its pos gives where node.pos space starts. - const tachyon::int2 origin = app.GetElementRect(NodeElementID(view, nodeA)).position - view.nodes[0].pos; + const tachyon::int2 origin = app.GetElementRect(nodes::NodeElementID(view, nodeA)).position - view.nodes[0].pos; const tachyon::int2 grab = origin + tachyon::int2{ 300, 200 }; app.InjectMouseMove(grab); app.InjectMouseDown(grab); @@ -1793,7 +1795,7 @@ namespace tachyon { const tachyon::ElementRef ref{ d, i }; if (app.elementStorage.IsValidRef(ref) && - app.elementStorage.GetElementUnsafe(ref).styleRef == app.theme.nodeViewMinimapStyleRef) { minimapRef = ref; break; } + app.elementStorage.GetElementUnsafe(ref).styleRef == nodes::GetStyles(app, nodesContext).nodeViewMinimapStyleRef) { minimapRef = ref; break; } } ASSERT_TRUE(minimapRef.IsValid()); const Element& minimap = app.elementStorage.GetElementUnsafe(minimapRef); @@ -1820,7 +1822,7 @@ namespace tachyon strength.name = "Strength"; strength.type = "float"; strength.value = [&] { ++asked; return std::string("0.75"); }; - strength.input = PropertyEndpoint{ 0, 0 }; + strength.input = nodes::PropertyEndpoint{ 0, 0 }; Settle(); EXPECT_EQ(asked, 0); @@ -1856,13 +1858,13 @@ namespace tachyon view.nodes[0].properties[0].name = "Value"; auto& through = view.nodes[1].properties[0]; through.name = "Through"; - through.input = PropertyEndpoint{ 0, 0 }; + through.input = nodes::PropertyEndpoint{ 0, 0 }; through.output = true; Settle(); // B's output socket: right of B. - const tachyon::IntRect n = app.GetElementRect(NodeElementID(view, nodeB)); + const tachyon::IntRect n = app.GetElementRect(nodes::NodeElementID(view, nodeB)); tachyon::int2 out{ -1, -1 }; - for (const auto& r : RectsWithStyle(app.theme.nodeSocketStyleRef)) + for (const auto& r : RectsWithStyle(nodes::GetStyles(app, nodesContext).nodeSocketStyleRef)) if (r.x + r.w / 2 > n.x + n.w / 2 && r.y >= n.y && r.y < n.y + n.h) out = { r.x + r.w / 2, r.y + r.h / 2 }; ASSERT_NE(out.x, -1); @@ -1882,7 +1884,7 @@ namespace tachyon for (uint32_t i = 0; i < app.elementStorage.DepthSizeOf(d); i++) { const tachyon::ElementRef ref{ d, i }; - if (app.elementStorage.IsValidRef(ref) && app.elementStorage.GetElementUnsafe(ref).styleRef == app.theme.nodeSocketStyleRef && + if (app.elementStorage.IsValidRef(ref) && app.elementStorage.GetElementUnsafe(ref).styleRef == nodes::GetStyles(app, nodesContext).nodeSocketStyleRef && app.elementStorage.GetElementRectUnsafe(ref).rect.Contains(SocketOf(nodeB))) { socket = ref; break; } } @@ -1920,10 +1922,10 @@ namespace tachyon const ID field = app.FindByText("1.00"); ASSERT_NE(field, ID::Invalid()) << "two decimals"; EXPECT_EQ(app.elementStorage.GetElementUnsafe(app.elementStorage.FindElementRefByID(field)).styleRef, - app.theme.nodeControls.number); + nodes::GetStyles(app, nodesContext).nodeControls.number); EXPECT_EQ(app.theme.controls, &app.theme.regularControls) << "back to the regular ones after the node"; - const tachyon::LayoutStyle* style = app.styleManager.GetLayoutStyle(app.theme.nodeControls.number.layoutStyleIndex); + const tachyon::LayoutStyle* style = app.styleManager.GetLayoutStyle(nodes::GetStyles(app, nodesContext).nodeControls.number.layoutStyleIndex); ASSERT_NE(style, nullptr); EXPECT_EQ(style->textLayoutStyle.horizontalAlignment, TextAlign::End) << "at the end of its box"; } @@ -1934,7 +1936,7 @@ namespace tachyon Settle(); const ID fit = app.FindByText("Fit"); ASSERT_NE(fit, ID::Invalid()); - const std::vector dividers = RectsWithStyle(app.theme.nodeViewOverlayDividerStyleRef); + const std::vector dividers = RectsWithStyle(nodes::GetStyles(app, nodesContext).nodeViewOverlayDividerStyleRef); ASSERT_EQ(dividers.size(), 1u); const tachyon::IntRect fitRect = app.GetElementRect(fit); const tachyon::IntRect plus = app.GetElementRect(app.FindByText("+")); @@ -1947,13 +1949,13 @@ namespace tachyon // only does: the output's at the end anyway. TEST_F(NodeViewControlTest, ATextRowWithSocketsOnBothSidesIsAtTheStart) { - view.nodes[0].properties[0].input = PropertyEndpoint{}; - view.nodes[0].properties[0].renderBody = [this] { app.NodeText("Bypass"); }; + view.nodes[0].properties[0].input = nodes::PropertyEndpoint{}; + view.nodes[0].properties[0].renderBody = [this] { nodes::NodeText(app, nodesContext, "Bypass"); }; Settle(); const ID text = app.FindByText("Bypass"); ASSERT_NE(text, ID::Invalid()); EXPECT_EQ(app.elementStorage.GetElementUnsafe(app.elementStorage.FindElementRefByID(text)).styleRef, - app.theme.nodeTextLeftStyleRef); + nodes::GetStyles(app, nodesContext).nodeTextLeftStyleRef); } } // namespace diff --git a/tests/node_view_drop_test.cpp b/tests/node_view_drop_test.cpp index 612c4f0f..3e9508a3 100644 --- a/tests/node_view_drop_test.cpp +++ b/tests/node_view_drop_test.cpp @@ -3,120 +3,121 @@ #include -#include +#include +#include namespace { using namespace tachyon; // Node 0 has one output; node 1 has a row without an input, then two inputs. - NodeView MakeView() + nodes::NodeView MakeView() { - NodeView view; + nodes::NodeView view; view.nodes.resize(2); view.nodes[0].properties.resize(1); view.nodes[0].properties[0].output = true; view.nodes[1].properties.resize(3); - view.nodes[1].properties[1].input = PropertyEndpoint{}; - view.nodes[1].properties[2].input = PropertyEndpoint{}; + view.nodes[1].properties[1].input = nodes::PropertyEndpoint{}; + view.nodes[1].properties[2].input = nodes::PropertyEndpoint{}; return view; } - constexpr PropertyEndpoint kOutput{ 0, 0 }; + constexpr nodes::PropertyEndpoint kOutput{ 0, 0 }; TEST(NodeViewDrop, PicksTheFirstInput) { - const NodeView view = MakeView(); - EXPECT_EQ(FirstInputAccepting(view, kOutput, 1), (PropertyEndpoint{ 1, 1 })); + const nodes::NodeView view = MakeView(); + EXPECT_EQ(nodes::FirstInputAccepting(view, kOutput, 1), (nodes::PropertyEndpoint{ 1, 1 })); } TEST(NodeViewDrop, SkipsInputsTheViewRefuses) { - NodeView view = MakeView(); - view.canConnect = [](const NodeGraph&, PropertyEndpoint, PropertyEndpoint in) { return in.propIdx != 1; }; - EXPECT_EQ(FirstInputAccepting(view, kOutput, 1), (PropertyEndpoint{ 1, 2 })); + nodes::NodeView view = MakeView(); + view.canConnect = [](const nodes::NodeGraph&, nodes::PropertyEndpoint, nodes::PropertyEndpoint in) { return in.propIdx != 1; }; + EXPECT_EQ(nodes::FirstInputAccepting(view, kOutput, 1), (nodes::PropertyEndpoint{ 1, 2 })); } TEST(NodeViewDrop, NothingWhenNoInputTakesIt) { - NodeView view = MakeView(); - view.canConnect = [](const NodeGraph&, PropertyEndpoint, PropertyEndpoint) { return false; }; - EXPECT_FALSE(FirstInputAccepting(view, kOutput, 1).valid()); + nodes::NodeView view = MakeView(); + view.canConnect = [](const nodes::NodeGraph&, nodes::PropertyEndpoint, nodes::PropertyEndpoint) { return false; }; + EXPECT_FALSE(nodes::FirstInputAccepting(view, kOutput, 1).valid()); } TEST(NodeViewDrop, NeverTheSourceNodeItself) { - NodeView view = MakeView(); - view.nodes[0].properties[0].input = PropertyEndpoint{}; - EXPECT_FALSE(FirstInputAccepting(view, kOutput, 0).valid()); + nodes::NodeView view = MakeView(); + view.nodes[0].properties[0].input = nodes::PropertyEndpoint{}; + EXPECT_FALSE(nodes::FirstInputAccepting(view, kOutput, 0).valid()); } TEST(NodeViewDrop, AnInputAlreadyInUseStillTakesIt) { - NodeView view = MakeView(); - view.nodes[1].properties[1].input = PropertyEndpoint{ 0, 0 }; - EXPECT_EQ(FirstInputAccepting(view, kOutput, 1), (PropertyEndpoint{ 1, 1 })); + nodes::NodeView view = MakeView(); + view.nodes[1].properties[1].input = nodes::PropertyEndpoint{ 0, 0 }; + EXPECT_EQ(nodes::FirstInputAccepting(view, kOutput, 1), (nodes::PropertyEndpoint{ 1, 1 })); } // A wire dragged from an input, dropped on a node: its first output that may feed it. TEST(NodeViewDrop, AWireFromAnInputPicksTheFirstOutput) { - NodeView view = MakeView(); + nodes::NodeView view = MakeView(); view.nodes[0].properties.resize(3); view.nodes[0].properties[0].output = false; view.nodes[0].properties[1].output = true; view.nodes[0].properties[2].output = true; - constexpr PropertyEndpoint kInput{ 1, 1 }; - EXPECT_EQ(FirstOutputAccepting(view, kInput, 0), (PropertyEndpoint{ 0, 1 })); + constexpr nodes::PropertyEndpoint kInput{ 1, 1 }; + EXPECT_EQ(nodes::FirstOutputAccepting(view, kInput, 0), (nodes::PropertyEndpoint{ 0, 1 })); - view.canConnect = [](const NodeGraph&, PropertyEndpoint out, PropertyEndpoint) { return out.propIdx != 1; }; - EXPECT_EQ(FirstOutputAccepting(view, kInput, 0), (PropertyEndpoint{ 0, 2 })) << "skips what the view refuses"; + view.canConnect = [](const nodes::NodeGraph&, nodes::PropertyEndpoint out, nodes::PropertyEndpoint) { return out.propIdx != 1; }; + EXPECT_EQ(nodes::FirstOutputAccepting(view, kInput, 0), (nodes::PropertyEndpoint{ 0, 2 })) << "skips what the view refuses"; - view.canConnect = [](const NodeGraph&, PropertyEndpoint, PropertyEndpoint) { return false; }; - EXPECT_FALSE(FirstOutputAccepting(view, kInput, 0).valid()); + view.canConnect = [](const nodes::NodeGraph&, nodes::PropertyEndpoint, nodes::PropertyEndpoint) { return false; }; + EXPECT_FALSE(nodes::FirstOutputAccepting(view, kInput, 0).valid()); view.canConnect = {}; view.nodes[1].properties[0].output = true; - EXPECT_FALSE(FirstOutputAccepting(view, kInput, 1).valid()) << "never the input's own node"; - EXPECT_FALSE(FirstOutputAccepting(view, kInput, 2).valid()) << "no such node"; - EXPECT_FALSE(FirstOutputAccepting(view, kInput, -1).valid()); + EXPECT_FALSE(nodes::FirstOutputAccepting(view, kInput, 1).valid()) << "never the input's own node"; + EXPECT_FALSE(nodes::FirstOutputAccepting(view, kInput, 2).valid()) << "no such node"; + EXPECT_FALSE(nodes::FirstOutputAccepting(view, kInput, -1).valid()); } // Which node a canvas point is on: the frontmost of those whose last laid-out rect holds it. TEST(NodeViewDrop, TheNodeAtACanvasPoint) { - NodeView view = MakeView(); + nodes::NodeView view = MakeView(); view.nodes[0].pos = { 0, 0 }; view.nodes[0].lastSize = { 100, 60 }; view.nodes[1].pos = { 50, 30 }; view.nodes[1].lastSize = { 100, 60 }; view.ordering = { 0, 1 }; - EXPECT_EQ(NodeAtCanvasPos(view, { 10.0f, 10.0f }), 0); - EXPECT_EQ(NodeAtCanvasPos(view, { 60.0f, 40.0f }), 1) << "both: the front one"; + EXPECT_EQ(nodes::NodeAtCanvasPos(view, { 10.0f, 10.0f }), 0); + EXPECT_EQ(nodes::NodeAtCanvasPos(view, { 60.0f, 40.0f }), 1) << "both: the front one"; view.ordering = { 1, 0 }; - EXPECT_EQ(NodeAtCanvasPos(view, { 60.0f, 40.0f }), 0); - EXPECT_EQ(NodeAtCanvasPos(view, { 149.0f, 89.0f }), 1) << "its last pixel"; - EXPECT_EQ(NodeAtCanvasPos(view, { 150.0f, 50.0f }), -1) << "right of it"; - EXPECT_EQ(NodeAtCanvasPos(view, { 60.0f, 90.0f }), -1) << "below it"; - EXPECT_EQ(NodeAtCanvasPos(view, { 0.0f, 0.0f }), 0) << "its first pixel"; - EXPECT_EQ(NodeAtCanvasPos(view, { -1.0f, 10.0f }), -1) << "left of it"; - EXPECT_EQ(NodeAtCanvasPos(view, { 10.0f, -1.0f }), -1) << "above it"; + EXPECT_EQ(nodes::NodeAtCanvasPos(view, { 60.0f, 40.0f }), 0); + EXPECT_EQ(nodes::NodeAtCanvasPos(view, { 149.0f, 89.0f }), 1) << "its last pixel"; + EXPECT_EQ(nodes::NodeAtCanvasPos(view, { 150.0f, 50.0f }), -1) << "right of it"; + EXPECT_EQ(nodes::NodeAtCanvasPos(view, { 60.0f, 90.0f }), -1) << "below it"; + EXPECT_EQ(nodes::NodeAtCanvasPos(view, { 0.0f, 0.0f }), 0) << "its first pixel"; + EXPECT_EQ(nodes::NodeAtCanvasPos(view, { -1.0f, 10.0f }), -1) << "left of it"; + EXPECT_EQ(nodes::NodeAtCanvasPos(view, { 10.0f, -1.0f }), -1) << "above it"; view.ordering = { 0, 5, -1 }; - EXPECT_EQ(NodeAtCanvasPos(view, { 10.0f, 10.0f }), 0) << "indices out of range are skipped"; + EXPECT_EQ(nodes::NodeAtCanvasPos(view, { 10.0f, 10.0f }), 0) << "indices out of range are skipped"; } // Through the place and pan/zoom the view was last drawn with, and back. TEST(NodeViewDrop, CanvasAndScreenPointsThroughTheView) { - NodeView view; + nodes::NodeView view; view.lastCanvasRect = { 100, 50, 800, 600 }; view.lastInnerSize = { 800, 600 }; view.transform = float3x2::Scale(0.5f); - const float2 screen = NodeViewCanvasToScreen(view, { 100.0f, -100.0f }); + const float2 screen = nodes::NodeViewCanvasToScreen(view, { 100.0f, -100.0f }); EXPECT_FLOAT_EQ(screen.x, 550.0f); EXPECT_FLOAT_EQ(screen.y, 300.0f); - const float2 back = NodeViewScreenToCanvas(view, { 550, 300 }); + const float2 back = nodes::NodeViewScreenToCanvas(view, { 550, 300 }); EXPECT_FLOAT_EQ(back.x, 100.0f); EXPECT_FLOAT_EQ(back.y, -100.0f); view.transform = float3x2::Translate(float2{ 40.0f, -20.0f }); - const float2 panned = NodeViewCanvasToScreen(view, { 0.0f, 0.0f }); + const float2 panned = nodes::NodeViewCanvasToScreen(view, { 0.0f, 0.0f }); EXPECT_FLOAT_EQ(panned.x, 540.0f); EXPECT_FLOAT_EQ(panned.y, 330.0f); } @@ -125,11 +126,11 @@ namespace TEST(NodeViewDrop, AScreenPointOnTheCanvas) { const IntRect canvas{ 100, 50, 800, 600 }; // centre (500, 350) - EXPECT_EQ(NodeViewScreenToCanvas(float3x2::Scale(1.0f), canvas, { 500, 350 }).x, 0.0f); - const float2 panned = NodeViewScreenToCanvas(float3x2::Translate(float2{ 40.0f, -20.0f }), canvas, { 510, 360 }); + EXPECT_EQ(nodes::NodeViewScreenToCanvas(float3x2::Scale(1.0f), canvas, { 500, 350 }).x, 0.0f); + const float2 panned = nodes::NodeViewScreenToCanvas(float3x2::Translate(float2{ 40.0f, -20.0f }), canvas, { 510, 360 }); EXPECT_FLOAT_EQ(panned.x, -30.0f); EXPECT_FLOAT_EQ(panned.y, 30.0f); - const float2 zoomed = NodeViewScreenToCanvas(float3x2::Scale(0.5f), canvas, { 550, 300 }); + const float2 zoomed = nodes::NodeViewScreenToCanvas(float3x2::Scale(0.5f), canvas, { 550, 300 }); EXPECT_FLOAT_EQ(zoomed.x, 100.0f); EXPECT_FLOAT_EQ(zoomed.y, -100.0f); } diff --git a/tests/node_view_edit_test.cpp b/tests/node_view_edit_test.cpp index d2fd4d4b..a00f0561 100644 --- a/tests/node_view_edit_test.cpp +++ b/tests/node_view_edit_test.cpp @@ -1,9 +1,10 @@ // Node-view edits as values a host can undo and redo: what the view changes is built -// as a NodeViewEdit, applied with ApplyNodeViewEdit and reported to NodeGraph::onEdit. +// as a nodes::NodeViewEdit, applied with ApplyNodeViewEdit and reported to nodes::NodeGraph::onEdit. #include -#include +#include +#include #include #include @@ -13,20 +14,20 @@ namespace using namespace tachyon; // Node 0: one output. Node 1: two inputs, the first wired to node 0's output. - NodeView MakeView() + nodes::NodeView MakeView() { - NodeView view; + nodes::NodeView view; view.nodes.resize(2); view.nodes[0].properties.resize(1); view.nodes[0].properties[0].output = true; view.nodes[1].properties.resize(2); - view.nodes[1].properties[0].input = PropertyEndpoint{ 0, 0 }; - view.nodes[1].properties[1].input = PropertyEndpoint{}; + view.nodes[1].properties[0].input = nodes::PropertyEndpoint{ 0, 0 }; + view.nodes[1].properties[1].input = nodes::PropertyEndpoint{}; view.nodes[1].pos = { 300, 40 }; return view; } - PropertyEndpoint SourceOf(const NodeView& view, int node, int prop) + nodes::PropertyEndpoint SourceOf(const nodes::NodeView& view, int node, int prop) { return *view.nodes[size_t(node)].properties[size_t(prop)].input; } @@ -35,150 +36,150 @@ namespace // on both sides of 0. TEST(NodeViewGrid, GridLinesAroundAValue) { - EXPECT_EQ(GridLineLE(25, 0, 10), 20); - EXPECT_EQ(GridLineGE(25, 0, 10), 30); - EXPECT_EQ(GridLineLE(20, 0, 10), 20) << "on a line"; - EXPECT_EQ(GridLineGE(20, 0, 10), 20); - - EXPECT_EQ(GridLineLE(-5, 0, 10), -10) << "below 0 it still goes down"; - EXPECT_EQ(GridLineGE(-5, 0, 10), 0); - EXPECT_EQ(GridLineLE(-10, 0, 10), -10); - - EXPECT_EQ(GridLineLE(25, 3, 10), 23) << "lines at 3 + 10k"; - EXPECT_EQ(GridLineGE(25, 3, 10), 33); - - EXPECT_EQ(GridLineNearest(24, 0, 10), 20); - EXPECT_EQ(GridLineNearest(26, 0, 10), 30); - EXPECT_EQ(GridLineNearest(25, 0, 10), 20) << "a tie goes down"; - EXPECT_EQ(GridLineNearest(-6, 0, 10), -10); - EXPECT_EQ(GridLineNearest(-5, 0, 10), -10) << "a tie goes down below 0 too"; + EXPECT_EQ(nodes::GridLineLE(25, 0, 10), 20); + EXPECT_EQ(nodes::GridLineGE(25, 0, 10), 30); + EXPECT_EQ(nodes::GridLineLE(20, 0, 10), 20) << "on a line"; + EXPECT_EQ(nodes::GridLineGE(20, 0, 10), 20); + + EXPECT_EQ(nodes::GridLineLE(-5, 0, 10), -10) << "below 0 it still goes down"; + EXPECT_EQ(nodes::GridLineGE(-5, 0, 10), 0); + EXPECT_EQ(nodes::GridLineLE(-10, 0, 10), -10); + + EXPECT_EQ(nodes::GridLineLE(25, 3, 10), 23) << "lines at 3 + 10k"; + EXPECT_EQ(nodes::GridLineGE(25, 3, 10), 33); + + EXPECT_EQ(nodes::GridLineNearest(24, 0, 10), 20); + EXPECT_EQ(nodes::GridLineNearest(26, 0, 10), 30); + EXPECT_EQ(nodes::GridLineNearest(25, 0, 10), 20) << "a tie goes down"; + EXPECT_EQ(nodes::GridLineNearest(-6, 0, 10), -10); + EXPECT_EQ(nodes::GridLineNearest(-5, 0, 10), -10) << "a tie goes down below 0 too"; } TEST(NodeViewEdit, UndoAndRedoAMove) { - NodeView view = MakeView(); - NodeViewEdit edit; + nodes::NodeView view = MakeView(); + nodes::NodeViewEdit edit; edit.moves.push_back({ 1, { 300, 40 }, { 420, 80 } }); - ApplyNodeViewEdit(view, edit); + nodes::ApplyNodeViewEdit(view, edit); EXPECT_EQ(view.nodes[1].pos.x, 420); - ApplyNodeViewEdit(view, edit, /*undo*/ true); + nodes::ApplyNodeViewEdit(view, edit, /*undo*/ true); EXPECT_EQ(view.nodes[1].pos.x, 300); EXPECT_EQ(view.nodes[1].pos.y, 40); } TEST(NodeViewEdit, UndoAndRedoACollapse) { - NodeView view = MakeView(); - NodeViewEdit edit; + nodes::NodeView view = MakeView(); + nodes::NodeViewEdit edit; edit.collapses.push_back({ 1, false, true }); - ApplyNodeViewEdit(view, edit); + nodes::ApplyNodeViewEdit(view, edit); EXPECT_TRUE(view.nodes[1].collapsed); - ApplyNodeViewEdit(view, edit, true); + nodes::ApplyNodeViewEdit(view, edit, true); EXPECT_FALSE(view.nodes[1].collapsed); } TEST(NodeViewEdit, AConnectRemembersTheInputsOldSource) { - NodeView view = MakeView(); + nodes::NodeView view = MakeView(); view.nodes.resize(3); view.nodes[2].properties.resize(1); view.nodes[2].properties[0].output = true; - const NodeViewEdit edit = ConnectEdit(view, { 2, 0 }, { 1, 0 }); - ApplyNodeViewEdit(view, edit); - EXPECT_EQ(SourceOf(view, 1, 0), (PropertyEndpoint{ 2, 0 })); - ApplyNodeViewEdit(view, edit, true); - EXPECT_EQ(SourceOf(view, 1, 0), (PropertyEndpoint{ 0, 0 })); + const nodes::NodeViewEdit edit = nodes::ConnectEdit(view, { 2, 0 }, { 1, 0 }); + nodes::ApplyNodeViewEdit(view, edit); + EXPECT_EQ(SourceOf(view, 1, 0), (nodes::PropertyEndpoint{ 2, 0 })); + nodes::ApplyNodeViewEdit(view, edit, true); + EXPECT_EQ(SourceOf(view, 1, 0), (nodes::PropertyEndpoint{ 0, 0 })); } TEST(NodeViewEdit, ConnectingWhatIsConnectedIsNoEdit) { - const NodeView view = MakeView(); - EXPECT_TRUE(ConnectEdit(view, { 0, 0 }, { 1, 0 }).empty()); - EXPECT_TRUE(ConnectEdit(view, { 0, 0 }, { 0, 0 }).empty()) << "not an input"; + const nodes::NodeView view = MakeView(); + EXPECT_TRUE(nodes::ConnectEdit(view, { 0, 0 }, { 1, 0 }).empty()); + EXPECT_TRUE(nodes::ConnectEdit(view, { 0, 0 }, { 0, 0 }).empty()) << "not an input"; } TEST(NodeViewEdit, UndoingADisconnectBringsBackTheWireAndItsLanes) { - NodeView view = MakeView(); - view.wireOverrides[WireKey(1, 0)].laneX = 160; + nodes::NodeView view = MakeView(); + view.wireOverrides[nodes::WireKey(1, 0)].laneX = 160; - const NodeViewEdit edit = DisconnectEdit(view, { 1, 0 }); - ApplyNodeViewEdit(view, edit); + const nodes::NodeViewEdit edit = nodes::DisconnectEdit(view, { 1, 0 }); + nodes::ApplyNodeViewEdit(view, edit); EXPECT_FALSE(SourceOf(view, 1, 0).valid()); - EXPECT_EQ(view.wireOverrides.count(WireKey(1, 0)), 0u); + EXPECT_EQ(view.wireOverrides.count(nodes::WireKey(1, 0)), 0u); - ApplyNodeViewEdit(view, edit, true); - EXPECT_EQ(SourceOf(view, 1, 0), (PropertyEndpoint{ 0, 0 })); - ASSERT_EQ(view.wireOverrides.count(WireKey(1, 0)), 1u); - EXPECT_EQ(view.wireOverrides[WireKey(1, 0)].laneX, 160); + nodes::ApplyNodeViewEdit(view, edit, true); + EXPECT_EQ(SourceOf(view, 1, 0), (nodes::PropertyEndpoint{ 0, 0 })); + ASSERT_EQ(view.wireOverrides.count(nodes::WireKey(1, 0)), 1u); + EXPECT_EQ(view.wireOverrides[nodes::WireKey(1, 0)].laneX, 160); } // Pulling a wire off one input and dropping it on another is one edit: a detach and // a connect, undone in reverse order. TEST(NodeViewEdit, AMovedWireUndoesInOneStep) { - NodeView view = MakeView(); - NodeViewEdit edit; + nodes::NodeView view = MakeView(); + nodes::NodeViewEdit edit; edit.rewires.push_back({ { 1, 0 }, { 0, 0 }, {} }); edit.rewires.push_back({ { 1, 1 }, {}, { 0, 0 } }); - ApplyNodeViewEdit(view, edit); + nodes::ApplyNodeViewEdit(view, edit); EXPECT_FALSE(SourceOf(view, 1, 0).valid()); - EXPECT_EQ(SourceOf(view, 1, 1), (PropertyEndpoint{ 0, 0 })); + EXPECT_EQ(SourceOf(view, 1, 1), (nodes::PropertyEndpoint{ 0, 0 })); - ApplyNodeViewEdit(view, edit, true); - EXPECT_EQ(SourceOf(view, 1, 0), (PropertyEndpoint{ 0, 0 })); + nodes::ApplyNodeViewEdit(view, edit, true); + EXPECT_EQ(SourceOf(view, 1, 0), (nodes::PropertyEndpoint{ 0, 0 })); EXPECT_FALSE(SourceOf(view, 1, 1).valid()); } TEST(NodeViewEdit, LaneEditsRestoreNoOverridesAsNone) { - NodeView view = MakeView(); - NodeViewEdit edit; - WireRouteOverrides moved; + nodes::NodeView view = MakeView(); + nodes::NodeViewEdit edit; + nodes::WireRouteOverrides moved; moved.laneX = 200; - edit.lanes.push_back({ WireKey(1, 0), {}, moved }); - ApplyNodeViewEdit(view, edit); - EXPECT_EQ(view.wireOverrides[WireKey(1, 0)].laneX, 200); - ApplyNodeViewEdit(view, edit, true); - EXPECT_EQ(view.wireOverrides.count(WireKey(1, 0)), 0u); + edit.lanes.push_back({ nodes::WireKey(1, 0), {}, moved }); + nodes::ApplyNodeViewEdit(view, edit); + EXPECT_EQ(view.wireOverrides[nodes::WireKey(1, 0)].laneX, 200); + nodes::ApplyNodeViewEdit(view, edit, true); + EXPECT_EQ(view.wireOverrides.count(nodes::WireKey(1, 0)), 0u); } // ---- Adding and removing nodes ---- // 0 Src: out. 1 Mid: in (from Src), out. 2 Out: in (from Mid), in (from Src), out. // 3 Extra: in (from Out). Lanes on three wires; all four selected, Mid clicked last. - NodeView MakeGraph() + nodes::NodeView MakeGraph() { - NodeView view; + nodes::NodeView view; view.nodes.resize(4); for (int n = 0; n < 4; ++n) view.nodes[size_t(n)].stableID = ID{ uint64_t(n + 1) }; view.nodes[0].properties.resize(1); view.nodes[0].properties[0].output = true; view.nodes[1].properties.resize(2); - view.nodes[1].properties[0].input = PropertyEndpoint{ 0, 0 }; + view.nodes[1].properties[0].input = nodes::PropertyEndpoint{ 0, 0 }; view.nodes[1].properties[1].output = true; view.nodes[2].properties.resize(3); - view.nodes[2].properties[0].input = PropertyEndpoint{ 1, 1 }; - view.nodes[2].properties[1].input = PropertyEndpoint{ 0, 0 }; + view.nodes[2].properties[0].input = nodes::PropertyEndpoint{ 1, 1 }; + view.nodes[2].properties[1].input = nodes::PropertyEndpoint{ 0, 0 }; view.nodes[2].properties[2].output = true; view.nodes[3].properties.resize(1); - view.nodes[3].properties[0].input = PropertyEndpoint{ 2, 2 }; - view.wireOverrides[WireKey(1, 0)].laneX = 50; - view.wireOverrides[WireKey(2, 0)].laneX = 100; - view.wireOverrides[WireKey(3, 0)].laneX = 200; + view.nodes[3].properties[0].input = nodes::PropertyEndpoint{ 2, 2 }; + view.wireOverrides[nodes::WireKey(1, 0)].laneX = 50; + view.wireOverrides[nodes::WireKey(2, 0)].laneX = 100; + view.wireOverrides[nodes::WireKey(3, 0)].laneX = 200; view.ordering = { 0, 1, 2, 3 }; - for (const NodeModel& node : view.nodes) view.selectedNodeIDs.insert(node.stableID); + for (const nodes::NodeModel& node : view.nodes) view.selectedNodeIDs.insert(node.stableID); view.lastClickedNodeID = view.nodes[1].stableID; return view; } // Each node's inputs' sources, in order: what the wires are. - std::vector Wires(const NodeView& view) + std::vector Wires(const nodes::NodeView& view) { - std::vector out; - for (const NodeModel& node : view.nodes) - for (const NodeProperty& prop : node.properties) + std::vector out; + for (const nodes::NodeModel& node : view.nodes) + for (const nodes::NodeProperty& prop : node.properties) if (prop.input) out.push_back(*prop.input); return out; } @@ -187,31 +188,31 @@ namespace TEST(NodeViewEdit, RemovingANodeTakesItsWiresAndMovesTheRestDown) { - NodeView view = MakeGraph(); - const NodeView before = view; + nodes::NodeView view = MakeGraph(); + const nodes::NodeView before = view; const int mid[] = { 1 }; - const NodeViewEdit edit = RemoveNodesEdit(view, mid); + const nodes::NodeViewEdit edit = nodes::RemoveNodesEdit(view, mid); ASSERT_EQ(edit.nodes.size(), 1u); - view.hoveredWire.part = WireKey(3, 0); - view.wireMenuWire = WireKey(3, 0); - view.wireHandleCache.push_back(CachedWireHandle{ .wireKey = WireKey(3, 0) }); - ApplyNodeViewEdit(view, edit); + view.hoveredWire.part = nodes::WireKey(3, 0); + view.wireMenuWire = nodes::WireKey(3, 0); + view.wireHandleCache.push_back(nodes::CachedWireHandle{ .wireKey = nodes::WireKey(3, 0) }); + nodes::ApplyNodeViewEdit(view, edit); EXPECT_FALSE(view.hoveredWire.part) << "they named wires by the old numbers"; EXPECT_FALSE(view.wireMenuWire); EXPECT_TRUE(view.wireHandleCache.empty()); ASSERT_EQ(view.nodes.size(), 3u); EXPECT_EQ(view.nodes[1].stableID, before.nodes[2].stableID); - EXPECT_EQ(Wires(view), (std::vector{ {}, { 0, 0 }, { 1, 2 } })) + EXPECT_EQ(Wires(view), (std::vector{ {}, { 0, 0 }, { 1, 2 } })) << "Out loses Mid's wire, keeps Src's; Extra's now comes from node 1"; EXPECT_EQ(view.wireOverrides.size(), 1u) << "the lanes of Mid's wires go"; - EXPECT_EQ(view.wireOverrides[WireKey(2, 0)].laneX, 200) << "Extra's moved with it"; + EXPECT_EQ(view.wireOverrides[nodes::WireKey(2, 0)].laneX, 200) << "Extra's moved with it"; EXPECT_EQ(Sorted(view.ordering), (std::vector{ 0, 1, 2 })); EXPECT_EQ(view.selectedNodeIDs.count(before.nodes[1].stableID), 0u); EXPECT_EQ(view.selectedNodeIDs.size(), 3u); EXPECT_EQ(view.lastClickedNodeID, ID::Invalid()); - ApplyNodeViewEdit(view, edit, /*undo*/ true); + nodes::ApplyNodeViewEdit(view, edit, /*undo*/ true); ASSERT_EQ(view.nodes.size(), 4u); for (size_t n = 0; n < 4; ++n) EXPECT_EQ(view.nodes[n].stableID, before.nodes[n].stableID) << n; @@ -220,28 +221,28 @@ namespace EXPECT_EQ(Sorted(view.ordering), (std::vector{ 0, 1, 2, 3 })); EXPECT_EQ(view.ordering.back(), 1) << "back in front"; - ApplyNodeViewEdit(view, edit); // redo - EXPECT_EQ(Wires(view), (std::vector{ {}, { 0, 0 }, { 1, 2 } })); + nodes::ApplyNodeViewEdit(view, edit); // redo + EXPECT_EQ(Wires(view), (std::vector{ {}, { 0, 0 }, { 1, 2 } })); } // Several at once, in any order, repeats and strays skipped; the wires between them come // back too. TEST(NodeViewEdit, RemovingSeveralNodesAndPuttingThemBack) { - NodeView view = MakeGraph(); - const NodeView before = view; + nodes::NodeView view = MakeGraph(); + const nodes::NodeView before = view; const int some[] = { 0, 2, 2, 9, -1 }; - const NodeViewEdit edit = RemoveNodesEdit(view, some); + const nodes::NodeViewEdit edit = nodes::RemoveNodesEdit(view, some); ASSERT_EQ(edit.nodes.size(), 2u); - ApplyNodeViewEdit(view, edit); + nodes::ApplyNodeViewEdit(view, edit); ASSERT_EQ(view.nodes.size(), 2u); EXPECT_EQ(view.nodes[0].stableID, before.nodes[1].stableID); EXPECT_EQ(view.nodes[1].stableID, before.nodes[3].stableID); - EXPECT_EQ(Wires(view), (std::vector{ {}, {} })); + EXPECT_EQ(Wires(view), (std::vector{ {}, {} })); EXPECT_TRUE(view.wireOverrides.empty()); EXPECT_EQ(Sorted(view.ordering), (std::vector{ 0, 1 })); - ApplyNodeViewEdit(view, edit, true); + nodes::ApplyNodeViewEdit(view, edit, true); ASSERT_EQ(view.nodes.size(), 4u); for (size_t n = 0; n < 4; ++n) EXPECT_EQ(view.nodes[n].stableID, before.nodes[n].stableID) << n; @@ -252,25 +253,25 @@ namespace // A node added in the middle moves the ones after it up, wires and all. TEST(NodeViewEdit, AddingANodeMovesTheRestUp) { - NodeView view = MakeGraph(); - const NodeView before = view; - NodeModel added; + nodes::NodeView view = MakeGraph(); + const nodes::NodeView before = view; + nodes::NodeModel added; added.stableID = ID{ 9 }; added.properties.resize(1); - added.properties[0].input = PropertyEndpoint{ 0, 0 }; // as numbered once it's in - const NodeViewEdit edit = AddNodeEdit(view, added, 1); - ApplyNodeViewEdit(view, edit); + added.properties[0].input = nodes::PropertyEndpoint{ 0, 0 }; // as numbered once it's in + const nodes::NodeViewEdit edit = nodes::AddNodeEdit(view, added, 1); + nodes::ApplyNodeViewEdit(view, edit); ASSERT_EQ(view.nodes.size(), 5u); EXPECT_EQ(view.nodes[1].stableID, added.stableID); - EXPECT_EQ(Wires(view), (std::vector{ { 0, 0 }, { 0, 0 }, { 2, 1 }, { 0, 0 }, { 3, 2 } })); - EXPECT_EQ(view.wireOverrides[WireKey(2, 0)].laneX, 50); - EXPECT_EQ(view.wireOverrides[WireKey(3, 0)].laneX, 100); - EXPECT_EQ(view.wireOverrides[WireKey(4, 0)].laneX, 200); - EXPECT_EQ(view.wireOverrides.count(WireKey(1, 0)), 0u); + EXPECT_EQ(Wires(view), (std::vector{ { 0, 0 }, { 0, 0 }, { 2, 1 }, { 0, 0 }, { 3, 2 } })); + EXPECT_EQ(view.wireOverrides[nodes::WireKey(2, 0)].laneX, 50); + EXPECT_EQ(view.wireOverrides[nodes::WireKey(3, 0)].laneX, 100); + EXPECT_EQ(view.wireOverrides[nodes::WireKey(4, 0)].laneX, 200); + EXPECT_EQ(view.wireOverrides.count(nodes::WireKey(1, 0)), 0u); EXPECT_EQ(view.ordering, (std::vector{ 0, 2, 3, 4, 1 })) << "the new one in front"; - ApplyNodeViewEdit(view, edit, true); + nodes::ApplyNodeViewEdit(view, edit, true); EXPECT_EQ(view.nodes.size(), 4u); EXPECT_EQ(Wires(view), Wires(before)); EXPECT_EQ(view.wireOverrides, before.wireOverrides); @@ -280,20 +281,20 @@ namespace // At -1 or past the end it goes last; with a rewire into it, wired in the same step. TEST(NodeViewEdit, AddingANodeLastAndWiringIt) { - NodeView view = MakeGraph(); - NodeModel added; + nodes::NodeView view = MakeGraph(); + nodes::NodeModel added; added.properties.resize(1); - added.properties[0].input = PropertyEndpoint{}; - EXPECT_EQ(AddNodeEdit(view, added, 99).nodes[0].index, 4); - EXPECT_EQ(AddNodeEdit(view, added, 4).nodes[0].index, 4); - NodeViewEdit edit = AddNodeEdit(view, added); + added.properties[0].input = nodes::PropertyEndpoint{}; + EXPECT_EQ(nodes::AddNodeEdit(view, added, 99).nodes[0].index, 4); + EXPECT_EQ(nodes::AddNodeEdit(view, added, 4).nodes[0].index, 4); + nodes::NodeViewEdit edit = nodes::AddNodeEdit(view, added); ASSERT_EQ(edit.nodes.size(), 1u); EXPECT_EQ(edit.nodes[0].index, 4); EXPECT_TRUE(edit.nodes[0].added); edit.rewires.push_back({ .input = { 4, 0 }, .from = {}, .to = { 2, 2 } }); - ApplyNodeViewEdit(view, edit); - EXPECT_EQ(*view.nodes[4].properties[0].input, (PropertyEndpoint{ 2, 2 })); - ApplyNodeViewEdit(view, edit, true); + nodes::ApplyNodeViewEdit(view, edit); + EXPECT_EQ(*view.nodes[4].properties[0].input, (nodes::PropertyEndpoint{ 2, 2 })); + nodes::ApplyNodeViewEdit(view, edit, true); EXPECT_EQ(view.nodes.size(), 4u); EXPECT_EQ(Wires(view), Wires(MakeGraph())); } @@ -301,47 +302,47 @@ namespace // A reroute on a wire: the wire runs into it and on out of it; undone, as it was. TEST(NodeViewEdit, ARerouteOnAWire) { - NodeView view = MakeGraph(); - const NodeView before = view; + nodes::NodeView view = MakeGraph(); + const nodes::NodeView before = view; view.nodes[1].properties[1].socketColor = { 0.2f, 0.4f, 0.6f, 1.0f }; - const NodeViewEdit edit = RerouteWireEdit(view, WireKey(2, 0), ID{ 42 }, { 240, 96 }); + const nodes::NodeViewEdit edit = nodes::RerouteWireEdit(view, nodes::WireKey(2, 0), ID{ 42 }, { 240, 96 }); ASSERT_EQ(edit.nodes.size(), 1u); - ApplyNodeViewEdit(view, edit); + nodes::ApplyNodeViewEdit(view, edit); ASSERT_EQ(view.nodes.size(), 5u); - const NodeModel& reroute = view.nodes[4]; + const nodes::NodeModel& reroute = view.nodes[4]; EXPECT_TRUE(reroute.reroute); EXPECT_EQ(reroute.stableID, ID{ 42 }); EXPECT_EQ(reroute.pos, (int2{ 240, 96 })); ASSERT_EQ(reroute.properties.size(), 1u); - EXPECT_EQ(*reroute.properties[0].input, (PropertyEndpoint{ 1, 1 })) << "from the wire's output"; + EXPECT_EQ(*reroute.properties[0].input, (nodes::PropertyEndpoint{ 1, 1 })) << "from the wire's output"; EXPECT_TRUE(reroute.properties[0].output); EXPECT_EQ(reroute.properties[0].socketColor.b, 0.6f) << "in its color"; - EXPECT_EQ(*view.nodes[2].properties[0].input, (PropertyEndpoint{ 4, 0 })) << "on to the input"; - EXPECT_EQ(view.wireOverrides.count(WireKey(2, 0)), 0u) << "its lanes go"; + EXPECT_EQ(*view.nodes[2].properties[0].input, (nodes::PropertyEndpoint{ 4, 0 })) << "on to the input"; + EXPECT_EQ(view.wireOverrides.count(nodes::WireKey(2, 0)), 0u) << "its lanes go"; EXPECT_EQ(view.wireOverrides.size(), before.wireOverrides.size() - 1); - ApplyNodeViewEdit(view, edit, true); + nodes::ApplyNodeViewEdit(view, edit, true); EXPECT_EQ(view.nodes.size(), 4u); EXPECT_EQ(Wires(view), Wires(before)); EXPECT_EQ(view.wireOverrides, before.wireOverrides); // A wire without lanes: no lane change. - EXPECT_TRUE(RerouteWireEdit(view, WireKey(2, 1), ID{ 43 }, {}).lanes.empty()); + EXPECT_TRUE(nodes::RerouteWireEdit(view, nodes::WireKey(2, 1), ID{ 43 }, {}).lanes.empty()); } TEST(NodeViewEdit, NoRerouteWhereThereIsNoWire) { - NodeView view = MakeGraph(); - view.nodes[3].properties[0].input = PropertyEndpoint{}; - EXPECT_TRUE(RerouteWireEdit(view, WireKey(3, 0), ID{ 1 }, {}).empty()) << "an unwired input"; - EXPECT_TRUE(RerouteWireEdit(view, WireKey(0, 0), ID{ 1 }, {}).empty()) << "not an input"; - EXPECT_TRUE(RerouteWireEdit(view, WireKey(9, 0), ID{ 1 }, {}).empty()) << "no such node"; - EXPECT_TRUE(RerouteWireEdit(view, WireKey(2, 7), ID{ 1 }, {}).empty()) << "no such row"; - view.nodes[2].properties[0].input = PropertyEndpoint{ 9, 0 }; - EXPECT_TRUE(RerouteWireEdit(view, WireKey(2, 0), ID{ 1 }, {}).empty()) << "a source that isn't there"; - view.nodes[2].properties[0].input = PropertyEndpoint{ 1, 5 }; - EXPECT_TRUE(RerouteWireEdit(view, WireKey(2, 0), ID{ 1 }, {}).empty()) << "a source row that isn't there"; + nodes::NodeView view = MakeGraph(); + view.nodes[3].properties[0].input = nodes::PropertyEndpoint{}; + EXPECT_TRUE(nodes::RerouteWireEdit(view, nodes::WireKey(3, 0), ID{ 1 }, {}).empty()) << "an unwired input"; + EXPECT_TRUE(nodes::RerouteWireEdit(view, nodes::WireKey(0, 0), ID{ 1 }, {}).empty()) << "not an input"; + EXPECT_TRUE(nodes::RerouteWireEdit(view, nodes::WireKey(9, 0), ID{ 1 }, {}).empty()) << "no such node"; + EXPECT_TRUE(nodes::RerouteWireEdit(view, nodes::WireKey(2, 7), ID{ 1 }, {}).empty()) << "no such row"; + view.nodes[2].properties[0].input = nodes::PropertyEndpoint{ 9, 0 }; + EXPECT_TRUE(nodes::RerouteWireEdit(view, nodes::WireKey(2, 0), ID{ 1 }, {}).empty()) << "a source that isn't there"; + view.nodes[2].properties[0].input = nodes::PropertyEndpoint{ 1, 5 }; + EXPECT_TRUE(nodes::RerouteWireEdit(view, nodes::WireKey(2, 0), ID{ 1 }, {}).empty()) << "a source row that isn't there"; } // A reroute taken out: what it fed takes from what fed it, the nodes after it move down; @@ -349,83 +350,83 @@ namespace TEST(NodeViewEdit, RemovingARerouteKeepsItsWireRunning) { // 0 Src: out. 1 R (reroute): in from Src, out. 2 A: in from R. 3 B: in from R. - NodeView view; + nodes::NodeView view; view.nodes.resize(4); view.nodes[0].properties.resize(1); view.nodes[0].properties[0].output = true; view.nodes[1].reroute = true; - view.nodes[1].properties.push_back(NodeProperty{ .input = PropertyEndpoint{ 0, 0 }, .output = true }); - view.nodes[2].properties.push_back(NodeProperty{ .input = PropertyEndpoint{ 1, 0 } }); - view.nodes[3].properties.push_back(NodeProperty{ .input = PropertyEndpoint{ 1, 0 } }); - view.wireOverrides[WireKey(2, 0)].laneX = 80; + view.nodes[1].properties.push_back(nodes::NodeProperty{ .input = nodes::PropertyEndpoint{ 0, 0 }, .output = true }); + view.nodes[2].properties.push_back(nodes::NodeProperty{ .input = nodes::PropertyEndpoint{ 1, 0 } }); + view.nodes[3].properties.push_back(nodes::NodeProperty{ .input = nodes::PropertyEndpoint{ 1, 0 } }); + view.wireOverrides[nodes::WireKey(2, 0)].laneX = 80; view.ordering = { 0, 1, 2, 3 }; - const NodeView before = view; + const nodes::NodeView before = view; - const NodeViewEdit edit = RemoveRerouteEdit(view, 1); - ApplyNodeViewEdit(view, edit); + const nodes::NodeViewEdit edit = nodes::RemoveRerouteEdit(view, 1); + nodes::ApplyNodeViewEdit(view, edit); ASSERT_EQ(view.nodes.size(), 3u); - EXPECT_EQ(Wires(view), (std::vector{ { 0, 0 }, { 0, 0 } })) << "A and B take from Src"; + EXPECT_EQ(Wires(view), (std::vector{ { 0, 0 }, { 0, 0 } })) << "A and B take from Src"; EXPECT_TRUE(view.wireOverrides.empty()) << "its wires' lanes go"; - ApplyNodeViewEdit(view, edit, true); + nodes::ApplyNodeViewEdit(view, edit, true); ASSERT_EQ(view.nodes.size(), 4u); EXPECT_TRUE(view.nodes[1].reroute); EXPECT_EQ(Wires(view), Wires(before)); EXPECT_EQ(view.wireOverrides, before.wireOverrides); // Fed from a node after it: that one moves down too. - NodeView later = before; - later.nodes[1].properties[0].input = PropertyEndpoint{ 3, 1 }; - later.nodes[3].properties.push_back(NodeProperty{ .output = true }); - later.nodes[3].properties[0].input = PropertyEndpoint{}; - ApplyNodeViewEdit(later, RemoveRerouteEdit(later, 1)); - EXPECT_EQ(Wires(later), (std::vector{ { 2, 1 }, {} })) << "A takes from B, now node 2"; + nodes::NodeView later = before; + later.nodes[1].properties[0].input = nodes::PropertyEndpoint{ 3, 1 }; + later.nodes[3].properties.push_back(nodes::NodeProperty{ .output = true }); + later.nodes[3].properties[0].input = nodes::PropertyEndpoint{}; + nodes::ApplyNodeViewEdit(later, nodes::RemoveRerouteEdit(later, 1)); + EXPECT_EQ(Wires(later), (std::vector{ { 2, 1 }, {} })) << "A takes from B, now node 2"; } TEST(NodeViewEdit, RemovingARerouteThatNothingFeeds) { - NodeView view; + nodes::NodeView view; view.nodes.resize(2); view.nodes[0].reroute = true; - view.nodes[0].properties.push_back(NodeProperty{ .input = PropertyEndpoint{}, .output = true }); - view.nodes[1].properties.push_back(NodeProperty{ .input = PropertyEndpoint{ 0, 0 } }); - const NodeViewEdit edit = RemoveRerouteEdit(view, 0); + view.nodes[0].properties.push_back(nodes::NodeProperty{ .input = nodes::PropertyEndpoint{}, .output = true }); + view.nodes[1].properties.push_back(nodes::NodeProperty{ .input = nodes::PropertyEndpoint{ 0, 0 } }); + const nodes::NodeViewEdit edit = nodes::RemoveRerouteEdit(view, 0); EXPECT_TRUE(edit.rewires.empty()); - ApplyNodeViewEdit(view, edit); + nodes::ApplyNodeViewEdit(view, edit); ASSERT_EQ(view.nodes.size(), 1u); EXPECT_FALSE(view.nodes[0].properties[0].input->valid()) << "what it fed is unwired"; - NodeView none; + nodes::NodeView none; none.nodes.resize(1); - EXPECT_TRUE(RemoveRerouteEdit(none, 0).empty()) << "not a reroute"; - EXPECT_TRUE(RemoveRerouteEdit(none, 1).empty()); - EXPECT_TRUE(RemoveRerouteEdit(none, -1).empty()); + EXPECT_TRUE(nodes::RemoveRerouteEdit(none, 0).empty()) << "not a reroute"; + EXPECT_TRUE(nodes::RemoveRerouteEdit(none, 1).empty()); + EXPECT_TRUE(nodes::RemoveRerouteEdit(none, -1).empty()); none.nodes[0].reroute = true; - EXPECT_FALSE(RemoveRerouteEdit(none, 0).empty()) << "a reroute without rows still goes"; + EXPECT_FALSE(nodes::RemoveRerouteEdit(none, 0).empty()) << "a reroute without rows still goes"; } TEST(NodeViewEdit, RemovingNothingIsNoEdit) { - const NodeView view = MakeGraph(); + const nodes::NodeView view = MakeGraph(); const int none[] = { 4, -1 }; - EXPECT_TRUE(RemoveNodesEdit(view, none).empty()); - EXPECT_TRUE(RemoveNodesEdit(view, {}).empty()); - EXPECT_FALSE(AddNodeEdit(view, NodeModel{}).empty()); + EXPECT_TRUE(nodes::RemoveNodesEdit(view, none).empty()); + EXPECT_TRUE(nodes::RemoveNodesEdit(view, {}).empty()); + EXPECT_FALSE(nodes::AddNodeEdit(view, nodes::NodeModel{}).empty()); } TEST(NodeViewEdit, CommitAppliesAndReportsOnce) { - NodeView view = MakeView(); - std::vector reported; - view.onEdit = [&](const NodeViewEdit& e) { reported.push_back(e); }; + nodes::NodeView view = MakeView(); + std::vector reported; + view.onEdit = [&](const nodes::NodeViewEdit& e) { reported.push_back(e); }; - CommitNodeViewEdit(view, DisconnectEdit(view, { 1, 0 })); + nodes::CommitNodeViewEdit(view, nodes::DisconnectEdit(view, { 1, 0 })); EXPECT_FALSE(SourceOf(view, 1, 0).valid()); ASSERT_EQ(reported.size(), 1u); ASSERT_EQ(reported[0].rewires.size(), 1u); - EXPECT_EQ(reported[0].rewires[0].from, (PropertyEndpoint{ 0, 0 })); + EXPECT_EQ(reported[0].rewires[0].from, (nodes::PropertyEndpoint{ 0, 0 })); - CommitNodeViewEdit(view, NodeViewEdit{}); + nodes::CommitNodeViewEdit(view, nodes::NodeViewEdit{}); EXPECT_EQ(reported.size(), 1u) << "an empty edit isn't reported"; } } diff --git a/tests/node_view_frame_test.cpp b/tests/node_view_frame_test.cpp index f4d005d1..77d89aaa 100644 --- a/tests/node_view_frame_test.cpp +++ b/tests/node_view_frame_test.cpp @@ -10,7 +10,8 @@ #include #include -#include +#include +#include #include #include @@ -27,38 +28,39 @@ namespace tachyon { protected: HeadlessGUIApp app; - NodeView view; + nodes::Context nodesContext; + nodes::NodeView view; int32_t g = 0; // the grid ID nodeA{}, nodeB{}, frameOuter{}, frameInner{}; void SetUp() override { ASSERT_TRUE(app.Initialize()); - g = app.theme.nodeGridSize; + g = nodes::GetStyles(app, nodesContext).nodeGridSize; ASSERT_GT(g, 1); nodeA = app.idManager.CreateStaticID(); nodeB = app.idManager.CreateStaticID(); frameOuter = app.idManager.CreateStaticID(); frameInner = app.idManager.CreateStaticID(); - NodeModel a{}; + nodes::NodeModel a{}; a.stableID = nodeA; a.title = "A"; a.pos = { 8 * g, 7 * g }; - a.properties.push_back(NodeProperty{ .output = true }); - NodeModel b{}; + a.properties.push_back(nodes::NodeProperty{ .output = true }); + nodes::NodeModel b{}; b.stableID = nodeB; b.title = "B"; b.pos = { 60 * g, 30 * g }; - b.properties.push_back(NodeProperty{ .input = PropertyEndpoint{} }); + b.properties.push_back(nodes::NodeProperty{ .input = nodes::PropertyEndpoint{} }); view = {}; view.transform = float3x2::Scale(1.0f); view.nodes = { std::move(a), std::move(b) }; // The outer frame holds A and the inner frame; B is out of both. view.frames = { - NodeFrame{ .stableID = frameOuter, .title = "Lighting", .pos = { 4 * g, 2 * g }, .size = { 40 * g, 22 * g } }, - NodeFrame{ .stableID = frameInner, .title = "Notes", .color = { 0.3f, 0.8f, 0.7f, 1.0f }, + nodes::NodeFrame{ .stableID = frameOuter, .title = "Lighting", .pos = { 4 * g, 2 * g }, .size = { 40 * g, 22 * g } }, + nodes::NodeFrame{ .stableID = frameInner, .title = "Notes", .color = { 0.3f, 0.8f, 0.7f, 1.0f }, .pos = { 26 * g, 12 * g }, .size = { 12 * g, 8 * g } }, }; } @@ -70,16 +72,16 @@ namespace tachyon { view = {}; view.transform = float3x2::Scale(1.0f); - NodeFrame frame{ .stableID = frameOuter, .title = "Held", .pos = { 0, 0 }, .size = { 40 * g, 40 * g }, .collapsed = true }; + nodes::NodeFrame frame{ .stableID = frameOuter, .title = "Held", .pos = { 0, 0 }, .size = { 40 * g, 40 * g }, .collapsed = true }; frame.members.emplace(); for (int n = 0; n < count; ++n) { - NodeModel node{}; + nodes::NodeModel node{}; node.stableID = app.idManager.CreateStaticID(); node.title = "N"; node.pos = { (n % 10) * 20 * g, (n / 10) * 12 * g }; - node.properties.push_back(NodeProperty{ .input = n > 0 ? std::optional(PropertyEndpoint{ n - 1, 1 }) : std::nullopt }); - node.properties.push_back(NodeProperty{ .output = true }); + node.properties.push_back(nodes::NodeProperty{ .input = n > 0 ? std::optional(nodes::PropertyEndpoint{ n - 1, 1 }) : std::nullopt }); + node.properties.push_back(nodes::NodeProperty{ .output = true }); if (n % 2 == 0) frame.members->push_back(node.stableID); view.nodes.push_back(std::move(node)); @@ -91,7 +93,7 @@ namespace tachyon { app.Frame([&] { app.BeginRootWindow({ 1920, 1080 }, ElementFlags::None, app.theme.mainWindowStyleRef); - app.RenderNodeView(view); + nodes::RenderNodeView(app, nodesContext, view); app.EndRootWindow(); }); } @@ -112,23 +114,23 @@ namespace tachyon } // A frame's title element, by its title. - ID TitleOf(std::string_view title) const + ID TitleOf(std::string_view title) { - for (const ID id : WithStyle(app.theme.nodeFrameTitleStyleRef)) + for (const ID id : WithStyle(nodes::GetStyles(app, nodesContext).nodeFrameTitleStyleRef)) if (app.TextOf(id) == title) return id; return ID::Invalid(); } int2 Middle(ID id) const { return app.CenterOf(id); } - IntRect CanvasInner() const + IntRect CanvasInner() { - for (const ID id : WithStyle(app.theme.nodeViewStyleRef)) + for (const ID id : WithStyle(nodes::GetStyles(app, nodesContext).nodeViewStyleRef)) if (const auto* rp = app.elementStorage.GetElementRectPtr(app.elementStorage.FindElementRefByID(id))) return rp->innerRect; return {}; } // A point on the canvas well clear of the nodes and frames. - int2 Empty() const + int2 Empty() { const IntRect inner = CanvasInner(); return { inner.x + inner.w * 7 / 8, inner.y + inner.h / 8 }; @@ -200,7 +202,7 @@ namespace tachyon Settle(); const ID title = TitleOf("Lighting"); ASSERT_NE(title, ID::Invalid()); - const IntRect t = app.GetElementRect(title), a = app.GetElementRect(NodeElementID(view, nodeA)); + const IntRect t = app.GetElementRect(title), a = app.GetElementRect(nodes::NodeElementID(view, nodeA)); EXPECT_EQ(t.w, 40 * g); EXPECT_EQ(t.h, 2 * g); EXPECT_EQ(t.x - a.x, (4 - 8) * g) << "where the frame is, in node.pos space"; @@ -251,7 +253,7 @@ namespace tachyon EXPECT_TRUE(view.selectedFrameIDs.empty()); Click(Middle(TitleOf("Lighting"))); - const IntRect b = app.GetElementRect(NodeElementID(view, nodeB)); + const IntRect b = app.GetElementRect(nodes::NodeElementID(view, nodeB)); Click({ b.x + b.w / 2, b.y + g }); EXPECT_TRUE(view.selectedFrameIDs.empty()); EXPECT_EQ(view.selectedNodeIDs, std::unordered_set{ nodeB }); @@ -266,9 +268,9 @@ namespace tachyon TEST_F(NodeViewFrameTest, DraggingTheTitleMovesTheFrameAndWhatsInside) { Settle(); - std::vector edits; - view.onEdit = [&](const NodeViewEdit& edit) { edits.push_back(edit); }; - const NodeFrame outer = view.frames[0], inner = view.frames[1]; + std::vector edits; + view.onEdit = [&](const nodes::NodeViewEdit& edit) { edits.push_back(edit); }; + const nodes::NodeFrame outer = view.frames[0], inner = view.frames[1]; const int2 a = view.nodes[0].pos, b = view.nodes[1].pos; const int2 from = Middle(TitleOf("Lighting")); Drag(from, { from.x + 5 * g + 2, from.y + 3 * g - 1 }); @@ -285,11 +287,11 @@ namespace tachyon ASSERT_EQ(edits[0].moves.size(), 1u); EXPECT_EQ(edits[0].moves[0].node, 0); - ApplyNodeViewEdit(view, edits[0], /*undo=*/true); + nodes::ApplyNodeViewEdit(view, edits[0], /*undo=*/true); EXPECT_EQ(view.frames[0], outer); EXPECT_EQ(view.frames[1], inner); EXPECT_EQ(view.nodes[0].pos, a); - ApplyNodeViewEdit(view, edits[0]); + nodes::ApplyNodeViewEdit(view, edits[0]); EXPECT_EQ(view.nodes[0].pos, (int2{ a.x + step.x, a.y + step.y })); } @@ -298,8 +300,8 @@ namespace tachyon { Settle(); int edits = 0; - view.onEdit = [&](const NodeViewEdit&) { ++edits; }; - const NodeFrame outer = view.frames[0]; + view.onEdit = [&](const nodes::NodeViewEdit&) { ++edits; }; + const nodes::NodeFrame outer = view.frames[0]; const int2 a = view.nodes[0].pos; Click(Middle(TitleOf("Notes"))); EXPECT_EQ(edits, 0) << "a click moves nothing"; @@ -330,8 +332,8 @@ namespace tachyon TEST_F(NodeViewFrameTest, ADragLetGoAtOnceEndsOnTheGrid) { Settle(); - std::vector edits; - view.onEdit = [&](const NodeViewEdit& edit) { edits.push_back(edit); }; + std::vector edits; + view.onEdit = [&](const nodes::NodeViewEdit& edit) { edits.push_back(edit); }; auto dragAtOnce = [&](int2 from, int2 to) { Single(); app.InjectMouseMove(from); @@ -342,7 +344,7 @@ namespace tachyon Frame(); Settle(); }; - const NodeFrame outer = view.frames[0]; + const nodes::NodeFrame outer = view.frames[0]; const int2 a = view.nodes[0].pos; const int2 from = Middle(TitleOf("Lighting")); dragAtOnce(from, { from.x + 5 * g + 2, from.y + 3 * g - 1 }); @@ -370,8 +372,8 @@ namespace tachyon { Settle(); int edits = 0; - view.onEdit = [&](const NodeViewEdit&) { ++edits; }; - const NodeFrame outer = view.frames[0]; + view.onEdit = [&](const nodes::NodeViewEdit&) { ++edits; }; + const nodes::NodeFrame outer = view.frames[0]; const int2 a = view.nodes[0].pos; const int2 from = Middle(TitleOf("Lighting")); app.InjectMouseMove(from); @@ -394,9 +396,9 @@ namespace tachyon TEST_F(NodeViewFrameTest, TheEdgesResizeIt) { Settle(); - std::vector edits; - view.onEdit = [&](const NodeViewEdit& edit) { edits.push_back(edit); }; - const NodeFrame outer = view.frames[0]; + std::vector edits; + view.onEdit = [&](const nodes::NodeViewEdit& edit) { edits.push_back(edit); }; + const nodes::NodeFrame outer = view.frames[0]; const int2 a = view.nodes[0].pos; const IntRect t = app.GetElementRect(TitleOf("Lighting")); const int2 corner{ t.x + outer.size.x - 3, t.y + outer.size.y - 3 }; @@ -446,8 +448,8 @@ namespace tachyon TEST_F(NodeViewFrameTest, ADoubleClickRenamesIt) { Settle(); - std::vector edits; - view.onEdit = [&](const NodeViewEdit& edit) { edits.push_back(edit); }; + std::vector edits; + view.onEdit = [&](const nodes::NodeViewEdit& edit) { edits.push_back(edit); }; auto startRename = [&](std::string_view title) { const int2 at = Middle(TitleOf(title)); Single(); @@ -458,7 +460,7 @@ namespace tachyon Frame(); }; auto field = [&] { - const std::vector fields = WithStyle(app.theme.nodeFrameRenameStyleRef); + const std::vector fields = WithStyle(nodes::GetStyles(app, nodesContext).nodeFrameRenameStyleRef); return fields.empty() ? ID::Invalid() : fields[0]; }; @@ -504,12 +506,12 @@ namespace tachyon TEST_F(NodeViewFrameTest, RenameFrameStartsTheSameRename) { Settle(); - RenameFrame(view, 7); // none such: nothing + nodes::RenameFrame(view, 7); // none such: nothing Settle(); - EXPECT_TRUE(WithStyle(app.theme.nodeFrameRenameStyleRef).empty()); - RenameFrame(view, 1); + EXPECT_TRUE(WithStyle(nodes::GetStyles(app, nodesContext).nodeFrameRenameStyleRef).empty()); + nodes::RenameFrame(view, 1); Settle(); - const std::vector fields = WithStyle(app.theme.nodeFrameRenameStyleRef); + const std::vector fields = WithStyle(nodes::GetStyles(app, nodesContext).nodeFrameRenameStyleRef); ASSERT_EQ(fields.size(), 1u); EXPECT_EQ(app.guiStateManager.Interaction().GetFocusedID(), fields[0]); EXPECT_EQ(app.TextOf(fields[0]), "Notes"); @@ -543,12 +545,12 @@ namespace tachyon TEST_F(NodeViewFrameTest, TheTitleBarsMoreButtonOpensItsMenu) { Settle(); - EXPECT_TRUE(WithStyle(app.theme.nodeFrameMenuStyleRef).empty()) << "no menu, no button"; + EXPECT_TRUE(WithStyle(nodes::GetStyles(app, nodesContext).nodeFrameMenuStyleRef).empty()) << "no menu, no button"; int framesMenu = -1; view.onFrameContextMenu = [&](int frame) { framesMenu = frame; }; Settle(); - const std::vector buttons = WithStyle(app.theme.nodeFrameMenuStyleRef); + const std::vector buttons = WithStyle(nodes::GetStyles(app, nodesContext).nodeFrameMenuStyleRef); ASSERT_EQ(buttons.size(), 2u) << "one per frame"; const IntRect title = app.GetElementRect(TitleOf("Notes")); ID notesButton = ID::Invalid(); @@ -592,12 +594,12 @@ namespace tachyon void SetUp() override { NodeViewFrameTest::SetUp(); - NodeModel& a = view.nodes[0]; + nodes::NodeModel& a = view.nodes[0]; a.properties[0].name = "Out"; - a.properties.push_back(NodeProperty{ .input = PropertyEndpoint{ 1, 1 }, .name = "In" }); - NodeModel& b = view.nodes[1]; - b.properties[0].input = PropertyEndpoint{ 0, 0 }; - b.properties.push_back(NodeProperty{ .output = true, .name = "Value" }); + a.properties.push_back(nodes::NodeProperty{ .input = nodes::PropertyEndpoint{ 1, 1 }, .name = "In" }); + nodes::NodeModel& b = view.nodes[1]; + b.properties[0].input = nodes::PropertyEndpoint{ 0, 0 }; + b.properties.push_back(nodes::NodeProperty{ .output = true, .name = "Value" }); } // Clicks the chevron at the title's left. @@ -607,10 +609,10 @@ namespace tachyon Click({ t.x + app.styleManager.Px(12), t.y + t.h / 2 }); } - std::vector SocketRects() const + std::vector SocketRects() { std::vector out; - for (const ID id : WithStyle(app.theme.nodeSocketStyleRef)) + for (const ID id : WithStyle(nodes::GetStyles(app, nodesContext).nodeSocketStyleRef)) out.push_back(app.GetElementRect(id)); return out; } @@ -621,8 +623,8 @@ namespace tachyon TEST_F(NodeViewCollapsedFrameTest, TheChevronCollapsesItIntoANodesBox) { Settle(); - std::vector edits; - view.onEdit = [&](const NodeViewEdit& edit) { edits.push_back(edit); }; + std::vector edits; + view.onEdit = [&](const nodes::NodeViewEdit& edit) { edits.push_back(edit); }; ToggleAt("Lighting"); Settle(); ASSERT_TRUE(view.frames[0].collapsed); @@ -633,7 +635,7 @@ namespace tachyon const IntRect title = app.GetElementRect(TitleOf("Lighting")); EXPECT_EQ(title.w, 16 * g); - const std::vector boxes = WithStyle(app.theme.nodeStyleRef); + const std::vector boxes = WithStyle(nodes::GetStyles(app, nodesContext).nodeStyleRef); ASSERT_FALSE(boxes.empty()); IntRect box{}; for (const ID id : boxes) @@ -648,7 +650,7 @@ namespace tachyon EXPECT_TRUE(view.nodes[0].hidden); EXPECT_FALSE(view.nodes[1].hidden); view.nodes[0].lastSize = { 6 * g, 4 * g }; // as a layout would have left it - EXPECT_EQ(NodeAtCanvasPos(view,{ float(view.nodes[0].pos.x + 2), float(view.nodes[0].pos.y + 2) }), -1); + EXPECT_EQ(nodes::NodeAtCanvasPos(view,{ float(view.nodes[0].pos.x + 2), float(view.nodes[0].pos.y + 2) }), -1); Key(KeyCode::KeyA, KeyModifier::Control); EXPECT_FALSE(view.selectedNodeIDs.contains(nodeA)); EXPECT_TRUE(view.selectedNodeIDs.contains(nodeB)); @@ -671,8 +673,8 @@ namespace tachyon TEST_F(NodeViewCollapsedFrameTest, ItExpandsAgain) { Settle(); - std::vector edits; - view.onEdit = [&](const NodeViewEdit& edit) { edits.push_back(edit); }; + std::vector edits; + view.onEdit = [&](const nodes::NodeViewEdit& edit) { edits.push_back(edit); }; ToggleAt("Lighting"); Settle(); ASSERT_TRUE(view.frames[0].collapsed); @@ -695,10 +697,10 @@ namespace tachyon EXPECT_FALSE(view.frames[0].collapsed); ASSERT_EQ(edits.size(), 4u); - ApplyNodeViewEdit(view, edits[0], /*undo=*/false); + nodes::ApplyNodeViewEdit(view, edits[0], /*undo=*/false); Settle(); EXPECT_TRUE(view.frames[0].collapsed); - ApplyNodeViewEdit(view, edits[0], /*undo=*/true); + nodes::ApplyNodeViewEdit(view, edits[0], /*undo=*/true); Settle(); EXPECT_FALSE(view.frames[0].collapsed); EXPECT_NE(TitleOf("Notes"), ID::Invalid()); @@ -716,7 +718,7 @@ namespace tachyon // B, from below and right of it, to where the open frame's middle would be (well // past the collapsed box), on frames of its own, as a pointer goes. - const IntRect b = app.GetElementRect(NodeElementID(view, nodeB)); + const IntRect b = app.GetElementRect(nodes::NodeElementID(view, nodeB)); const int2 from{ b.x + b.w / 2, b.y + g }; const int2 to{ from.x - 30 * g, from.y - 18 * g }; Single(); @@ -734,13 +736,13 @@ namespace tachyon Settle(); EXPECT_FALSE(view.nodes[1].hidden); EXPECT_EQ(view.nodes[1].pos, (int2{ 30 * g, 12 * g })) << "where it was let go"; - EXPECT_EQ(NodesInFrame(view, 0), std::vector{ 0 }) << "still only A"; + EXPECT_EQ(nodes::NodesInFrame(view, 0), std::vector{ 0 }) << "still only A"; // Opened, B lies inside it, and is in it. ToggleAt("Lighting"); Settle(); EXPECT_FALSE(view.frames[0].members.has_value()); - EXPECT_EQ(NodesInFrame(view, 0), (std::vector{ 0, 1 })); + EXPECT_EQ(nodes::NodesInFrame(view, 0), (std::vector{ 0, 1 })); } // Collapsed in code, by setting the flag: it holds what lies inside it then. @@ -752,11 +754,11 @@ namespace tachyon ASSERT_TRUE(view.frames[0].members.has_value()); EXPECT_TRUE(view.nodes[0].hidden); EXPECT_EQ(view.selectedNodeIDs, std::unordered_set{ nodeB }) << "what can't be seen isn't selected"; - const NodeViewEdit expand = CollapseFrameEdit(view, 0, false); + const nodes::NodeViewEdit expand = nodes::CollapseFrameEdit(view, 0, false); ASSERT_EQ(expand.frameChanges.size(), 1u); EXPECT_FALSE(expand.frameChanges[0].to.collapsed); - EXPECT_TRUE(CollapseFrameEdit(view, 0, true).empty()) << "collapsed already"; - EXPECT_TRUE(CollapseFrameEdit(view, 9, true).empty()); + EXPECT_TRUE(nodes::CollapseFrameEdit(view, 0, true).empty()) << "collapsed already"; + EXPECT_TRUE(nodes::CollapseFrameEdit(view, 9, true).empty()); } // Collapsed, a drag on its title still moves what's inside it; it has no edges to resize. @@ -785,11 +787,12 @@ namespace tachyon // The canvas's own pass (grid, frames, wires) into a stub renderer. void DrawCanvas(HeadlessGUIApp& app, GUITest::StubGUIRenderer& renderer) { + nodes::Context nodesContext; for (uint32_t d = 0; d < app.elementStorage.NumberOfDepthLevels(); d++) for (uint32_t i = 0; i < app.elementStorage.DepthSizeOf(d); i++) { const ElementRef ref{ d, i }; - if (!app.elementStorage.IsValidRef(ref) || app.elementStorage.GetElementUnsafe(ref).styleRef != app.theme.nodeViewStyleRef) + if (!app.elementStorage.IsValidRef(ref) || app.elementStorage.GetElementUnsafe(ref).styleRef != nodes::GetStyles(app, nodesContext).nodeViewStyleRef) continue; const ElementCustomDraw* draw = app.elementStorage.GetCustomDraw(ref); if (draw == nullptr || !draw->callback) @@ -837,11 +840,11 @@ namespace tachyon // between them isn't drawn. TEST_F(NodeViewFrameTest, AWireBetweenTwoNodesInsideIsNotDrawnCollapsed) { - NodeModel c{}; + nodes::NodeModel c{}; c.stableID = app.idManager.CreateStaticID(); c.title = "C"; c.pos = { 20 * g, 16 * g }; - c.properties.push_back(NodeProperty{ .input = PropertyEndpoint{ 0, 0 } }); + c.properties.push_back(nodes::NodeProperty{ .input = nodes::PropertyEndpoint{ 0, 0 } }); view.nodes.push_back(std::move(c)); view.frames.resize(1); // just the outer one, round A and C Settle(); @@ -851,7 +854,7 @@ namespace tachyon const size_t collapsed = WireLinesDrawn(app); EXPECT_TRUE(view.nodes[0].hidden); EXPECT_TRUE(view.nodes[2].hidden); - view.nodes[2].properties[0].input = PropertyEndpoint{}; // no wire at all + view.nodes[2].properties[0].input = nodes::PropertyEndpoint{}; // no wire at all view.frames[0].collapsed = false; Settle(); const size_t none = WireLinesDrawn(app); @@ -863,11 +866,11 @@ namespace tachyon TEST_F(NodeViewCollapsedFrameTest, AWireInsideIsNotShown) { // A third node in the outer frame, fed by A: that wire stays inside. - NodeModel c{}; + nodes::NodeModel c{}; c.stableID = app.idManager.CreateStaticID(); c.title = "C"; c.pos = { 20 * g, 16 * g }; - c.properties.push_back(NodeProperty{ .input = PropertyEndpoint{ 0, 0 } }); + c.properties.push_back(nodes::NodeProperty{ .input = nodes::PropertyEndpoint{ 0, 0 } }); view.nodes.push_back(std::move(c)); Settle(); const size_t expanded = SocketRects().size(); @@ -881,18 +884,18 @@ namespace tachyon // An output inside feeding two nodes outside is one row, not one per wire. TEST_F(NodeViewCollapsedFrameTest, AnOutputFeedingTwoNodesIsOneRow) { - NodeModel c{}; + nodes::NodeModel c{}; c.stableID = app.idManager.CreateStaticID(); c.title = "C"; c.pos = { 60 * g, 10 * g }; - c.properties.push_back(NodeProperty{ .input = PropertyEndpoint{ 0, 0 } }); + c.properties.push_back(nodes::NodeProperty{ .input = nodes::PropertyEndpoint{ 0, 0 } }); view.nodes.push_back(std::move(c)); Settle(); ToggleAt("Lighting"); Settle(); const IntRect title = app.GetElementRect(TitleOf("Lighting")); IntRect box{}; - for (const ID id : WithStyle(app.theme.nodeStyleRef)) + for (const ID id : WithStyle(nodes::GetStyles(app, nodesContext).nodeStyleRef)) if (app.GetElementRect(id).x == title.x && app.GetElementRect(id).y == title.y) box = app.GetElementRect(id); EXPECT_EQ(box.h, 2 * g + 2 * g + g) << "A.In and A.Out side by side on one row"; } @@ -932,7 +935,7 @@ namespace tachyon ASSERT_TRUE(app.menuManager.IsOpen()); const ID menuWindow = app.menuManager.levels[0].windowID; const float3x2 transform = view.transform; - const IntRect a = app.GetElementRect(NodeElementID(view, nodeA)); + const IntRect a = app.GetElementRect(nodes::NodeElementID(view, nodeA)); for (const char* item : { "Add Reroute here", "Frame all", "Add frame here", "Add node", "Add Reroute here" }) { const ID id = app.FindByText(item); @@ -945,7 +948,7 @@ namespace tachyon ASSERT_TRUE(app.menuManager.IsOpen()) << item << ", frame " << f; EXPECT_EQ(app.menuManager.levels[0].windowID, menuWindow) << item << ", frame " << f; EXPECT_EQ(view.transform, transform) << item << ", frame " << f; - EXPECT_EQ(app.GetElementRect(NodeElementID(view, nodeA)), a) << item << ", frame " << f; + EXPECT_EQ(app.GetElementRect(nodes::NodeElementID(view, nodeA)), a) << item << ", frame " << f; EXPECT_EQ(app.FindByText(item), id) << item << " keeps its ID, frame " << f; } } @@ -959,28 +962,28 @@ namespace tachyon TEST_F(NodeViewFrameTest, AddingAndRemovingFramesUndoes) { const ID added = app.idManager.CreateStaticID(); - const NodeViewEdit add = AddFrameEdit(view, NodeFrame{ .stableID = added, .title = "New", .pos = { 0, 0 }, .size = { 10 * g, 6 * g } }, 1); - ApplyNodeViewEdit(view, add); + const nodes::NodeViewEdit add = nodes::AddFrameEdit(view, nodes::NodeFrame{ .stableID = added, .title = "New", .pos = { 0, 0 }, .size = { 10 * g, 6 * g } }, 1); + nodes::ApplyNodeViewEdit(view, add); ASSERT_EQ(view.frames.size(), 3u); EXPECT_EQ(view.frames[1].stableID, added); EXPECT_EQ(view.frames[2].stableID, frameInner); - ApplyNodeViewEdit(view, add, /*undo=*/true); + nodes::ApplyNodeViewEdit(view, add, /*undo=*/true); ASSERT_EQ(view.frames.size(), 2u); EXPECT_EQ(view.frames[1].stableID, frameInner); // No place given, or one past the end: the end. - EXPECT_EQ(AddFrameEdit(view, NodeFrame{}, -1).frames[0].index, 2); - EXPECT_EQ(AddFrameEdit(view, NodeFrame{}, 9).frames[0].index, 2); + EXPECT_EQ(nodes::AddFrameEdit(view, nodes::NodeFrame{}, -1).frames[0].index, 2); + EXPECT_EQ(nodes::AddFrameEdit(view, nodes::NodeFrame{}, 9).frames[0].index, 2); view.selectedFrameIDs = { frameOuter, frameInner }; const int both[] = { 1, 0, 1, 7 }; - const NodeViewEdit remove = RemoveFramesEdit(view, both); + const nodes::NodeViewEdit remove = nodes::RemoveFramesEdit(view, both); ASSERT_EQ(remove.frames.size(), 2u); - const std::vector before = view.frames; - ApplyNodeViewEdit(view, remove); + const std::vector before = view.frames; + nodes::ApplyNodeViewEdit(view, remove); EXPECT_TRUE(view.frames.empty()); EXPECT_TRUE(view.selectedFrameIDs.empty()) << "gone from the selection"; EXPECT_EQ(view.nodes.size(), 2u) << "the nodes stay"; - ApplyNodeViewEdit(view, remove, /*undo=*/true); + nodes::ApplyNodeViewEdit(view, remove, /*undo=*/true); EXPECT_EQ(view.frames, before); } @@ -993,9 +996,9 @@ namespace tachyon view.nodes[0].lastSize = { 6 * g, 4 * g }; view.nodes[1].lastSize = { 7 * g + 5, 3 * g }; const int both[] = { 0, 1 }; - const NodeFrame frame = FrameAroundNodes(view, both); - const NodeModel& a = view.nodes[0]; - const NodeModel& b = view.nodes[1]; + const nodes::NodeFrame frame = nodes::FrameAroundNodes(view, both); + const nodes::NodeModel& a = view.nodes[0]; + const nodes::NodeModel& b = view.nodes[1]; ASSERT_GT(a.lastSize.x, 0); EXPECT_EQ(frame.pos, (int2{ a.pos.x - g, a.pos.y - 3 * g })); EXPECT_GE(frame.pos.x + frame.size.x, b.pos.x + b.lastSize.x + g); @@ -1003,11 +1006,11 @@ namespace tachyon EXPECT_GE(frame.pos.y + frame.size.y, b.pos.y + b.lastSize.y + g); EXPECT_EQ(frame.size.x % g, 0); EXPECT_EQ(frame.size.y % g, 0); - EXPECT_EQ(FrameAroundNodes(view, std::span{}).size, (int2{ 0, 0 })); + EXPECT_EQ(nodes::FrameAroundNodes(view, std::span{}).size, (int2{ 0, 0 })); view.frames = { frame }; - EXPECT_EQ(NodesInFrame(view, 0), (std::vector{ 0, 1 })); - EXPECT_TRUE(NodesInFrame(view, 3).empty()); + EXPECT_EQ(nodes::NodesInFrame(view, 0), (std::vector{ 0, 1 })); + EXPECT_TRUE(nodes::NodesInFrame(view, 3).empty()); } // Round the selected nodes and frames, behind the frames it holds so they stay on top. @@ -1017,43 +1020,43 @@ namespace tachyon view.nodes[0].lastSize = { 6 * g, 4 * g }; view.nodes[1].lastSize = { 6 * g, 4 * g }; const ID group = app.idManager.CreateStaticID(); - const NodeFrame named{ .stableID = group, .title = "Group", .color = { 0.9f, 0.5f, 0.2f, 1.0f } }; - EXPECT_TRUE(GroupSelectionEdit(view, named).frames.empty()) << "nothing selected"; + const nodes::NodeFrame named{ .stableID = group, .title = "Group", .color = { 0.9f, 0.5f, 0.2f, 1.0f } }; + EXPECT_TRUE(nodes::GroupSelectionEdit(view, named).frames.empty()) << "nothing selected"; view.selectedNodeIDs = { nodeB }; view.selectedFrameIDs = { frameInner }; - const NodeViewEdit edit = GroupSelectionEdit(view, named); + const nodes::NodeViewEdit edit = nodes::GroupSelectionEdit(view, named); ASSERT_EQ(edit.frames.size(), 1u); EXPECT_EQ(edit.frames[0].index, 1) << "behind the inner frame"; - ApplyNodeViewEdit(view, edit); + nodes::ApplyNodeViewEdit(view, edit); ASSERT_EQ(view.frames.size(), 3u); - const NodeFrame& made = view.frames[1]; + const nodes::NodeFrame& made = view.frames[1]; EXPECT_EQ(made.stableID, group); EXPECT_EQ(made.title, "Group"); EXPECT_EQ(made.color, named.color); - const NodeFrame& inner = view.frames[2]; - const NodeModel& b = view.nodes[1]; + const nodes::NodeFrame& inner = view.frames[2]; + const nodes::NodeModel& b = view.nodes[1]; EXPECT_EQ(made.pos, (int2{ inner.pos.x - g, inner.pos.y - 3 * g })) << "a cell round, the title bar above"; EXPECT_GE(made.pos.x + made.size.x, b.pos.x + b.lastSize.x + g); EXPECT_GE(made.pos.y + made.size.y, b.pos.y + b.lastSize.y + g); EXPECT_EQ(made.size.x % g, 0); - EXPECT_EQ(NodesInFrame(view, 1), (std::vector{ 1 })) << "B moves with it"; - ApplyNodeViewEdit(view, edit, /*undo=*/true); + EXPECT_EQ(nodes::NodesInFrame(view, 1), (std::vector{ 1 })) << "B moves with it"; + nodes::ApplyNodeViewEdit(view, edit, /*undo=*/true); EXPECT_EQ(view.frames.size(), 2u); // Round both frames: behind the first of them. view.selectedFrameIDs = { frameOuter, frameInner }; - EXPECT_EQ(GroupSelectionEdit(view, named).frames[0].index, 0); + EXPECT_EQ(nodes::GroupSelectionEdit(view, named).frames[0].index, 0); // Only nodes: in front of the other frames. view.selectedFrameIDs.clear(); - EXPECT_EQ(GroupSelectionEdit(view, named).frames[0].index, 2); + EXPECT_EQ(nodes::GroupSelectionEdit(view, named).frames[0].index, 2); // A collapsed frame counts with its open size, so it fits when it opens again. view.selectedNodeIDs.clear(); view.selectedFrameIDs = { frameInner }; view.frames[1].collapsed = true; - const NodeFrame around = GroupSelectionEdit(view, named).frames[0].frame; + const nodes::NodeFrame around = nodes::GroupSelectionEdit(view, named).frames[0].frame; EXPECT_GE(around.pos.x + around.size.x, view.frames[1].pos.x + view.frames[1].size.x + g); } @@ -1062,16 +1065,16 @@ namespace tachyon Settle(); view.nodes[0].lastSize = { 6 * g, 4 * g }; view.nodes[1].lastSize = { 6 * g, 4 * g }; - EXPECT_EQ(NodesInFrame(view, 0), std::vector{ 0 }); - EXPECT_TRUE(NodesInFrame(view, 1).empty()); + EXPECT_EQ(nodes::NodesInFrame(view, 0), std::vector{ 0 }); + EXPECT_TRUE(nodes::NodesInFrame(view, 1).empty()); view.nodes[0].lastSize = { 40 * g, 4 * g }; - EXPECT_TRUE(NodesInFrame(view, 0).empty()) << "sticking out to the right: not inside"; + EXPECT_TRUE(nodes::NodesInFrame(view, 0).empty()) << "sticking out to the right: not inside"; view.nodes[0].lastSize = { 6 * g, 4 * g }; // The title bar, a row pitch high; the inner frame is the frontmost where both are. - EXPECT_EQ(FrameTitleAtCanvasPos(view, { float(5 * g), float(3 * g) }), 0); - EXPECT_EQ(FrameTitleAtCanvasPos(view, { float(5 * g), float(4 * g) }), -1) << "below the title bar"; - EXPECT_EQ(FrameTitleAtCanvasPos(view, { float(27 * g), float(13 * g) }), 1); - EXPECT_EQ(FrameTitleAtCanvasPos(view, { float(3 * g), float(3 * g) }), -1); + EXPECT_EQ(nodes::FrameTitleAtCanvasPos(view, { float(5 * g), float(3 * g) }), 0); + EXPECT_EQ(nodes::FrameTitleAtCanvasPos(view, { float(5 * g), float(4 * g) }), -1) << "below the title bar"; + EXPECT_EQ(nodes::FrameTitleAtCanvasPos(view, { float(27 * g), float(13 * g) }), 1); + EXPECT_EQ(nodes::FrameTitleAtCanvasPos(view, { float(3 * g), float(3 * g) }), -1); } } } diff --git a/tests/node_view_hit_test.cpp b/tests/node_view_hit_test.cpp index db92e430..06411774 100644 --- a/tests/node_view_hit_test.cpp +++ b/tests/node_view_hit_test.cpp @@ -14,6 +14,7 @@ #include #include #include +#include namespace tachyon { @@ -25,6 +26,7 @@ namespace tachyon { protected: HeadlessGUIApp app; + nodes::Context nodesContext; // Created once so hit-test finds the same elements after each rebuild. ID canvasID; @@ -54,7 +56,7 @@ namespace tachyon { Element node{}; node.id = nodeID; - node.styleRef = app.theme.nodeStyleRef; + node.styleRef = nodes::GetStyles(app, nodesContext).nodeStyleRef; node.state = app.guiStateManager.GetCurrentState(nodeID); auto nodeRes = app.elementStorage.Add(std::move(node), LayoutOverride{}.FixedWidth(kNodeW).Absolute(pos.x, pos.y)); @@ -84,7 +86,7 @@ namespace tachyon // a centring contentTransform applied AFTER Add(). Element canvas{}; canvas.id = canvasID; - canvas.styleRef = app.theme.nodeViewStyleRef; + canvas.styleRef = nodes::GetStyles(app, nodesContext).nodeViewStyleRef; canvas.state = app.guiStateManager.GetCurrentState(canvasID); auto canvasRes = app.elementStorage.Add(std::move(canvas), LayoutOverride{}.Size(kCanvasW, kCanvasH).Position(0, 0)); @@ -238,7 +240,7 @@ namespace tachyon app.BeginRootWindow({ 1920, 1080 }); Element canvas{}; canvas.id = canvasID; - canvas.styleRef = app.theme.nodeViewStyleRef; + canvas.styleRef = nodes::GetStyles(app, nodesContext).nodeViewStyleRef; canvas.state = app.guiStateManager.GetCurrentState(canvasID); auto cv = app.elementStorage.Add(std::move(canvas), LayoutOverride{}.Size(800, 600).Position(0, 0)); @@ -252,7 +254,7 @@ namespace tachyon // a single Label("Name") + Field row. Element node{}; node.id = negNodeID; - node.styleRef = app.theme.nodeStyleRef; + node.styleRef = nodes::GetStyles(app, nodesContext).nodeStyleRef; node.state = app.guiStateManager.GetCurrentState(negNodeID); auto n = app.elementStorage.Add(std::move(node), LayoutOverride{}.FixedWidth(180).Absolute(-340, -60)); diff --git a/tests/node_view_lane_offset_test.cpp b/tests/node_view_lane_offset_test.cpp index b82e4bc6..9ae2846e 100644 --- a/tests/node_view_lane_offset_test.cpp +++ b/tests/node_view_lane_offset_test.cpp @@ -1,9 +1,10 @@ // Wires between the same two nodes get their default corridor lanes spread apart -// (ComputeWireLaneOffsets and WireRouteOverrides::lane in gui_node_view_helpers). +// (ComputeWireLaneOffsets and nodes::WireRouteOverrides::lane in gui_node_view_helpers). #include -#include +#include +#include #include @@ -12,27 +13,27 @@ namespace using namespace tachyon; // Node 0 has `wires` outputs; node 1 has as many inputs, each wired to the matching output. - NodeView WiredPair(int wires) + nodes::NodeView WiredPair(int wires) { - NodeView view; + nodes::NodeView view; view.nodes.resize(2); view.nodes[0].properties.resize(size_t(wires)); view.nodes[1].properties.resize(size_t(wires)); for (int i = 0; i < wires; ++i) { view.nodes[0].properties[size_t(i)].output = true; - view.nodes[1].properties[size_t(i)].input = PropertyEndpoint{ 0, i }; + view.nodes[1].properties[size_t(i)].input = nodes::PropertyEndpoint{ 0, i }; } return view; } - std::vector Offsets(const NodeView& view, int wires) + std::vector Offsets(const nodes::NodeView& view, int wires) { - const auto offsets = ComputeWireLaneOffsets(view); + const auto offsets = nodes::ComputeWireLaneOffsets(view); std::vector result; for (int i = 0; i < wires; ++i) { - const auto it = offsets.find(WireKey(1, i)); + const auto it = offsets.find(nodes::WireKey(1, i)); result.push_back(it != offsets.end() ? it->second.offset : 999); } return result; @@ -51,7 +52,7 @@ namespace // they nest instead of crossing: the top wire turns first. TEST(NodeViewLaneOffset, WiresRunningUpTakeTheLanesInReverse) { - NodeView view = WiredPair(3); + nodes::NodeView view = WiredPair(3); view.nodes[0].pos = { 0, 200 }; view.nodes[1].pos = { 300, 0 }; EXPECT_EQ(Offsets(view, 3), (std::vector{ -1, 0, 1 })); @@ -61,27 +62,27 @@ namespace TEST(NodeViewLaneOffset, WiresToDifferentNodesAreSeparateGroups) { - NodeView view; + nodes::NodeView view; view.nodes.resize(3); view.nodes[0].properties.resize(2); view.nodes[1].properties.resize(1); view.nodes[2].properties.resize(1); - view.nodes[1].properties[0].input = PropertyEndpoint{ 0, 0 }; - view.nodes[2].properties[0].input = PropertyEndpoint{ 0, 1 }; - const auto offsets = ComputeWireLaneOffsets(view); - EXPECT_EQ(offsets.at(WireKey(1, 0)).offset, 0); - EXPECT_EQ(offsets.at(WireKey(2, 0)).offset, 0); + view.nodes[1].properties[0].input = nodes::PropertyEndpoint{ 0, 0 }; + view.nodes[2].properties[0].input = nodes::PropertyEndpoint{ 0, 1 }; + const auto offsets = nodes::ComputeWireLaneOffsets(view); + EXPECT_EQ(offsets.at(nodes::WireKey(1, 0)).offset, 0); + EXPECT_EQ(offsets.at(nodes::WireKey(2, 0)).offset, 0); } // An input still naming a removed node (the app erased from `nodes` directly) gets no // lane, and the others are unaffected. TEST(NodeViewLaneOffset, AWireFromARemovedNodeIsSkipped) { - NodeView view = WiredPair(2); - view.nodes[1].properties[1].input = PropertyEndpoint{ 7, 0 }; - const auto offsets = ComputeWireLaneOffsets(view); + nodes::NodeView view = WiredPair(2); + view.nodes[1].properties[1].input = nodes::PropertyEndpoint{ 7, 0 }; + const auto offsets = nodes::ComputeWireLaneOffsets(view); EXPECT_EQ(offsets.size(), 1u); - EXPECT_EQ(offsets.at(WireKey(1, 0)).offset, 0); + EXPECT_EQ(offsets.at(nodes::WireKey(1, 0)).offset, 0); } TEST(NodeViewLaneOffset, MovesTheDefaultCorridorLaneByGridSteps) @@ -91,9 +92,9 @@ namespace const IntRect tgt{ 300, 200, 180, 80 }; const int2 outPt{ 174, 40 }, inPt{ 306, 240 }; auto laneX = [&](int32_t offset) { - WireRouteOverrides o; + nodes::WireRouteOverrides o; o.lane.offset = offset; - return BuildWireRoute(outPt, inPt, src, tgt, grid, {}, o).points[1].x; + return nodes::BuildWireRoute(outPt, inPt, src, tgt, grid, {}, o).points[1].x; }; EXPECT_EQ(laneX(1), laneX(0) + grid); EXPECT_EQ(laneX(-1), laneX(0) - grid); @@ -103,10 +104,10 @@ namespace TEST(NodeViewLaneOffset, APinnedLaneIgnoresTheOffset) { - WireRouteOverrides o; + nodes::WireRouteOverrides o; o.laneX = 240; o.lane.offset = 2; - const auto route = BuildWireRoute({ 174, 40 }, { 306, 240 }, { 0, 0, 180, 80 }, { 300, 200, 180, 80 }, 20, {}, o); + const auto route = nodes::BuildWireRoute({ 174, 40 }, { 306, 240 }, { 0, 0, 180, 80 }, { 300, 200, 180, 80 }, 20, {}, o); EXPECT_EQ(route.points[1].x, 240); } @@ -114,37 +115,37 @@ namespace // and the wire it would replace on that input drops out. TEST(NodeViewLaneOffset, ADraggedWireCountsAsConnected) { - NodeView view = WiredPair(2); + nodes::NodeView view = WiredPair(2); view.nodes[0].properties.resize(3); view.nodes[1].properties.resize(3); - view.nodes[1].properties[2].input = PropertyEndpoint{}; // free input + view.nodes[1].properties[2].input = nodes::PropertyEndpoint{}; // free input - const auto offsets = ComputeWireLaneOffsets(view, PropertyEndpoint{ 0, 2 }, PropertyEndpoint{ 1, 2 }); - EXPECT_EQ(offsets.at(WireKey(1, 0)).offset, 1); - EXPECT_EQ(offsets.at(WireKey(1, 1)).offset, 0); - EXPECT_EQ(offsets.at(WireKey(1, 2)).offset, -1) << "the dragged wire"; + const auto offsets = nodes::ComputeWireLaneOffsets(view, nodes::PropertyEndpoint{ 0, 2 }, nodes::PropertyEndpoint{ 1, 2 }); + EXPECT_EQ(offsets.at(nodes::WireKey(1, 0)).offset, 1); + EXPECT_EQ(offsets.at(nodes::WireKey(1, 1)).offset, 0); + EXPECT_EQ(offsets.at(nodes::WireKey(1, 2)).offset, -1) << "the dragged wire"; } TEST(NodeViewLaneOffset, ADraggedWireReplacesTheInputsWire) { - NodeView view = WiredPair(2); + nodes::NodeView view = WiredPair(2); view.nodes[0].properties.resize(3); // Output 2 dragged onto input 1, which output 1 feeds now. - const auto offsets = ComputeWireLaneOffsets(view, PropertyEndpoint{ 0, 2 }, PropertyEndpoint{ 1, 1 }); - EXPECT_EQ(offsets.at(WireKey(1, 0)).offset, 0); - EXPECT_EQ(offsets.at(WireKey(1, 1)).offset, -1); + const auto offsets = nodes::ComputeWireLaneOffsets(view, nodes::PropertyEndpoint{ 0, 2 }, nodes::PropertyEndpoint{ 1, 1 }); + EXPECT_EQ(offsets.at(nodes::WireKey(1, 0)).offset, 0); + EXPECT_EQ(offsets.at(nodes::WireKey(1, 1)).offset, -1); EXPECT_EQ(offsets.size(), 2u); } TEST(NodeViewLaneOffset, ADraggedWireFromAWiredOutputKeepsItsOtherWires) { - NodeView view = WiredPair(2); + nodes::NodeView view = WiredPair(2); view.nodes[1].properties.resize(3); - view.nodes[1].properties[2].input = PropertyEndpoint{}; + view.nodes[1].properties[2].input = nodes::PropertyEndpoint{}; // Output 0 (wired to input 0) dragged onto input 2: outputs fan out, so input 0 keeps it. - const auto offsets = ComputeWireLaneOffsets(view, PropertyEndpoint{ 0, 0 }, PropertyEndpoint{ 1, 2 }); - EXPECT_EQ(offsets.at(WireKey(1, 0)).offset, 1); - EXPECT_EQ(offsets.at(WireKey(1, 1)).offset, 0); - EXPECT_EQ(offsets.at(WireKey(1, 2)).offset, -1); + const auto offsets = nodes::ComputeWireLaneOffsets(view, nodes::PropertyEndpoint{ 0, 0 }, nodes::PropertyEndpoint{ 1, 2 }); + EXPECT_EQ(offsets.at(nodes::WireKey(1, 0)).offset, 1); + EXPECT_EQ(offsets.at(nodes::WireKey(1, 1)).offset, 0); + EXPECT_EQ(offsets.at(nodes::WireKey(1, 2)).offset, -1); } } diff --git a/tests/node_view_marquee_test.cpp b/tests/node_view_marquee_test.cpp index 32749fca..26998cf1 100644 --- a/tests/node_view_marquee_test.cpp +++ b/tests/node_view_marquee_test.cpp @@ -5,15 +5,16 @@ // // Coordinate spaces (see panel_node_view.cpp top-of-function docs): // SCREEN : absolute window pixels (mouse positions). -// CANVAS_LAY : canvas-local LAYOUT, where NodeModel::pos lives. +// CANVAS_LAY : canvas-local LAYOUT, where nodes::NodeModel::pos lives. // The helper converts the marquee corners SCREEN -> CANVAS_LAY using the // canvas's inner-rect screen position + view.transform, then strict-contains. #include -#include +#include #include #include +#include #include @@ -21,10 +22,10 @@ namespace tachyon { namespace { - // NodeModel at a CANVAS_LAY pos with a layout size; idx becomes its stableID. - NodeModel MakeNode(uint32_t idx, int2 pos, int2 size) + // nodes::NodeModel at a CANVAS_LAY pos with a layout size; idx becomes its stableID. + nodes::NodeModel MakeNode(uint32_t idx, int2 pos, int2 size) { - NodeModel n; + nodes::NodeModel n; // The helper only compares stableIDs, so any distinct IDs work. n.stableID = ID{ idx }; n.pos = pos; @@ -42,12 +43,12 @@ namespace tachyon // therefore renders at SCREEN (500, 400). TEST(NodeViewMarqueeTest, ScreenToCanvasLayMapsCenterToOrigin) { - std::vector nodes; + std::vector nodes; // Node at CANVAS_LAY (0, 0), 100x100. Renders at SCREEN (500..600, 400..500). nodes.push_back(MakeNode(1, { 0, 0 }, { 100, 100 })); // Marquee in SCREEN: just covering the node's rendered area. - const auto hits = ComputeNodesInMarquee( + const auto hits = nodes::ComputeNodesInMarquee( nodes, kCanvasInner, float3x2::Identity(), /*start=*/ { 500, 400 }, /*current=*/ { 600, 500 }); @@ -61,11 +62,11 @@ namespace tachyon // Node at CANVAS_LAY (-340, -60), 180x80. Renders at SCREEN around // (160..340, 340..420). A marquee in the bottom-right corner of the // canvas is nowhere near it. - std::vector nodes; + std::vector nodes; nodes.push_back(MakeNode(1, { -340, -60 }, { 180, 80 })); nodes.push_back(MakeNode(2, { 200, 80 }, { 180, 80 })); - const auto hits = ComputeNodesInMarquee( + const auto hits = nodes::ComputeNodesInMarquee( nodes, kCanvasInner, float3x2::Identity(), /*start=*/ { 820, 620 }, /*current=*/ { 880, 680 }); @@ -76,12 +77,12 @@ namespace tachyon TEST(NodeViewMarqueeTest, MarqueeFullyContainingOneNode_SelectsOnlyThatNode) { // Two nodes, one negative-positioned and one positive. - std::vector nodes; + std::vector nodes; nodes.push_back(MakeNode(1, { -340, -60 }, { 180, 80 })); // SCREEN ~ (160..340, 340..420) nodes.push_back(MakeNode(2, { 200, 80 }, { 180, 80 })); // SCREEN ~ (700..880, 480..560) // Marquee fully around node 1's rendered position. - const auto hits = ComputeNodesInMarquee( + const auto hits = nodes::ComputeNodesInMarquee( nodes, kCanvasInner, float3x2::Identity(), /*start=*/ { 150, 330 }, /*current=*/ { 360, 430 }); @@ -94,11 +95,11 @@ namespace tachyon TEST(NodeViewMarqueeTest, MarqueePartiallyOverlappingNode_DoesNotSelect) { // Strict containment: a marquee that only partially overlaps a node doesn't select it. - std::vector nodes; + std::vector nodes; nodes.push_back(MakeNode(1, { -340, -60 }, { 180, 80 })); // Marquee covers the left half of node 1's rendered area only. - const auto hits = ComputeNodesInMarquee( + const auto hits = nodes::ComputeNodesInMarquee( nodes, kCanvasInner, float3x2::Identity(), /*start=*/ { 100, 330 }, /*current=*/ { 250, 430 }); @@ -111,10 +112,10 @@ namespace tachyon { // Marquee is smaller than the node and lives strictly inside it. // Strict containment means the NODE isn't inside the MARQUEE, so no hit. - std::vector nodes; + std::vector nodes; nodes.push_back(MakeNode(1, { -340, -60 }, { 180, 80 })); - const auto hits = ComputeNodesInMarquee( + const auto hits = nodes::ComputeNodesInMarquee( nodes, kCanvasInner, float3x2::Identity(), /*start=*/ { 200, 360 }, /*current=*/ { 240, 400 }); @@ -125,11 +126,11 @@ namespace tachyon TEST(NodeViewMarqueeTest, GiantMarqueeSelectsAllNodes) { // A marquee containing everything selects every node. - std::vector nodes; + std::vector nodes; nodes.push_back(MakeNode(1, { -340, -60 }, { 180, 80 })); nodes.push_back(MakeNode(2, { 200, 80 }, { 180, 80 })); - const auto hits = ComputeNodesInMarquee( + const auto hits = nodes::ComputeNodesInMarquee( nodes, kCanvasInner, float3x2::Identity(), /*start=*/ { 0, 0 }, /*current=*/ { 1000, 1000 }); @@ -143,11 +144,11 @@ namespace tachyon { // A node not yet laid out (lastSize == 0) is skipped even if its pos lies // inside the marquee: it has no real bounds yet. - std::vector nodes; + std::vector nodes; nodes.push_back(MakeNode(1, { -340, -60 }, { 0, 0 })); // not yet laid out nodes.push_back(MakeNode(2, { 200, 80 }, { 180, 80 })); - const auto hits = ComputeNodesInMarquee( + const auto hits = nodes::ComputeNodesInMarquee( nodes, kCanvasInner, float3x2::Identity(), /*start=*/ { 0, 0 }, /*current=*/ { 1000, 1000 }); @@ -164,12 +165,12 @@ namespace tachyon // Pan the view by +100 in X (content shifts right on screen by 100). // A node at CANVAS_LAY (0, 0) now renders at SCREEN (500+100, 400). // A marquee at the new rendered position must still select that node. - std::vector nodes; + std::vector nodes; nodes.push_back(MakeNode(1, { 0, 0 }, { 100, 100 })); const float3x2 panRight = float3x2::Translate(100.0f, 0.0f); - const auto hits = ComputeNodesInMarquee( + const auto hits = nodes::ComputeNodesInMarquee( nodes, kCanvasInner, panRight, /*start=*/ { 590, 390 }, /*current=*/ { 710, 510 }); @@ -182,12 +183,12 @@ namespace tachyon { // Same setup, but marquee where the node USED to render before the pan // (i.e., near the canvas center). After the pan, no node is there. - std::vector nodes; + std::vector nodes; nodes.push_back(MakeNode(1, { 0, 0 }, { 100, 100 })); const float3x2 panRight = float3x2::Translate(200.0f, 0.0f); - const auto hits = ComputeNodesInMarquee( + const auto hits = nodes::ComputeNodesInMarquee( nodes, kCanvasInner, panRight, /*start=*/ { 490, 390 }, /*current=*/ { 610, 510 }); @@ -199,7 +200,7 @@ namespace tachyon { // At zoom 0.5, nodes render at half their size and distance from // canvas center. The same screen-pixel marquee covers more CANVAS_LAY. - std::vector nodes; + std::vector nodes; nodes.push_back(MakeNode(1, { -340, -60 }, { 180, 80 })); nodes.push_back(MakeNode(2, { 200, 80 }, { 180, 80 })); @@ -207,7 +208,7 @@ namespace tachyon // Marquee covering most of the screen - at zoom 0.5, this corresponds // to a CANVAS_LAY rect twice as wide, easily containing both nodes. - const auto hits = ComputeNodesInMarquee( + const auto hits = nodes::ComputeNodesInMarquee( nodes, kCanvasInner, zoomHalf, /*start=*/ { 200, 200 }, /*current=*/ { 800, 600 }); @@ -222,7 +223,7 @@ namespace tachyon TEST(NodeViewZOrderTest, BringToFrontMovesOnlyTheClickedNode) { std::vector ordering{ 0, 1, 2, 3 }; // last == front - BringNodeToFront(ordering, 1); + nodes::BringNodeToFront(ordering, 1); // The others keep their relative order; only node 1 changes position. EXPECT_EQ(ordering, (std::vector{ 0, 2, 3, 1 })); } @@ -230,29 +231,29 @@ namespace tachyon TEST(NodeViewZOrderTest, BringToFrontIsANoOpForTheFrontNodeAndUnknownNodes) { std::vector ordering{ 2, 0, 1 }; - BringNodeToFront(ordering, 1); + nodes::BringNodeToFront(ordering, 1); EXPECT_EQ(ordering, (std::vector{ 2, 0, 1 })); - BringNodeToFront(ordering, 7); + nodes::BringNodeToFront(ordering, 7); EXPECT_EQ(ordering, (std::vector{ 2, 0, 1 })); } // ---- ConnectSockets: an output drives any number of inputs, an input has one source ---- - static NodeView ThreeNodeView() + static nodes::NodeView ThreeNodeView() { - NodeView view; + nodes::NodeView view; view.nodes.resize(3); for (auto& n : view.nodes) - n.properties.push_back(NodeProperty{ .input = PropertyEndpoint{}, .output = true }); + n.properties.push_back(nodes::NodeProperty{ .input = nodes::PropertyEndpoint{}, .output = true }); return view; } TEST(NodeViewConnectTest, AnOutputFansOutToSeveralInputs) { - NodeView view = ThreeNodeView(); - const PropertyEndpoint out{ 0, 0 }, x{ 1, 0 }, y{ 2, 0 }; - ConnectSockets(view, out, x); - ConnectSockets(view, out, y); + nodes::NodeView view = ThreeNodeView(); + const nodes::PropertyEndpoint out{ 0, 0 }, x{ 1, 0 }, y{ 2, 0 }; + nodes::ConnectSockets(view, out, x); + nodes::ConnectSockets(view, out, y); EXPECT_EQ(view.nodes[1].properties[0].input, out); EXPECT_EQ(view.nodes[2].properties[0].input, out); @@ -260,10 +261,10 @@ namespace tachyon TEST(NodeViewConnectTest, RewiringAnInputReplacesItsSource) { - NodeView view = ThreeNodeView(); - const PropertyEndpoint a{ 0, 0 }, b{ 1, 0 }, in{ 2, 0 }; - ConnectSockets(view, a, in); - ConnectSockets(view, b, in); + nodes::NodeView view = ThreeNodeView(); + const nodes::PropertyEndpoint a{ 0, 0 }, b{ 1, 0 }, in{ 2, 0 }; + nodes::ConnectSockets(view, a, in); + nodes::ConnectSockets(view, b, in); EXPECT_EQ(view.nodes[2].properties[0].input, b); } diff --git a/tests/node_view_state_machine_test.cpp b/tests/node_view_state_machine_test.cpp index 66657935..96f69fa3 100644 --- a/tests/node_view_state_machine_test.cpp +++ b/tests/node_view_state_machine_test.cpp @@ -1,4 +1,4 @@ -// A node view as a state machine (NodeViewKind::StateMachine): states without fields, joined +// A node view as a state machine (nodes::NodeViewKind::StateMachine): states without fields, joined // by transitions that may run both ways and back into the same state, drawn, picked and edited // through the headless harness. @@ -7,7 +7,8 @@ #include "headless_gui_app.h" #include -#include +#include +#include #include #include @@ -22,9 +23,10 @@ namespace tachyon { protected: HeadlessGUIApp app; - NodeView view; + nodes::Context nodesContext; + nodes::NodeView view; ID sleep{}, patrol{}, chase{}; - std::vector edits; + std::vector edits; void SetUp() override { @@ -34,16 +36,16 @@ namespace tachyon patrol = app.idManager.CreateStaticID(); chase = app.idManager.CreateStaticID(); view = {}; - view.kind = NodeViewKind::StateMachine; + view.kind = nodes::NodeViewKind::StateMachine; view.transform = float3x2::Scale(1.0f); view.showMinimap = false; view.showZoomControls = false; view.nodes = { - NodeModel{ .stableID = sleep, .title = "Sleep", .pos = { -400, -120 } }, - NodeModel{ .stableID = patrol, .title = "Patrol", .pos = { 80, -120 } }, - NodeModel{ .stableID = chase, .title = "Chase", .pos = { 80, 200 } }, + nodes::NodeModel{ .stableID = sleep, .title = "Sleep", .pos = { -400, -120 } }, + nodes::NodeModel{ .stableID = patrol, .title = "Patrol", .pos = { 80, -120 } }, + nodes::NodeModel{ .stableID = chase, .title = "Chase", .pos = { 80, 200 } }, }; - view.onEdit = [this](const NodeViewEdit& edit) { edits.push_back(edit); }; + view.onEdit = [this](const nodes::NodeViewEdit& edit) { edits.push_back(edit); }; } void TearDown() override { app.Cleanup(); } @@ -51,7 +53,7 @@ namespace tachyon { app.Frame([&] { app.BeginRootWindow({ 1600, 1000 }, ElementFlags::None, app.theme.mainWindowStyleRef); - app.RenderNodeView(view); + nodes::RenderNodeView(app, nodesContext, view); app.EndRootWindow(); }); } @@ -63,17 +65,17 @@ namespace tachyon view.transitions.push_back({ .stableID = id, .from = from, .to = to, .label = std::move(label) }); return id; } - const NodeModel& State(ID id) const { return view.nodes[size_t(NodeIndex(view, id))]; } + const nodes::NodeModel& State(ID id) const { return view.nodes[size_t(nodes::NodeIndex(view, id))]; } IntRect Box(ID id) const { - const NodeModel& s = State(id); + const nodes::NodeModel& s = State(id); return { s.pos.x, s.pos.y, s.lastSize.x, s.lastSize.y }; } // A point in node.pos space on screen. node.pos is measured from the canvas's border // box, the screen mapping's points from its content box. int2 Screen(float2 canvas) const { - const float2 p = NodeViewCanvasToScreen(view, { canvas.x + float(view.lastGridOrigin.x), canvas.y + float(view.lastGridOrigin.y) }); + const float2 p = nodes::NodeViewCanvasToScreen(view, { canvas.x + float(view.lastGridOrigin.x), canvas.y + float(view.lastGridOrigin.y) }); return { int32_t(std::lround(p.x)), int32_t(std::lround(p.y)) }; } int2 Centre(ID id) const @@ -90,7 +92,7 @@ namespace tachyon int2 Empty() const { return Screen({ 500.0f, 320.0f }); } int2 PathMiddle(ID transition) const { - const TransitionPath path = StateTransitionPath(view, view.transitions[size_t(TransitionIndex(view, transition))], + const nodes::TransitionPath path = nodes::StateTransitionPath(view, view.transitions[size_t(nodes::TransitionIndex(view, transition))], app.styleManager.Px(6), app.styleManager.Px(24)); if (path.loop) return Screen({ float(path.labelAt.x), float(path.labelAt.y) }); @@ -154,20 +156,20 @@ namespace tachyon const ID self = Transition(chase, chase); Settle(); const int32_t gap = app.styleManager.Px(6), loop = app.styleManager.Px(24); - auto path = [&](ID t) { return StateTransitionPath(view, view.transitions[size_t(TransitionIndex(view, t))], gap, loop); }; + auto path = [&](ID t) { return nodes::StateTransitionPath(view, view.transitions[size_t(nodes::TransitionIndex(view, t))], gap, loop); }; - const TransitionPath a = path(there), b = path(back); + const nodes::TransitionPath a = path(there), b = path(back); ASSERT_TRUE(a.valid && b.valid); EXPECT_EQ(a.from.x, Box(sleep).x + Box(sleep).w) << "leaves the right edge"; EXPECT_EQ(a.to.x, Box(patrol).x) << "ends on the left edge"; EXPECT_NE(a.from.y, b.to.y) << "the pair doesn't overlap"; EXPECT_EQ(std::abs(a.from.y - b.to.y), 2 * gap); - const TransitionPath down = path(on); + const nodes::TransitionPath down = path(on); EXPECT_EQ(down.from.y, Box(patrol).y + Box(patrol).h) << "a single one aims centre to centre: out of the bottom"; EXPECT_EQ(down.to.y, Box(chase).y) << "into the top"; - const TransitionPath l = path(self); + const nodes::TransitionPath l = path(self); EXPECT_TRUE(l.loop); EXPECT_EQ(l.from.y, Box(chase).y); EXPECT_LT(l.c1.y, Box(chase).y) << "over its top"; @@ -184,23 +186,23 @@ namespace tachyon Settle(); const int32_t gap = app.styleManager.Px(6), loop = app.styleManager.Px(24), margin = app.styleManager.Px(4); const int2 size{ 60, 16 }; - auto path = [&](ID t) { return StateTransitionPath(view, view.transitions[size_t(TransitionIndex(view, t))], gap, loop); }; + auto path = [&](ID t) { return nodes::StateTransitionPath(view, view.transitions[size_t(nodes::TransitionIndex(view, t))], gap, loop); }; // Sleep -> Patrol runs right: its label below its line; Patrol -> Sleep runs left: above. - const TransitionPath a = path(there), b = path(back); - const int2 la = TransitionLabelCentre(a, size, margin), lb = TransitionLabelCentre(b, size, margin); + const nodes::TransitionPath a = path(there), b = path(back); + const int2 la = nodes::TransitionLabelCentre(a, size, margin), lb = nodes::TransitionLabelCentre(b, size, margin); EXPECT_EQ(la.y - size.y / 2, a.from.y + margin) << "below, clear of the line by the margin"; EXPECT_EQ(lb.y + size.y / 2, b.from.y - margin) << "above"; EXPECT_EQ(la.x, (a.from.x + a.to.x) / 2) << "half way along"; // Patrol -> Chase runs down: its label to its left (the arrow's right, facing down). - const TransitionPath d = path(down); - const int2 ld = TransitionLabelCentre(d, size, margin); + const nodes::TransitionPath d = path(down); + const int2 ld = nodes::TransitionLabelCentre(d, size, margin); EXPECT_LT(ld.x + size.x / 2, std::min(d.from.x, d.to.x)) << "clear of the line"; // A loop's over its top. - const TransitionPath l = path(self); - const int2 ll = TransitionLabelCentre(l, size, margin); + const nodes::TransitionPath l = path(self); + const int2 ll = nodes::TransitionLabelCentre(l, size, margin); // Drawn as two quadratic halves, the curve's top is the middle of its controls. EXPECT_EQ(ll.y + size.y / 2, (l.c1.y + l.c2.y) / 2 - margin) << "clear of the curve's top by the margin"; EXPECT_EQ(ll.x, (l.from.x + l.to.x) / 2); @@ -211,7 +213,7 @@ namespace tachyon TEST_F(NodeViewStateMachineTest, AMenuStartsATransition) { Settle(); - StartTransition(view, NodeIndex(view, sleep)); + nodes::StartTransition(view, nodes::NodeIndex(view, sleep)); app.InjectMouseMove(Centre(chase)); Frame(); Click(Centre(chase)); @@ -220,13 +222,13 @@ namespace tachyon EXPECT_EQ(view.transitions[0].to, chase); EXPECT_FALSE(view.transitionPicking); - StartTransition(view, NodeIndex(view, patrol)); + nodes::StartTransition(view, nodes::NodeIndex(view, patrol)); Click(Empty()); EXPECT_FALSE(view.transitionPicking); EXPECT_EQ(view.transitions.size(), 1u) << "a click elsewhere drops it"; // The canvas has the focus from that click, so Escape comes to it. - StartTransition(view, NodeIndex(view, patrol)); + nodes::StartTransition(view, nodes::NodeIndex(view, patrol)); Key(KeyCode::Escape); EXPECT_FALSE(view.transitionPicking) << "Escape drops it"; EXPECT_EQ(view.transitions.size(), 1u); @@ -235,9 +237,9 @@ namespace tachyon // A state shows no fields: properties stay out of a state machine. TEST_F(NodeViewStateMachineTest, StatesShowNoFields) { - view.nodes[0].properties.push_back(NodeProperty{ .input = PropertyEndpoint{}, .output = true }); + view.nodes[0].properties.push_back(nodes::NodeProperty{ .input = nodes::PropertyEndpoint{}, .output = true }); Settle(); - EXPECT_EQ(CountWithStyle(app.theme.nodeSocketStyleRef), 0); + EXPECT_EQ(CountWithStyle(nodes::GetStyles(app, nodesContext).nodeSocketStyleRef), 0); } // A drag from the band round a state onto another state adds a transition; onto itself, @@ -316,7 +318,7 @@ namespace tachyon { const ID t = Transition(sleep, patrol, "noise"); Settle(); - const IntRect before = app.GetElementRect(NodeElementID(view, sleep)); + const IntRect before = app.GetElementRect(nodes::NodeElementID(view, sleep)); ASSERT_EQ(view.transitionLabelBoxes.size(), 1u); const IntRect chip = view.transitionLabelBoxes[0].second; Single(); @@ -327,12 +329,12 @@ namespace tachyon app.ClickAt(PathMiddle(t)); Settle(); ASSERT_EQ(view.renamingTransition, std::optional{ t }); - EXPECT_EQ(app.GetElementRect(NodeElementID(view, sleep)), before) << "the field taking the focus scrolls nothing"; + EXPECT_EQ(app.GetElementRect(nodes::NodeElementID(view, sleep)), before) << "the field taking the focus scrolls nothing"; int fields = 0; for (uint32_t d = 0; d < app.elementStorage.NumberOfDepthLevels(); d++) for (uint32_t i = 0; i < app.elementStorage.DepthSizeOf(d); i++) if (const ElementRef ref{ d, i }; app.elementStorage.IsValidRef(ref) - && app.elementStorage.GetElementUnsafe(ref).styleRef == app.theme.nodeTransitionRenameStyleRef) + && app.elementStorage.GetElementUnsafe(ref).styleRef == nodes::GetStyles(app, nodesContext).nodeTransitionRenameStyleRef) { ++fields; EXPECT_EQ(app.elementStorage.GetElementRectUnsafe(ref).rect, chip) << "the field is where the label was"; @@ -346,7 +348,7 @@ namespace tachyon Settle(); EXPECT_FALSE(view.renamingTransition); EXPECT_EQ(view.transitions[0].label, "noise heard"); - EXPECT_EQ(app.GetElementRect(NodeElementID(view, sleep)), before) << "the states stay where their arrows are"; + EXPECT_EQ(app.GetElementRect(nodes::NodeElementID(view, sleep)), before) << "the states stay where their arrows are"; ASSERT_EQ(edits.size(), 1u); ASSERT_EQ(edits[0].transitionChanges.size(), 1u); EXPECT_EQ(edits[0].transitionChanges[0].from.label, "noise"); @@ -361,20 +363,20 @@ namespace tachyon ASSERT_EQ(view.transitions.size(), 1u); const ID t = view.transitions[0].stableID; Settle(); - const IntRect before = app.GetElementRect(NodeElementID(view, sleep)); - RenameTransition(view, 0); + const IntRect before = app.GetElementRect(nodes::NodeElementID(view, sleep)); + nodes::RenameTransition(view, 0); Settle(); ASSERT_EQ(view.renamingTransition, std::optional{ t }); for (const char* text : { "h", "i", "t", " by the player" }) { app.InjectText(text); Frame(); - EXPECT_EQ(app.GetElementRect(NodeElementID(view, sleep)), before) << "after typing \"" << text << "\""; + EXPECT_EQ(app.GetElementRect(nodes::NodeElementID(view, sleep)), before) << "after typing \"" << text << "\""; } Key(KeyCode::Return); Settle(); EXPECT_EQ(view.transitions[0].label, "hit by the player"); - EXPECT_EQ(app.GetElementRect(NodeElementID(view, sleep)), before); + EXPECT_EQ(app.GetElementRect(nodes::NodeElementID(view, sleep)), before); } // The canvas never scrolls: its nodes go where its pan and zoom put them, as its arrows @@ -382,18 +384,18 @@ namespace tachyon TEST_F(NodeViewStateMachineTest, TheCanvasNeverScrolls) { Settle(); - const IntRect before = app.GetElementRect(NodeElementID(view, sleep)); + const IntRect before = app.GetElementRect(nodes::NodeElementID(view, sleep)); ID canvas = ID::Invalid(); for (uint32_t d = 0; d < app.elementStorage.NumberOfDepthLevels() && canvas == ID::Invalid(); d++) for (uint32_t i = 0; i < app.elementStorage.DepthSizeOf(d); i++) if (const ElementRef ref{ d, i }; app.elementStorage.IsValidRef(ref) - && app.elementStorage.GetElementUnsafe(ref).styleRef == app.theme.nodeViewStyleRef) + && app.elementStorage.GetElementUnsafe(ref).styleRef == nodes::GetStyles(app, nodesContext).nodeViewStyleRef) canvas = app.elementStorage.GetElementUnsafe(ref).id; ASSERT_NE(canvas, ID::Invalid()); auto& scrolling = app.guiStateManager.GetScrollManagement(); scrolling.SetScrollOffset(scrolling.GetOrCreateScrollOffsetHandle(canvas), int2{ -180, -15 }); Frame(); - EXPECT_EQ(app.GetElementRect(NodeElementID(view, sleep)), before); + EXPECT_EQ(app.GetElementRect(nodes::NodeElementID(view, sleep)), before); EXPECT_EQ(scrolling.GetScrollOffset(scrolling.GetOrCreateScrollOffsetHandle(canvas)), (int2{ 0, 0 })); } @@ -403,10 +405,10 @@ namespace tachyon const ID t = Transition(sleep, chase); Settle(); view.selectedTransitionIDs = { t }; - NodeView expected = view; - const int both[] = { NodeIndex(view, sleep), NodeIndex(view, chase) }; - FrameNodes(expected, both); - FrameSelectedNodes(view); + nodes::NodeView expected = view; + const int both[] = { nodes::NodeIndex(view, sleep), nodes::NodeIndex(view, chase) }; + nodes::FrameNodes(expected, both); + nodes::FrameSelectedNodes(view); EXPECT_EQ(view.transform.TransformPoint({ 0.0f, 0.0f }), expected.transform.TransformPoint({ 0.0f, 0.0f })); EXPECT_EQ(view.transform.TransformPoint({ 100.0f, 0.0f }), expected.transform.TransformPoint({ 100.0f, 0.0f })); } @@ -422,16 +424,16 @@ namespace tachyon const IntRect chip = view.transitionLabelBoxes[0].second; const int2 onB = Screen({ float(chip.x + chip.w / 2), float(chip.y + chip.h / 2) }); - RenameTransition(view, TransitionIndex(view, a)); + nodes::RenameTransition(view, nodes::TransitionIndex(view, a)); Settle(); app.InjectText("noise"); Frame(); Click(onB); EXPECT_FALSE(view.renamingTransition); - EXPECT_EQ(view.transitions[size_t(TransitionIndex(view, a))].label, "noise"); - EXPECT_EQ(view.transitions[size_t(TransitionIndex(view, b))].label, "sees player"); + EXPECT_EQ(view.transitions[size_t(nodes::TransitionIndex(view, a))].label, "noise"); + EXPECT_EQ(view.transitions[size_t(nodes::TransitionIndex(view, b))].label, "sees player"); - RenameTransition(view, TransitionIndex(view, a)); + nodes::RenameTransition(view, nodes::TransitionIndex(view, a)); Settle(); app.InjectKey(KeyCode::End, KeyAction::KeyDown); Frame(); @@ -444,8 +446,8 @@ namespace tachyon Frame(); app.ClickAt(onB); Settle(); - EXPECT_EQ(view.transitions[size_t(TransitionIndex(view, a))].label, "noise heard") << "the first keeps what was typed"; - EXPECT_EQ(view.transitions[size_t(TransitionIndex(view, b))].label, "sees player"); + EXPECT_EQ(view.transitions[size_t(nodes::TransitionIndex(view, a))].label, "noise heard") << "the first keeps what was typed"; + EXPECT_EQ(view.transitions[size_t(nodes::TransitionIndex(view, b))].label, "sees player"); EXPECT_EQ(view.renamingTransition, std::optional{ b }); EXPECT_EQ(view.renameText, "sees player") << "the second starts from its own"; } @@ -456,14 +458,14 @@ namespace tachyon { const ID a = Transition(sleep, patrol); Settle(); - RenameTransition(view, TransitionIndex(view, a)); + nodes::RenameTransition(view, nodes::TransitionIndex(view, a)); Settle(); app.InjectText("noise"); Frame(); Click(Centre(chase)); Settle(); EXPECT_FALSE(view.renamingTransition) << "the field closes"; - EXPECT_EQ(view.transitions[size_t(TransitionIndex(view, a))].label, "noise"); + EXPECT_EQ(view.transitions[size_t(nodes::TransitionIndex(view, a))].label, "noise"); EXPECT_EQ(State(chase).title, "Chase"); EXPECT_EQ(State(sleep).title, "Sleep"); } @@ -499,15 +501,15 @@ namespace tachyon Transition(patrol, sleep); const ID kept = Transition(sleep, chase); view.initialState = patrol; - const std::vector before = view.transitions; + const std::vector before = view.transitions; const int only[] = { 1 }; - const NodeViewEdit edit = RemoveNodesEdit(view, only); - ApplyNodeViewEdit(view, edit); + const nodes::NodeViewEdit edit = nodes::RemoveNodesEdit(view, only); + nodes::ApplyNodeViewEdit(view, edit); ASSERT_EQ(view.transitions.size(), 1u); EXPECT_EQ(view.transitions[0].stableID, kept); EXPECT_EQ(view.initialState, ID::Invalid()); - ApplyNodeViewEdit(view, edit, /*undo*/ true); + nodes::ApplyNodeViewEdit(view, edit, /*undo*/ true); EXPECT_EQ(view.transitions, before); EXPECT_EQ(view.initialState, patrol); } @@ -518,24 +520,24 @@ namespace tachyon const ID a = Transition(sleep, patrol); const ID b = Transition(patrol, chase); const ID both[] = { a, b }; - const NodeViewEdit removed = RemoveTransitionsEdit(view, both); - ApplyNodeViewEdit(view, removed); + const nodes::NodeViewEdit removed = nodes::RemoveTransitionsEdit(view, both); + nodes::ApplyNodeViewEdit(view, removed); EXPECT_TRUE(view.transitions.empty()); - ApplyNodeViewEdit(view, removed, /*undo*/ true); + nodes::ApplyNodeViewEdit(view, removed, /*undo*/ true); ASSERT_EQ(view.transitions.size(), 2u); EXPECT_EQ(view.transitions[0].stableID, a); - const NodeViewEdit initial = SetInitialStateEdit(view, sleep); - ApplyNodeViewEdit(view, initial); + const nodes::NodeViewEdit initial = nodes::SetInitialStateEdit(view, sleep); + nodes::ApplyNodeViewEdit(view, initial); EXPECT_EQ(view.initialState, sleep); - EXPECT_TRUE(SetInitialStateEdit(view, sleep).empty()); - ApplyNodeViewEdit(view, initial, /*undo*/ true); + EXPECT_TRUE(nodes::SetInitialStateEdit(view, sleep).empty()); + nodes::ApplyNodeViewEdit(view, initial, /*undo*/ true); EXPECT_EQ(view.initialState, ID::Invalid()); - const NodeViewEdit added = AddTransitionEdit(view, StateTransition{ .stableID = app.idManager.CreateStaticID(), .from = chase, .to = sleep }, 0); - ApplyNodeViewEdit(view, added); + const nodes::NodeViewEdit added = nodes::AddTransitionEdit(view, nodes::StateTransition{ .stableID = app.idManager.CreateStaticID(), .from = chase, .to = sleep }, 0); + nodes::ApplyNodeViewEdit(view, added); EXPECT_EQ(view.transitions[0].from, chase); - ApplyNodeViewEdit(view, added, /*undo*/ true); + nodes::ApplyNodeViewEdit(view, added, /*undo*/ true); EXPECT_EQ(view.transitions[0].stableID, a); } @@ -546,15 +548,15 @@ namespace tachyon const ID self = Transition(chase, chase); Settle(); const int32_t gap = app.styleManager.Px(6), loop = app.styleManager.Px(24); - const TransitionPath p = StateTransitionPath(view, view.transitions[0], gap, loop); + const nodes::TransitionPath p = nodes::StateTransitionPath(view, view.transitions[0], gap, loop); const float2 mid{ float(p.from.x + p.to.x) / 2.0f, float(p.from.y + p.to.y) / 2.0f + 3.0f }; - EXPECT_EQ(TransitionAt(view, mid, 5.0f, gap, loop), std::optional{ t }); - const TransitionPath l = StateTransitionPath(view, view.transitions[1], gap, loop); - EXPECT_EQ(TransitionAt(view, float2{ float(l.labelAt.x), float(l.labelAt.y) + 2.0f }, 6.0f, gap, loop), + EXPECT_EQ(nodes::TransitionAt(view, mid, 5.0f, gap, loop), std::optional{ t }); + const nodes::TransitionPath l = nodes::StateTransitionPath(view, view.transitions[1], gap, loop); + EXPECT_EQ(nodes::TransitionAt(view, float2{ float(l.labelAt.x), float(l.labelAt.y) + 2.0f }, 6.0f, gap, loop), std::optional{ self }) << "at its top, which it reaches as drawn"; - EXPECT_FALSE(TransitionAt(view, float2{ float(l.labelAt.x), float(l.labelAt.y) + float(loop) * 0.5f }, 6.0f, gap, loop)) + EXPECT_FALSE(nodes::TransitionAt(view, float2{ float(l.labelAt.x), float(l.labelAt.y) + float(loop) * 0.5f }, 6.0f, gap, loop)) << "under its top, inside the loop"; - EXPECT_FALSE(TransitionAt(view, float2{ 900.0f, 900.0f }, 5.0f, gap, loop)); + EXPECT_FALSE(nodes::TransitionAt(view, float2{ 900.0f, 900.0f }, 5.0f, gap, loop)); } // A state holding a machine of its own has its mark in its title bar, at the end, after @@ -568,11 +570,11 @@ namespace tachyon for (uint32_t i = 0; i < app.elementStorage.DepthSizeOf(d); i++) { const ElementRef ref{ d, i }; - if (app.elementStorage.IsValidRef(ref) && app.elementStorage.GetElementUnsafe(ref).styleRef == app.theme.nodeStateNestedMarkStyleRef) + if (app.elementStorage.IsValidRef(ref) && app.elementStorage.GetElementUnsafe(ref).styleRef == nodes::GetStyles(app, nodesContext).nodeStateNestedMarkStyleRef) marks.push_back(app.elementStorage.GetElementRectUnsafe(ref).rect); } ASSERT_EQ(marks.size(), 1u) << "Patrol's only"; - const IntRect state = app.GetElementRect(NodeElementID(view, patrol)); + const IntRect state = app.GetElementRect(nodes::NodeElementID(view, patrol)); const IntRect name = app.GetElementRect(app.FindByText("Patrol")); EXPECT_GT(marks[0].w, 0); EXPECT_GE(marks[0].x, name.x + name.w) << "after its name"; diff --git a/tests/node_view_stress_test.cpp b/tests/node_view_stress_test.cpp index 3823448b..e6208fa0 100644 --- a/tests/node_view_stress_test.cpp +++ b/tests/node_view_stress_test.cpp @@ -6,7 +6,8 @@ #include "headless_gui_app.h" -#include +#include +#include #include #include @@ -17,24 +18,24 @@ namespace tachyon namespace { - NodeModel MakeNode(HeadlessGUIApp& app, int2 pos, int inputs, int outputs) + nodes::NodeModel MakeNode(HeadlessGUIApp& app, int2 pos, int inputs, int outputs) { - NodeModel node{}; + nodes::NodeModel node{}; node.stableID = app.idManager.CreateStaticID(); node.title = "N"; node.pos = pos; for (int i = 0; i < std::max(inputs, outputs); ++i) - node.properties.push_back(NodeProperty{ - .input = i < inputs ? std::optional(PropertyEndpoint{}) : std::nullopt, + node.properties.push_back(nodes::NodeProperty{ + .input = i < inputs ? std::optional(nodes::PropertyEndpoint{}) : std::nullopt, .output = i < outputs }); return node; } // Every wire names a node and row that are there, and an input on that row. - void ExpectSound(const NodeView& view) + void ExpectSound(const nodes::NodeView& view) { - for (const NodeModel& node : view.nodes) - for (const NodeProperty& prop : node.properties) + for (const nodes::NodeModel& node : view.nodes) + for (const nodes::NodeProperty& prop : node.properties) if (prop.input && prop.input->valid()) { ASSERT_LT(prop.input->nodeIdx, (int)view.nodes.size()); @@ -50,25 +51,26 @@ namespace tachyon for (uint32_t seed = 1; seed <= 12; ++seed) { HeadlessGUIApp app; + nodes::Context nodesContext; ASSERT_TRUE(app.Initialize()); app.runPostLayoutCallbacks = (seed % 2) == 0; - NodeView view; + nodes::NodeView view; view.transform = float3x2::Scale(1.0f); view.nodes.push_back(MakeNode(app, { 40, 40 }, 0, 2)); view.nodes.push_back(MakeNode(app, { 360, 60 }, 2, 1)); view.nodes.push_back(MakeNode(app, { 680, 120 }, 2, 0)); view.nodes.push_back(MakeNode(app, { 360, 360 }, 1, 1)); - view.nodes[1].properties[0].input = PropertyEndpoint{ 0, 0 }; - view.nodes[2].properties[0].input = PropertyEndpoint{ 1, 0 }; - view.nodes[3].properties[0].input = PropertyEndpoint{ 0, 1 }; + view.nodes[1].properties[0].input = nodes::PropertyEndpoint{ 0, 0 }; + view.nodes[2].properties[0].input = nodes::PropertyEndpoint{ 1, 0 }; + view.nodes[3].properties[0].input = nodes::PropertyEndpoint{ 0, 1 }; // The host's history: done edits, and undone ones to redo. - std::vector done, undone; - view.onEdit = [&](const NodeViewEdit& edit) { done.push_back(edit); undone.clear(); }; - view.onWireDroppedOnCanvas = [&](PropertyEndpoint, bool, float2 at) { - NodeModel r = MakeNode(app, { int32_t(at.x), int32_t(at.y) }, 1, 1); + std::vector done, undone; + view.onEdit = [&](const nodes::NodeViewEdit& edit) { done.push_back(edit); undone.clear(); }; + view.onWireDroppedOnCanvas = [&](nodes::PropertyEndpoint, bool, float2 at) { + nodes::NodeModel r = MakeNode(app, { int32_t(at.x), int32_t(at.y) }, 1, 1); r.reroute = true; - CommitNodeViewEdit(view, AddNodeEdit(view, std::move(r))); + nodes::CommitNodeViewEdit(view, nodes::AddNodeEdit(view, std::move(r))); }; view.onCanvasContextMenu = [&](float2) { app.MenuItem("Item", [] {}); }; view.onNodeContextMenu = [&](int) { app.MenuItem("Item", [] {}); }; @@ -76,7 +78,7 @@ namespace tachyon auto frame = [&] { app.Frame([&] { app.BeginRootWindow({ 1280, 800 }, ElementFlags::None, app.theme.mainWindowStyleRef); - app.RenderNodeView(view); + nodes::RenderNodeView(app, nodesContext, view); app.EndRootWindow(); }); }; @@ -126,9 +128,9 @@ namespace tachyon for (int n = 0; n < (int)view.nodes.size(); ++n) for (int p = 0; p < (int)view.nodes[size_t(n)].properties.size(); ++p) if (const auto& in = view.nodes[size_t(n)].properties[size_t(p)].input; in && in->valid()) - wires.push_back(WireKey(n, p)); + wires.push_back(nodes::WireKey(n, p)); if (!wires.empty()) - CommitNodeViewEdit(view, RerouteWireEdit(view, wires[size_t(pick((int)wires.size()))], + nodes::CommitNodeViewEdit(view, nodes::RerouteWireEdit(view, wires[size_t(pick((int)wires.size()))], app.idManager.CreateStaticID(), point())); break; } @@ -138,13 +140,13 @@ namespace tachyon for (int n = 0; n < (int)view.nodes.size(); ++n) if (pick(3) == 0) some.push_back(n); if (view.nodes.size() > 2) - CommitNodeViewEdit(view, RemoveNodesEdit(view, some)); + nodes::CommitNodeViewEdit(view, nodes::RemoveNodesEdit(view, some)); break; } case 7: if (!done.empty()) { - ApplyNodeViewEdit(view, done.back(), /*undo*/ true); + nodes::ApplyNodeViewEdit(view, done.back(), /*undo*/ true); undone.push_back(done.back()); done.pop_back(); } @@ -152,7 +154,7 @@ namespace tachyon case 8: if (!undone.empty()) { - ApplyNodeViewEdit(view, undone.back()); + nodes::ApplyNodeViewEdit(view, undone.back()); done.push_back(undone.back()); undone.pop_back(); } diff --git a/tests/node_view_two_views_test.cpp b/tests/node_view_two_views_test.cpp index bb5b3aa1..358f2cb0 100644 --- a/tests/node_view_two_views_test.cpp +++ b/tests/node_view_two_views_test.cpp @@ -1,4 +1,4 @@ -// One graph shown in two places: a NodeGraph and a NodeViewState for each view of it +// One graph shown in two places: a nodes::NodeGraph and a nodes::NodeViewState for each view of it // (RenderNodeView({ graph, state })). Each view pans, zooms and selects on its own; an edit // made in one shows in both. @@ -7,7 +7,8 @@ #include "headless_gui_app.h" #include "misuse_reports.h" -#include +#include +#include namespace tachyon { @@ -19,8 +20,9 @@ namespace tachyon { protected: HeadlessGUIApp app; - NodeGraph graph; - NodeViewState left, right; + nodes::Context nodesContext; + nodes::NodeGraph graph; + nodes::NodeViewState left, right; ID nodeA{}, nodeB{}; void SetUp() override @@ -29,8 +31,8 @@ namespace tachyon nodeA = app.idManager.CreateStaticID(); nodeB = app.idManager.CreateStaticID(); graph.nodes = { - NodeModel{ .stableID = nodeA, .title = "A", .pos = { 40, 40 }, .properties = { NodeProperty{ .output = true } } }, - NodeModel{ .stableID = nodeB, .title = "B", .pos = { 320, 160 }, .properties = { NodeProperty{ .input = PropertyEndpoint{} } } }, + nodes::NodeModel{ .stableID = nodeA, .title = "A", .pos = { 40, 40 }, .properties = { nodes::NodeProperty{ .output = true } } }, + nodes::NodeModel{ .stableID = nodeB, .title = "B", .pos = { 320, 160 }, .properties = { nodes::NodeProperty{ .input = nodes::PropertyEndpoint{} } } }, }; } @@ -43,16 +45,16 @@ namespace tachyon app.BeginRootWindow({ 1600, 800 }, ElementFlags::None, app.theme.mainWindowStyleRef); app.BeginHorizontal(app.idManager.AllocateDynamicID("views"), app.theme.flexFillRowStyleRef, LayoutOverride::Auto().FlexGrow(1)); - app.RenderNodeView({ graph, left }); - app.RenderNodeView({ graph, right }); + nodes::RenderNodeView(app, nodesContext, { graph, left }); + nodes::RenderNodeView(app, nodesContext, { graph, right }); app.EndHorizontal(); app.EndRootWindow(); }); } void Settle() { Frame(); Frame(); } - IntRect NodeRect(const NodeViewState& view, ID node) const { return app.GetElementRect(NodeElementID(view, node)); } - int2 Header(const NodeViewState& view, ID node) const + IntRect NodeRect(const nodes::NodeViewState& view, ID node) const { return app.GetElementRect(nodes::NodeElementID(view, node)); } + int2 Header(const nodes::NodeViewState& view, ID node) const { const IntRect r = NodeRect(view, node); return { r.x + r.w / 2, r.y + 6 }; @@ -81,10 +83,10 @@ namespace tachyon { Settle(); const float3x2 rightBefore = right.transform; - ZoomNodeView({ graph, left }, 2.0f); + nodes::ZoomNodeView({ graph, left }, 2.0f); Settle(); - EXPECT_FLOAT_EQ(NodeViewZoom({ graph, left }), 2.0f); - EXPECT_FLOAT_EQ(NodeViewZoom({ graph, right }), 1.0f); + EXPECT_FLOAT_EQ(nodes::NodeViewZoom({ graph, left }), 2.0f); + EXPECT_FLOAT_EQ(nodes::NodeViewZoom({ graph, right }), 1.0f); EXPECT_EQ(right.transform.r0, rightBefore.r0) << "the other view's pan and zoom as they were"; EXPECT_EQ(right.transform.r1, rightBefore.r1); } @@ -148,7 +150,7 @@ namespace tachyon ASSERT_EQ(rightChanges, 1); const int b = 1; - ApplyNodeViewEdit({ graph, left }, RemoveNodesEdit({ graph, left }, std::span(&b, 1))); + nodes::ApplyNodeViewEdit({ graph, left }, nodes::RemoveNodesEdit({ graph, left }, std::span(&b, 1))); Settle(); ASSERT_EQ(graph.nodes.size(), 1u); EXPECT_TRUE(right.selectedNodeIDs.empty()) << "nothing left of it to select"; diff --git a/tests/node_view_wire_edit_test.cpp b/tests/node_view_wire_edit_test.cpp index 2f57bd87..5fc25a95 100644 --- a/tests/node_view_wire_edit_test.cpp +++ b/tests/node_view_wire_edit_test.cpp @@ -3,7 +3,8 @@ #include -#include +#include +#include #include @@ -11,47 +12,47 @@ namespace { using namespace tachyon; - const std::vector kWires{ - { .wireKey = WireKey(1, 0), .points = { { 0, 0 }, { 100, 0 }, { 100, 100 } } }, - { .wireKey = WireKey(2, 3), .points = { { 0, 20 }, { 60, 20 }, { 60, 100 } } }, + const std::vector kWires{ + { .wireKey = nodes::WireKey(1, 0), .points = { { 0, 0 }, { 100, 0 }, { 100, 100 } } }, + { .wireKey = nodes::WireKey(2, 3), .points = { { 0, 20 }, { 60, 20 }, { 60, 100 } } }, }; TEST(NodeViewWireEdit, WireAtFindsTheWireUnderThePoint) { - EXPECT_EQ(WireAt(kWires, { 50, 2 }, 5.0f), WireKey(1, 0)) << "near a horizontal run"; - EXPECT_EQ(WireAt(kWires, { 103, 60 }, 5.0f), WireKey(1, 0)) << "near a vertical run"; - EXPECT_EQ(WireAt(kWires, { 30, 18 }, 5.0f), WireKey(2, 3)); + EXPECT_EQ(nodes::WireAt(kWires, { 50, 2 }, 5.0f), nodes::WireKey(1, 0)) << "near a horizontal run"; + EXPECT_EQ(nodes::WireAt(kWires, { 103, 60 }, 5.0f), nodes::WireKey(1, 0)) << "near a vertical run"; + EXPECT_EQ(nodes::WireAt(kWires, { 30, 18 }, 5.0f), nodes::WireKey(2, 3)); } TEST(NodeViewWireEdit, WireAtTakesTheClosest) { - EXPECT_EQ(WireAt(kWires, { 30, 8 }, 20.0f), WireKey(1, 0)); - EXPECT_EQ(WireAt(kWires, { 30, 13 }, 20.0f), WireKey(2, 3)); + EXPECT_EQ(nodes::WireAt(kWires, { 30, 8 }, 20.0f), nodes::WireKey(1, 0)); + EXPECT_EQ(nodes::WireAt(kWires, { 30, 13 }, 20.0f), nodes::WireKey(2, 3)); } TEST(NodeViewWireEdit, WireAtFindsNothingFarAway) { - EXPECT_FALSE(WireAt(kWires, { 30, 60 }, 5.0f).has_value()); - EXPECT_FALSE(WireAt(kWires, { 108, 0 }, 5.0f).has_value()) << "past the end of a run"; - EXPECT_FALSE(WireAt({}, { 0, 0 }, 5.0f).has_value()); + EXPECT_FALSE(nodes::WireAt(kWires, { 30, 60 }, 5.0f).has_value()); + EXPECT_FALSE(nodes::WireAt(kWires, { 108, 0 }, 5.0f).has_value()) << "past the end of a run"; + EXPECT_FALSE(nodes::WireAt({}, { 0, 0 }, 5.0f).has_value()); } // A curved wire is hit along the curve it's drawn as, not along its control points. TEST(NodeViewWireEdit, WireAtFollowsACurvedWire) { - const DrawnWire curve{ .wireKey = WireKey(1, 0), .points = { { 0, 0 }, { 100, 0 }, { 100, 100 }, { 200, 100 } }, .curved = true }; - const std::vector wires{ curve }; + const nodes::DrawnWire curve{ .wireKey = nodes::WireKey(1, 0), .points = { { 0, 0 }, { 100, 0 }, { 100, 100 }, { 200, 100 } }, .curved = true }; + const std::vector wires{ curve }; for (const float t : { 0.1f, 0.3f, 0.5f, 0.7f, 0.9f }) { - const float2 p = WireCurvePoint(curve.points[0], curve.points[1], curve.points[2], curve.points[3], t); - EXPECT_EQ(WireAt(wires, { int(std::lround(p.x)), int(std::lround(p.y)) }, 3.0f), WireKey(1, 0)) << t; + const float2 p = nodes::WireCurvePoint(curve.points[0], curve.points[1], curve.points[2], curve.points[3], t); + EXPECT_EQ(nodes::WireAt(wires, { int(std::lround(p.x)), int(std::lround(p.y)) }, 3.0f), nodes::WireKey(1, 0)) << t; } - EXPECT_FALSE(WireAt(wires, { 100, 0 }, 3.0f).has_value()) << "a control point, off the curve"; - EXPECT_FALSE(WireAt(wires, { 130, 100 }, 3.0f).has_value()) << "on the control lines, off the curve"; + EXPECT_FALSE(nodes::WireAt(wires, { 100, 0 }, 3.0f).has_value()) << "a control point, off the curve"; + EXPECT_FALSE(nodes::WireAt(wires, { 130, 100 }, 3.0f).has_value()) << "on the control lines, off the curve"; - DrawnWire straight = curve; + nodes::DrawnWire straight = curve; straight.curved = false; - EXPECT_EQ(WireAt(std::vector{ straight }, { 100, 0 }, 3.0f), WireKey(1, 0)) << "as a polyline"; + EXPECT_EQ(nodes::WireAt(std::vector{ straight }, { 100, 0 }, 3.0f), nodes::WireKey(1, 0)) << "as a polyline"; } // The curve the renderer draws for four points: two quadratics meeting halfway between @@ -60,7 +61,7 @@ namespace { const int2 p0{ 0, 0 }, p1{ 100, 0 }, p2{ 60, 80 }, p3{ 200, 100 }; auto at = [&](float t, float x, float y) { - const float2 p = WireCurvePoint(p0, p1, p2, p3, t); + const float2 p = nodes::WireCurvePoint(p0, p1, p2, p3, t); EXPECT_NEAR(p.x, x, 1e-3f) << t; EXPECT_NEAR(p.y, y, 1e-3f) << t; }; @@ -75,37 +76,37 @@ namespace // the distance across, or `reach` when that's further, as when the input is behind. TEST(NodeViewWireEdit, ACurvedRouteReachesOutLevel) { - const WireRoute route = BuildCurvedWireRoute({ 0, 0 }, { 400, 100 }, 48); + const nodes::WireRoute route = nodes::BuildCurvedWireRoute({ 0, 0 }, { 400, 100 }, 48); EXPECT_TRUE(route.curved); EXPECT_TRUE(route.handles.empty()); EXPECT_EQ(route.points, (std::vector{ { 0, 0 }, { 200, 0 }, { 200, 100 }, { 400, 100 } })); - EXPECT_EQ(BuildCurvedWireRoute({ 0, 0 }, { 40, 100 }, 48).points, + EXPECT_EQ(nodes::BuildCurvedWireRoute({ 0, 0 }, { 40, 100 }, 48).points, (std::vector{ { 0, 0 }, { 48, 0 }, { -8, 100 }, { 40, 100 } })) << "close: at least reach"; - EXPECT_EQ(BuildCurvedWireRoute({ 0, 0 }, { -200, 100 }, 48).points, + EXPECT_EQ(nodes::BuildCurvedWireRoute({ 0, 0 }, { -200, 100 }, 48).points, (std::vector{ { 0, 0 }, { 100, 0 }, { -300, 100 }, { -200, 100 } })) << "behind: loops round"; } TEST(NodeViewWireEdit, WireInputUndoesWireKey) { - EXPECT_EQ(WireInput(WireKey(7, 12)), (PropertyEndpoint{ 7, 12 })); + EXPECT_EQ(nodes::WireInput(nodes::WireKey(7, 12)), (nodes::PropertyEndpoint{ 7, 12 })); } TEST(NodeViewWireEdit, DisconnectRemovesTheWireAndItsLanes) { - NodeView view; + nodes::NodeView view; view.nodes.resize(2); view.nodes[0].properties.resize(1); view.nodes[0].properties[0].output = true; view.nodes[1].properties.resize(1); - view.nodes[1].properties[0].input = PropertyEndpoint{ 0, 0 }; - view.wireOverrides[WireKey(1, 0)].laneX = 120; + view.nodes[1].properties[0].input = nodes::PropertyEndpoint{ 0, 0 }; + view.wireOverrides[nodes::WireKey(1, 0)].laneX = 120; - ApplyNodeViewEdit(view, DisconnectEdit(view, { 1, 0 })); + nodes::ApplyNodeViewEdit(view, nodes::DisconnectEdit(view, { 1, 0 })); ASSERT_TRUE(view.nodes[1].properties[0].input.has_value()) << "the socket stays"; EXPECT_FALSE(view.nodes[1].properties[0].input->valid()); - EXPECT_EQ(view.wireOverrides.count(WireKey(1, 0)), 0u); + EXPECT_EQ(view.wireOverrides.count(nodes::WireKey(1, 0)), 0u); - EXPECT_TRUE(DisconnectEdit(view, { 5, 0 }).empty()) << "out of range: nothing to do"; + EXPECT_TRUE(nodes::DisconnectEdit(view, { 5, 0 }).empty()) << "out of range: nothing to do"; } } diff --git a/tests/node_view_wire_route_test.cpp b/tests/node_view_wire_route_test.cpp index 309715f9..a5a340a9 100644 --- a/tests/node_view_wire_route_test.cpp +++ b/tests/node_view_wire_route_test.cpp @@ -9,8 +9,9 @@ #include -#include +#include #include +#include #include #include @@ -106,7 +107,7 @@ namespace tachyon const int2 outPt{ src.Max(0) - 6, 40 }; const int2 inPt { tgt.Min(0) + 6, 240 }; - const auto route = BuildWireRoute(outPt, inPt, src, tgt, kGrid, kOrigin).points; + const auto route = nodes::BuildWireRoute(outPt, inPt, src, tgt, kGrid, kOrigin).points; ExpectEndpoints(route, outPt, inPt); ExpectOrthogonal(route); @@ -124,7 +125,7 @@ namespace tachyon const int2 outPt{ src.Max(0) - 6, 30 }; const int2 inPt { tgt.Min(0) + 6, 200 }; - const auto route = BuildWireRoute(outPt, inPt, src, tgt, kGrid, kOrigin).points; + const auto route = nodes::BuildWireRoute(outPt, inPt, src, tgt, kGrid, kOrigin).points; ExpectEndpoints(route, outPt, inPt); ExpectOrthogonal(route); @@ -142,7 +143,7 @@ namespace tachyon const int2 outPt{ src.Max(0) - 6, 40 }; const int2 inPt { tgt.Min(0) + 6, 60 }; - const auto route = BuildWireRoute(outPt, inPt, src, tgt, kGrid, kOrigin).points; + const auto route = nodes::BuildWireRoute(outPt, inPt, src, tgt, kGrid, kOrigin).points; ExpectEndpoints(route, outPt, inPt); ExpectOrthogonal(route); @@ -162,7 +163,7 @@ namespace tachyon const int2 outPt{ src.Max(0) - 6, 40 }; const int2 inPt { tgt.Min(0) + 6, 40 }; // same row - const auto route = BuildWireRoute(outPt, inPt, src, tgt, kGrid, kOrigin).points; + const auto route = nodes::BuildWireRoute(outPt, inPt, src, tgt, kGrid, kOrigin).points; ExpectEndpoints(route, outPt, inPt); ExpectOrthogonal(route); @@ -175,7 +176,7 @@ namespace tachyon { const int2 outPt{ 10, 10 }; const int2 inPt { 90, 70 }; - const auto route = BuildWireRoute(outPt, inPt, IntRect{}, IntRect{ 80, 40, 40, 40 }, kGrid, kOrigin).points; + const auto route = nodes::BuildWireRoute(outPt, inPt, IntRect{}, IntRect{ 80, 40, 40, 40 }, kGrid, kOrigin).points; ASSERT_EQ(route.size(), 2u); ExpectEndpoints(route, outPt, inPt); @@ -185,7 +186,7 @@ namespace tachyon { const int2 outPt{ 10, 10 }; const int2 inPt { 90, 70 }; - const auto route = BuildWireRoute(outPt, inPt, IntRect{ 0, 0, 40, 40 }, IntRect{ 80, 40, 40, 40 }, + const auto route = nodes::BuildWireRoute(outPt, inPt, IntRect{ 0, 0, 40, 40 }, IntRect{ 80, 40, 40, 40 }, /*grid=*/0, kOrigin).points; ASSERT_EQ(route.size(), 2u); @@ -210,7 +211,7 @@ namespace tachyon continue; const int2 inPt{ tgt.Min(0) + 6, tgt.Center().y }; - const auto route = BuildWireRoute(outPt, inPt, src, tgt, kGrid, kOrigin).points; + const auto route = nodes::BuildWireRoute(outPt, inPt, src, tgt, kGrid, kOrigin).points; ExpectEndpoints(route, outPt, inPt); ExpectOrthogonal(route); ExpectClearOfBodies(route, src, tgt); @@ -223,10 +224,10 @@ namespace tachyon { const IntRect src{ 0, 0, 180, 80 }; const IntRect tgt{ 300, 200, 180, 80 }; - const auto route = BuildWireRoute({ src.Max(0) - 6, 40 }, { tgt.Min(0) + 6, 240 }, + const auto route = nodes::BuildWireRoute({ src.Max(0) - 6, 40 }, { tgt.Min(0) + 6, 240 }, src, tgt, kGrid, kOrigin); ASSERT_EQ(route.handles.size(), 1u); - EXPECT_EQ(route.handles[0].role, WireHandle::LaneX); + EXPECT_EQ(route.handles[0].role, nodes::WireHandle::LaneX); EXPECT_TRUE(route.handles[0].vertical); EXPECT_EQ(route.handles[0].a.x, route.handles[0].b.x); // genuinely vertical } @@ -235,12 +236,12 @@ namespace tachyon { const IntRect src{ 0, 0, 180, 80 }; const IntRect tgt{ -300, 20, 180, 80 }; // around-case detour shape - const auto route = BuildWireRoute({ src.Max(0) - 6, 40 }, { tgt.Min(0) + 6, 60 }, + const auto route = nodes::BuildWireRoute({ src.Max(0) - 6, 40 }, { tgt.Min(0) + 6, 60 }, src, tgt, kGrid, kOrigin); ASSERT_EQ(route.handles.size(), 3u); - EXPECT_EQ(route.handles[0].role, WireHandle::ExitX); EXPECT_TRUE (route.handles[0].vertical); - EXPECT_EQ(route.handles[1].role, WireHandle::LaneY); EXPECT_FALSE(route.handles[1].vertical); - EXPECT_EQ(route.handles[2].role, WireHandle::EntryX); EXPECT_TRUE (route.handles[2].vertical); + EXPECT_EQ(route.handles[0].role, nodes::WireHandle::ExitX); EXPECT_TRUE (route.handles[0].vertical); + EXPECT_EQ(route.handles[1].role, nodes::WireHandle::LaneY); EXPECT_FALSE(route.handles[1].vertical); + EXPECT_EQ(route.handles[2].role, nodes::WireHandle::EntryX); EXPECT_TRUE (route.handles[2].vertical); EXPECT_EQ(route.handles[0].a.x, route.handles[0].b.x); // vertical EXPECT_EQ(route.handles[1].a.y, route.handles[1].b.y); // horizontal EXPECT_EQ(route.handles[2].a.x, route.handles[2].b.x); // vertical @@ -254,8 +255,8 @@ namespace tachyon const int2 inPt { tgt.Min(0) + 6, 240 }; // An in-range override snaps to the nearest grid line (250 -> 240 @ grid 20). - WireRouteOverrides ov; ov.laneX = 250; - const auto r1 = BuildWireRoute(outPt, inPt, src, tgt, kGrid, kOrigin, ov); + nodes::WireRouteOverrides ov; ov.laneX = 250; + const auto r1 = nodes::BuildWireRoute(outPt, inPt, src, tgt, kGrid, kOrigin, ov); ASSERT_EQ(r1.handles.size(), 1u); EXPECT_EQ(r1.handles[0].a.x, 240); EXPECT_EQ(r1.handles[0].a.x % kGrid, 0) << "dragged lane must land on a grid line"; @@ -263,7 +264,7 @@ namespace tachyon // Out-of-range override (deep inside the source) clamps into the // corridor, stays on the grid, and the wire still clears both bodies. ov.laneX = -1000; - const auto r2 = BuildWireRoute(outPt, inPt, src, tgt, kGrid, kOrigin, ov); + const auto r2 = nodes::BuildWireRoute(outPt, inPt, src, tgt, kGrid, kOrigin, ov); ASSERT_EQ(r2.handles.size(), 1u); EXPECT_GE(r2.handles[0].a.x, src.Max(0)); EXPECT_LE(r2.handles[0].a.x, tgt.Min(0)); @@ -281,11 +282,11 @@ namespace tachyon const int2 outPt{ src.Max(0) - 6, 30 }; const int2 inPt { tgt.Min(0) + 6, 200 }; auto laneFor = [&](int32_t y) { - WireRouteOverrides ov; ov.laneY = y; - const auto route = BuildWireRoute(outPt, inPt, src, tgt, kGrid, kOrigin, ov); + nodes::WireRouteOverrides ov; ov.laneY = y; + const auto route = nodes::BuildWireRoute(outPt, inPt, src, tgt, kGrid, kOrigin, ov); ExpectClearOfBodies(route.points, src, tgt); for (const auto& h : route.handles) - if (h.role == WireHandle::LaneY) + if (h.role == nodes::WireHandle::LaneY) return h.a.y; ADD_FAILURE() << "no return lane for " << y; return 0; @@ -306,12 +307,12 @@ namespace tachyon const IntRect src{ 0, 160, 180, 80 }; const int2 outPt{ src.Max(0) - 6, 200 }; const int2 inPt { tgt.Min(0) + 6, 30 }; - WireRouteOverrides ov; ov.laneY = 400; - const auto route = BuildWireRoute(outPt, inPt, src, tgt, kGrid, kOrigin, ov); + nodes::WireRouteOverrides ov; ov.laneY = 400; + const auto route = nodes::BuildWireRoute(outPt, inPt, src, tgt, kGrid, kOrigin, ov); ExpectClearOfBodies(route.points, src, tgt); bool found = false; for (const auto& h : route.handles) - if (h.role == WireHandle::LaneY) + if (h.role == nodes::WireHandle::LaneY) { found = true; EXPECT_EQ(h.a.y, 400) << "below the source, as it was put"; @@ -329,8 +330,8 @@ namespace tachyon const int2 inPt { tgt.Min(0) + 6, 240 }; const int2 cursor{ inPt.x + 20, inPt.y }; - const auto dragged = BuildPendingWireRoute(outPt, src, cursor, inPt, tgt, kGrid, kOrigin).points; - const auto connected = BuildWireRoute(outPt, inPt, src, tgt, kGrid, kOrigin).points; + const auto dragged = nodes::BuildPendingWireRoute(outPt, src, cursor, inPt, tgt, kGrid, kOrigin).points; + const auto connected = nodes::BuildWireRoute(outPt, inPt, src, tgt, kGrid, kOrigin).points; ASSERT_EQ(dragged.size(), connected.size()); for (size_t i = 0; i < dragged.size(); ++i) { @@ -347,13 +348,13 @@ namespace tachyon const int2 outPt { src.Max(0) - 6, 40 }; for (const int2 cursor : { int2{ 600, 200 }, int2{ 100, 300 }, int2{ 300, 40 } }) { - const auto route = BuildPendingWireRoute(outPt, src, cursor, std::nullopt, {}, kGrid, kOrigin).points; + const auto route = nodes::BuildPendingWireRoute(outPt, src, cursor, std::nullopt, {}, kGrid, kOrigin).points; ExpectEndpoints(route, outPt, cursor); ExpectOrthogonal(route); ASSERT_GE(route.size(), 3u); EXPECT_GT(route[1].x, outPt.x) << "leaves the output to the right"; const IntRect atCursor{ cursor.x, cursor.y, 1, 1 }; - const auto expected = BuildWireRoute(outPt, cursor, src, atCursor, kGrid, kOrigin).points; + const auto expected = nodes::BuildWireRoute(outPt, cursor, src, atCursor, kGrid, kOrigin).points; EXPECT_EQ(route.size(), expected.size()); } } @@ -367,14 +368,14 @@ namespace tachyon const IntRect tgt{ 40, 200, 180, 80 }; const int2 outPt{ src.Max(0) - 6, 40 }; const int2 inPt { tgt.Min(0) + 6, 240 }; - WireLane lane; + nodes::WireLane lane; lane.offset = -1; lane.count = 2; - WireRouteOverrides withLane; + nodes::WireRouteOverrides withLane; withLane.lane = lane; - const auto over = BuildPendingWireRouteToInput(inPt, tgt, { 10, 10 }, outPt, src, kGrid, kOrigin, lane).points; - const auto connected = BuildWireRoute(outPt, inPt, src, tgt, kGrid, kOrigin, withLane).points; + const auto over = nodes::BuildPendingWireRouteToInput(inPt, tgt, { 10, 10 }, outPt, src, kGrid, kOrigin, lane).points; + const auto connected = nodes::BuildWireRoute(outPt, inPt, src, tgt, kGrid, kOrigin, withLane).points; ASSERT_EQ(over.size(), connected.size()); for (size_t i = 0; i < over.size(); ++i) { @@ -384,10 +385,10 @@ namespace tachyon for (const int2 cursor : { int2{ -300, 40 }, int2{ 600, 400 }, int2{ 0, 240 } }) { - const auto route = BuildPendingWireRouteToInput(inPt, tgt, cursor, std::nullopt, {}, kGrid, kOrigin, lane).points; + const auto route = nodes::BuildPendingWireRouteToInput(inPt, tgt, cursor, std::nullopt, {}, kGrid, kOrigin, lane).points; ExpectEndpoints(route, cursor, inPt); ExpectOrthogonal(route); - const auto expected = BuildWireRoute(cursor, inPt, IntRect{ cursor.x, cursor.y, 1, 1 }, tgt, kGrid, kOrigin).points; + const auto expected = nodes::BuildWireRoute(cursor, inPt, IntRect{ cursor.x, cursor.y, 1, 1 }, tgt, kGrid, kOrigin).points; ASSERT_EQ(route.size(), expected.size()); for (size_t i = 0; i < route.size(); ++i) EXPECT_EQ(route[i].x, expected[i].x) << i; @@ -403,9 +404,9 @@ namespace tachyon const int2 outPt{ 174, 40 }, inPt{ 306, 40 }; for (const int32_t offset : { 0, -1, 1 }) { - WireRouteOverrides o; + nodes::WireRouteOverrides o; o.lane.offset = offset; - const auto route = BuildWireRoute(outPt, inPt, src, tgt, kGrid, kOrigin, o).points; + const auto route = nodes::BuildWireRoute(outPt, inPt, src, tgt, kGrid, kOrigin, o).points; ASSERT_EQ(route.size(), 2u) << offset; ExpectEndpoints(route, outPt, inPt); } @@ -447,9 +448,9 @@ namespace tachyon std::vector> wires; for (int32_t i = 0; i < count; ++i) { - WireRouteOverrides o; - o.lane = WireLane{ .offset = 0, .index = i, .count = count }; - const auto route = BuildWireRoute({ src.Max(0) - 6, srcRows[size_t(i)] }, { tgt.Min(0) + 6, tgtRows[size_t(i)] }, + nodes::WireRouteOverrides o; + o.lane = nodes::WireLane{ .offset = 0, .index = i, .count = count }; + const auto route = nodes::BuildWireRoute({ src.Max(0) - 6, srcRows[size_t(i)] }, { tgt.Min(0) + 6, tgtRows[size_t(i)] }, src, tgt, kGrid, kOrigin, o); wires.push_back(Segments(route.points)); } diff --git a/tests/node_view_zoom_test.cpp b/tests/node_view_zoom_test.cpp index 1d711cd7..36ff9522 100644 --- a/tests/node_view_zoom_test.cpp +++ b/tests/node_view_zoom_test.cpp @@ -1,22 +1,23 @@ #include -#include +#include +#include namespace { using namespace tachyon; // The canvas point that view position `p` (pixels from the canvas centre) shows. - float2 CanvasAt(const NodeView& view, float2 p) { return view.transform.Inverse().TransformPoint(p); } + float2 CanvasAt(const nodes::NodeView& view, float2 p) { return view.transform.Inverse().TransformPoint(p); } TEST(NodeViewZoom, ZoomsAroundThePivot) { - NodeView view; + nodes::NodeView view; view.transform = float3x2::Scale(0.5f); const int2 pivot{ 40, -30 }; const float2 before = CanvasAt(view, { 40.0f, -30.0f }); - ZoomNodeView(view, 1.25f, pivot); - EXPECT_NEAR(NodeViewZoom(view), 0.625f, 1e-4f); + nodes::ZoomNodeView(view, 1.25f, pivot); + EXPECT_NEAR(nodes::NodeViewZoom(view), 0.625f, 1e-4f); const float2 after = CanvasAt(view, { 40.0f, -30.0f }); EXPECT_NEAR(after.x, before.x, 1e-3f); EXPECT_NEAR(after.y, before.y, 1e-3f); @@ -25,80 +26,80 @@ namespace // Past 100% up to 400%, and down to 10%, by default. TEST(NodeViewZoom, StaysBetweenTenAndFourHundredPercent) { - NodeView view; - ZoomNodeView(view, 1.25f); - EXPECT_NEAR(NodeViewZoom(view), 1.25f, 1e-4f) << "past 100%"; + nodes::NodeView view; + nodes::ZoomNodeView(view, 1.25f); + EXPECT_NEAR(nodes::NodeViewZoom(view), 1.25f, 1e-4f) << "past 100%"; for (int i = 0; i < 40; ++i) - ZoomNodeView(view, 2.0f); - EXPECT_NEAR(NodeViewZoom(view), 4.0f, 1e-4f); + nodes::ZoomNodeView(view, 2.0f); + EXPECT_NEAR(nodes::NodeViewZoom(view), 4.0f, 1e-4f); for (int i = 0; i < 40; ++i) - ZoomNodeView(view, 0.5f); - EXPECT_NEAR(NodeViewZoom(view), 0.1f, 1e-4f); + nodes::ZoomNodeView(view, 0.5f); + EXPECT_NEAR(nodes::NodeViewZoom(view), 0.1f, 1e-4f); } // An app's own range; one set wrong (none, or upside down) is put right. TEST(NodeViewZoom, TheViewsOwnRange) { - NodeView view; + nodes::NodeView view; view.minZoom = 0.5f; view.maxZoom = 2.0f; - for (int i = 0; i < 10; ++i) ZoomNodeView(view, 2.0f); - EXPECT_NEAR(NodeViewZoom(view), 2.0f, 1e-4f); - for (int i = 0; i < 10; ++i) ZoomNodeView(view, 0.5f); - EXPECT_NEAR(NodeViewZoom(view), 0.5f, 1e-4f); - SetNodeViewCenter(view, {}, 8.0f); - EXPECT_NEAR(NodeViewZoom(view), 2.0f, 1e-4f); - SetNodeViewCenter(view, {}, 0.01f); - EXPECT_NEAR(NodeViewZoom(view), 0.5f, 1e-4f); + for (int i = 0; i < 10; ++i) nodes::ZoomNodeView(view, 2.0f); + EXPECT_NEAR(nodes::NodeViewZoom(view), 2.0f, 1e-4f); + for (int i = 0; i < 10; ++i) nodes::ZoomNodeView(view, 0.5f); + EXPECT_NEAR(nodes::NodeViewZoom(view), 0.5f, 1e-4f); + nodes::SetNodeViewCenter(view, {}, 8.0f); + EXPECT_NEAR(nodes::NodeViewZoom(view), 2.0f, 1e-4f); + nodes::SetNodeViewCenter(view, {}, 0.01f); + EXPECT_NEAR(nodes::NodeViewZoom(view), 0.5f, 1e-4f); view.maxZoom = 0.25f; // below the minimum: the minimum - SetNodeViewCenter(view, {}, 3.0f); - EXPECT_NEAR(NodeViewZoom(view), 0.5f, 1e-4f); + nodes::SetNodeViewCenter(view, {}, 3.0f); + EXPECT_NEAR(nodes::NodeViewZoom(view), 0.5f, 1e-4f); view.minZoom = 0.0f; // none: 10% view.maxZoom = 1.0f; - SetNodeViewCenter(view, {}, 0.01f); - EXPECT_NEAR(NodeViewZoom(view), 0.1f, 1e-4f); + nodes::SetNodeViewCenter(view, {}, 0.01f); + EXPECT_NEAR(nodes::NodeViewZoom(view), 0.1f, 1e-4f); view.minZoom = -1.0f; - SetNodeViewCenter(view, {}, 0.01f); - EXPECT_NEAR(NodeViewZoom(view), 0.1f, 1e-4f); + nodes::SetNodeViewCenter(view, {}, 0.01f); + EXPECT_NEAR(nodes::NodeViewZoom(view), 0.1f, 1e-4f); } // Fit doesn't magnify: a small graph shows at 100%; a large one fits. TEST(NodeViewZoom, FitStopsAtAHundredPercent) { - NodeView view; + nodes::NodeView view; view.lastInnerSize = { 1000, 800 }; view.nodes.resize(1); view.nodes[0].lastSize = { 100, 50 }; - FrameAllNodes(view); - EXPECT_NEAR(NodeViewZoom(view), 1.0f, 1e-4f); + nodes::FrameAllNodes(view); + EXPECT_NEAR(nodes::NodeViewZoom(view), 1.0f, 1e-4f); view.nodes[0].lastSize = { 2000, 400 }; // wider than the view - FrameAllNodes(view); - EXPECT_NEAR(NodeViewZoom(view), 1000.0f / 2000.0f * 0.9f, 1e-4f); + nodes::FrameAllNodes(view); + EXPECT_NEAR(nodes::NodeViewZoom(view), 1000.0f / 2000.0f * 0.9f, 1e-4f); view.nodes[0].lastSize = { 400, 1600 }; // taller - FrameAllNodes(view); - EXPECT_NEAR(NodeViewZoom(view), 800.0f / 1600.0f * 0.9f, 1e-4f); + nodes::FrameAllNodes(view); + EXPECT_NEAR(nodes::NodeViewZoom(view), 800.0f / 1600.0f * 0.9f, 1e-4f); } TEST(NodeViewZoom, SetCenterShowsThatPointInTheMiddle) { - NodeView view; - SetNodeViewCenter(view, { 300.0f, -120.0f }, 0.5f); + nodes::NodeView view; + nodes::SetNodeViewCenter(view, { 300.0f, -120.0f }, 0.5f); const float2 middle = CanvasAt(view, { 0.0f, 0.0f }); EXPECT_NEAR(middle.x, 300.0f, 1e-3f); EXPECT_NEAR(middle.y, -120.0f, 1e-3f); - EXPECT_NEAR(NodeViewZoom(view), 0.5f, 1e-4f); + EXPECT_NEAR(nodes::NodeViewZoom(view), 0.5f, 1e-4f); } TEST(NodeViewZoom, FitCentresOnAllNodesAndFitsThem) { - NodeView view; + nodes::NodeView view; view.lastInnerSize = { 400, 300 }; view.nodes.resize(2); view.nodes[0].pos = { 0, 0 }; view.nodes[0].lastSize = { 100, 50 }; view.nodes[1].pos = { 900, 600 }; view.nodes[1].lastSize = { 100, 50 }; - FrameAllNodes(view); + nodes::FrameAllNodes(view); const float2 middle = CanvasAt(view, { 0.0f, 0.0f }); EXPECT_NEAR(middle.x, 500.0f, 1.0f); @@ -115,7 +116,7 @@ namespace // With nodes selected, Fit (and Home) frames those; with none, all of them. TEST(NodeViewZoom, FitFramesTheSelection) { - NodeView view; + nodes::NodeView view; view.lastInnerSize = { 400, 300 }; view.nodes.resize(3); view.nodes[0].stableID = ID{ .value{ .integer = 1 } }; @@ -126,72 +127,72 @@ namespace view.nodes[2].pos = { 1000, 700 }; view.nodes[2].lastSize = { 100, 50 }; view.selectedNodeIDs = { view.nodes[1].stableID, view.nodes[2].stableID }; - FrameSelectedNodes(view); + nodes::FrameSelectedNodes(view); float2 middle = CanvasAt(view, { 0.0f, 0.0f }); EXPECT_NEAR(middle.x, 1000.0f, 1.0f) << "between the two selected"; EXPECT_NEAR(middle.y, 675.0f, 1.0f); - EXPECT_NEAR(NodeViewZoom(view), 1.0f, 1e-4f) << "they fit at 100%"; + EXPECT_NEAR(nodes::NodeViewZoom(view), 1.0f, 1e-4f) << "they fit at 100%"; view.selectedNodeIDs.clear(); - FrameSelectedNodes(view); + nodes::FrameSelectedNodes(view); middle = CanvasAt(view, { 0.0f, 0.0f }); EXPECT_NEAR(middle.x, 550.0f, 1.0f) << "none selected: all of them"; EXPECT_NEAR(middle.y, 375.0f, 1.0f); - EXPECT_LT(NodeViewZoom(view), 1.0f); + EXPECT_LT(nodes::NodeViewZoom(view), 1.0f); } // FrameNodes frames those given, skips indices out of range, and leaves the view as it // is for none. TEST(NodeViewZoom, FrameNodesFramesTheOnesGiven) { - NodeView view; + nodes::NodeView view; view.lastInnerSize = { 400, 300 }; view.nodes.resize(2); view.nodes[0].pos = { -100, -100 }; view.nodes[0].lastSize = { 100, 50 }; view.nodes[1].pos = { 900, 600 }; view.nodes[1].lastSize = { 100, 50 }; const int one[] = { 1, 7, -1 }; - FrameNodes(view, one); + nodes::FrameNodes(view, one); const float2 middle = CanvasAt(view, { 0.0f, 0.0f }); EXPECT_NEAR(middle.x, 950.0f, 1.0f); EXPECT_NEAR(middle.y, 625.0f, 1.0f); // In any order: the bottom-right one first. const int both[] = { 1, 0 }; - FrameNodes(view, both); + nodes::FrameNodes(view, both); const float2 between = CanvasAt(view, { 0.0f, 0.0f }); EXPECT_NEAR(between.x, 450.0f, 1.0f); EXPECT_NEAR(between.y, 275.0f, 1.0f); const float3x2 before = view.transform; - FrameNodes(view, std::span{}); + nodes::FrameNodes(view, std::span{}); EXPECT_EQ(view.transform.r0.z, before.r0.z); EXPECT_EQ(view.transform.r1.z, before.r1.z); const int outOfRange[] = { 5 }; - FrameNodes(view, outOfRange); + nodes::FrameNodes(view, outOfRange); EXPECT_EQ(view.transform.r0.z, before.r0.z); } TEST(NodeViewScrollIntoView, ANodeInViewDoesntMove) { - NodeView view; + nodes::NodeView view; view.lastInnerSize = { 400, 300 }; view.nodes.resize(1); view.nodes[0].pos = { -50, -20 }; view.nodes[0].lastSize = { 100, 40 }; const float3x2 before = view.transform; - ScrollNodeIntoView(view, 0, 10); + nodes::ScrollNodeIntoView(view, 0, 10); EXPECT_EQ(view.transform.r0.z, before.r0.z); EXPECT_EQ(view.transform.r1.z, before.r1.z); } TEST(NodeViewScrollIntoView, PansByAsLittleAsBringsItIn) { - NodeView view; + nodes::NodeView view; view.lastInnerSize = { 400, 300 }; view.transform = float3x2::Scale(0.5f); view.nodes.resize(1); view.nodes[0].pos = { 1000, -2000 }; view.nodes[0].lastSize = { 100, 40 }; - ScrollNodeIntoView(view, 0, 10); - EXPECT_NEAR(NodeViewZoom(view), 0.5f, 1e-4f) << "the zoom stays"; + nodes::ScrollNodeIntoView(view, 0, 10); + EXPECT_NEAR(nodes::NodeViewZoom(view), 0.5f, 1e-4f) << "the zoom stays"; const float2 tl = view.transform.TransformPoint({ 1000.0f, -2000.0f }); const float2 br = view.transform.TransformPoint({ 1100.0f, -1960.0f }); EXPECT_NEAR(br.x, 200.0f - 10.0f, 1e-3f) << "right edge just inside"; @@ -200,11 +201,11 @@ namespace TEST(NodeViewScrollIntoView, ANodeLargerThanTheViewShowsItsTopLeft) { - NodeView view; + nodes::NodeView view; view.lastInnerSize = { 400, 300 }; view.nodes.resize(1); view.nodes[0].pos = { 2000, 2000 }; view.nodes[0].lastSize = { 900, 700 }; - ScrollNodeIntoView(view, 0, 10); + nodes::ScrollNodeIntoView(view, 0, 10); const float2 tl = view.transform.TransformPoint({ 2000.0f, 2000.0f }); EXPECT_NEAR(tl.x, -200.0f + 10.0f, 1e-3f); EXPECT_NEAR(tl.y, -150.0f + 10.0f, 1e-3f); diff --git a/tests/plot_test.cpp b/tests/plot_test.cpp index fcaea89a..60c8f69d 100644 --- a/tests/plot_test.cpp +++ b/tests/plot_test.cpp @@ -7,7 +7,8 @@ #include -#include +#include +#include #include #include @@ -27,18 +28,18 @@ namespace tachyon { const float nan = std::numeric_limits::quiet_NaN(); const float samples[] = { 0.0f, 0.1f, 0.24f, 0.25f, 0.5f, 0.99f, 1.0f, -0.1f, 1.5f, nan }; - const std::vector bins = HistogramBins(samples, 4); + const std::vector bins = curves::HistogramBins(samples, 4); EXPECT_EQ(bins, (std::vector{ 3.0f, 1.0f, 1.0f, 2.0f })) << "1.0 in the last; outside and NaN in none"; const float wide[] = { 10.0f, 15.0f, 19.0f, 20.0f }; - EXPECT_EQ(HistogramBins(wide, 2, 10.0f, 20.0f), (std::vector{ 1.0f, 3.0f })); - EXPECT_TRUE(HistogramBins(samples, 0).empty()); - EXPECT_EQ(HistogramBins(samples, 2, 1.0f, 1.0f), (std::vector{ 0.0f, 0.0f })) << "an empty range counts nothing"; + EXPECT_EQ(curves::HistogramBins(wide, 2, 10.0f, 20.0f), (std::vector{ 1.0f, 3.0f })); + EXPECT_TRUE(curves::HistogramBins(samples, 0).empty()); + EXPECT_EQ(curves::HistogramBins(samples, 2, 1.0f, 1.0f), (std::vector{ 0.0f, 0.0f })) << "an empty range counts nothing"; } - PlotView Levels() + curves::PlotView Levels() { - PlotView view; + curves::PlotView view; view.xMin = 0.0f; view.xMax = 255.0f; view.handles = { { "Black", 0.0f }, { "Gray", 128.0f }, { "White", 255.0f } }; @@ -47,40 +48,40 @@ namespace tachyon TEST(PlotHelpers, AHandleStaysBetweenItsNeighboursAndInTheRange) { - PlotView view = Levels(); - PlotEdit edit = MovePlotHandleEdit(view, 0, 60.0f); + curves::PlotView view = Levels(); + curves::PlotEdit edit = curves::MovePlotHandleEdit(view, 0, 60.0f); EXPECT_EQ(edit.from, (std::vector{ 0.0f, 128.0f, 255.0f })); EXPECT_EQ(edit.to, (std::vector{ 60.0f, 128.0f, 255.0f })); - EXPECT_EQ(MovePlotHandleEdit(view, 0, 200.0f).to[0], 128.0f) << "not past the gray point"; - EXPECT_EQ(MovePlotHandleEdit(view, 0, -20.0f).to[0], 0.0f); - EXPECT_TRUE(MovePlotHandleEdit(view, 0, -20.0f).empty()) << "already there"; - EXPECT_EQ(MovePlotHandleEdit(view, 2, 300.0f).to[2], 255.0f); - EXPECT_EQ(MovePlotHandleEdit(view, 2, 100.0f).to[2], 128.0f) << "not before the gray point"; - EXPECT_EQ(MovePlotHandleEdit(view, 1, 10.0f).to[1], 10.0f); - EXPECT_TRUE(MovePlotHandleEdit(view, 5, 10.0f).empty()) << "no such handle"; - EXPECT_TRUE(MovePlotHandleEdit(view, 1, std::nanf("")).empty()); + EXPECT_EQ(curves::MovePlotHandleEdit(view, 0, 200.0f).to[0], 128.0f) << "not past the gray point"; + EXPECT_EQ(curves::MovePlotHandleEdit(view, 0, -20.0f).to[0], 0.0f); + EXPECT_TRUE(curves::MovePlotHandleEdit(view, 0, -20.0f).empty()) << "already there"; + EXPECT_EQ(curves::MovePlotHandleEdit(view, 2, 300.0f).to[2], 255.0f); + EXPECT_EQ(curves::MovePlotHandleEdit(view, 2, 100.0f).to[2], 128.0f) << "not before the gray point"; + EXPECT_EQ(curves::MovePlotHandleEdit(view, 1, 10.0f).to[1], 10.0f); + EXPECT_TRUE(curves::MovePlotHandleEdit(view, 5, 10.0f).empty()) << "no such handle"; + EXPECT_TRUE(curves::MovePlotHandleEdit(view, 1, std::nanf("")).empty()); } TEST(PlotHelpers, EditsUndoAndReachTheApp) { - PlotView view = Levels(); - std::vector seen; - view.onEdit = [&](const PlotEdit& e) { seen.push_back(e); }; - const PlotEdit edit = MovePlotHandleEdit(view, 2, 200.0f); - CommitPlotEdit(view, edit); + curves::PlotView view = Levels(); + std::vector seen; + view.onEdit = [&](const curves::PlotEdit& e) { seen.push_back(e); }; + const curves::PlotEdit edit = curves::MovePlotHandleEdit(view, 2, 200.0f); + curves::CommitPlotEdit(view, edit); EXPECT_EQ(view.handles[2].x, 200.0f); ASSERT_EQ(seen.size(), 1u); EXPECT_EQ(view.edits, 1u); - ApplyPlotEdit(view, edit, /*undo*/ true); + curves::ApplyPlotEdit(view, edit, /*undo*/ true); EXPECT_EQ(view.handles[2].x, 255.0f); - ApplyPlotEdit(view, edit); + curves::ApplyPlotEdit(view, edit); EXPECT_EQ(view.handles[2].x, 200.0f); - CommitPlotEdit(view, PlotEdit{}); + curves::CommitPlotEdit(view, curves::PlotEdit{}); EXPECT_EQ(seen.size(), 1u) << "an empty edit isn't reported"; EXPECT_EQ(view.edits, 1u); view.handles.pop_back(); - ApplyPlotEdit(view, edit); + curves::ApplyPlotEdit(view, edit); EXPECT_EQ(view.handles.size(), 2u) << "an edit for other handles is left alone"; EXPECT_EQ(view.handles[1].x, 128.0f); } @@ -88,42 +89,42 @@ namespace tachyon // Fitted, the range starts at yMin and reaches values below it as well as above. TEST(PlotHelpers, AFittedYRangeTakesNegativeValues) { - PlotView view; - view.series = { PlotSeries{ .name = "R", .values = { -5.0f, 3.0f } } }; - EXPECT_EQ(PlotShownY(view).min, -5.0f); - EXPECT_EQ(PlotShownY(view).max, 3.0f); + curves::PlotView view; + view.series = { curves::PlotSeries{ .name = "R", .values = { -5.0f, 3.0f } } }; + EXPECT_EQ(curves::PlotShownY(view).min, -5.0f); + EXPECT_EQ(curves::PlotShownY(view).max, 3.0f); view.yMin = -10.0f; - EXPECT_EQ(PlotShownY(view).min, -10.0f) << "yMin when the values stay above it"; + EXPECT_EQ(curves::PlotShownY(view).min, -10.0f) << "yMin when the values stay above it"; } TEST(PlotHelpers, TheYRangeFitsWhatsShown) { - PlotView view; - view.series = { PlotSeries{ .name = "R", .values = { 1.0f, 8.0f } }, - PlotSeries{ .name = "G", .values = { 20.0f, 2.0f } } }; - EXPECT_EQ(PlotShownY(view).max, 20.0f); + curves::PlotView view; + view.series = { curves::PlotSeries{ .name = "R", .values = { 1.0f, 8.0f } }, + curves::PlotSeries{ .name = "G", .values = { 20.0f, 2.0f } } }; + EXPECT_EQ(curves::PlotShownY(view).max, 20.0f); view.series[1].visible = false; - EXPECT_EQ(PlotShownY(view).max, 8.0f) << "a hidden series doesn't count"; + EXPECT_EQ(curves::PlotShownY(view).max, 8.0f) << "a hidden series doesn't count"; view.series[1].visible = true; view.shownSeries = 0; - EXPECT_EQ(PlotShownY(view).max, 8.0f) << "only the one shown"; + EXPECT_EQ(curves::PlotShownY(view).max, 8.0f) << "only the one shown"; view.series[0].values = { 0.0f, 0.0f }; - EXPECT_GT(PlotShownY(view).max, 0.0f) << "room for nothing"; + EXPECT_GT(curves::PlotShownY(view).max, 0.0f) << "room for nothing"; view.fitY = false; view.yMin = -1.0f; view.yMax = 3.0f; - EXPECT_EQ(PlotShownY(view).min, -1.0f); - EXPECT_EQ(PlotShownY(view).max, 3.0f); + EXPECT_EQ(curves::PlotShownY(view).min, -1.0f); + EXPECT_EQ(curves::PlotShownY(view).max, 3.0f); view.yMin = 0.0f; view.yMax = 99.0f; - view.yScale = PlotScale::Log; - EXPECT_FLOAT_EQ(PlotShownY(view).max, 2.0f) << "log10(1 + 99)"; - EXPECT_FLOAT_EQ(PlotScaleY(view, 9.0f), 1.0f); - EXPECT_EQ(PlotScaleY(view, -5.0f), 0.0f) << "nothing below zero on a log scale"; - view.yScale = PlotScale::Linear; - EXPECT_EQ(PlotScaleY(view, 9.0f), 9.0f); + view.yScale = curves::PlotScale::Log; + EXPECT_FLOAT_EQ(curves::PlotShownY(view).max, 2.0f) << "log10(1 + 99)"; + EXPECT_FLOAT_EQ(curves::PlotScaleY(view, 9.0f), 1.0f); + EXPECT_EQ(curves::PlotScaleY(view, -5.0f), 0.0f) << "nothing below zero on a log scale"; + view.yScale = curves::PlotScale::Linear; + EXPECT_EQ(curves::PlotScaleY(view, 9.0f), 9.0f); } // --------------------------------------------------------------------- @@ -134,11 +135,12 @@ namespace tachyon { protected: HeadlessGUIApp app; - PlotView view; + curves::Context curvesContext; + curves::PlotView view; ID plotID{}; bool changed = false; int changes = 0; - std::vector edits; + std::vector edits; void SetUp() override { @@ -146,9 +148,9 @@ namespace tachyon app.runPostLayoutCallbacks = true; plotID = app.idManager.CreateStaticID(); view = Levels(); - view.series = { PlotSeries{ .name = "R", .color = CurveChannelColor::Red, .values = { 1, 4, 9, 4, 1 } }, - PlotSeries{ .name = "G", .color = CurveChannelColor::Green, .values = { 2, 2, 2, 2, 2 } } }; - view.onEdit = [this](const PlotEdit& e) { edits.push_back(e); }; + view.series = { curves::PlotSeries{ .name = "R", .color = curves::CurveChannelColor::Red, .values = { 1, 4, 9, 4, 1 } }, + curves::PlotSeries{ .name = "G", .color = curves::CurveChannelColor::Green, .values = { 2, 2, 2, 2, 2 } } }; + view.onEdit = [this](const curves::PlotEdit& e) { edits.push_back(e); }; Settle(); } void TearDown() override { app.Cleanup(); } @@ -157,7 +159,7 @@ namespace tachyon { app.Frame([&] { app.BeginRootWindow({ 800, 600 }, ElementFlags::None, app.theme.mainWindowStyleRef); - changed = app.Plot(plotID, view, LayoutOverride{}.Size(510, 300)); + changed = curves::Plot(app, curvesContext, plotID, view, LayoutOverride{}.Size(510, 300)); if (changed) ++changes; app.EndRootWindow(); }); @@ -168,7 +170,7 @@ namespace tachyon std::vector Chips() { std::vector ids; - const StyleRef style = app.theme.plotChannelStyleRef; + const StyleRef style = curves::GetStyles(app, curvesContext).plotChannelStyleRef; const auto& storage = app.elementStorage; for (auto it = storage.TopDownDepthScanBegin(); it != storage.TopDownDepthScanEnd(); ++it) for (const Element& e : it->GetChildren(storage)) @@ -182,14 +184,14 @@ namespace tachyon int2 HandleAt(int handle) const { const IntRect r = view.plotRect; - const PlotRange shown = PlotShownX(view); + const curves::PlotRange shown = curves::PlotShownX(view); const float x = float(r.x) + (view.handles[size_t(handle)].x - shown.min) / (shown.max - shown.min) * float(r.w); return { int32_t(std::lround(x)), r.y + r.h + app.styleManager.Px(5) }; } int2 AtX(float x) const { const IntRect r = view.plotRect; - const PlotRange shown = PlotShownX(view); + const curves::PlotRange shown = curves::PlotShownX(view); return { int32_t(std::lround(float(r.x) + (x - shown.min) / (shown.max - shown.min) * float(r.w))), r.y + r.h / 2 }; } }; @@ -219,7 +221,7 @@ namespace tachyon const size_t before = app.styleManager.VisualColorStyleCount(); for (int i = 0; i < 60; ++i) { - for (PlotHandle& handle : view.handles) + for (curves::PlotHandle& handle : view.handles) handle.color = color4f{ float(i) / 60.0f, 0.5f, 0.25f, 1.0f }; Frame(); draw(); @@ -310,24 +312,24 @@ namespace tachyon TEST(PlotHelpers, TheShownRangeIsKeptInsideTheData) { - PlotView view = Levels(); - EXPECT_EQ(PlotShownX(view).min, 0.0f) << "all of it at first"; - EXPECT_EQ(PlotShownX(view).max, 255.0f); + curves::PlotView view = Levels(); + EXPECT_EQ(curves::PlotShownX(view).min, 0.0f) << "all of it at first"; + EXPECT_EQ(curves::PlotShownX(view).max, 255.0f); view.shownXMin = -50.0f; view.shownXMax = 50.0f; view.shownSet = true; - EXPECT_EQ(PlotShownX(view).min, 0.0f) << "slid back inside"; - EXPECT_EQ(PlotShownX(view).max, 100.0f); + EXPECT_EQ(curves::PlotShownX(view).min, 0.0f) << "slid back inside"; + EXPECT_EQ(curves::PlotShownX(view).max, 100.0f); view.shownXMin = 10.0f; view.shownXMax = 900.0f; - EXPECT_EQ(PlotShownX(view).min, 0.0f) << "no wider than the data"; - EXPECT_EQ(PlotShownX(view).max, 255.0f); + EXPECT_EQ(curves::PlotShownX(view).min, 0.0f) << "no wider than the data"; + EXPECT_EQ(curves::PlotShownX(view).max, 255.0f); // The y range fits the slots in view. - view.series = { PlotSeries{ .values = { 50.0f, 2.0f, 3.0f, 4.0f } } }; + view.series = { curves::PlotSeries{ .values = { 50.0f, 2.0f, 3.0f, 4.0f } } }; view.shownXMin = 128.0f; view.shownXMax = 255.0f; - EXPECT_EQ(PlotShownY(view).max, 4.0f) << "the tall first slot is out of view"; + EXPECT_EQ(curves::PlotShownY(view).max, 4.0f) << "the tall first slot is out of view"; } TEST_F(PlotTest, TheWheelZoomsRoundThePointer) @@ -336,14 +338,14 @@ namespace tachyon app.InjectMouseMove(at); app.InjectMouseScroll(at, { 0, 2 }); Frame(); - const PlotRange shown = PlotShownX(view); + const curves::PlotRange shown = curves::PlotShownX(view); EXPECT_LT(shown.max - shown.min, 255.0f) << "in"; EXPECT_NEAR((64.0f - shown.min) / (shown.max - shown.min), 64.0f / 255.0f, 0.02f) << "64 stays under the pointer"; app.InjectMouseScroll(at, { 0, -5 }); Frame(); - EXPECT_EQ(PlotShownX(view).min, 0.0f) << "out, no further than all of it"; - EXPECT_EQ(PlotShownX(view).max, 255.0f); + EXPECT_EQ(curves::PlotShownX(view).min, 0.0f) << "out, no further than all of it"; + EXPECT_EQ(curves::PlotShownX(view).max, 255.0f); } TEST_F(PlotTest, TheMiddleButtonOrAltLeftDragsTheView) @@ -351,15 +353,15 @@ namespace tachyon const int2 at = AtX(128.0f); app.InjectMouseScroll(at, { 0, 3 }); Frame(); - const PlotRange zoomed = PlotShownX(view); + const curves::PlotRange zoomed = curves::PlotShownX(view); ASSERT_GT(zoomed.min, 0.0f); app.DragFrom(at, { at.x - 60, at.y }, MouseButtons::Middle); Frame(); - EXPECT_GT(PlotShownX(view).min, zoomed.min) << "dragged left: further right"; - EXPECT_FLOAT_EQ(PlotShownX(view).max - PlotShownX(view).min, zoomed.max - zoomed.min); + EXPECT_GT(curves::PlotShownX(view).min, zoomed.min) << "dragged left: further right"; + EXPECT_FLOAT_EQ(curves::PlotShownX(view).max - curves::PlotShownX(view).min, zoomed.max - zoomed.min); - const PlotRange before = PlotShownX(view); + const curves::PlotRange before = curves::PlotShownX(view); const int2 onHandle = HandleAt(1); app.InjectMouseMove(onHandle, MouseButtons::None, KeyModifier::Alt); app.InjectMouseDown(onHandle, MouseButtons::Left, KeyModifier::Alt); @@ -368,7 +370,7 @@ namespace tachyon Frame(); app.InjectMouseUp({ onHandle.x + 60, onHandle.y }, MouseButtons::Left, KeyModifier::Alt); Frame(); - EXPECT_LT(PlotShownX(view).min, before.min) << "Alt + left drags the view, over a handle too"; + EXPECT_LT(curves::PlotShownX(view).min, before.min) << "Alt + left drags the view, over a handle too"; EXPECT_EQ(view.handles[1].x, 128.0f) << "the handle stays"; EXPECT_TRUE(edits.empty()); } @@ -382,8 +384,8 @@ namespace tachyon Frame(); app.InjectKey(KeyCode::KeyA); Frame(); - EXPECT_EQ(PlotShownX(view).min, 0.0f); - EXPECT_EQ(PlotShownX(view).max, 255.0f); + EXPECT_EQ(curves::PlotShownX(view).min, 0.0f); + EXPECT_EQ(curves::PlotShownX(view).max, 255.0f); } // With the wheel set to scroll: sideways it scrolls the plot, up and down is left to @@ -395,18 +397,18 @@ namespace tachyon app.InjectMouseMove(at); app.InjectMouseScroll(at, { 0, 2 }, KeyModifier::Control); Frame(); - const PlotRange zoomed = PlotShownX(view); + const curves::PlotRange zoomed = curves::PlotShownX(view); ASSERT_LT(zoomed.max - zoomed.min, 255.0f) << "Ctrl zooms"; app.InjectMouseScroll(at, { 0, -1 }, KeyModifier::Shift); Frame(); - EXPECT_GT(PlotShownX(view).min, zoomed.min) << "Shift: sideways"; - const PlotRange scrolled = PlotShownX(view); + EXPECT_GT(curves::PlotShownX(view).min, zoomed.min) << "Shift: sideways"; + const curves::PlotRange scrolled = curves::PlotShownX(view); app.InjectMouseScroll(at, { 0, -1 }); Frame(); - EXPECT_EQ(PlotShownX(view).min, scrolled.min) << "up and down isn't the plot's"; + EXPECT_EQ(curves::PlotShownX(view).min, scrolled.min) << "up and down isn't the plot's"; app.InjectPinch(0.25f); Frame(); - EXPECT_EQ(PlotShownX(view).max - PlotShownX(view).min, 255.0f) << "a pinch zooms out"; + EXPECT_EQ(curves::PlotShownX(view).max - curves::PlotShownX(view).min, 255.0f) << "a pinch zooms out"; } // With the wheel set to scroll, up and down reaches what the plot is in (an inspector @@ -427,7 +429,7 @@ namespace tachyon }; app.RegisterElement(std::move(outer), LayoutOverride{}.Size(600, 400)); VERIFY(app.elementStorage.BeginChildren()); - app.Plot(plotID, view, LayoutOverride{}.Size(510, 300)); + curves::Plot(app, curvesContext, plotID, view, LayoutOverride{}.Size(510, 300)); VERIFY(app.elementStorage.EndChildren()); app.EndRootWindow(); }); @@ -450,7 +452,7 @@ namespace tachyon app.Frame([&] { app.BeginRootWindow({ 800, 600 }, ElementFlags::None, app.theme.mainWindowStyleRef); app.BeginDisabled(); - app.Plot(plotID, view, LayoutOverride{}.Size(510, 300)); + curves::Plot(app, curvesContext, plotID, view, LayoutOverride{}.Size(510, 300)); app.EndDisabled(); app.EndRootWindow(); }); @@ -459,7 +461,7 @@ namespace tachyon app.Frame([&] { app.BeginRootWindow({ 800, 600 }, ElementFlags::None, app.theme.mainWindowStyleRef); app.BeginDisabled(); - app.Plot(plotID, view, LayoutOverride{}.Size(510, 300)); + curves::Plot(app, curvesContext, plotID, view, LayoutOverride{}.Size(510, 300)); app.EndDisabled(); app.EndRootWindow(); }); 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/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 35d8869f..724d3076 100644 --- a/tests/static_id_release_test.cpp +++ b/tests/static_id_release_test.cpp @@ -4,10 +4,12 @@ #include #include "headless_gui_app.h" +#include -#include +#include #include #include +#include namespace tachyon { @@ -19,23 +21,26 @@ namespace tachyon { protected: HeadlessGUIApp app; + docking::Context dockingContext; + color::Context colorContext; + dialogs::Context dialogContext; void SetUp() override { ASSERT_TRUE(app.Initialize()); } - void TearDown() override { 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 // 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)); @@ -46,20 +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); @@ -71,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); } @@ -86,30 +92,31 @@ 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); (void)app.menuManager.GetOrCreateNextLevel(app.idManager); app.idManager.ReleaseStaticID(trigger); - app.m_colorPickerSub->State().windowID = app.idManager.CreateStaticID(); - app.m_gradientEditorSub->State().windowID = app.idManager.CreateStaticID(); + 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); - app.Cleanup(); + docking::Cleanup(app, dockingContext); 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/subsystem_test.cpp b/tests/subsystem_test.cpp index 4f1a2e85..99e0c701 100644 --- a/tests/subsystem_test.cpp +++ b/tests/subsystem_test.cpp @@ -8,12 +8,12 @@ #include #include #include -#include -#include +#include #include #include #include #include +#include #include "headless_gui_app.h" @@ -53,36 +53,42 @@ namespace tachyon // indices they held must be dropped, or they'd draw (and write) through // slots the new theme reuses. // --------------------------------------------------------------------- - TEST(ColorPickerSubsystemTest, ForgetStylesDropsEveryHeldStyle) + TEST(ColorContextTest, AThemeLoadDropsEveryHeldStyle) { - FramePipeline frame; - ColorPickerSubsystem sub(frame); + HeadlessGUIApp app; + ASSERT_TRUE(app.Initialize()); + color::Context context; + color::GetStyles(app, context); // looked up at this load const ID swatch = ID{ .value{ .integer = 42 } }; - sub.ClaimSwatchStyle(swatch) = VisualColorStyleIndex(5); - sub.State().hueStrip = VisualColorStyleIndex(7); - sub.State().gradientStyles[2] = VisualColorStyleIndex(9); - sub.State().originalStyle = VisualColorStyleIndex(11); - - sub.ForgetStyles(); - - EXPECT_EQ(sub.ClaimSwatchStyle(swatch), VisualColorStyleIndex::Invalid); - EXPECT_EQ(sub.State().hueStrip, VisualColorStyleIndex::Invalid); - EXPECT_EQ(sub.State().gradientStyles[2], VisualColorStyleIndex::Invalid); - EXPECT_EQ(sub.State().originalStyle, VisualColorStyleIndex::Invalid); + context.gradientSwatches.Claim(swatch).index = VisualColorStyleIndex(5); + context.picker.hueStrip = VisualColorStyleIndex(7); + context.picker.gradientStyles[2] = VisualColorStyleIndex(9); + context.picker.originalStyle = VisualColorStyleIndex(11); + context.gradientEditor.stopHaloColor = VisualColorStyleIndex(7); + + ASSERT_TRUE(app.InitializeStyles()); // a load, as a reload does + color::GetStyles(app, context); + + EXPECT_EQ(context.gradientSwatches.Claim(swatch).index, VisualColorStyleIndex::Invalid); + EXPECT_EQ(context.picker.hueStrip, VisualColorStyleIndex::Invalid); + EXPECT_EQ(context.picker.gradientStyles[2], VisualColorStyleIndex::Invalid); + EXPECT_EQ(context.picker.originalStyle, VisualColorStyleIndex::Invalid); + EXPECT_EQ(context.gradientEditor.stopHaloColor, VisualColorStyleIndex::Invalid); + app.Cleanup(); } - TEST(GradientEditorSubsystemTest, ForgetStylesDropsEveryHeldStyle) + // The app's own swatch slots (ClaimSwatchStyle, AppColorStyle) are dropped by a reload too. + TEST(SwatchSlotsTest, AThemeReloadDropsTheirStyles) { - FramePipeline frame; - GradientEditorSubsystem sub(frame); + HeadlessGUIApp app; + ASSERT_TRUE(app.Initialize()); const ID swatch = ID{ .value{ .integer = 42 } }; - sub.ClaimSwatchStyle(swatch) = VisualColorStyleIndex(5); - sub.State().stopHaloColor = VisualColorStyleIndex(7); - - sub.ForgetStyles(); - - EXPECT_EQ(sub.ClaimSwatchStyle(swatch), VisualColorStyleIndex::Invalid); - EXPECT_EQ(sub.State().stopHaloColor, VisualColorStyleIndex::Invalid); + app.Frame([&] { app.BeginRootWindow(); app.AppColorStyle(swatch, color4f{ 1, 0, 0, 1 }); app.EndRootWindow(); }); + EXPECT_NE(app.ClaimSwatchStyle(swatch), VisualColorStyleIndex::Invalid); + app.RequestReloadTheme("themes/light.css", 1.0f); // another theme: the same one is no reload + app.Frame([&] { app.BeginRootWindow(); app.EndRootWindow(); }); + EXPECT_EQ(app.ClaimSwatchStyle(swatch), VisualColorStyleIndex::Invalid); + app.Cleanup(); } // --------------------------------------------------------------------- @@ -345,7 +351,7 @@ namespace tachyon // --------------------------------------------------------------------- - // RenameSubsystem - verify the Start/Cancel state machine. + // views::RenameState - verify the Start/Cancel state machine. // // Start writes all four fields atomically (targetID, isActive, // firstFrame, editBuffer) and seeds the buffer text. Cancel resets the @@ -353,18 +359,18 @@ namespace tachyon // buffer contents, since the caller still owns the string. // --------------------------------------------------------------------- - TEST(RenameSubsystemTest, DefaultStateIsInactive) + TEST(RenameStateTest, DefaultStateIsInactive) { - RenameSubsystem r; + views::RenameState r; EXPECT_EQ(r.targetID, tachyon::ID::Invalid()); EXPECT_FALSE(r.isActive); EXPECT_FALSE(r.firstFrame); EXPECT_EQ(r.editBuffer, nullptr); } - TEST(RenameSubsystemTest, StartSetsAllFieldsAndSeedsBuffer) + TEST(RenameStateTest, StartSetsAllFieldsAndSeedsBuffer) { - RenameSubsystem r; + views::RenameState r; std::string buf = "old text"; tachyon::ID id{}; id.value.dynamicParts.mode = tachyon::IDMode::Static; @@ -379,9 +385,9 @@ namespace tachyon EXPECT_EQ(buf, "new seed"); // seed text overwrites prior contents } - TEST(RenameSubsystemTest, CancelResetsStateButLeavesBufferContents) + TEST(RenameStateTest, CancelResetsStateButLeavesBufferContents) { - RenameSubsystem r; + views::RenameState r; std::string buf; tachyon::ID id{}; id.value.dynamicParts.mode = tachyon::IDMode::Static; @@ -463,6 +469,7 @@ namespace tachyon TEST(ListViewItemIndexTest, SecondListInFrameKeepsFirstListsIndices) { GUITest::HeadlessGUIApp app; + views::Context viewsContext; ASSERT_TRUE(app.Initialize()); const ID listA = app.idManager.CreateStaticID(); const ID listB = app.idManager.CreateStaticID(); @@ -475,22 +482,22 @@ namespace tachyon app.Frame([&] { app.BeginRootWindow(); - if (app.BeginListView(listA, &selA, 2, &dd)) + if (views::BeginListView(app, viewsContext, listA, &selA, 2, &dd)) { - app.ListItem(itemA0, "a0", LayoutOverride{}); - app.ListItem(itemA1, "a1", LayoutOverride{}); - app.EndListView(); + views::ListItem(app, viewsContext, itemA0, "a0", LayoutOverride{}); + views::ListItem(app, viewsContext, itemA1, "a1", LayoutOverride{}); + views::EndListView(app, viewsContext); } - if (app.BeginListView(listB, &selB, 1, &dd)) + if (views::BeginListView(app, viewsContext, listB, &selB, 1, &dd)) { - app.ListItem(itemB0, "b0", LayoutOverride{}); - app.EndListView(); + views::ListItem(app, viewsContext, itemB0, "b0", LayoutOverride{}); + views::EndListView(app, viewsContext); } app.EndRootWindow(); }); - EXPECT_EQ(app.FindListItemIndex(itemA1), 1); - EXPECT_EQ(app.FindListItemIndex(itemB0), 0); + EXPECT_EQ(views::FindListItemIndex(viewsContext, itemA1), 1); + EXPECT_EQ(views::FindListItemIndex(viewsContext, itemB0), 0); app.Cleanup(); } diff --git a/tests/table_helpers_test.cpp b/tests/table_helpers_test.cpp index eb01195a..b9135430 100644 --- a/tests/table_helpers_test.cpp +++ b/tests/table_helpers_test.cpp @@ -1,14 +1,15 @@ #include -#include +#include #include #include +#include #include namespace tachyon { - using TableHelpers::VirtualRowRange; + using views::TableHelpers::VirtualRowRange; // =========================================================================== // ComputeVirtualRowRange - the visibility window used by VirtualTable to @@ -19,7 +20,7 @@ namespace tachyon TEST_F(VirtualRowRangeTest, EmptyDatasetProducesEmptyRange) { - auto r = TableHelpers::ComputeVirtualRowRange(/*scrollY*/0, + auto r = views::TableHelpers::ComputeVirtualRowRange(/*scrollY*/0, /*viewportH*/400, /*rowHeight*/20, /*totalRowCount*/0, @@ -32,7 +33,7 @@ namespace tachyon { // Guard: a 0 rowHeight would otherwise divide-by-zero. The helper must // return an empty range instead of exploding. - auto r = TableHelpers::ComputeVirtualRowRange(0, 400, 0, 1000, 5); + auto r = views::TableHelpers::ComputeVirtualRowRange(0, 400, 0, 1000, 5); EXPECT_EQ(r.firstVisible, 0); EXPECT_EQ(r.lastVisible, 0); } @@ -48,7 +49,7 @@ namespace tachyon const int totalRows = 50000; const int buffer = 5; - auto r = TableHelpers::ComputeVirtualRowRange(scrollY, viewportH, rowHeight, + auto r = views::TableHelpers::ComputeVirtualRowRange(scrollY, viewportH, rowHeight, totalRows, buffer); EXPECT_EQ(r.firstVisible, 0); // (0 + 0)/20 + 1 + 5 = 6. @@ -60,7 +61,7 @@ namespace tachyon // scrollY=0, viewport=200, rowHeight=20 -> visible rows 0..10. // With a 5-row buffer below: last = 200/20 + 1 + 5 = 16. // first clamped to 0. - auto r = TableHelpers::ComputeVirtualRowRange(0, 200, 20, 50000, 5); + auto r = views::TableHelpers::ComputeVirtualRowRange(0, 200, 20, 50000, 5); EXPECT_EQ(r.firstVisible, 0); EXPECT_EQ(r.lastVisible, 16); } @@ -70,7 +71,7 @@ namespace tachyon // scrollY=1000 (row 50), viewport=200 (10 rows), buffer=5. // first = 1000/20 - 5 = 45 // last = (1000+200)/20 + 1 + 5 = 66 - auto r = TableHelpers::ComputeVirtualRowRange(1000, 200, 20, 50000, 5); + auto r = views::TableHelpers::ComputeVirtualRowRange(1000, 200, 20, 50000, 5); EXPECT_EQ(r.firstVisible, 45); EXPECT_EQ(r.lastVisible, 66); } @@ -81,7 +82,7 @@ namespace tachyon // Scrolled to the end: scrollY = 2000 - 200 = 1800. // first = 1800/20 - 5 = 85 // last = (1800+200)/20 + 1 + 5 = 106, clamped to totalRowCount=100. - auto r = TableHelpers::ComputeVirtualRowRange(1800, 200, 20, 100, 5); + auto r = views::TableHelpers::ComputeVirtualRowRange(1800, 200, 20, 100, 5); EXPECT_EQ(r.firstVisible, 85); EXPECT_EQ(r.lastVisible, 100); } @@ -90,7 +91,7 @@ namespace tachyon { // If something asks for a scroll offset past the end, both bounds // should clamp to totalRowCount - no rows emitted, no negative counts. - auto r = TableHelpers::ComputeVirtualRowRange(/*scrollY*/1'000'000, + auto r = views::TableHelpers::ComputeVirtualRowRange(/*scrollY*/1'000'000, /*viewportH*/400, /*rowHeight*/20, /*totalRowCount*/100, @@ -103,7 +104,7 @@ namespace tachyon { // Scroll offsets below 0 shouldn't be reachable, but the helper must // stay safe - first is clamped to 0, last to a small leading slice. - auto r = TableHelpers::ComputeVirtualRowRange(-500, 200, 20, 1000, 5); + auto r = views::TableHelpers::ComputeVirtualRowRange(-500, 200, 20, 1000, 5); EXPECT_EQ(r.firstVisible, 0); EXPECT_GE(r.lastVisible, 0); EXPECT_LE(r.lastVisible, 1000); @@ -113,7 +114,7 @@ namespace tachyon { // Buffer = 0: exactly the viewport slice, inclusive on both ends. // scrollY=100, viewport=80, rowHeight=20: visible rows 5..10. - auto r = TableHelpers::ComputeVirtualRowRange(100, 80, 20, 1000, 0); + auto r = views::TableHelpers::ComputeVirtualRowRange(100, 80, 20, 1000, 0); EXPECT_EQ(r.firstVisible, 5); EXPECT_EQ(r.lastVisible, 10); // (100+80)/20 + 1 = 10 } @@ -126,7 +127,7 @@ namespace tachyon for (int32_t rh : {1, 10, 28}) for (int total : {0, 1, 50, 50'000}) { - auto r = TableHelpers::ComputeVirtualRowRange(scroll, vh, rh, total, 5); + auto r = views::TableHelpers::ComputeVirtualRowRange(scroll, vh, rh, total, 5); EXPECT_LE(r.firstVisible, r.lastVisible) << "scroll=" << scroll << " vh=" << vh << " rh=" << rh << " total=" << total; @@ -156,49 +157,49 @@ namespace tachyon TEST_F(ColumnInsertionIndexTest, NoMovementReturnsFromCol) { // Mouse at the center of column 2 (dragged column) -> still column 2. - int to = TableHelpers::ComputeColumnInsertionIndex(250, /*fromCol*/2, rects); + int to = views::TableHelpers::ComputeColumnInsertionIndex(250, /*fromCol*/2, rects); EXPECT_EQ(to, 2); } TEST_F(ColumnInsertionIndexTest, CrossingRightNeighborLeftEdgeSnapsIntoIt) { // Dragging col 0. Mouse at x=100 (exactly col 1's left edge) -> target 1. - int to = TableHelpers::ComputeColumnInsertionIndex(100, /*fromCol*/0, rects); + int to = views::TableHelpers::ComputeColumnInsertionIndex(100, /*fromCol*/0, rects); EXPECT_EQ(to, 1); } TEST_F(ColumnInsertionIndexTest, CrossingMultipleRightNeighborsCascades) { // Dragging col 0. Mouse at x=250 (past col 1's AND col 2's left edges). - int to = TableHelpers::ComputeColumnInsertionIndex(250, 0, rects); + int to = views::TableHelpers::ComputeColumnInsertionIndex(250, 0, rects); EXPECT_EQ(to, 2); } TEST_F(ColumnInsertionIndexTest, DraggingFarRightPinsToLastColumn) { // Mouse way past the rightmost column -> target = last column index. - int to = TableHelpers::ComputeColumnInsertionIndex(10'000, 0, rects); + int to = views::TableHelpers::ComputeColumnInsertionIndex(10'000, 0, rects); EXPECT_EQ(to, 3); } TEST_F(ColumnInsertionIndexTest, CrossingLeftNeighborRightEdgeSnapsIntoIt) { // Dragging col 3. Mouse at x=299 (inside col 2's right edge = 300). - int to = TableHelpers::ComputeColumnInsertionIndex(299, /*fromCol*/3, rects); + int to = views::TableHelpers::ComputeColumnInsertionIndex(299, /*fromCol*/3, rects); EXPECT_EQ(to, 2); } TEST_F(ColumnInsertionIndexTest, DraggingFarLeftPinsToFirstColumn) { // Mouse way to the left of the leftmost column -> target = 0. - int to = TableHelpers::ComputeColumnInsertionIndex(-500, 3, rects); + int to = views::TableHelpers::ComputeColumnInsertionIndex(-500, 3, rects); EXPECT_EQ(to, 0); } TEST_F(ColumnInsertionIndexTest, EmptyHeadersYieldsZero) { std::vector empty; - int to = TableHelpers::ComputeColumnInsertionIndex(0, 0, empty); + int to = views::TableHelpers::ComputeColumnInsertionIndex(0, 0, empty); EXPECT_EQ(to, 0); } @@ -206,9 +207,9 @@ namespace tachyon { // Defensive: if the caller passes an out-of-range fromCol, the helper // clamps rather than reading past the end of headerRects. - int to = TableHelpers::ComputeColumnInsertionIndex(50, /*fromCol*/99, rects); + int to = views::TableHelpers::ComputeColumnInsertionIndex(50, /*fromCol*/99, rects); EXPECT_EQ(to, 3); // clamped to last - int to2 = TableHelpers::ComputeColumnInsertionIndex(50, /*fromCol*/-2, rects); + int to2 = views::TableHelpers::ComputeColumnInsertionIndex(50, /*fromCol*/-2, rects); EXPECT_EQ(to2, 0); } @@ -216,7 +217,7 @@ namespace tachyon { // Dragging col 0. Mouse at x=150 (past col 1's left edge 100, not past // col 2's left edge 200). Target should be 1, not 2. - int to = TableHelpers::ComputeColumnInsertionIndex(150, 0, rects); + int to = views::TableHelpers::ComputeColumnInsertionIndex(150, 0, rects); EXPECT_EQ(to, 1); } @@ -230,18 +231,18 @@ namespace tachyon }; // Dragging col 0. Mouse at x=49 (one px inside col 0): no neighbor // crossing, target = 0. - EXPECT_EQ(TableHelpers::ComputeColumnInsertionIndex(49, 0, nonuniform), 0); + EXPECT_EQ(views::TableHelpers::ComputeColumnInsertionIndex(49, 0, nonuniform), 0); // Mouse at x=50 (col 1's left edge): past -> target 1. - EXPECT_EQ(TableHelpers::ComputeColumnInsertionIndex(50, 0, nonuniform), 1); + EXPECT_EQ(views::TableHelpers::ComputeColumnInsertionIndex(50, 0, nonuniform), 1); // Mouse at x=249 (inside col 1, before col 2's left): still 1. - EXPECT_EQ(TableHelpers::ComputeColumnInsertionIndex(249, 0, nonuniform), 1); + EXPECT_EQ(views::TableHelpers::ComputeColumnInsertionIndex(249, 0, nonuniform), 1); // Mouse at x=250 (col 2's left edge): past -> target 2. - EXPECT_EQ(TableHelpers::ComputeColumnInsertionIndex(250, 0, nonuniform), 2); + EXPECT_EQ(views::TableHelpers::ComputeColumnInsertionIndex(250, 0, nonuniform), 2); } // Apply a reorder(from, to) to a pair of parallel vectors so columns and // their persisted widths stay in lockstep. Semantics match the callback - // contract used by TableState::onReorderColumns. No-op when from == to. + // contract used by views::TableState::onReorderColumns. No-op when from == to. template inline void RotateColumns(std::vector& a, std::vector& b, int from, int to) { diff --git a/tests/table_integration_test.cpp b/tests/table_integration_test.cpp index 243b2976..bc39d0b7 100644 --- a/tests/table_integration_test.cpp +++ b/tests/table_integration_test.cpp @@ -1,5 +1,5 @@ // Integration tests for Table / VirtualTable event handlers: real headless frames, -// so BeginTable's handlers fire and the resulting TableState can be checked. +// so BeginTable's handlers fire and the resulting views::TableState can be checked. #include @@ -7,6 +7,7 @@ #include #include +#include #include #include @@ -21,10 +22,11 @@ namespace tachyon { protected: HeadlessGUIApp app; + views::Context viewsContext; // A tiny, stable test dataset. Sortable on all three columns so we can // exercise click-to-sort paths and verify the sort-column resolution. - tachyon::VirtualTableColumn kColumns[3] = { + tachyon::views::VirtualTableColumn kColumns[3] = { { {.header = "Name", .initialWidth = 120, .minWidth = 40, .maxWidth = 400, .sortable = true } }, { {.header = "Type", .initialWidth = 100, .minWidth = 40, .maxWidth = 400, .sortable = true } }, { {.header = "Value", .initialWidth = 140, .minWidth = 40, .maxWidth = 400, .sortable = true } }, @@ -47,10 +49,10 @@ namespace tachyon // Convenience: render a 3-row, 3-column table. Row IDs are allocated // with a fixed seed so selectedRowID stays consistent across frames. - void EmitSimpleTable(tachyon::TableState& state) + void EmitSimpleTable(tachyon::views::TableState& state) { app.BeginRootWindow(); - if (app.BeginTable(tableID, kColumns, state, LayoutOverride{}.Size(400, 200))) + if (views::BeginTable(app, viewsContext, tableID, kColumns, state, LayoutOverride{}.Size(400, 200))) { static const char* rows[][3] = { { "Position", "float3", "1,2,3" }, @@ -59,13 +61,13 @@ namespace tachyon }; for (int r = 0; r < 3; r++) { - app.BeginRow(); - app.Cell(rows[r][0]); - app.Cell(rows[r][1]); - app.Cell(rows[r][2]); - app.EndRow(); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, rows[r][0]); + views::Cell(app, viewsContext, rows[r][1]); + views::Cell(app, viewsContext, rows[r][2]); + views::EndRow(app, viewsContext); } - app.EndTable(); + views::EndTable(app, viewsContext); } app.EndRootWindow(); } @@ -79,7 +81,7 @@ namespace tachyon { // Driving a single frame is enough to verify the table container and // header cells actually land in ElementStorage at sensible rects. - tachyon::TableState state{}; + tachyon::views::TableState state{}; app.Frame([&] { EmitSimpleTable(state); }); ASSERT_TRUE(app.HasElement(tableID)); auto rect = app.GetElementRect(tableID); @@ -94,9 +96,9 @@ namespace tachyon TEST_F(TableIntegrationTest, HeaderAndBodyGapMatchAcrossThemes) { const auto* headerLs = app.styleManager.GetLayoutStyle( - app.theme.tableHeaderSectionStyleRef.layoutStyleIndex); + views::GetStyles(app, viewsContext).tableHeaderSectionStyleRef.layoutStyleIndex); const auto* bodyLs = app.styleManager.GetLayoutStyle( - app.theme.tableScrollableBodyStyleRef.layoutStyleIndex); + views::GetStyles(app, viewsContext).tableScrollableBodyStyleRef.layoutStyleIndex); ASSERT_NE(headerLs, nullptr); ASSERT_NE(bodyLs, nullptr); EXPECT_EQ(headerLs->layoutData.grid.column.gap, @@ -108,14 +110,14 @@ namespace tachyon // and no row IDs accumulate. TEST_F(TableIntegrationTest, EmptyColumnArrayDoesNotCrash) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; app.Frame([&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, - /*columns*/static_cast(nullptr), + if (views::BeginTable(app, viewsContext, tableID, + /*columns*/static_cast(nullptr), /*columnCount*/0u, state, LayoutOverride{}.Size(200, 100))) - app.EndTable(); + views::EndTable(app, viewsContext); app.EndRootWindow(); }); EXPECT_TRUE(app.HasElement(tableID)); @@ -126,11 +128,11 @@ namespace tachyon // _orderedRowIDs stays empty. TEST_F(TableIntegrationTest, ZeroRowsEmitsHeaderButNoBackdrops) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; app.Frame([&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, kColumns, state, LayoutOverride{}.Size(400, 200))) - app.EndTable(); + if (views::BeginTable(app, viewsContext, tableID, kColumns, state, LayoutOverride{}.Size(400, 200))) + views::EndTable(app, viewsContext); app.EndRootWindow(); }); EXPECT_TRUE(app.HasElement(tableID)); @@ -140,7 +142,7 @@ namespace tachyon TEST_F(TableIntegrationTest, ColumnWidthsLazyInitFromDefaults) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; EXPECT_TRUE(state.columnWidths.empty()); app.Frame([&] { EmitSimpleTable(state); }); ASSERT_EQ(state.columnWidths.size(), 3u); @@ -152,7 +154,7 @@ namespace tachyon // Column widths are CSS pixels: they follow a live UI scale change. TEST_F(TableIntegrationTest, ColumnWidthsFollowTheUIScale) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; app.Frame([&] { EmitSimpleTable(state); }); app.Frame([&] { EmitSimpleTable(state); }); auto headerWidth = [&] { @@ -172,7 +174,7 @@ namespace tachyon { // Default sortColumn is -1. BeginTable should auto-resolve it to the // first sortable column (here, col 0). - tachyon::TableState state{}; + tachyon::views::TableState state{}; EXPECT_EQ(state.sortColumn, -1); app.Frame([&] { EmitSimpleTable(state); }); EXPECT_EQ(state.sortColumn, 0); @@ -181,7 +183,7 @@ namespace tachyon TEST_F(TableIntegrationTest, SortColumnClampsToSortableWhenOutOfRange) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; state.sortColumn = 99; // absurd value app.Frame([&] { EmitSimpleTable(state); }); // Clamped back to the first sortable column. @@ -194,7 +196,7 @@ namespace tachyon TEST_F(TableIntegrationTest, ClickingDifferentColumnHeaderChangesSortColumn) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; // Frame 1 establishes the table (default sort = column 0 asc). app.Frame([&] { EmitSimpleTable(state); }); ASSERT_EQ(state.sortColumn, 0); @@ -215,7 +217,7 @@ namespace tachyon TEST_F(TableIntegrationTest, ClickingSameColumnHeaderTogglesDirection) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; app.Frame([&] { EmitSimpleTable(state); }); ASSERT_EQ(state.sortColumn, 0); ASSERT_FALSE(state.sortDescending); @@ -250,7 +252,7 @@ namespace tachyon TEST_F(TableIntegrationTest, ClickingRowSelectsIt) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; app.Frame([&] { EmitSimpleTable(state); }); EXPECT_EQ(state.selectedRowID, tachyon::ID::Invalid()); @@ -276,7 +278,7 @@ namespace tachyon TEST_F(TableIntegrationTest, DraggingHeaderFiresReorderCallback) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; struct { int from = -1, to = -1; int calls = 0; } seen; state.onReorderColumns = [&](int f, int t) { seen.from = f; seen.to = t; seen.calls++; }; @@ -310,7 +312,7 @@ namespace tachyon // When onReorderColumns is set, a simple click (no drag) on a sortable // header still toggles sort state - the threshold check distinguishes // the gestures. - tachyon::TableState state{}; + tachyon::views::TableState state{}; bool reorderCalled = false; state.onReorderColumns = [&](int, int) { reorderCalled = true; }; @@ -333,7 +335,7 @@ namespace tachyon // Dragging column 0 past column 2 shifts columns 1 and 2 left by // (draggedWidth + column-gap) to open the drop slot, as in // BeginReorderableGroup. Checked on the final element rects. - tachyon::TableState state{}; + tachyon::views::TableState state{}; state.onReorderColumns = [](int, int) {}; // enable reorder path app.Frame([&] { EmitSimpleTable(state); }); @@ -377,11 +379,11 @@ namespace tachyon // and dragging its header must not fire onReorderColumns no matter // how far the user drags. Click-to-sort on a sortable locked column // still works. - tachyon::TableState state{}; + tachyon::views::TableState state{}; int reorderCalls = 0; state.onReorderColumns = [&](int, int) { reorderCalls++; }; - tachyon::VirtualTableColumn cols[] = { + tachyon::views::VirtualTableColumn cols[] = { { {.header = "Pinned", .initialWidth = 120, .sortable = true, .locked = true } }, { {.header = "B", .initialWidth = 100, .sortable = true } }, { {.header = "C", .initialWidth = 100, .sortable = true } }, @@ -389,12 +391,12 @@ namespace tachyon auto build = [&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, cols, state, LayoutOverride{}.Size(500, 200))) + if (views::BeginTable(app, viewsContext, tableID, cols, state, LayoutOverride{}.Size(500, 200))) { - app.BeginRow(); - app.Cell("a"); app.Cell("b"); app.Cell("c"); - app.EndRow(); - app.EndTable(); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "a"); views::Cell(app, viewsContext, "b"); views::Cell(app, viewsContext, "c"); + views::EndRow(app, viewsContext); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }; @@ -419,11 +421,11 @@ namespace tachyon { // Locked column at index 0 acts as a left barrier: dragging columns // to its left should clamp the insertion index to 1, never 0. - tachyon::TableState state{}; + tachyon::views::TableState state{}; std::pair lastReorder{ -1, -1 }; state.onReorderColumns = [&](int f, int t) { lastReorder = { f, t }; }; - tachyon::VirtualTableColumn cols[] = { + tachyon::views::VirtualTableColumn cols[] = { { {.header = "Pinned", .initialWidth = 80, .locked = true } }, { {.header = "B", .initialWidth = 100 } }, { {.header = "C", .initialWidth = 100 } }, @@ -431,12 +433,12 @@ namespace tachyon auto build = [&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, cols, state, LayoutOverride{}.Size(500, 200))) + if (views::BeginTable(app, viewsContext, tableID, cols, state, LayoutOverride{}.Size(500, 200))) { - app.BeginRow(); - app.Cell("a"); app.Cell("b"); app.Cell("c"); - app.EndRow(); - app.EndTable(); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "a"); views::Cell(app, viewsContext, "b"); views::Cell(app, viewsContext, "c"); + views::EndRow(app, viewsContext); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }; @@ -463,11 +465,11 @@ namespace tachyon TEST_F(TableIntegrationTest, LockedColumnAtEndPreventsOthersFromMovingPast) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; std::pair lastReorder{ -1, -1 }; state.onReorderColumns = [&](int f, int t) { lastReorder = { f, t }; }; - tachyon::VirtualTableColumn cols[] = { + tachyon::views::VirtualTableColumn cols[] = { { {.header = "A", .initialWidth = 100 } }, { {.header = "B", .initialWidth = 100 } }, { {.header = "Pinned", .initialWidth = 80, .locked = true } }, @@ -475,12 +477,12 @@ namespace tachyon auto build = [&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, cols, state, LayoutOverride{}.Size(500, 200))) + if (views::BeginTable(app, viewsContext, tableID, cols, state, LayoutOverride{}.Size(500, 200))) { - app.BeginRow(); - app.Cell("a"); app.Cell("b"); app.Cell("c"); - app.EndRow(); - app.EndTable(); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "a"); views::Cell(app, viewsContext, "b"); views::Cell(app, viewsContext, "c"); + views::EndRow(app, viewsContext); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }; @@ -508,7 +510,7 @@ namespace tachyon { // If the drag never crosses another column's edge (target == from), // onReorderColumns should be skipped even though a real drag happened. - tachyon::TableState state{}; + tachyon::views::TableState state{}; int reorderCalls = 0; state.onReorderColumns = [&](int, int) { reorderCalls++; }; @@ -536,7 +538,7 @@ namespace tachyon { // During a column drag the header holds mouse capture; Escape reaches it // through keyboard-to-capture routing, without moving focus. - tachyon::TableState state{}; + tachyon::views::TableState state{}; int reorderCalls = 0; state.onReorderColumns = [&](int, int) { reorderCalls++; }; @@ -571,20 +573,20 @@ namespace tachyon TEST_F(TableIntegrationTest, VirtualTableEmitsOnlyVisibleRows) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; int cellsEmitted = 0; - tachyon::VirtualTableColumn vcols[] = { + tachyon::views::VirtualTableColumn vcols[] = { { {.header = "#", .initialWidth = 80 }, - [&](int rowIdx) { char b[16]; std::snprintf(b, sizeof(b), "%d", rowIdx); app.Cell(b); cellsEmitted++; } }, + [&](int rowIdx) { char b[16]; std::snprintf(b, sizeof(b), "%d", rowIdx); views::Cell(app, viewsContext, b); cellsEmitted++; } }, { {.header = "Name", .initialWidth = 160 }, - [&](int rowIdx) { (void)rowIdx; app.Cell("row"); cellsEmitted++; } }, + [&](int rowIdx) { (void)rowIdx; views::Cell(app, viewsContext, "row"); cellsEmitted++; } }, }; const int totalRows = 50'000; app.Frame([&] { app.BeginRootWindow(); - app.VirtualTable(tableID, state, vcols, totalRows, + views::VirtualTable(app, viewsContext, tableID, state, vcols, totalRows, /*rowHeight*/ 28, /*style*/ StyleRef{}, LayoutOverride{}.Size(400, 200)); app.EndRootWindow(); @@ -601,19 +603,19 @@ namespace tachyon // A VirtualTable body's intrinsic height is enormous (50 000 rows of // spacer). With flex-basis honoured its rect stays the same across frames // instead of oscillating with the sampled viewport height. - tachyon::TableState state{}; + tachyon::views::TableState state{}; state.internal.lastViewportH = 400; - tachyon::VirtualTableColumn vcols[] = { + tachyon::views::VirtualTableColumn vcols[] = { { {.header = "A", .initialWidth = 80 }, - [&](int rowIdx) { (void)rowIdx; app.Cell("a"); } }, + [&](int rowIdx) { (void)rowIdx; views::Cell(app, viewsContext, "a"); } }, { {.header = "B", .initialWidth = 80 }, - [&](int rowIdx) { (void)rowIdx; app.Cell("b"); } }, + [&](int rowIdx) { (void)rowIdx; views::Cell(app, viewsContext, "b"); } }, }; auto build = [&] { app.BeginRootWindow(); - app.VirtualTable(tableID, state, vcols, /*totalRows*/50'000, + views::VirtualTable(app, viewsContext, tableID, state, vcols, /*totalRows*/50'000, /*rowHeight*/28, StyleRef{}, LayoutOverride{}.Size(400, 400)); app.EndRootWindow(); @@ -640,10 +642,10 @@ namespace tachyon { // In a table wider than its fixed columns, the last (Fractional) column is // at least its initialWidth and absorbs the leftover width. - tachyon::TableState state{}; + tachyon::views::TableState state{}; // Three columns with configured widths summing to 80+100+120 = 300. // Table width 600 -> 300px of leftover width should go to the last col. - tachyon::VirtualTableColumn cols[] = { + tachyon::views::VirtualTableColumn cols[] = { { {.header = "A", .initialWidth = 80 } }, { {.header = "B", .initialWidth = 100 } }, { {.header = "C", .initialWidth = 120 } }, @@ -651,14 +653,14 @@ namespace tachyon app.Frame([&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, cols, state, LayoutOverride{}.Size(600, 200))) + if (views::BeginTable(app, viewsContext, tableID, cols, state, LayoutOverride{}.Size(600, 200))) { - app.BeginRow(); - app.Cell("a"); - app.Cell("b"); - app.Cell("c"); - app.EndRow(); - app.EndTable(); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "a"); + views::Cell(app, viewsContext, "b"); + views::Cell(app, viewsContext, "c"); + views::EndRow(app, viewsContext); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }); @@ -681,8 +683,8 @@ namespace tachyon // Symmetric: even when the table is NARROWER than the sum of fixed // columns, the last column must not collapse - it uses its configured // width as a floor and the outer wrapper handles horizontal overflow. - tachyon::TableState state{}; - tachyon::VirtualTableColumn cols[] = { + tachyon::views::TableState state{}; + tachyon::views::VirtualTableColumn cols[] = { { {.header = "A", .initialWidth = 200 } }, { {.header = "B", .initialWidth = 200 } }, { {.header = "C", .initialWidth = 200 } }, @@ -691,12 +693,12 @@ namespace tachyon // Table width 400 - less than sum of 600. app.Frame([&] { app.BeginRootWindow(); - if (app.BeginTable(tableID, cols, state, LayoutOverride{}.Size(400, 200))) + if (views::BeginTable(app, viewsContext, tableID, cols, state, LayoutOverride{}.Size(400, 200))) { - app.BeginRow(); - app.Cell("a"); app.Cell("b"); app.Cell("c"); - app.EndRow(); - app.EndTable(); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "a"); views::Cell(app, viewsContext, "b"); views::Cell(app, viewsContext, "c"); + views::EndRow(app, viewsContext); + views::EndTable(app, viewsContext); } app.EndRootWindow(); }); @@ -714,19 +716,19 @@ namespace tachyon { // The header section must not shrink: the body's huge intrinsic height // (50 000 spacer rows) would otherwise squeeze the header to ~0px. - tachyon::TableState state{}; + tachyon::views::TableState state{}; state.internal.lastViewportH = 400; - tachyon::VirtualTableColumn vcols[] = { + tachyon::views::VirtualTableColumn vcols[] = { { {.header = "A", .initialWidth = 80 }, - [&](int rowIdx) { (void)rowIdx; app.Cell("a"); } }, + [&](int rowIdx) { (void)rowIdx; views::Cell(app, viewsContext, "a"); } }, { {.header = "B", .initialWidth = 80 }, - [&](int rowIdx) { (void)rowIdx; app.Cell("b"); } }, + [&](int rowIdx) { (void)rowIdx; views::Cell(app, viewsContext, "b"); } }, }; auto build = [&] { app.BeginRootWindow(); - app.VirtualTable(tableID, state, vcols, /*totalRows*/50'000, + views::VirtualTable(app, viewsContext, tableID, state, vcols, /*totalRows*/50'000, /*rowHeight*/28, StyleRef{}, LayoutOverride{}.Size(400, 400)); app.EndRootWindow(); @@ -748,19 +750,19 @@ namespace tachyon { // Header and body are sibling grids, so scrolling the body leaves the // header's Y unchanged. - tachyon::TableState state{}; + tachyon::views::TableState state{}; state.internal.lastViewportH = 400; - tachyon::VirtualTableColumn vcols[] = { + tachyon::views::VirtualTableColumn vcols[] = { { {.header = "A", .initialWidth = 80 }, - [&](int rowIdx) { (void)rowIdx; app.Cell("a"); } }, + [&](int rowIdx) { (void)rowIdx; views::Cell(app, viewsContext, "a"); } }, { {.header = "B", .initialWidth = 80 }, - [&](int rowIdx) { (void)rowIdx; app.Cell("b"); } }, + [&](int rowIdx) { (void)rowIdx; views::Cell(app, viewsContext, "b"); } }, }; auto build = [&] { app.BeginRootWindow(); - app.VirtualTable(tableID, state, vcols, /*totalRows*/500, + views::VirtualTable(app, viewsContext, tableID, state, vcols, /*totalRows*/500, /*rowHeight*/28, StyleRef{}, LayoutOverride{}.Size(400, 400)); app.EndRootWindow(); @@ -799,9 +801,9 @@ namespace tachyon // room) keeps its scroll position for when it comes back. TEST_F(TableIntegrationTest, SqueezedTableKeepsItsScrollPosition) { - tachyon::TableState state{}; - tachyon::VirtualTableColumn vcols[] = { - { {.header = "A", .initialWidth = 80 }, [&](int) { app.Cell("a"); } }, + tachyon::views::TableState state{}; + tachyon::views::VirtualTableColumn vcols[] = { + { {.header = "A", .initialWidth = 80 }, [&](int) { views::Cell(app, viewsContext, "a"); } }, }; int siblingHeight = 100; auto build = [&] { @@ -810,7 +812,7 @@ namespace tachyon app.BeginVertical(LayoutOverride{}.Height(CssPx(siblingHeight)).NoShrink()); app.EndVertical(); app.BeginHorizontal(app.theme.flexFillRowStyleRef, LayoutOverride{}.FlexGrow(1)); - app.VirtualTable(tableID, state, vcols, /*totalRows*/500, + views::VirtualTable(app, viewsContext, tableID, state, vcols, /*totalRows*/500, /*rowHeight*/28, StyleRef{}, LayoutOverride{}.FlexGrow(1)); app.EndHorizontal(); app.EndVertical(); @@ -840,19 +842,19 @@ namespace tachyon // rather than estimating from the font size. TEST_F(TableIntegrationTest, RowHeightFallbackIsMeasured) { - const TextID probe = app.textSystem->RegisterText(tachyon::ID::Invalid(), "Mg", app.theme.tableCellStyleRef, tachyon::ElementState::None); + const TextID probe = app.textSystem->RegisterText(tachyon::ID::Invalid(), "Mg", views::GetStyles(app, viewsContext).tableCellStyleRef, tachyon::ElementState::None); int32_t expected = app.textSystem->GetTextMeasurement(probe).minHeight; - if (const auto* ls = app.styleManager.GetLayoutStyle(app.theme.tableCellStyleRef.layoutStyleIndex)) + if (const auto* ls = app.styleManager.GetLayoutStyle(views::GetStyles(app, viewsContext).tableCellStyleRef.layoutStyleIndex)) expected += ls->padding.Vertical() + ls->borderWidths.Vertical(); - app.theme.tableRowHeight = 0; - tachyon::TableState state{}; - tachyon::VirtualTableColumn vcols[] = { - { {.header = "A", .initialWidth = 80 }, [&](int) { app.Cell("a"); } }, + viewsContext.styles.tableRowHeight = 0; // looked up above + tachyon::views::TableState state{}; + tachyon::views::VirtualTableColumn vcols[] = { + { {.header = "A", .initialWidth = 80 }, [&](int) { views::Cell(app, viewsContext, "a"); } }, }; app.Frame([&] { app.BeginRootWindow(); - app.VirtualTable(tableID, state, vcols, 10, /*rowHeight*/0, StyleRef{}, LayoutOverride{}.Size(400, 200)); + views::VirtualTable(app, viewsContext, tableID, state, vcols, 10, /*rowHeight*/0, StyleRef{}, LayoutOverride{}.Size(400, 200)); app.EndRootWindow(); }); EXPECT_EQ(state.internal.actualRowHeight, expected); @@ -862,20 +864,20 @@ namespace tachyon { // The production viewport-height measurement happens in a custom-draw // callback that only runs during RENDER. Our headless harness stops at - // layout, so we simulate the sampled height directly on the TableState + // layout, so we simulate the sampled height directly on the views::TableState // and verify VirtualTable uses it on the next frame. - tachyon::TableState state{}; + tachyon::views::TableState state{}; int cellsEmitted = 0; int* counter = &cellsEmitted; - tachyon::VirtualTableColumn vcols[] = { + tachyon::views::VirtualTableColumn vcols[] = { { {.header = "#", .initialWidth = 80 }, - [&](int rowIdx) { (void)rowIdx; app.Cell("n"); (*counter)++; } }, + [&](int rowIdx) { (void)rowIdx; views::Cell(app, viewsContext, "n"); (*counter)++; } }, }; auto build = [&] { app.BeginRootWindow(); - app.VirtualTable(tableID, state, vcols, + views::VirtualTable(app, viewsContext, tableID, state, vcols, /*totalRows*/50'000, /*rowHeight*/28, StyleRef{}, LayoutOverride{}.Size(400, 400)); app.EndRootWindow(); @@ -905,7 +907,7 @@ namespace tachyon TEST_F(TableIntegrationTest, DownArrowAdvancesSelectedRow) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; app.Frame([&] { EmitSimpleTable(state); }); ASSERT_EQ(state.internal.totalRowCount, 3); @@ -937,7 +939,7 @@ namespace tachyon TEST_F(TableIntegrationTest, HomeAndEndJumpToBoundaryRows) { - tachyon::TableState state{}; + tachyon::views::TableState state{}; app.Frame([&] { EmitSimpleTable(state); }); ASSERT_EQ(state.internal.totalRowCount, 3); @@ -969,23 +971,24 @@ namespace tachyon struct PagingTable { HeadlessGUIApp& app; + views::Context& viewsContext; tachyon::ID tableID; - tachyon::VirtualTableColumn* cols; + tachyon::views::VirtualTableColumn* cols; size_t colCount; int rowCount; - void emit(tachyon::TableState& state) const + void emit(tachyon::views::TableState& state) const { app.BeginRootWindow(); - if (app.BeginTable(tableID, cols, colCount, state, + if (views::BeginTable(app, viewsContext, tableID, cols, colCount, state, LayoutOverride{}.Size(400, 200))) { for (int r = 0; r < rowCount; r++) { - app.BeginRow(); - app.Cell("a"); app.Cell("b"); app.Cell("c"); - app.EndRow(); + views::BeginRow(app, viewsContext); + views::Cell(app, viewsContext, "a"); views::Cell(app, viewsContext, "b"); views::Cell(app, viewsContext, "c"); + views::EndRow(app, viewsContext); } - app.EndTable(); + views::EndTable(app, viewsContext); } app.EndRootWindow(); } @@ -993,8 +996,8 @@ namespace tachyon TEST_F(TableIntegrationTest, PageDownAdvancesByVisibleRowCount) { - tachyon::TableState state{}; - PagingTable t{ app, tableID, kColumns, 3, 30 }; + tachyon::views::TableState state{}; + PagingTable t{ app, viewsContext, tableID, kColumns, 3, 30 }; auto build = [&] { t.emit(state); }; app.Frame(build); // Headless never renders, so simulate the render-time viewport @@ -1023,8 +1026,8 @@ namespace tachyon TEST_F(TableIntegrationTest, PageUpRetreatsByVisibleRowCount) { - tachyon::TableState state{}; - PagingTable t{ app, tableID, kColumns, 3, 30 }; + tachyon::views::TableState state{}; + PagingTable t{ app, viewsContext, tableID, kColumns, 3, 30 }; auto build = [&] { t.emit(state); }; app.Frame(build); state.internal.lastViewportH = 200; // simulate render-time sampling @@ -1053,8 +1056,8 @@ namespace tachyon TEST_F(TableIntegrationTest, PageDownStopsAtLastRow) { - tachyon::TableState state{}; - PagingTable t{ app, tableID, kColumns, 3, 30 }; + tachyon::views::TableState state{}; + PagingTable t{ app, viewsContext, tableID, kColumns, 3, 30 }; auto build = [&] { t.emit(state); }; app.Frame(build); state.internal.lastViewportH = 200; // simulate render-time sampling @@ -1078,8 +1081,8 @@ namespace tachyon TEST_F(TableIntegrationTest, PageUpStopsAtFirstRow) { - tachyon::TableState state{}; - PagingTable t{ app, tableID, kColumns, 3, 30 }; + tachyon::views::TableState state{}; + PagingTable t{ app, viewsContext, tableID, kColumns, 3, 30 }; auto build = [&] { t.emit(state); }; app.Frame(build); state.internal.lastViewportH = 200; // simulate render-time sampling diff --git a/tests/table_row_heights_test.cpp b/tests/table_row_heights_test.cpp index 003b77d5..42076dda 100644 --- a/tests/table_row_heights_test.cpp +++ b/tests/table_row_heights_test.cpp @@ -3,6 +3,7 @@ // headers 26-28. #include +#include #include "headless_gui_app.h" @@ -35,12 +36,13 @@ namespace } int Px(int n) { return app.styleManager.Px(n); } HeadlessGUIApp app; + views::Context viewsContext; }; TEST_F(TableRowHeights, ProfilerRowsAre22) { - EXPECT_EQ(RowHeight(app, app.theme.tableCellStyleRef), Px(22)); - EXPECT_EQ(app.theme.tableRowHeight, Px(22)); + EXPECT_EQ(RowHeight(app, views::GetStyles(app, viewsContext).tableCellStyleRef), Px(22)); + EXPECT_EQ(views::GetStyles(app, viewsContext).tableRowHeight, Px(22)); } TEST_F(TableRowHeights, DataTableRowsAre24) @@ -61,13 +63,13 @@ namespace // Number cells sit in the same rows as text cells, so they are as high. TEST_F(TableRowHeights, NumberCellsMatchTheirRows) { - EXPECT_EQ(RowHeight(app, app.theme.tableCellNumberStyleRef), RowHeight(app, app.theme.tableCellStyleRef)); + EXPECT_EQ(RowHeight(app, views::GetStyles(app, viewsContext).tableCellNumberStyleRef), RowHeight(app, views::GetStyles(app, viewsContext).tableCellStyleRef)); EXPECT_EQ(RowHeight(app, app.theme.GetStyle("data-table-number")), RowHeight(app, app.theme.GetStyle("data-table-cell"))); } TEST_F(TableRowHeights, HeadersAre26To28) { - const int h = RowHeight(app, app.theme.tableHeaderStyleRef); + const int h = RowHeight(app, views::GetStyles(app, viewsContext).tableHeaderStyleRef); EXPECT_GE(h, Px(26)); EXPECT_LE(h, Px(28)); } diff --git a/tests/table_scrollbar_test.cpp b/tests/table_scrollbar_test.cpp index 8b27c79b..b526898f 100644 --- a/tests/table_scrollbar_test.cpp +++ b/tests/table_scrollbar_test.cpp @@ -1,6 +1,6 @@ // Scrollbar emission for VirtualTable under different sizing regimes. // -// Production gates each bar on TableState's overflow flags, which a +// Production gates each bar on views::TableState's overflow flags, which a // POST-LAYOUT sampler on the section body sets (contentSize vs innerRect). // The harness skips per-element post-layout, so this fixture fires the // registered entries manually after each frame - the same loop production @@ -13,6 +13,8 @@ #include #include +#include +#include #include @@ -22,13 +24,10 @@ namespace tachyon namespace { - // SettingsPanelState is protected on GUIApplication (the showcase reaches - // it via inheritance); expose it the same way for the fixture. class SettingsHostApp : public HeadlessGUIApp { public: - using SettingsState = GUIApplication::SettingsPanelState; - using GUIApplication::RenderSettingsPanel; + using SettingsState = views::SettingsPanelState; SettingsState settings; }; @@ -36,17 +35,20 @@ namespace tachyon { protected: SettingsHostApp app; - tachyon::TableState state; - std::vector cols; + 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; app.Cell("name"); }; + cols[0].generateCell = [this](int r) { (void)r; views::Cell(app, viewsContext, "name"); }; cols[1].column = { .header = "Value", .initialWidth = 120, .minWidth = 40, .maxWidth = 400 }; - cols[1].generateCell = [this](int r) { (void)r; app.Cell("value"); }; + cols[1].generateCell = [this](int r) { (void)r; views::Cell(app, viewsContext, "value"); }; } void TearDown() override { app.Cleanup(); } @@ -73,9 +75,9 @@ namespace tachyon void BuildFixedSize() { app.BeginRootWindow(); - app.VirtualTable(app.idManager.AllocateDynamicID("tbl"), state, - std::span(cols), - /*rows*/200, 0, app.theme.tableStyleRef, + views::VirtualTable(app, viewsContext, app.idManager.AllocateDynamicID("tbl"), state, + std::span(cols), + /*rows*/200, 0, views::GetStyles(app, viewsContext).tableStyleRef, tachyon::LayoutOverride{}.Width(500).Height(300)); app.EndRootWindow(); } @@ -86,14 +88,14 @@ namespace tachyon { app.BeginRootWindow(); app.BeginArea(app.idManager.AllocateDynamicID("pane"), - app.theme.settingsPageStyleRef, + views::GetStyles(app, viewsContext).settingsPageStyleRef, tachyon::LayoutOverride{}.Size(700, 300).NoGrow().NoShrink()); app.BeginHorizontal(app.idManager.AllocateDynamicID("fill"), app.theme.flexFillRowStyleRef, tachyon::LayoutOverride::Auto().FlexGrow(1)); - app.VirtualTable(app.idManager.AllocateDynamicID("tbl"), state, - std::span(cols), - /*rows*/200, 0, app.theme.tableStyleRef, + views::VirtualTable(app, viewsContext, app.idManager.AllocateDynamicID("tbl"), state, + std::span(cols), + /*rows*/200, 0, views::GetStyles(app, viewsContext).tableStyleRef, tachyon::LayoutOverride::Auto().FlexGrow(1)); app.EndHorizontal(); app.EndArea(); @@ -106,22 +108,22 @@ namespace tachyon // the given outer style. The container is fixed at 300 wide. void BuildWideColumns(tachyon::StyleRef tableStyle) { - std::vector wide(2); + std::vector wide(2); wide[0].column = { .header = "A", .initialWidth = 250, .minWidth = 200, .maxWidth = 400 }; - wide[0].generateCell = [this](int r){ (void)r; app.Cell("aaaa"); }; + wide[0].generateCell = [this](int r){ (void)r; views::Cell(app, viewsContext, "aaaa"); }; wide[1].column = { .header = "B", .initialWidth = 250, .minWidth = 200, .maxWidth = 400 }; - wide[1].generateCell = [this](int r){ (void)r; app.Cell("bbbb"); }; + wide[1].generateCell = [this](int r){ (void)r; views::Cell(app, viewsContext, "bbbb"); }; // Keep them alive for the frame; static so the sizer pointers // (if any) stay valid like the showcase's persistent columns. - static std::vector held; + static std::vector held; held = std::move(wide); app.BeginRootWindow(); app.BeginArea(app.idManager.AllocateDynamicID("wpane"), app.theme.flexFillRowStyleRef, tachyon::LayoutOverride{}.Size(300, 300).NoGrow().NoShrink()); - app.VirtualTable(app.idManager.AllocateDynamicID("wtbl"), state, - std::span(held), + views::VirtualTable(app, viewsContext, app.idManager.AllocateDynamicID("wtbl"), state, + std::span(held), /*rows*/200, 0, tableStyle, tachyon::LayoutOverride{}.FlexGrow(1)); app.EndArea(); @@ -157,12 +159,13 @@ namespace tachyon TEST(SettingsPanelTest, TreeWidthIsInCssPixels) { SettingsHostApp app; + views::Context viewsContext; app.SetUIScale(2.0f); ASSERT_TRUE(app.Initialize()); app.settings.AddPage(app.idManager.CreateStaticID(), "Page", [] {}); app.Frame([&] { app.BeginRootWindow(); - app.RenderSettingsPanel(app.settings); + views::RenderSettingsPanel(app, viewsContext, app.settings); app.EndRootWindow(); }); EXPECT_EQ(app.settings.treeWidth, 200); @@ -175,9 +178,9 @@ namespace tachyon TEST_F(TableScrollbarTest, ShortcutsShapedSettingsPageEmitsVerticalScrollbar) { auto& sp = app.settings; - std::vector catRows; + std::vector catRows; std::vector catVisible; - tachyon::TableState catTable; + tachyon::views::TableState catTable; std::string searchText; int catWidth = 160; @@ -200,19 +203,19 @@ namespace tachyon tachyon::LayoutOverride::Auto().FlexGrow(1)); catRows.clear(); - tachyon::TreeViewRow r{}; + tachyon::views::TreeViewRow r{}; r.id = app.idManager.AllocateDynamicID("cat"); r.name = "All"; catRows.push_back(std::move(r)); - app.RebuildTreeViewIndex(catRows); - app.VirtualTreeView(app.idManager.AllocateDynamicID("catTree"), + views::RebuildTreeViewIndex(catRows); + views::VirtualTreeView(app, viewsContext, app.idManager.AllocateDynamicID("catTree"), catRows, catVisible, catTable, - app.theme.treeViewStyleRef, + views::GetStyles(app, viewsContext).treeViewStyleRef, tachyon::LayoutOverride::Auto().FixedWidth(CssPx(catWidth)).NoGrow()); 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); @@ -224,9 +227,9 @@ namespace tachyon app.BeginHorizontal(app.idManager.AllocateDynamicID("gridCol"), app.theme.flexFillRowStyleRef, tachyon::LayoutOverride::Auto().FlexGrow(1)); - app.VirtualTable(app.idManager.AllocateDynamicID("tbl"), state, - std::span(cols), - /*rows*/200, 0, app.theme.tableStyleRef, + views::VirtualTable(app, viewsContext, app.idManager.AllocateDynamicID("tbl"), state, + std::span(cols), + /*rows*/200, 0, views::GetStyles(app, viewsContext).tableStyleRef, tachyon::LayoutOverride::Auto().FlexGrow(1)); app.EndHorizontal(); @@ -244,9 +247,9 @@ 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)); - app.RenderSettingsPanel(sp); + views::RenderSettingsPanel(app, viewsContext, sp); app.EndArea(); // dockContent app.EndArea(); // leaf app.EndRootWindow(); @@ -271,9 +274,9 @@ namespace tachyon // vertical bar stays inside the visible pane. TEST_F(TableScrollbarTest, OverflowingColumnsKeepVerticalBarInBounds) { - Frame([&] { BuildWideColumns(app.theme.tableFillStyleRef); }); - Frame([&] { BuildWideColumns(app.theme.tableFillStyleRef); }); - Frame([&] { BuildWideColumns(app.theme.tableFillStyleRef); }); + Frame([&] { BuildWideColumns(views::GetStyles(app, viewsContext).tableFillStyleRef); }); + Frame([&] { BuildWideColumns(views::GetStyles(app, viewsContext).tableFillStyleRef); }); + Frame([&] { BuildWideColumns(views::GetStyles(app, viewsContext).tableFillStyleRef); }); ASSERT_TRUE(app.HasElement(state.internal.vertScrollbarID)); const auto bar = BarRect(); diff --git a/tests/theme_metrics_test.cpp b/tests/theme_metrics_test.cpp index 8e782f2b..2bc12853 100644 --- a/tests/theme_metrics_test.cpp +++ b/tests/theme_metrics_test.cpp @@ -1,6 +1,9 @@ // Theme metrics from the default theme that code relies on. #include +#include +#include +#include #include "headless_gui_app.h" @@ -34,10 +37,11 @@ namespace TEST(ThemeMetrics, ButtonIconsAreFourteenPixels) { HeadlessGUIApp app; + nodes::Context nodesContext; ASSERT_TRUE(app.Initialize()); for (const StyleRef style : { app.theme.controls->button, app.theme.controls->toggle, app.theme.toolbarControls.button, app.theme.toolbarControls.toggle, - app.theme.nodeViewOverlayButtonStyleRef }) + nodes::GetStyles(app, nodesContext).nodeViewOverlayButtonStyleRef }) for (const ElementState state : { ElementState::None, ElementState::Hover, ElementState::Selected }) EXPECT_EQ(IconSize(app, style, state), app.styleManager.Px(14)) << int(state); } @@ -46,14 +50,17 @@ 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); - EXPECT_EQ(hoverBackground(app.theme.tableSizerStyleRef), 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 6c8df76e..9ac1dcb7 100644 --- a/tests/theme_variables_test.cpp +++ b/tests/theme_variables_test.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include @@ -309,6 +310,7 @@ namespace tachyon { protected: HeadlessGUIApp app; + dialogs::Context dialogContext; void SetUp() override { ASSERT_TRUE(app.Initialize()); Frame(); } void TearDown() override { app.Cleanup(); } @@ -361,7 +363,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 +371,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"; } diff --git a/tests/tree_utils_test.cpp b/tests/tree_utils_test.cpp index fc54cd68..00a46043 100644 --- a/tests/tree_utils_test.cpp +++ b/tests/tree_utils_test.cpp @@ -3,7 +3,8 @@ #include -#include +#include +#include #include #include @@ -63,7 +64,7 @@ namespace tachyon if (step == 0 && depth < 40) depth++; else if (step == 1 && depth > 0) depth -= 1 + int(next() % uint32_t(depth)); } - TreeUtils::RebuildTreeIndex(rows); + views::TreeUtils::RebuildTreeIndex(rows); const int n = int(rows.size()); for (int i = 0; i < n; ++i) { @@ -87,7 +88,7 @@ namespace tachyon TEST(TreeUtilsTest, RebuildIndexComputesSkipCounts) { auto rows = MakeTree(); - TreeUtils::RebuildTreeIndex(rows); + views::TreeUtils::RebuildTreeIndex(rows); EXPECT_EQ(rows[0].skipCount, 4); // A spans B,C,D,E EXPECT_EQ(rows[1].skipCount, 2); // B spans C,D EXPECT_EQ(rows[2].skipCount, 0); @@ -99,7 +100,7 @@ namespace tachyon TEST(TreeUtilsTest, RebuildIndexComputesAncestorLineMask) { auto rows = MakeTree(); - TreeUtils::RebuildTreeIndex(rows); + views::TreeUtils::RebuildTreeIndex(rows); // C and D draw a depth-0 guide column because their depth-1 // ancestor (B) has a later sibling (E). EXPECT_EQ(rows[2].ancestorLineMask, 1u); @@ -113,7 +114,7 @@ namespace tachyon TEST(TreeUtilsTest, RebuildIndexMarksLastSiblings) { auto rows = MakeTree(); - TreeUtils::RebuildTreeIndex(rows); + views::TreeUtils::RebuildTreeIndex(rows); EXPECT_FALSE(rows[0].isLastSibling); // A has sibling F EXPECT_FALSE(rows[1].isLastSibling); // B has sibling E EXPECT_FALSE(rows[2].isLastSibling); // C has sibling D @@ -125,10 +126,10 @@ namespace tachyon TEST(TreeUtilsTest, ReorderBeforeInsertsAtTarget) { auto rows = MakeTree(); - TreeUtils::RebuildTreeIndex(rows); + views::TreeUtils::RebuildTreeIndex(rows); // Move F before B -> F becomes A's first child position-wise but // keeps B's depth (reparent to depth 1). - const int newIdx = TreeUtils::ReorderTreeRow(rows, 5, 1, DropPos::Before); + const int newIdx = views::TreeUtils::ReorderTreeRow(rows, 5, 1, DropPos::Before); EXPECT_EQ(newIdx, 1); EXPECT_EQ(Names(rows), (std::vector{ "A", "F", "B", "C", "D", "E" })); EXPECT_EQ(rows[1].depth, 1); @@ -137,9 +138,9 @@ namespace tachyon TEST(TreeUtilsTest, ReorderAfterSkipsTargetSubtree) { auto rows = MakeTree(); - TreeUtils::RebuildTreeIndex(rows); + views::TreeUtils::RebuildTreeIndex(rows); // Move F after B -> lands past B's whole subtree (C,D), before E. - const int newIdx = TreeUtils::ReorderTreeRow(rows, 5, 1, DropPos::After); + const int newIdx = views::TreeUtils::ReorderTreeRow(rows, 5, 1, DropPos::After); EXPECT_EQ(newIdx, 4); EXPECT_EQ(Names(rows), (std::vector{ "A", "B", "C", "D", "F", "E" })); EXPECT_EQ(rows[4].depth, 1); @@ -148,8 +149,8 @@ namespace tachyon TEST(TreeUtilsTest, ReorderInsideBecomesFirstChild) { auto rows = MakeTree(); - TreeUtils::RebuildTreeIndex(rows); - const int newIdx = TreeUtils::ReorderTreeRow(rows, 5, 1, DropPos::Inside); + views::TreeUtils::RebuildTreeIndex(rows); + const int newIdx = views::TreeUtils::ReorderTreeRow(rows, 5, 1, DropPos::Inside); EXPECT_EQ(newIdx, 2); EXPECT_EQ(Names(rows), (std::vector{ "A", "B", "F", "C", "D", "E" })); EXPECT_EQ(rows[2].depth, 2); @@ -158,8 +159,8 @@ namespace tachyon TEST(TreeUtilsTest, ReorderInsideLastBecomesLastChild) { auto rows = MakeTree(); - TreeUtils::RebuildTreeIndex(rows); - const int newIdx = TreeUtils::ReorderTreeRow(rows, 5, 1, DropPos::InsideLast); + views::TreeUtils::RebuildTreeIndex(rows); + const int newIdx = views::TreeUtils::ReorderTreeRow(rows, 5, 1, DropPos::InsideLast); EXPECT_EQ(newIdx, 4); EXPECT_EQ(Names(rows), (std::vector{ "A", "B", "C", "D", "F", "E" })); EXPECT_EQ(rows[4].depth, 2); @@ -168,9 +169,9 @@ namespace tachyon TEST(TreeUtilsTest, ReorderInsideOpensParent) { auto rows = MakeTree(); - TreeUtils::RebuildTreeIndex(rows); + views::TreeUtils::RebuildTreeIndex(rows); ASSERT_FALSE(rows[1].isOpen); - TreeUtils::ReorderTreeRow(rows, 5, 1, DropPos::Inside); + views::TreeUtils::ReorderTreeRow(rows, 5, 1, DropPos::Inside); // B (still at index 1) was opened so the drop is visible. EXPECT_TRUE(rows[1].isOpen); } @@ -178,23 +179,23 @@ namespace tachyon TEST(TreeUtilsTest, ReorderRejectsSelfAndDescendantDrop) { auto rows = MakeTree(); - TreeUtils::RebuildTreeIndex(rows); + views::TreeUtils::RebuildTreeIndex(rows); const auto before = Names(rows); - EXPECT_EQ(TreeUtils::ReorderTreeRow(rows, 1, 1, DropPos::Before), -1); // self - EXPECT_EQ(TreeUtils::ReorderTreeRow(rows, 1, 2, DropPos::Before), -1); // own child - EXPECT_EQ(TreeUtils::ReorderTreeRow(rows, 0, 4, DropPos::After), -1); // own descendant - EXPECT_EQ(TreeUtils::ReorderTreeRow(rows, -1, 2, DropPos::Before), -1); - EXPECT_EQ(TreeUtils::ReorderTreeRow(rows, 1, 99, DropPos::Before), -1); + EXPECT_EQ(views::TreeUtils::ReorderTreeRow(rows, 1, 1, DropPos::Before), -1); // self + EXPECT_EQ(views::TreeUtils::ReorderTreeRow(rows, 1, 2, DropPos::Before), -1); // own child + EXPECT_EQ(views::TreeUtils::ReorderTreeRow(rows, 0, 4, DropPos::After), -1); // own descendant + EXPECT_EQ(views::TreeUtils::ReorderTreeRow(rows, -1, 2, DropPos::Before), -1); + EXPECT_EQ(views::TreeUtils::ReorderTreeRow(rows, 1, 99, DropPos::Before), -1); EXPECT_EQ(Names(rows), before); } TEST(TreeUtilsTest, ReorderReparentShiftsSubtreeDepths) { auto rows = MakeTree(); - TreeUtils::RebuildTreeIndex(rows); + views::TreeUtils::RebuildTreeIndex(rows); // Move B's subtree (B,C,D) after F -> B reparents to depth 0 and // its children shift by the same delta. - const int newIdx = TreeUtils::ReorderTreeRow(rows, 1, 5, DropPos::After); + const int newIdx = views::TreeUtils::ReorderTreeRow(rows, 1, 5, DropPos::After); EXPECT_EQ(newIdx, 3); EXPECT_EQ(Names(rows), (std::vector{ "A", "E", "F", "B", "C", "D" })); EXPECT_EQ(rows[3].depth, 0); @@ -205,10 +206,10 @@ namespace tachyon TEST(TreeUtilsTest, ReorderReturnsAdjustedIndexWhenMovingForward) { auto rows = MakeTree(); - TreeUtils::RebuildTreeIndex(rows); + views::TreeUtils::RebuildTreeIndex(rows); // Moving forward past the erased slice: insertAt is adjusted by // the slice size, so the returned index addresses the moved row. - const int newIdx = TreeUtils::ReorderTreeRow(rows, 1, 5, DropPos::Before); + const int newIdx = views::TreeUtils::ReorderTreeRow(rows, 1, 5, DropPos::Before); ASSERT_GE(newIdx, 0); EXPECT_EQ(rows[size_t(newIdx)].name, "B"); } diff --git a/tests/ui_cache_test.cpp b/tests/ui_cache_test.cpp index 26154dd2..977faca5 100644 --- a/tests/ui_cache_test.cpp +++ b/tests/ui_cache_test.cpp @@ -14,7 +14,9 @@ #include #include #include -#include +#include +#include +#include #include @@ -28,12 +30,15 @@ namespace tachyon { protected: HeadlessGUIApp app; + docking::Context dockingContext; + nodes::Context nodesContext; ID scopeID, btnA, btnB, outsideID; int bodyRuns = 0; void SetUp() override { ASSERT_TRUE(app.Initialize()); + docking::Install(app, dockingContext); scopeID = app.idManager.CreateStaticID(); btnA = app.idManager.CreateStaticID(); btnB = app.idManager.CreateStaticID(); @@ -222,8 +227,8 @@ namespace tachyon { app.SetDrawCacheEnabled(true); app.runPostLayoutCallbacks = true; // the view learns its canvas size there - NodeView view; - NodeModel node{}; + nodes::NodeView view; + nodes::NodeModel node{}; node.stableID = app.idManager.CreateStaticID(); node.title = "A"; node.pos = { 40, 40 }; @@ -235,13 +240,13 @@ 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++; app.BeginVertical(headerID, LayoutOverride{}.Height(CssPx(headerHeight)).NoGrow().NoShrink()); app.EndVertical(); - app.RenderNodeView(view); + nodes::RenderNodeView(app, nodesContext, view); } app.EndCached(); app.EndRootWindow(); @@ -673,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(); }); }; @@ -703,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(); } @@ -711,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(); } @@ -739,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(); } @@ -767,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(); } @@ -800,7 +817,9 @@ namespace tachyon { protected: HeadlessGUIApp app; - tachyon::DockingLayout layout; + docking::Context dockingContext; + nodes::Context nodesContext; + 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 @@ -812,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(); } @@ -836,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(); }); } @@ -894,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 9343fdb0..3e799c30 100644 --- a/tests/ui_scale_test.cpp +++ b/tests/ui_scale_test.cpp @@ -2,6 +2,8 @@ // (the primary monitor's before any window exists) times the app's zoom. #include +#include +#include #include "headless_gui_app.h" #include "scoped_temp_dir.h" @@ -40,11 +42,13 @@ namespace tachyon TEST(UIScaleTest, ThemeMetricsAreScaled) { HeadlessGUIApp normal; + nodes::Context normalContext; ASSERT_TRUE(normal.Initialize()); HeadlessGUIApp zoomed; + nodes::Context zoomedContext; zoomed.SetUIScale(2.0f); ASSERT_TRUE(zoomed.Initialize()); - EXPECT_EQ(zoomed.theme.socketSize, 2 * normal.theme.socketSize); + EXPECT_EQ(nodes::GetStyles(zoomed, zoomedContext).socketSize, 2 * nodes::GetStyles(normal, normalContext).socketSize); EXPECT_EQ(normal.theme.scrollbarThickness, 12); EXPECT_EQ(zoomed.theme.scrollbarThickness, 24); } @@ -66,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 42f7acbc..98ae6465 100644 --- a/tests/ui_state_test.cpp +++ b/tests/ui_state_test.cpp @@ -5,8 +5,10 @@ #include "headless_gui_app.h" #include "mock_window_backend.h" -#include +#include #include +#include +#include #include #include @@ -69,6 +71,8 @@ namespace { protected: HeadlessGUIApp app; + docking::Context dockingContext; + views::Context viewsContext; void SetUp() override { ASSERT_TRUE(app.Initialize()); } void TearDown() override { app.Cleanup(); } }; @@ -186,24 +190,24 @@ namespace TEST_F(UIStateTest, TableColumnOrderAndWidthsComeBack) { auto makeColumns = [] { - std::vector columns(3); + std::vector columns(3); columns[0].column.header = "Name"; columns[1].column.header = "Size"; columns[2].column.header = "Date"; return columns; }; - TableState state; - std::vector columns = makeColumns(); + views::TableState state; + std::vector columns = makeColumns(); std::swap(columns[0], columns[2]); // the user moved Date first state.columnWidths = { 90, 60, 200 }; // Date, Size, Name - app.PersistTable("files", state, columns); + views::PersistTable(app, "files", state, columns); const std::string saved = app.SaveUIState(); - TableState fresh; - std::vector freshColumns = makeColumns(); + views::TableState fresh; + std::vector freshColumns = makeColumns(); freshColumns.push_back({}); freshColumns.back().column.header = "Kind"; // added since the save - app.PersistTable("files", fresh, freshColumns); + views::PersistTable(app, "files", fresh, freshColumns); ASSERT_TRUE(app.RestoreUIState(saved)); ASSERT_EQ(freshColumns.size(), 4u); EXPECT_EQ(freshColumns[0].column.header, "Date"); @@ -215,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); @@ -251,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; }; @@ -269,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" }); @@ -279,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"; @@ -290,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); @@ -524,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) @@ -548,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"); @@ -576,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"; @@ -588,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"); } @@ -614,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; })); @@ -653,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. @@ -686,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"); @@ -711,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"); @@ -725,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 1eaaa022..6ba9e168 100644 --- a/tests/view_state_test.cpp +++ b/tests/view_state_test.cpp @@ -1,11 +1,13 @@ -// A view's own state as text, for a panel to keep with its layout (Panel::saveState): a node -// view's pan and zoom, the part of a timeline or curve plot in view, a viewport's camera, the -// settings page open. Each comes back as it was; text that can't be read changes nothing. +// 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 #include -#include +#include +#include +#include +#include namespace tachyon { @@ -13,82 +15,43 @@ namespace tachyon { TEST(ViewState, ANodeViewsPanAndZoomComeBack) { - NodeView view; + nodes::NodeView view; view.transform.r0 = float3{ 1.5f, 0.0f, 120.0f }; view.transform.r1 = float3{ 0.0f, 1.5f, -40.0f }; const std::string saved = SaveViewState(view); - NodeView again; + nodes::NodeView again; ASSERT_TRUE(RestoreViewState(again, saved)); EXPECT_EQ(again.transform, view.transform); } - TEST(ViewState, ATimelinesViewComesBack) - { - TimelineView view; - view.viewStart = 2.5f; - view.viewLength = 4.0f; - view.zoom = 60; - TimelineView again; - ASSERT_TRUE(RestoreViewState(again, SaveViewState(view))); - EXPECT_EQ(again.viewStart, 2.5f); - EXPECT_EQ(again.viewLength, 4.0f); - EXPECT_EQ(again.zoom, 60); - } - // A damaged state: numbers that would leave the view unusable are refused. TEST(ViewState, AnUnusableViewIsRefused) { - NodeView view; + nodes::NodeView view; view.transform.r0 = float3{ 2.0f, 0.0f, 5.0f }; EXPECT_FALSE(RestoreViewState(view, R"({"transform":[0,0,10,0,0,20]})")) << "no scale: can't be inverted"; EXPECT_EQ(view.transform.r0.x, 2.0f); - TimelineView timeline; - timeline.viewLength = 3.0f; - EXPECT_FALSE(RestoreViewState(timeline, R"({"start":0,"length":-2,"zoom":10})")); - EXPECT_EQ(timeline.viewLength, 3.0f); - EXPECT_TRUE(RestoreViewState(timeline, R"({"start":0,"length":0,"zoom":10})")) << "0: the whole duration"; } TEST(ViewState, ACurvePlotsShownPartComesBack) { - CurveView view; - view.shown = CurveRange{ 0.25f, 0.75f, -1.0f, 2.0f }; + curves::CurveView view; + view.shown = curves::CurveRange{ 0.25f, 0.75f, -1.0f, 2.0f }; view.shownSet = true; - CurveView again; + curves::CurveView again; ASSERT_TRUE(RestoreViewState(again, SaveViewState(view))); EXPECT_TRUE(again.shownSet); EXPECT_EQ(again.shown, view.shown); - CurveView never; // never opened: nothing in view yet, and nothing to keep + curves::CurveView never; // never opened: nothing in view yet, and nothing to keep EXPECT_EQ(SaveViewState(never), ""); } - TEST(ViewState, AViewportsCameraComesBack) - { - ViewportCamera camera; - camera.target = float3{ 1.0f, 2.0f, 3.0f }; - camera.distance = 12.0f; - camera.yaw = -0.3f; - camera.pitch = -0.8f; - camera.fovY = 1.0f; - camera.orthographic = true; - ViewportCamera again; - ASSERT_TRUE(RestoreViewState(again, SaveViewState(camera))); - EXPECT_EQ(again.target, camera.target); - EXPECT_EQ(again.distance, 12.0f); - EXPECT_EQ(again.yaw, -0.3f); - EXPECT_EQ(again.pitch, -0.8f); - EXPECT_EQ(again.fovY, 1.0f); - EXPECT_TRUE(again.orthographic); - } - - // The page open, by its name: IDs change between runs, names don't. A page that's - // gone keeps the one open. TEST(ViewState, TheSettingsPageOpenComesBackByName) { - GUIApplication::SettingsPanelState settings; + views::SettingsPanelState settings; const ID general { .value{ .integer = 11 } }; const ID advanced { .value{ .integer = 12 } }; settings.AddPage(general, "General", [] {}); @@ -96,7 +59,7 @@ namespace tachyon settings.selectedID = advanced; const std::string saved = SaveViewState(settings); - GUIApplication::SettingsPanelState again; + views::SettingsPanelState again; const ID generalAgain { .value{ .integer = 21 } }; const ID advancedAgain { .value{ .integer = 22 } }; again.AddPage(generalAgain, "General", [] {}); @@ -104,7 +67,7 @@ namespace tachyon ASSERT_TRUE(RestoreViewState(again, saved)); EXPECT_EQ(again.selectedID, advancedAgain); - GUIApplication::SettingsPanelState fewer; + views::SettingsPanelState fewer; fewer.AddPage(generalAgain, "General", [] {}); EXPECT_FALSE(RestoreViewState(fewer, saved)); EXPECT_EQ(fewer.selectedID, generalAgain); @@ -112,7 +75,7 @@ namespace tachyon TEST(ViewState, TextItCantReadChangesNothing) { - NodeView view; + nodes::NodeView view; view.transform.r0 = float3{ 2.0f, 0.0f, 5.0f }; const float3x2 before = view.transform; for (std::string_view text : { "", "not json", "{}", R"({"transform":[1,2]})", R"({"transform":"x"})" }) @@ -120,9 +83,6 @@ namespace tachyon EXPECT_FALSE(RestoreViewState(view, text)) << text; EXPECT_EQ(view.transform, before) << text; } - ViewportCamera camera; - EXPECT_FALSE(RestoreViewState(camera, R"({"distance":-5})")) << "a camera behind its target"; - EXPECT_EQ(camera.distance, ViewportCamera{}.distance); } } } diff --git a/workdirectory/themes/app_controls.css b/workdirectory/themes/app_controls.css new file mode 100644 index 00000000..9d44118e --- /dev/null +++ b/workdirectory/themes/app_controls.css @@ -0,0 +1,591 @@ +/* The examples' app-level controls (examples/app_controls): the timeline, its editor and the + 3D viewport. An app that uses them adds this file to its style files, after styles.css: + + const std::string_view styleFiles[] = { "styles.css", "app_controls.css" }; + SetStyleFiles(styleFiles); + + Their colors are variables of the palettes (dark.css, light.css): --timeline-ready and the + rest. */ + +/* Timeline: the transport buttons, the time in a well, and the scrubber. */ +.timeline { + display: flex; + flex-direction: row; + flex-wrap: nowrap; + align-items: center; + gap: 8px; + min-height: 34px; + margin: 0px; + padding: 0px; + border-width: 0px; + background-color: transparent; + border-color: transparent; +} +.timeline-transport { + display: flex; + flex-direction: row; + flex-wrap: nowrap; + align-items: center; + gap: 2px; + margin: 0px; + padding: 0px; + border-width: 0px; + background-color: transparent; + border-color: transparent; + flex-grow: 0; + flex-shrink: 0; +} +.timeline-button, .timeline-play, .timeline-loop { + -tachyon-state-layer: content; /* hover and pressed: the text color over the background, 8% / 14% */ + width: 26px; + height: 26px; + margin: 0px; + padding: 0px; + border-width: 0px; + border-radius: 4px; + background-color: transparent; + border-color: transparent; + color: var(--text-2); + -tachyon-icon-size: 14px; + text-align: center; + -tachyon-vertical-text-align: middle; + cursor: pointer; + flex-grow: 0; + flex-shrink: 0; +} +.timeline-button:hover, .timeline-loop:hover { color: var(--text-1); } +.timeline-play { background-color: var(--accent); color: var(--on-accent); } +.timeline-play:hover { color: var(--on-accent); } +.timeline-loop::highlight(selected) { background-color: var(--bg-active); color: var(--accent); } +.timeline-loop:hover::highlight(selected) { color: var(--accent); } +.timeline-time { + display: flex; + flex-direction: row; + flex-wrap: nowrap; + align-items: center; + gap: 8px; + height: 26px; + margin: 0px; + padding: 0px 10px; + border-width: 1px; + border-radius: 4px; + background-color: var(--bg-input); + border-color: var(--line-subtle); + flex-grow: 0; + flex-shrink: 0; +} +.timeline-time-current, .timeline-time-total, .timeline-frame { + margin: 0px; + padding: 0px; + border-width: 0px; + background-color: transparent; + font-family: monospace; + text-wrap: nowrap; + vertical-align: middle; + flex-grow: 0; + flex-shrink: 0; +} +.timeline-time-current { color: var(--text-1); font-size: 13px; font-weight: 500; } +.timeline-time-total { color: var(--text-3); font-size: 12px; } +.timeline-frame { padding: 0px 5px; border-radius: 3px; background-color: var(--bg-hover); color: var(--text-2); font-size: 11px; } +/* The scrubber: its padding box runs from the start to the length, so the playhead at either + end stays whole. */ +.timeline-scrubber { + height: 26px; + min-width: 120px; + margin: 0px; + padding: 0px 8px; + border-width: 1px; + border-radius: 4px; + background-color: var(--bg-input); + border-color: var(--line-subtle); + cursor: pointer; + flex-grow: 1; + flex-shrink: 1; +} +.timeline-scrubber:hover { border-color: var(--line-strong); } +.timeline-ready { border-width: 0px; border-radius: 3px; background-color: var(--timeline-ready); border-color: transparent; } +.timeline-tick { border-width: 0px; background-color: var(--timeline-tick); border-color: transparent; } +.timeline-tick-major { border-width: 0px; background-color: var(--text-3); border-color: transparent; } +.timeline-marker { border-width: 0px; border-radius: 1px; background-color: var(--timeline-marker); border-color: transparent; } +.timeline-playhead { border-width: 0px; border-radius: 1px; background-color: var(--accent); border-color: transparent; } +/* TimelineEditor: a toolbar, the track list beside the ruler and lanes, and a scroll bar. */ +.timeline-editor { + display: flex; + flex-direction: column; + flex-wrap: nowrap; + align-items: stretch; + gap: 0px; + margin: 0px; + padding: 0px; + border-width: 1px; + border-radius: 6px; + background-color: var(--bg-panel); + border-color: var(--panel-border); + overflow: hidden; + flex-grow: 1; + flex-shrink: 1; +} +.timeline-toolbar { + display: flex; + flex-direction: row; + flex-wrap: nowrap; + align-items: center; + gap: 8px; + height: 40px; + margin: 0px; + padding: 0px 8px; + border-width: 0px 0px 1px 0px; + background-color: transparent; + border-color: var(--line-subtle); + flex-grow: 0; + flex-shrink: 0; +} +.timeline-divider { + width: 1px; + height: 18px; + margin: 0px; + padding: 0px; + border-width: 0px; + background-color: var(--line-subtle); + border-color: transparent; + flex-grow: 0; + flex-shrink: 0; +} +.timeline-fps { + -tachyon-state-layer: content; + height: 26px; + margin: 0px; + padding: 0px 6px 0px 8px; + border-width: 1px; + border-radius: 4px; + background-color: var(--bg-control); + border-color: var(--line-strong); + color: var(--text-1); + font-size: var(--font-size); + -tachyon-vertical-text-align: middle; + text-wrap: nowrap; + cursor: pointer; + flex-grow: 0; + flex-shrink: 0; + display: flex; + flex-direction: row; + align-items: center; + gap: 6px; /* between its content and its arrow */ +} +/* timeline-fps's parts: its content (an icon, if any, and the text), then the dropdown arrow. */ +.timeline-fps-text { + margin: 0px; + padding: 0px; + border-width: 0px; + background-color: transparent; + border-color: transparent; + color: var(--text-1); + font-size: var(--font-size); + vertical-align: middle; + -tachyon-vertical-text-align: middle; + text-wrap: nowrap; + -tachyon-icon-side: left; + -tachyon-icon-size: 14px; + -tachyon-icon-text-gap: 6px; + flex-grow: 0; + flex-shrink: 0; +} +.timeline-fps-arrow { + margin: 0px; + padding: 0px; + border-width: 0px; + background-color: transparent; + border-color: transparent; + color: var(--text-3); + -tachyon-icon-size: 12px; + -tachyon-icon-text-gap: 0px; + vertical-align: middle; + -tachyon-vertical-text-align: middle; + flex-grow: 0; + flex-shrink: 0; +} +.timeline-snap { + -tachyon-state-layer: content; + height: 26px; + margin: 0px; + padding: 0px 8px; + border-width: 0px; + border-radius: 4px; + background-color: transparent; + border-color: transparent; + color: var(--text-2); + font-size: var(--font-size); + -tachyon-icon-size: 13px; + -tachyon-icon-text-gap: 6px; + -tachyon-vertical-text-align: middle; + text-wrap: nowrap; + cursor: pointer; + flex-grow: 0; + flex-shrink: 0; +} +.timeline-snap:hover { color: var(--text-1); } +/* ---- viewport: the app's 3D view, its tools and axes ----------------------------- */ +/* The scene fills the box; the tools float at its top left, the axes at its top right. */ +.viewport { + border-width: 0px; + margin: 0px; + padding: 0px; + min-width: 120px; + min-height: 120px; + flex-grow: 1; + flex-shrink: 1; + background-color: var(--curve-plot); + overflow: hidden; +} +.viewport-tools { + display: flex; + flex-direction: column; + flex-wrap: nowrap; + gap: 2px; + padding: 3px; + margin: 0px; + border-width: 1px; + border-color: var(--line-subtle); + border-radius: var(--radius-lg); + background-color: var(--bg-panel); +} +.viewport-tool { + -tachyon-state-layer: content; + -tachyon-icon-size: 14px; + width: 24px; + height: 24px; + padding: 0px; + margin: 0px; + border-width: 0px; + border-radius: var(--radius-md); + background-color: transparent; + color: var(--text-2); + -tachyon-icon-color: var(--text-2); + cursor: pointer; +} +.viewport-tool:hover { background-color: var(--bg-hover); -tachyon-icon-color: var(--text-1); } +.viewport-tool::highlight(selected) { background-color: var(--accent); -tachyon-icon-color: var(--on-accent); } +.viewport-axis-label { + font-size: 9px; + font-weight: 700; + color: var(--on-accent); + padding: 0px; + margin: 0px; + border-width: 0px; + text-wrap: nowrap; +} +.timeline-snap::highlight(selected) { background-color: var(--bg-active); color: var(--text-1); -tachyon-icon-color: var(--accent); } +.timeline-zoom { + display: flex; + flex-direction: row; + flex-wrap: nowrap; + align-items: center; + justify-content: flex-end; + gap: 8px; + margin: 0px; + padding: 0px; + border-width: 0px; + background-color: transparent; + border-color: transparent; + color: var(--text-3); + -tachyon-icon-size: 13px; + flex-grow: 1; + flex-shrink: 1; +} +.timeline-zoom-icon { + width: 13px; + height: 13px; + margin: 0px; + padding: 0px; + border-width: 0px; + background-color: transparent; + -tachyon-icon-size: 13px; + -tachyon-icon-color: var(--text-3); + flex-grow: 0; + flex-shrink: 0; +} +.timeline-header { + display: flex; + flex-direction: row; + flex-wrap: nowrap; + align-items: stretch; + height: 28px; + margin: 0px; + padding: 0px; + border-width: 0px 0px 1px 0px; + background-color: var(--bg-header); + border-color: var(--line-subtle); + flex-grow: 0; + flex-shrink: 0; +} +.timeline-list-header { + display: flex; + flex-direction: row; + flex-wrap: nowrap; + align-items: center; + gap: 4px; + width: 240px; + margin: 0px; + padding: 0px 6px 0px 10px; + border-width: 0px 1px 0px 0px; + background-color: transparent; + border-color: var(--line-subtle); + flex-grow: 0; + flex-shrink: 0; +} +.timeline-list-title { + margin: 0px; + padding: 0px; + border-width: 0px; + background-color: transparent; + color: var(--text-3); + font-size: 11px; + font-weight: 500; + text-wrap: nowrap; + vertical-align: middle; + flex-grow: 1; + flex-shrink: 1; +} +.timeline-filter { + width: 120px; + height: 20px; + margin: 0px; + padding: 0px 6px; + border-width: 1px; + border-radius: 4px; + background-color: var(--bg-input); + border-color: var(--line-subtle); + color: var(--text-1); + font-size: 11px; + -tachyon-icon-size: 11px; + -tachyon-icon-color: var(--text-3); + -tachyon-icon-text-gap: 4px; + -tachyon-vertical-text-align: middle; + cursor: text; + flex-grow: 0; + flex-shrink: 0; +} +.timeline-filter:hover { border-color: var(--line-strong); } +.timeline-filter:focus { border-color: var(--accent); } +.timeline-add-track { + -tachyon-state-layer: content; + width: 22px; + height: 22px; + margin: 0px; + padding: 0px; + border-width: 0px; + border-radius: 4px; + background-color: transparent; + border-color: transparent; + color: var(--text-2); + -tachyon-icon-size: 13px; + text-align: center; + -tachyon-vertical-text-align: middle; + cursor: pointer; + flex-grow: 0; + flex-shrink: 0; +} +.timeline-add-track:hover { color: var(--text-1); } +.timeline-body { + display: flex; + flex-direction: row; + flex-wrap: nowrap; + align-items: stretch; + margin: 0px; + padding: 0px; + border-width: 0px; + background-color: transparent; + border-color: transparent; + overflow-x: hidden; + overflow-y: auto; + flex-grow: 1; + flex-shrink: 1; +} +.timeline-list { + display: flex; + flex-direction: column; + flex-wrap: nowrap; + align-items: stretch; + width: 240px; + margin: 0px; + padding: 0px; + border-width: 0px 1px 0px 0px; + background-color: transparent; + border-color: var(--line-subtle); + flex-grow: 0; + flex-shrink: 0; +} +.timeline-row { + display: flex; + flex-direction: row; + flex-wrap: nowrap; + align-items: center; + gap: 6px; + height: 28px; + margin: 0px; + padding: 0px 8px 0px 10px; + border-width: 0px 0px 1px 0px; + background-color: transparent; + border-color: var(--timeline-row-line); + color: var(--text-2); + flex-grow: 0; + flex-shrink: 0; +} +.timeline-row:hover { background-color: var(--bg-hover); } +.timeline-row::highlight(selected) { background-color: var(--accent-soft); color: var(--text-1); } +.timeline-chevron { + width: 14px; + height: 14px; + margin: 0px; + padding: 0px; + border-width: 0px; + background-color: transparent; + border-color: transparent; + color: var(--text-3); + -tachyon-icon-size: 12px; + text-align: center; + -tachyon-vertical-text-align: middle; + cursor: pointer; + flex-grow: 0; + flex-shrink: 0; +} +.timeline-chevron:hover { color: var(--text-1); } +.timeline-chip { + width: 8px; + height: 8px; + margin: 0px; + padding: 0px; + border-width: 0px; + border-radius: 2px; + background-color: var(--accent); + border-color: transparent; + flex-grow: 0; + flex-shrink: 0; +} +.timeline-group-name, .timeline-track-name { + margin: 0px; + padding: 0px; + border-width: 0px; + background-color: transparent; + color: var(--text-2); + font-size: var(--font-size); + -tachyon-icon-size: 13px; + -tachyon-icon-color: var(--text-3); + -tachyon-icon-text-gap: 6px; + text-wrap: nowrap; + text-overflow: ellipsis; + vertical-align: middle; + flex-grow: 1; + flex-shrink: 1; +} +.timeline-group-name { color: var(--text-1); font-weight: 600; } +.timeline-mute, .timeline-solo { + -tachyon-state-layer: content; + width: 18px; + height: 16px; + margin: 0px; + padding: 0px; + border-width: 0px; + border-radius: 3px; + background-color: var(--bg-hover); + border-color: transparent; + color: var(--text-3); + font-size: 10px; + font-weight: 600; + text-align: center; + -tachyon-vertical-text-align: middle; + cursor: pointer; + flex-grow: 0; + flex-shrink: 0; +} +/* Hovered: the letter brightens, and with it the state layer. */ +.timeline-mute:hover, .timeline-solo:hover { color: var(--text-1); } +.timeline-mute::highlight(selected) { background-color: var(--bg-active); color: var(--text-1); } +.timeline-solo::highlight(selected) { background-color: var(--warn-soft); color: var(--warn-text); } +.timeline-ruler { + margin: 0px; + padding: 0px 12px; + border-width: 0px; + background-color: transparent; + border-color: transparent; + cursor: pointer; + flex-grow: 1; + flex-shrink: 1; +} +.timeline-ruler-label { + margin: 0px; + padding: 0px; + border-width: 0px; + background-color: transparent; + color: var(--text-3); + font-family: monospace; + font-size: 10.5px; + text-wrap: nowrap; +} +/* The playhead's time: a pill in the accent, its text on it. */ +.timeline-playhead-label { + margin: 0px; + padding: 0px; + border-width: 0px; + border-radius: 4px; + background-color: var(--accent); + border-color: transparent; + color: var(--on-accent); + font-family: monospace; + font-size: 10.5px; + font-weight: 500; + text-wrap: nowrap; + -tachyon-state-layer: light 18% 30%; +} +.timeline-lanes { + margin: 0px; + padding: 0px 12px; + border-width: 0px; + background-color: transparent; + border-color: transparent; + flex-grow: 1; + flex-shrink: 1; +} +.timeline-lane-selected { border-width: 0px; background-color: var(--accent-soft); border-color: transparent; } +.timeline-row-line { border-width: 0px; background-color: var(--timeline-row-line); border-color: transparent; } +.timeline-outside { border-width: 0px; background-color: var(--timeline-outside); border-color: transparent; } +.timeline-loop-range { border-width: 0px; background-color: var(--accent-soft); border-color: transparent; } +.timeline-loop-edge { border-width: 0px; background-color: var(--accent); border-color: transparent; -tachyon-state-layer: light 30% 45%; } +.timeline-clip { border-width: 1px; border-radius: 4px; background-color: var(--timeline-clip); border-color: var(--timeline-clip-border); -tachyon-state-layer: light 10% 18%; } +.timeline-event { border-width: 0px; background-color: var(--timeline-marker); border-color: transparent; } +.timeline-event-chip { border-width: 0px; border-radius: 3px; background-color: var(--timeline-event-soft); border-color: transparent; -tachyon-state-layer: light 14% 24%; } +.timeline-event-label { + margin: 0px; + padding: 0px; + border-width: 0px; + background-color: transparent; + color: var(--text-1); + font-size: 11px; + text-wrap: nowrap; +} +.timeline-box-select { + border-width: 1px; + border-radius: 2px; + border-style: dashed; + background-color: var(--accent-soft); + border-color: var(--accent); +} +.timeline-scroll { + height: 16px; + margin: 0px; + padding: 0px 8px 0px 248px; + border-width: 1px 0px 0px 0px; + background-color: transparent; + border-color: var(--line-subtle); + flex-grow: 0; + flex-shrink: 0; +} +.timeline-scroll-thumb { border-width: 0px; border-radius: 3px; background-color: var(--line-strong); border-color: transparent; } +.timeline-scroll-thumb:hover { background-color: var(--text-3); } +.timeline-button:focus-visible, .timeline-play:focus-visible, .timeline-loop:focus-visible, .timeline-scrubber:focus-visible, .timeline-fps:focus-visible, .timeline-snap:focus-visible, .timeline-add-track:focus-visible, .timeline-chevron:focus-visible, .timeline-mute:focus-visible, .timeline-solo:focus-visible { + box-shadow: var(--focus-ring); +} +.timeline-lanes:focus-visible, .viewport:focus-visible, .viewport-tool:focus-visible { + box-shadow: inset 0 0 0 1px var(--accent); +} diff --git a/workdirectory/themes/styles.css b/workdirectory/themes/styles.css index 4f6a7dd2..82bfd8f1 100644 --- a/workdirectory/themes/styles.css +++ b/workdirectory/themes/styles.css @@ -3275,9 +3275,9 @@ } /* ---- node-text (text-only property body) --------------------------------- */ -/* Base for the left/centre/right variants the node view registers from this - one rule (they differ only in text-align). flex-grow is applied in code. */ -.node-text { +/* Aligned by the property's sockets: .node-text at the start, .node-text-center and + .node-text-end. flex-grow is applied in code. */ +.node-text, .node-text-center, .node-text-end { border-width: 0px; background-color: transparent; border-color: transparent; @@ -3290,6 +3290,8 @@ color: var(--text-2); font-size: var(--font-size); } +.node-text-center { text-align: center; } +.node-text-end { text-align: end; } /* ---- itemStyle ------------------------------------------------------------ */ .item { @@ -7261,224 +7263,10 @@ flex-grow: 0; flex-shrink: 0; } -/* Timeline: the transport buttons, the time in a well, and the scrubber. */ -.timeline { - display: flex; - flex-direction: row; - flex-wrap: nowrap; - align-items: center; - gap: 8px; - min-height: 34px; - margin: 0px; - padding: 0px; - border-width: 0px; - background-color: transparent; - border-color: transparent; -} -.timeline-transport { - display: flex; - flex-direction: row; - flex-wrap: nowrap; - align-items: center; - gap: 2px; - margin: 0px; - padding: 0px; - border-width: 0px; - background-color: transparent; - border-color: transparent; - flex-grow: 0; - flex-shrink: 0; -} -.timeline-button, .timeline-play, .timeline-loop { - -tachyon-state-layer: content; /* hover and pressed: the text color over the background, 8% / 14% */ - width: 26px; - height: 26px; - margin: 0px; - padding: 0px; - border-width: 0px; - border-radius: 4px; - background-color: transparent; - border-color: transparent; - color: var(--text-2); - -tachyon-icon-size: 14px; - text-align: center; - -tachyon-vertical-text-align: middle; - cursor: pointer; - flex-grow: 0; - flex-shrink: 0; -} -.timeline-button:hover, .timeline-loop:hover { color: var(--text-1); } -.timeline-play { background-color: var(--accent); color: var(--on-accent); } -.timeline-play:hover { color: var(--on-accent); } -.timeline-loop::highlight(selected) { background-color: var(--bg-active); color: var(--accent); } -.timeline-loop:hover::highlight(selected) { color: var(--accent); } -.timeline-time { - display: flex; - flex-direction: row; - flex-wrap: nowrap; - align-items: center; - gap: 8px; - height: 26px; - margin: 0px; - padding: 0px 10px; - border-width: 1px; - border-radius: 4px; - background-color: var(--bg-input); - border-color: var(--line-subtle); - flex-grow: 0; - flex-shrink: 0; -} -.timeline-time-current, .timeline-time-total, .timeline-frame { - margin: 0px; - padding: 0px; - border-width: 0px; - background-color: transparent; - font-family: monospace; - text-wrap: nowrap; - vertical-align: middle; - flex-grow: 0; - flex-shrink: 0; -} -.timeline-time-current { color: var(--text-1); font-size: 13px; font-weight: 500; } -.timeline-time-total { color: var(--text-3); font-size: 12px; } -.timeline-frame { padding: 0px 5px; border-radius: 3px; background-color: var(--bg-hover); color: var(--text-2); font-size: 11px; } -/* The scrubber: its padding box runs from the start to the length, so the playhead at either - end stays whole. */ -.timeline-scrubber { - height: 26px; - min-width: 120px; - margin: 0px; - padding: 0px 8px; - border-width: 1px; - border-radius: 4px; - background-color: var(--bg-input); - border-color: var(--line-subtle); - cursor: pointer; - flex-grow: 1; - flex-shrink: 1; -} -.timeline-scrubber:hover { border-color: var(--line-strong); } -.timeline-ready { border-width: 0px; border-radius: 3px; background-color: var(--timeline-ready); border-color: transparent; } -.timeline-tick { border-width: 0px; background-color: var(--timeline-tick); border-color: transparent; } -.timeline-tick-major { border-width: 0px; background-color: var(--text-3); border-color: transparent; } -.timeline-marker { border-width: 0px; border-radius: 1px; background-color: var(--timeline-marker); border-color: transparent; } -.timeline-playhead { border-width: 0px; border-radius: 1px; background-color: var(--accent); border-color: transparent; } -/* TimelineEditor: a toolbar, the track list beside the ruler and lanes, and a scroll bar. */ -.timeline-editor { - display: flex; - flex-direction: column; - flex-wrap: nowrap; - align-items: stretch; - gap: 0px; - margin: 0px; - padding: 0px; - border-width: 1px; - border-radius: 6px; - background-color: var(--bg-panel); - border-color: var(--panel-border); - overflow: hidden; - flex-grow: 1; - flex-shrink: 1; -} -.timeline-toolbar { - display: flex; - flex-direction: row; - flex-wrap: nowrap; - align-items: center; - gap: 8px; - height: 40px; - margin: 0px; - padding: 0px 8px; - border-width: 0px 0px 1px 0px; - background-color: transparent; - border-color: var(--line-subtle); - flex-grow: 0; - flex-shrink: 0; -} -.timeline-divider { - width: 1px; - height: 18px; - margin: 0px; - padding: 0px; - border-width: 0px; - background-color: var(--line-subtle); - border-color: transparent; - flex-grow: 0; - flex-shrink: 0; -} -.timeline-fps { - -tachyon-state-layer: content; - height: 26px; - margin: 0px; - padding: 0px 6px 0px 8px; - border-width: 1px; - border-radius: 4px; - background-color: var(--bg-control); - border-color: var(--line-strong); - color: var(--text-1); - font-size: var(--font-size); - -tachyon-vertical-text-align: middle; - text-wrap: nowrap; - cursor: pointer; - flex-grow: 0; - flex-shrink: 0; - display: flex; - flex-direction: row; - align-items: center; - gap: 6px; /* between its content and its arrow */ -} -/* timeline-fps's parts: its content (an icon, if any, and the text), then the dropdown arrow. */ -.timeline-fps-text { - margin: 0px; - padding: 0px; - border-width: 0px; - background-color: transparent; - border-color: transparent; - color: var(--text-1); - font-size: var(--font-size); - vertical-align: middle; - -tachyon-vertical-text-align: middle; - text-wrap: nowrap; - -tachyon-icon-side: left; - -tachyon-icon-size: 14px; - -tachyon-icon-text-gap: 6px; - flex-grow: 0; - flex-shrink: 0; -} -.timeline-fps-arrow { - margin: 0px; - padding: 0px; - border-width: 0px; - background-color: transparent; - border-color: transparent; - color: var(--text-3); - -tachyon-icon-size: 12px; - -tachyon-icon-text-gap: 0px; - vertical-align: middle; - -tachyon-vertical-text-align: middle; - flex-grow: 0; - flex-shrink: 0; -} -.timeline-snap { - -tachyon-state-layer: content; - height: 26px; - margin: 0px; - padding: 0px 8px; - border-width: 0px; - border-radius: 4px; - background-color: transparent; - border-color: transparent; - color: var(--text-2); - font-size: var(--font-size); - -tachyon-icon-size: 13px; - -tachyon-icon-text-gap: 6px; - -tachyon-vertical-text-align: middle; - text-wrap: nowrap; - cursor: pointer; - flex-grow: 0; - flex-shrink: 0; -} -.timeline-snap:hover { color: var(--text-1); } + + + + /* ---- EdgesField / CornersField: the link toggle before the four numbers ------ */ .box-sides-link { @@ -7804,56 +7592,7 @@ background-color: transparent; flex-shrink: 0; } -/* ---- viewport: the app's 3D view, its tools and axes ----------------------------- */ -/* The scene fills the box; the tools float at its top left, the axes at its top right. */ -.viewport { - border-width: 0px; - margin: 0px; - padding: 0px; - min-width: 120px; - min-height: 120px; - flex-grow: 1; - flex-shrink: 1; - background-color: var(--curve-plot); - overflow: hidden; -} -.viewport-tools { - display: flex; - flex-direction: column; - flex-wrap: nowrap; - gap: 2px; - padding: 3px; - margin: 0px; - border-width: 1px; - border-color: var(--line-subtle); - border-radius: var(--radius-lg); - background-color: var(--bg-panel); -} -.viewport-tool { - -tachyon-state-layer: content; - -tachyon-icon-size: 14px; - width: 24px; - height: 24px; - padding: 0px; - margin: 0px; - border-width: 0px; - border-radius: var(--radius-md); - background-color: transparent; - color: var(--text-2); - -tachyon-icon-color: var(--text-2); - cursor: pointer; -} -.viewport-tool:hover { background-color: var(--bg-hover); -tachyon-icon-color: var(--text-1); } -.viewport-tool::highlight(selected) { background-color: var(--accent); -tachyon-icon-color: var(--on-accent); } -.viewport-axis-label { - font-size: 9px; - font-weight: 700; - color: var(--on-accent); - padding: 0px; - margin: 0px; - border-width: 0px; - text-wrap: nowrap; -} + .plot { border-width: 1px; @@ -7868,211 +7607,6 @@ background-color: var(--curve-plot); overflow: hidden; } -.timeline-snap::highlight(selected) { background-color: var(--bg-active); color: var(--text-1); -tachyon-icon-color: var(--accent); } -.timeline-zoom { - display: flex; - flex-direction: row; - flex-wrap: nowrap; - align-items: center; - justify-content: flex-end; - gap: 8px; - margin: 0px; - padding: 0px; - border-width: 0px; - background-color: transparent; - border-color: transparent; - color: var(--text-3); - -tachyon-icon-size: 13px; - flex-grow: 1; - flex-shrink: 1; -} -.timeline-zoom-icon { - width: 13px; - height: 13px; - margin: 0px; - padding: 0px; - border-width: 0px; - background-color: transparent; - -tachyon-icon-size: 13px; - -tachyon-icon-color: var(--text-3); - flex-grow: 0; - flex-shrink: 0; -} -.timeline-header { - display: flex; - flex-direction: row; - flex-wrap: nowrap; - align-items: stretch; - height: 28px; - margin: 0px; - padding: 0px; - border-width: 0px 0px 1px 0px; - background-color: var(--bg-header); - border-color: var(--line-subtle); - flex-grow: 0; - flex-shrink: 0; -} -.timeline-list-header { - display: flex; - flex-direction: row; - flex-wrap: nowrap; - align-items: center; - gap: 4px; - width: 240px; - margin: 0px; - padding: 0px 6px 0px 10px; - border-width: 0px 1px 0px 0px; - background-color: transparent; - border-color: var(--line-subtle); - flex-grow: 0; - flex-shrink: 0; -} -.timeline-list-title { - margin: 0px; - padding: 0px; - border-width: 0px; - background-color: transparent; - color: var(--text-3); - font-size: 11px; - font-weight: 500; - text-wrap: nowrap; - vertical-align: middle; - flex-grow: 1; - flex-shrink: 1; -} -.timeline-filter { - width: 120px; - height: 20px; - margin: 0px; - padding: 0px 6px; - border-width: 1px; - border-radius: 4px; - background-color: var(--bg-input); - border-color: var(--line-subtle); - color: var(--text-1); - font-size: 11px; - -tachyon-icon-size: 11px; - -tachyon-icon-color: var(--text-3); - -tachyon-icon-text-gap: 4px; - -tachyon-vertical-text-align: middle; - cursor: text; - flex-grow: 0; - flex-shrink: 0; -} -.timeline-filter:hover { border-color: var(--line-strong); } -.timeline-filter:focus { border-color: var(--accent); } -.timeline-add-track { - -tachyon-state-layer: content; - width: 22px; - height: 22px; - margin: 0px; - padding: 0px; - border-width: 0px; - border-radius: 4px; - background-color: transparent; - border-color: transparent; - color: var(--text-2); - -tachyon-icon-size: 13px; - text-align: center; - -tachyon-vertical-text-align: middle; - cursor: pointer; - flex-grow: 0; - flex-shrink: 0; -} -.timeline-add-track:hover { color: var(--text-1); } -.timeline-body { - display: flex; - flex-direction: row; - flex-wrap: nowrap; - align-items: stretch; - margin: 0px; - padding: 0px; - border-width: 0px; - background-color: transparent; - border-color: transparent; - overflow-x: hidden; - overflow-y: auto; - flex-grow: 1; - flex-shrink: 1; -} -.timeline-list { - display: flex; - flex-direction: column; - flex-wrap: nowrap; - align-items: stretch; - width: 240px; - margin: 0px; - padding: 0px; - border-width: 0px 1px 0px 0px; - background-color: transparent; - border-color: var(--line-subtle); - flex-grow: 0; - flex-shrink: 0; -} -.timeline-row { - display: flex; - flex-direction: row; - flex-wrap: nowrap; - align-items: center; - gap: 6px; - height: 28px; - margin: 0px; - padding: 0px 8px 0px 10px; - border-width: 0px 0px 1px 0px; - background-color: transparent; - border-color: var(--timeline-row-line); - color: var(--text-2); - flex-grow: 0; - flex-shrink: 0; -} -.timeline-row:hover { background-color: var(--bg-hover); } -.timeline-row::highlight(selected) { background-color: var(--accent-soft); color: var(--text-1); } -.timeline-chevron { - width: 14px; - height: 14px; - margin: 0px; - padding: 0px; - border-width: 0px; - background-color: transparent; - border-color: transparent; - color: var(--text-3); - -tachyon-icon-size: 12px; - text-align: center; - -tachyon-vertical-text-align: middle; - cursor: pointer; - flex-grow: 0; - flex-shrink: 0; -} -.timeline-chevron:hover { color: var(--text-1); } -.timeline-chip { - width: 8px; - height: 8px; - margin: 0px; - padding: 0px; - border-width: 0px; - border-radius: 2px; - background-color: var(--accent); - border-color: transparent; - flex-grow: 0; - flex-shrink: 0; -} -.timeline-group-name, .timeline-track-name { - margin: 0px; - padding: 0px; - border-width: 0px; - background-color: transparent; - color: var(--text-2); - font-size: var(--font-size); - -tachyon-icon-size: 13px; - -tachyon-icon-color: var(--text-3); - -tachyon-icon-text-gap: 6px; - text-wrap: nowrap; - text-overflow: ellipsis; - vertical-align: middle; - flex-grow: 1; - flex-shrink: 1; -} -.timeline-group-name { color: var(--text-1); font-weight: 600; } .timeline-row-button { -tachyon-state-layer: content; width: 18px; @@ -8092,109 +7626,8 @@ flex-shrink: 0; } .timeline-row-button:hover { color: var(--text-1); } -.timeline-mute, .timeline-solo { - -tachyon-state-layer: content; - width: 18px; - height: 16px; - margin: 0px; - padding: 0px; - border-width: 0px; - border-radius: 3px; - background-color: var(--bg-hover); - border-color: transparent; - color: var(--text-3); - font-size: 10px; - font-weight: 600; - text-align: center; - -tachyon-vertical-text-align: middle; - cursor: pointer; - flex-grow: 0; - flex-shrink: 0; -} -/* Hovered: the letter brightens, and with it the state layer. */ -.timeline-mute:hover, .timeline-solo:hover { color: var(--text-1); } -.timeline-mute::highlight(selected) { background-color: var(--bg-active); color: var(--text-1); } -.timeline-solo::highlight(selected) { background-color: var(--warn-soft); color: var(--warn-text); } -.timeline-ruler { - margin: 0px; - padding: 0px 12px; - border-width: 0px; - background-color: transparent; - border-color: transparent; - cursor: pointer; - flex-grow: 1; - flex-shrink: 1; -} -.timeline-ruler-label { - margin: 0px; - padding: 0px; - border-width: 0px; - background-color: transparent; - color: var(--text-3); - font-family: monospace; - font-size: 10.5px; - text-wrap: nowrap; -} -/* The playhead's time: a pill in the accent, its text on it. */ -.timeline-playhead-label { - margin: 0px; - padding: 0px; - border-width: 0px; - border-radius: 4px; - background-color: var(--accent); - border-color: transparent; - color: var(--on-accent); - font-family: monospace; - font-size: 10.5px; - font-weight: 500; - text-wrap: nowrap; - -tachyon-state-layer: light 18% 30%; -} -.timeline-lanes { - margin: 0px; - padding: 0px 12px; - border-width: 0px; - background-color: transparent; - border-color: transparent; - flex-grow: 1; - flex-shrink: 1; -} -.timeline-lane-selected { border-width: 0px; background-color: var(--accent-soft); border-color: transparent; } -.timeline-row-line { border-width: 0px; background-color: var(--timeline-row-line); border-color: transparent; } -.timeline-outside { border-width: 0px; background-color: var(--timeline-outside); border-color: transparent; } -.timeline-loop-range { border-width: 0px; background-color: var(--accent-soft); border-color: transparent; } -.timeline-loop-edge { border-width: 0px; background-color: var(--accent); border-color: transparent; -tachyon-state-layer: light 30% 45%; } -.timeline-clip { border-width: 1px; border-radius: 4px; background-color: var(--timeline-clip); border-color: var(--timeline-clip-border); -tachyon-state-layer: light 10% 18%; } -.timeline-event { border-width: 0px; background-color: var(--timeline-marker); border-color: transparent; } -.timeline-event-chip { border-width: 0px; border-radius: 3px; background-color: var(--timeline-event-soft); border-color: transparent; -tachyon-state-layer: light 14% 24%; } -.timeline-event-label { - margin: 0px; - padding: 0px; - border-width: 0px; - background-color: transparent; - color: var(--text-1); - font-size: 11px; - text-wrap: nowrap; -} -.timeline-box-select { - border-width: 1px; - border-radius: 2px; - border-style: dashed; - background-color: var(--accent-soft); - border-color: var(--accent); -} -.timeline-scroll { - height: 16px; - margin: 0px; - padding: 0px 8px 0px 248px; - border-width: 1px 0px 0px 0px; - background-color: transparent; - border-color: var(--line-subtle); - flex-grow: 0; - flex-shrink: 0; -} -.timeline-scroll-thumb { border-width: 0px; border-radius: 3px; background-color: var(--line-strong); border-color: transparent; } -.timeline-scroll-thumb:hover { background-color: var(--text-3); } + + .toast-actions { display: flex; flex-direction: row; @@ -9137,9 +8570,7 @@ .color-hex:focus-visible, .typed-field:focus-visible, .color-picker-hdr:focus-visible, .gradient-editor-location:focus-visible, .collection-remove:focus-visible, .collection-add:focus-visible, .collection-add-entry:focus-visible, .toolbar-button:focus-visible, .toolbar-toggle:focus-visible, .toolbar-menu-trigger:focus-visible, -.timeline-button:focus-visible, .timeline-play:focus-visible, .timeline-loop:focus-visible, .timeline-scrubber:focus-visible, -.timeline-fps:focus-visible, .timeline-snap:focus-visible, .timeline-add-track:focus-visible, .timeline-chevron:focus-visible, -.timeline-row-button:focus-visible, .timeline-mute:focus-visible, .timeline-solo:focus-visible, +.timeline-row-button:focus-visible, .breadcrumb-segment:focus-visible, .message-box-close:focus-visible, .message-box-details-toggle:focus-visible, .dialog-close:focus-visible, .dialog-small-button:focus-visible, .dialog-icon-button:focus-visible, .dialog-square-button:focus-visible, .dialog-delete-button:focus-visible, .gradient-editor-preset:focus-visible, @@ -9166,10 +8597,9 @@ .list-item:focus-visible, .list-item-row:focus-visible, .menu-item:focus-visible, .menu-item-row:focus-visible, .menu-item-row-destructive:focus-visible, .menu-bar-trigger:focus-visible, .title-bar-button:focus-visible, .title-bar-close-button:focus-visible, -.color-picker-square:focus-visible, .gradient-editor-bar:focus-visible, .timeline-lanes:focus-visible, +.color-picker-square:focus-visible, .gradient-editor-bar:focus-visible, .box-sides-link:focus-visible, .curve-channel:focus-visible, .curve-plot:focus-visible, .plot-channel:focus-visible, .plot:focus-visible, -.curve-plot-frames:focus-visible, .curve-tree-row:focus-visible, .curve-tree-row-hidden:focus-visible, .curve-tree-group:focus-visible, -.viewport:focus-visible, .viewport-tool:focus-visible { +.curve-plot-frames:focus-visible, .curve-tree-row:focus-visible, .curve-tree-row-hidden:focus-visible, .curve-tree-group:focus-visible { box-shadow: inset 0 0 0 1px var(--accent); }