Skip to content

Stack Layout implementation - #846

Open
thedmd wants to merge 3 commits into
ocornut:masterfrom
thedmd:layouts
Open

thedmd wants to merge 3 commits into
ocornut:masterfrom
thedmd:layouts

Conversation

@thedmd

@thedmd thedmd commented Sep 26, 2016

Copy link
Copy Markdown
Contributor

PR was recreated due to lost references after changing fork origin. That was not my intention, sorry.
For comments please look at previous PR.

After searching for some layout related solution I decided to pull my own after everything I found was only issues listed on this repository (#97).

I think BeginHorizontal/EndHorizontal API was promissing, so I gave it a shot. There is how code look like and what results it produce.

            ImGui::BeginHorizontal("example_h1", spanToWindow ? bounds : ImVec2(0, 0));
                ImGui::TextUnformatted("Left");
                ImGui::Spring(middleWeight);
                ImGui::TextUnformatted("Middle");
                ImGui::Spring(1.0f - middleWeight);
                ImGui::TextUnformatted("Right");
            ImGui::EndHorizontal();

stack_layout

I tried to bend ImGui to help me layout widgets easly. This is what API I came up with:

    IMGUI_API void BeginHorizontal(const char* str_id, const ImVec2& size = ImVec2(0, 0));
    IMGUI_API void BeginHorizontal(const void* ptr_id, const ImVec2& size = ImVec2(0, 0));
    IMGUI_API void EndHorizontal();
    IMGUI_API void BeginVertical(const char* str_id, const ImVec2& size = ImVec2(0, 0));
    IMGUI_API void BeginVertical(const void* ptr_id, const ImVec2& size = ImVec2(0, 0));
    IMGUI_API void EndVertical();
    IMGUI_API void Spring(float weight = 1.0f, float spacing = -1.0f);

This code works by caching sizes of widgets in first frame and positioning them in next. Layout is evaluated only if something related to size changes.

Code was crafted in a few hours so it may be cruel in some places. I tried to be as consistent with ImGui code style. Please grab this code and try to use it. Let me know what you think about this solution. : )

Example code show one use case. There are however many more. Widgets can be interleaved by Springs which may have zero (sticking widgets together) weight or greater than zero. Free space will be divide according to them. There is an option to provide spacing which acts like in SameLine() function but works for both horizontal and vertical layouts. Layouts can be mixed together, you may put one in another as you can see on example gif.

@colesnicov

Copy link
Copy Markdown

Looks good. Will not be implemented?

@ocornut

ocornut commented Jan 9, 2017 •

Copy link
Copy Markdown
Owner

@colesnicov

Looks good. Will not be implemented?

imgui development is on hold for a few months and this is not a priority but it should eventually be merged in some way or another.

@mgerhardy

mgerhardy commented Mar 7, 2017 •

Copy link
Copy Markdown

There is a bom in imgui.cpp and imgui_internal.h (and maybe others) that shouldn't be there.

@sgf

sgf commented Jun 21, 2017 •

Copy link
Copy Markdown

Im just going to raise this question then searched for this issue.
This is a very important and useful feature.but im seem the code changes,it's a little complicated.
looking forward to joining soon!

@b1tc0der

Copy link
Copy Markdown

@thedmd Any chance you could share the basic node graph code you used for the screenshot you posted on issue 746?
#746

@thedmd

thedmd commented Jul 15, 2017

Copy link
Copy Markdown
Contributor Author

@b1tc0der I'm thinking about that. I need to find some time to update and wrap up code.

@b1tc0der

Copy link
Copy Markdown

@thedmd I think you've done an awesome job on this :-) If you need any help with wrapping up this code I am happy to help.

@francesco-cattoglio

Copy link
Copy Markdown

@thedmd I just found out the awesome job you made with the node editor. I am really interested in it because I was tasked with creating a small tool to help teaching design students the ropes of mathematics used in CG. I would love to have a blueprint-like interface for the software, but building something on top of the Unreal Engine would be complete overkill.
Please let me know if there's any news about sharing the source code of your component!

@thedmd

thedmd commented Dec 10, 2017

Copy link
Copy Markdown
Contributor Author

@francesco-cattoglio I just published all code related to Node Editor. You can find it here.

@francesco-cattoglio

Copy link
Copy Markdown

@thedmd ty so much! I'll keep you posted about any good or bad news that will show up in 2018!

@sherief

sherief commented Mar 5, 2018

Copy link
Copy Markdown

It would be awesome if this could get merged into mainline. I'm trying to use @thedmd's awesome node editor, but its current code is built against v1.50 and my code base is all v1.60.

I'm hoping to clean up the node editor's code, have it compile against 1.60 (once this is merged), and submit a pull request to the node editor's repository. Having these layout options wouldn't hurt either.

@ocornut, any chance you might be able to look at this soon?

@ocornut

ocornut commented Mar 5, 2018 •

Copy link
Copy Markdown
Owner

@sherief Unfortunately I don't think this would realistically get merged soon, I have too much open topics on my plate and need to close the Nav then Viewport/Docking features before I embark into layout stuff.

I am however going to try replacing the 3 IndentX, GroupOffsetX, ColumnsOffsetX with ImVec2 (without using the .y coordinates at all) so ease with merging this code (those are the main reasons for conflicts afaik). I consider those 3 variables a mess at the moment, I don't mind adding 3 unused float per-window to facilitate this work. EDIT I tried that and it didn't look like it made much of a difference in term of the patch.

@ocornut

ocornut commented Mar 5, 2018

Copy link
Copy Markdown
Owner

Here's a quick attempt at merging this with current master
(patch from master)
Stack Layout implementation (merge).zip

It looks like there are some spacing bugs, I don't know what caused them. Maybe thedmd may want to look at it.

@sherief

sherief commented Mar 6, 2018

Copy link
Copy Markdown

Totally understandable. Nav, viewports, and docking are also incredibly useful for everyone.
I'll take a look at the merge attempt later today and try to update @thedmd's code to work against it - basically, I hope to keep the node editor in a state where it doesn't stray too far from the mainline imgui branch so that it's easier to use once you finally get around to merging the layout changes.

Thanks a ton!

@thedmd

thedmd commented Mar 6, 2018

Copy link
Copy Markdown
Contributor Author

Bounds measurement code relied heavily on internal positioning code and cursor placement, if I recall correctly there were changes and unfortunately errors in spacing are expected.

I will look into that, since this is one of the features used in node editor.
thedmd/imgui-node-editor#3

@thedmd

thedmd commented May 1, 2018 •

Copy link
Copy Markdown
Contributor Author

Summary:

  • Based on latest ImGui 1.61 (thanks for patch Omar!)
  • Eliminated one-frame delay, results are immediate
  • Eliminated flickering or jiggling

Scroll down for details.

(Spring drawing is debug mechanism and is not 100% accurate, has one frame delay).
imgui-layout-2 0

I decided to not use BeginGroup()/EndGroup() to measure items, because they touched too many states and I'm still not comfortable with a way ImGui handle cursor movement. This time I'm using Indent() to hold layout elements in line and record cursor position inside layout internal data. Turns out it is easier to reason about that.
Code dealing with composite layouts (layouts in layouts) was rewritten to eliminate need for multiple passes before everything stabilize. With current approach everything is in proper place after call to EndHorizontal()/EndVertical().
I started using references in internal functions to enforce correct usage. Is that ok Omar or should I change them back to pointers?

Layout items now record ImDrawList vertex buffer write index. This way I'm able to move drawn widgets to proper places and give immediate result. Logic code is mismatched with visual state for one frame. I think this is easier to swallow than errors in visual state.
Anyway, layout is trying to reuse data from previous frame to handle spacing and place cursor for user to draw. If user drawn element change size layout can fixup widget geometry by translating it to proper position.

Example from imgui_demo.cpp was not ported back. My intent is to bring one you see above eventually.

@thedmd

thedmd commented May 9, 2018

Copy link
Copy Markdown
Contributor Author

Rebased to resolve conflict with master branch.

@thedmd
thedmd force-pushed the layouts branch 2 times, most recently from 2ad726b to 437adbe Compare May 17, 2018 20:08
@altschuler

Copy link
Copy Markdown

my workaround for this issue: since a "Spring" used ItemAdd, you can either use SetCursorScreenPos to GetItemRectMin or implement a custom widget using Behaviour API.

Thank you! It works well with setting cursor pos, although it's somewhat cumbersome, so I'm curious what you mean by implementing a custom widget using Behaviour API?

@wyxather

wyxather commented Sep 9, 2024 •

Copy link
Copy Markdown

my workaround for this issue: since a "Spring" used ItemAdd, you can either use SetCursorScreenPos to GetItemRectMin or implement a custom widget using Behaviour API.

Thank you! It works well with setting cursor pos, although it's somewhat cumbersome, so I'm curious what you mean by implementing a custom widget using Behaviour API?

since im using it for my custom widget this is how i do it

Spring();
if (!IsItemVisible()) [[unlikely]] {
    return;
}

auto& g = *GImGui;
auto& window = *g.CurrentWindow;
auto& item = g.LastItemData; // This is Spring

item.ID  =  window.GetID("ToggleText");  // Spring use Dummy which has 0 id, we need to change it.

KeepAliveID(item.ID); // This is probably not needed if you want single press. but if you use sliderbehaviour, you need this.

if (ButtonBehavior(item.Rect, item.ID, nullptr, nullptr)) [[unlikely]] {
    value = !value;
    MarkItemEdited(item.ID);
}

RenderToggleText(item.Rect, item.ID, value, text);

@thedmd

thedmd commented Sep 15, 2024

Copy link
Copy Markdown
Contributor Author

is there any reason why you use PushID instead of PushOverrideID in imgui_stacklayout.cpp->ImGui::BeginLayout?

I think there is no other that this function appeared around 3 years after this PR was open 😅
Switching to PushOverrideID in BeginLayout does look like a good idea at the first glance. Thanks!

@thedmd

thedmd commented Sep 15, 2024

Copy link
Copy Markdown
Contributor Author

@altschuler @wyxather

Measuring springs

I'm toying with an idea of an API that does return size of a spring. What is holding me up is breaking that perfect frame behavior. Notice that whatever you throw in stack layout it is in correct place in very same frame. There will be no flickering.

The problem is spring size information is available after top most stack layout ends. This mean returned size will be lagging one frame, because you do need it while doing layouts. This in turn can influence layout measurements and start feedback look of updates that will launch layout size to infinity if not played correctly.

I will give such API a try with next update/rebase. We will see how practical it will be. I think I will make it internal first because of that one frame lag.

@altschuler

Copy link
Copy Markdown

Yeah that makes sense. I implemented versions of @wyxather idea, calling them BeginSpring and EndSpring, where begin adds a spring, records its size and sets the cursor back to the starting point and returns the size. EndSpring resets the cursors.

It generally works well, but I ran into both the issues you mention. The layout is off by a frame, which is mostly fine for static layouts, but once you start resizing a window it obviously looks a little strange.

I also had the infinite size problem, eg using a standard ImGui::Selectable() adds some padding, so if you try to size it to the returned spring size it grows every frame. In this particular case using ImGuiSelectableFlags_NoPadWithHalfSpacing flag solves it, but it does highlight the problem of infinite size. I was wondering whether using clipping or setting item size explicitly in EndSpring could help, but I didn't dig much further.

@jstreibel

Copy link
Copy Markdown

@ocornut Omar plz merge this! Signed an ImGui fan

@Lumengine

Copy link
Copy Markdown

Hi,

I'm very curious about the current status and whether there are plans to merge these features into the main branch, it's not clear to me as I've read different things.
I understand this might be a complex decision, and I'm just looking to better understand the roadmap to help plan my own development. @ocornut @thedmd

Thanks for your time!

@ocornut

ocornut commented Jan 17, 2025

Copy link
Copy Markdown
Owner

I plan to allow for this or an equivalent feature by revamping the layout system so this can be distributed as an extension rather an a patch. I unfortunately can't provide any solid timeline.

Note the variation here:
#846 (comment)

I believe this PR should ideally use the -external approach and the non-external versions could/should be removed, imho. As ultimately this is the direction we are aiming at.

@ocornut ocornut mentioned this pull request Jun 9, 2025
@philippeflorent

Copy link
Copy Markdown

cant wait for this PR to land !! ;-)

@thedmd

thedmd commented Mar 29, 2026

Copy link
Copy Markdown
Contributor Author

Rebased on 19267.

Changes:

  • now both version use new error recovery, so when user forget EndHorizontal/EndVertical ImGui will complain but not crash

master 1.92.7 WIP r19267:

docking ImGui 1.92.7 WIP r19267:

Notice: layouts and docking-layout will be dropped in favor of layout-external and docking-layout-external respectively.
This will require users to explicitly include imgui_stacklayout.cpp in their project.

@thedmd

thedmd commented Mar 29, 2026

Copy link
Copy Markdown
Contributor Author

@wkster

Hi @thedmd

Thanks your contribution. I'm encountering an issue with layouts where a button doesn't appear when I have nested BeginHorizontal calls within the same layout. Here’s a simplified version of the code I'm working with:

void Inspector::showDemo() {
    static float x, y, z;
    static const float FIXED_SIZE = 28;
    static const float HEIGHT = 28;
    auto width = ImGui::GetContentRegionAvail().x;
    auto column_width = (width - FIXED_SIZE) / 2;

    ImGui::BeginHorizontal("##showDemoh1", ImVec2(width, HEIGHT));
        ImGui::BeginHorizontal("##showDemoh2", ImVec2(column_width, HEIGHT), 0);
            ImGui::Text("Scale");
            ImGui::Spring();
            ImGui::Button("ICO");
        ImGui::EndHorizontal();

        // ImGui::BeginHorizontal("##showDemoh3", ImVec2(column_width, HEIGHT), 1);
        //   ImGui::Text("X");
        //   ImGui::InputFloat("##X", &x);
        //   ImGui::Text("Y");
        //   ImGui::InputFloat("##Y", &y);
        //   ImGui::Text("Z");
        //   ImGui::InputFloat("##Z", &z);
        // ImGui::EndHorizontal();

        ImGui::Button("RESET");
        ImGui::Spring();
    ImGui::EndHorizontal();
}

When these nested blocks are commented out, the button appears as expected. Do you have any insights or suggestions on how to resolve this issue?

Thank you for your time and assistance!

Stack layout expected user to interleave horizontal/vertical layouts. Mixing same type layout in a row isn't supported. Sorry, this will make layout math more complicated. Stack layout work hard to produce correct result within same frame. I'm not sure if case provided by your example can be resolved in single pass.

Your example would probably benefit from tables:

image
{
    static float x, y, z;

    ImGui::BeginTable("##properties", 2);
    ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthFixed);
    ImGui::TableSetupColumn("Value", ImGuiTableColumnFlags_WidthStretch);

    ImGui::TableNextColumn();
    ImGui::AlignTextToFramePadding();
    ImGui::Text("Scale");

    ImGui::TableNextColumn();

    auto cellWidth = ImGui::GetContentRegionAvail().x;
    ImGui::BeginHorizontal("##showDemoh1", ImVec2(cellWidth, 0.0f));
    ImGui::Button("ICO");
    ImGui::Spring(0.0f);

    auto totalButtonsWidth   = ImGui::CalcTextSize("ICO").x + ImGui::CalcTextSize("RESET").x + style.FramePadding.x * 4.0f; // 'ICO' + 'RESET' + spacing between them
    auto totalLabelTextWidth = ImGui::CalcTextSize("X").x + ImGui::CalcTextSize("Y").x + ImGui::CalcTextSize("Y").x;
    auto totalSpacingWidth   = style.ItemSpacing.x * 7.0f; // spacing between after 'ICO', 'X', 'Y', 'Z', 'RESET', and two springs
    auto inputContentWidth   = cellWidth - totalButtonsWidth - totalLabelTextWidth - totalSpacingWidth;
    auto inputWidth          = inputContentWidth / 3.0f;

    ImGui::Text("X");
    ImGui::SetNextItemWidth(inputWidth);
    ImGui::InputFloat("##X", &x);
    ImGui::Text("Y");
    ImGui::SetNextItemWidth(inputWidth);
    ImGui::InputFloat("##Y", &y);
    ImGui::Text("Z");
    ImGui::SetNextItemWidth(inputWidth);
    ImGui::InputFloat("##Z", &z);

    ImGui::Spring();
    ImGui::Button("RESET");
    ImGui::EndHorizontal();

    ImGui::EndTable();
}

@pthom

pthom commented Sep 18, 2026

Copy link
Copy Markdown
Contributor

Hi,

Some info for the users of @thedmd's Stack Layout branches (March 2026 rebase): three PRs that correct issues are available. I thought I ought to mention them here, after posting them on thedmd repo.

1. Content submitted after a nested layout is not displayed.

This is the cause of @wkster's report above (the RESET button comes after a nested layout). I proposed a fix in the PR below. Workaround until then: wrap this content in its own nested layout, e.g. BeginVertical("reset"); Button("RESET"); EndVertical();

thedmd#10

2. Small fixes

Three smaller fixes are proposed in this other PR: compilation warnings, a BeginGroup() around a nested layout that grows and never shrinks, and the vertical drift of #9333.

thedmd#9

3. PushStyleVar() is broken for 20 style vars

Another PR (by @firesgc) is worth checking out. ImGuiStyleVar_LayoutAlign is not at the same index in the enum and in GStyleVarsInfo, so every style var from ImGuiStyleVar_LayoutAlign to ImGuiStyleVar_DockingSeparatorSize is shifted by one. For example PushStyleVar(ImGuiStyleVar_TabRounding, ...) silently changes TabBorderSize, and PushStyleVar(ImGuiStyleVar_TableAngledHeadersAngle, ...) asserts with "wrong type". I can confirm the mismatch in both -external branches.

thedmd#7


Thanks again @thedmd for this awesome work: I'm using it every day with great success :-)

@thedmd

thedmd commented Oct 11, 2026

Copy link
Copy Markdown
Contributor Author

Stack Layout update

All four Stack Layout branches are rebased on Dear ImGui 1.93.0 WIP (master 2859f67, docking 778992f) and include a round of fixes, several of them contributed by @pthom and @firesgc. Each branch is still a single commit on top of Dear ImGui, so they were force-pushed.

Branch Based on Variant
layouts (this PR) master built into imgui.cpp
docking-layout docking built into imgui.cpp
feature/layout-external master separate imgui_stacklayout.* files
feature/docking-layout-external docking separate imgui_stacklayout.* files

feature/layout now holds the external variant with each fix as a separate commit, for anyone who wants to review them one by one. The external branches also carry a changelog at the top of imgui_stacklayout.h.

Breaking change

  • BeginHorizontal()/BeginVertical() now scope their contents like PushID() with the same identifier, as BeginTable() and TreeNode() do. IDs of items inside stack layouts change, so settings saved under them (e.g. tables in imgui.ini) reset once.

Fixes

Thanks @pthom, @firesgc and @wkster!

@ocornut

ocornut commented Oct 12, 2026 •

Copy link
Copy Markdown
Owner

Thanks for rebasing and updating!
I really think you should remove the non-external versions. Less maintenance, less conflicts, easier to identify a modded version.

@pthom

pthom commented Oct 14, 2026

Copy link
Copy Markdown
Contributor

I agree with Omar. The external version is much easier to maintain and this is the one I use (and would advise to use).

@thedmd

thedmd commented Oct 16, 2026

Copy link
Copy Markdown
Contributor Author

Sure. I will drop non-external version in next update.

…le is submitted in a horizontal layout (e.g. a menu bar).

Items in cells used the layout type of the host window, so each ItemSize() in a cell ended with SameLine(). BeginTable() now sets a vertical layout until EndTable(). Tables with their own child window were not affected.
…en a hook callback adds a hook.

A callback calling AddContextHook(), e.g. an extension registering its hooks on first use from inside another hook, could reallocate g.Hooks while CallContextHooks() iterated it with a range-based for loop. Later hooks were then skipped or read from freed memory.
@thedmd

thedmd commented Oct 17, 2026

Copy link
Copy Markdown
Contributor Author

Stack Layout v2.2

With this update, branches layouts (this PR) and docking-layout do point to same version as external ones. v2.0 is ofiicialy retired.

PR does grow to three commits, because CI needs updating. Stack Layouts remain a single commit.

Branch Based on Variant
layouts (this PR) v1.93.0 same as external
docking-layout v1.93.0-docking same as external
feature/layout-external v1.93.0 separate imgui_stacklayout.* files
feature/docking-layout-external v1.93.0-docking separate imgui_stacklayout.* files

I did run PR through review and I did put some work to Stack Layouts, resulting in v2.2 version.

v2.2 highlights

The full list is in the changelog at the top of imgui_stacklayout.h.

Breaking:

  • Sizes follow CalcItemSize(): negative is relative to the far edge (-FLT_MIN fills). It used to mean automatic.
  • Items flow with DC.LayoutType, as in menu bars. In horizontal layouts, Separator() is vertical, MenuItem()/BeginMenu() render as in a menu bar, and NewLine() starts a new row.

Changes:

  • Layout fixes:

    • SameLine() inside horizontal layouts, which collapsed DragFloat3(), InputInt(), ColorEdit3();
    • BeginVertical() after SameLine();
    • ImGuiListClipper inside BeginVertical();
    • tables without scrolling in horizontal layouts (needs the Tables fix, PR Tables: Make cells to be always laid out horizontally #9589);
    • BeginGroup() around a nested layout with springs never shrinking.
  • Clipping fixes:

    • no draw channel splitting;
    • decorations at a layout's edge are no longer cut;
    • draw calls batch across layouts;
    • content moved by the root layout is no longer clipped for one frame, which made items after an appearing item lose their text.
  • Crash fixes: a layout begun while its parent is suspended; nested SuspendLayout().

  • Context fixes:

    • state is kept per context and per window: thread-local GImGui, plugin DLLs and hot reload;
    • layout state for changing IDs is freed after io.ConfigMemoryCompactTimer;
    • fixed an allocation outliving DestroyContext().
  • Error handling:

    • misuse is reported and recovered instead of crashing;
    • the same ID used twice is reported, and each use gets its own state;
    • recovery to a state from ErrorRecoveryStoreState() leaves earlier layouts open.
  • Additions:

    • SetNextLayoutDebugFlags() (ImGuiLayoutDebugFlags_DrawSprings, _DrawItems);
    • IMGUI_STACK_LAYOUT_VERSION and _NUM;
    • the ID scope is documented, with how to open a popup inside a layout.
  • Spring() always submits an item, so GetItemRect*() after it refers to the spring.

  • The module that submits a context's first layout registers its hooks; keep it loaded while the context lives.

  • Cost outside layouts matches upstream. Release build, 200 000 Dummy() per frame:

    Windows v1.93.0 v2.2 v2.1 (review)
    1 9.5-9.6 ns 9.5-9.6 ns 26.2 ns
    50 9.7-9.9 ns 9.8 ns 29.9 ns

Known limitations

  • Commands moved by a root's rebalancing keep their clip rects. This matters for nested fixed-size layouts that overflow.
  • Child windows inside layouts are not moved.
  • Items misplaced toward the near side or on the cross axis can still be culled for one frame.

@pthom

pthom commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

@thedmd, thank you for this update! Dear ImGui Bundle now uses it as is, and it replaces all five of my StackLayout patches. All my C++ and Python demos + the node editor tests inside the bundle run without a single regression (DragFloat3() and friends also now work in horizontal layouts), so that is great!

@thedmd

thedmd commented Oct 19, 2026

Copy link
Copy Markdown
Contributor Author

That's great news

@JamesWrigley

Copy link
Copy Markdown
Contributor

Very cool work :) Out of curiosity, what would it take to make stack layouts completely external to imgui such that users wouldn't need to use your custom branch? (sorry if I missed some discussion about this earlier in the thread)

@ocornut

ocornut commented Nov 17, 2026

Copy link
Copy Markdown
Owner

The signature and feature set of ItemSize/ItemAdd needs to be redesigned and it is planned in order to support many other features.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

⌂ 换网址