Skip to content

Finaling event from various widgets (sliders etc.) for Undo/Redo systems #1875

Closed

Description

@waidschrath

Hi!
Thanks for the great imgui! I really made big leaps in no time with this fantastic library. I'm implementing an editor for my game but i'm failing to grab the right events for my undo/redo stack.

If i do
if(ImGui::SliderFloat())

i get every value change which makes my stack a mess. However i want only the value that was changed after the slider was released.

Is there a functionality or an event for that? I tried to hook manually by waiting for ImGui::GetIO().WantCaptureMouse to become false again but this is not set immediately but only when i move to another item (and does not resemble release states). Same goes for the TextInput, i don't want each character but only if the change was completed.

Is there a way to do that intuitively or what would be best practice?

Thanks!

TL;DR: how to grab slider input changes immediately after sliding is finished? need it for undo.

Activity

  1. ocornut commented on Jun 12, 2018

    @ocornut
    Owner

    This is what you could use:

    #include <imgui_internal.h>
    
    bool IsItemActiveLastFrame()
    {
        ImGuiContext& g = *GImGui;
        if (g.ActiveIdPreviousFrame)
            return g.ActiveIdPreviousFrame == g.CurrentWindow->DC.LastItemId;
        return false;
    }
    
    bool IsItemJustMadeInactive()
    {
        return IsItemActiveLastFrame() && !ImGui::IsItemActive();
    }
    

    (from #820)

    I've been meaning to add it but couldn't think of a function name (naming is the hardest thing) :)

    EDIT IsItemReleased() would be nice but it is ambiguous because we have IsItemActive() and IsItemClicked().

  2. ocornut commented on Jun 12, 2018

    @ocornut
    Owner

    Here's a better name, IsItemDeactivated()

    bool ImGui::IsItemDeactivated()
    {
        ImGuiContext& g = *GImGui;
        ImGuiWindow* window = g.CurrentWindow;
        return (g.ActiveIdPreviousFrame == window->DC.LastItemId && g.ActiveIdPreviousFrame != 0 && g.ActiveId != window->DC.LastItemId);
    }
    

    The problem with this approach is highlighted in #956, it currently fails with multi-component widgets (can be fixed) and it's particularly tricker to handle for e.g. the color edit popup. Working on finding a solution.

  3. ocornut commented on Jun 12, 2018

    @ocornut
    Owner

    After agonizing a over the naming convention (*) I think I've got a decent solution for this long-standing issue.

    Some cases may be unsatisfactory: e.g. if you use InputFloat() and the user presses the +/- buttons several times. Depending on how your Undo system may work you may detect no-ops, or merge events in the undo stack. You might also use GetItemID() from imgui_internal.h if querying an unique ID for the item can help you merging modifications.

    Let me know how it works for you.

    (*) I am still not very happy with them, but considering the wide amount of widget they support I find it tricky to find a non-ambiguous name. Suggestions welcome, I can still rename the functions while they are fresh and not in a tagged release.
    EDIT IsItemDeactivatedAfterChange was eventually renamed to IsItemDeactivatedAfterEdit.

    This section of the Demo window can let you understand how it works:

    image

  4. changed the title [-]Events from Input Sliders (for Undo/Redo)[/-] [+]Finally event from various widgets (sliders etc.) for Undo/Redo systems[/+] on Jun 13, 2018
  5. changed the title [-]Finally event from various widgets (sliders etc.) for Undo/Redo systems[/-] [+]Finaling event from various widgets (sliders etc.) for Undo/Redo systems[/+] on Jun 13, 2018
  6. devkaiwang commented on Jun 19, 2018

    @devkaiwang

    We need a pair of API to record undo:
    BeginChange - e.g. drag begins. In this case we can record the orignal old value.
    EndChange - e.g. drag ends. As the new final value got, we can record the new and old values for the undo.

    Edit: the IsItemDeactivatedAfterChange API only acts as the EndChange phase, so it's hard to track the old value, since for sliders, value is always changing.

  7. JSandusky commented on Jun 20, 2018

    @JSandusky

    I deal with this by just merging actions together. Whenever an action is pushed onto the undo-stack the topmost action on the stack checks if it can merge the action, if it can then it merges and discards the added action. Same field edits are on a time threshold before they are classified as new actions.

    Code for one case (just to demonstrate how infantile those blocks are):

    virtual bool CanMergeWith(UndoRedo* rhs) const override {
        if (auto other = dynamic_cast<MaterialUndoRedo*>(rhs))
            return other->ptr_ == ptr_ && other->offset_ == offset_;
        return false;
    }
    
    virtual void Merge(UndoRedo* rhs) override {
        if (auto other = dynamic_cast<MaterialUndoRedo*>(rhs))
        {
            newValue_ = other->newValue_;
            text_ = other->text_;
        }
    }
    
  8. devkaiwang commented on Jun 20, 2018

    @devkaiwang

    @JSandusky It's a smart hack and we need something clean :)

  9. devkaiwang commented on Jun 20, 2018

    @devkaiwang

    Actually, we can properly handle undo recording by following code. Tested for DragFloat, DragFloat2 and DragFloat3.

    // Current editing value
    static float value = 0.0f;
    
    // Old value, used for store value before editing
    static float oldValue = 0.0f;
    
    if (ImGui::DragFloat("Drag float", &value))
    {
        // Here we apply change to editing target
    }
    
    if (ImGui::IsItemActive() && !IsItemActiveLastFrame())
    {
        // Here we record old value when item is actived for the first time.
        oldValue = value;
    }
    
    if (ImGui::IsItemDeactivatedAfterChange())
    {
        // Here we can save undo (to undo stack or something). Triggered once just after user stops editing. 
        // RecordUndo(oldValue, value);
    }
  10. ocornut commented on Jun 20, 2018

    @ocornut
    Owner

    @superwangkai Interestingly, every time in the past I have implemented an Undo system it didn't need the "old value" to function but I can see why yours would need it.
    I am not sure how your hypothetical BeginChange/EndChange api would work, and how it would scale to most complex widgets.
    Open to more changes if needed but I'm not sure what to do at the moment.

  11. devkaiwang commented on Jun 20, 2018

    @devkaiwang

    @ocornut To my understanding, old value and new value are store as a pair recored for a particular undo action. When we want to undo, we apply the old value to the target; when we redo, we apply the new value back to the target.

    if (ImGui::IsItemActive() && !IsItemActiveLastFrame()) acts as the BeginChange phase
    while
    if (ImGui::IsItemDeactivatedAfterChange()) acts as the EndChange phase. These two phases are just hypothetical as you mentioned, please don't be too serious about them.

    Edit: Plus, we don't want value changes between these two phases, so we can get a clean, single piece of undo action.

    Please inspire me if I'm wrong or there is something I missed.

  12. devkaiwang commented on Jun 20, 2018

    @devkaiwang

    For ColorEdit*, there will be two undo actions recorded and I need to study more to find the reason. However, for InputText/Drag*, AFAIK, it works great.

  13. JSandusky commented on Jun 20, 2018

    @JSandusky

    @superwangkai, not really a hack - IIRC that's what IBM laid down with CUA decades ago. Ends up being necessary for a lot of things anyways. Particularly things that have long-running consequences (ie. trigger a distance field recalc, baking, etc) or are prone to fine but meaningless editing (gizmos/manipulators), without merging actions just positioning something in a scene floods an undo-stack with garbage with all of the move -> change-view -> move -> change-view -> repeat ad-f.

    Edit: but yeah, start/end would still be handy for stuff.

  14. 27 remaining items

  15. eliasdaler commented on May 31, 2019

    @eliasdaler
    Contributor

    If the user clicks for multiple times, they should be regarded as multiple intended adjustments

    Are you talking about double-clicking on a slider and then editing the value via keyboard input?

  16. devkaiwang commented on May 31, 2019

    @devkaiwang

    @ocornut

    I hope I could express better...

    Yes, for DragFloat, DragFloat2, DragFloat3, DragFloat4, InputText, DragInt, DragInt2, DragInt3, DragInt4 and also widgets of the ColorEdit except the color wheel, I'm happy with current behavior. But I think it is more natural for ColorEdit to merge users mouse moves on the wheel and store one undo record after user closed the picker. (Edit: To me, for the mouse moves on the color wheel, they are more like adjustments before user finally submitting the update. So, I prefer to store only one undo record for this color editing.)

    @eliasdaler

    I can confirm that these functions work great for DragFloat, DragFloat2, DragFloat3, DragFloat4, > InputText, DragInt, DragInt2, DragInt3, DragInt4,

    I just met some issue with ColorEdit4, and should with as well as ColorEdit3

  17. devkaiwang commented on May 31, 2019

    @devkaiwang

    To make my expression better... Just imagine the following bad scenario -

    You suddenly want to adjust some color in your cool editor. So you open this color picker, and then you click and move around for some times on the color wheel, then you are happy with the result and close the color picker.

    Then you regret, so you press Ctrl+Z, but you are so confused, since there are many color editing records. You just don't know which one is the original color...

  18. ocornut commented on May 31, 2019

    @ocornut
    Owner

    I understand what you mean but wouldn't you have the exact same multiple CTRL+Z issue by editing a standard float multiple time?

    (I however acknowledge your request, I just don't know what's the best code and design to achieve it nor when I will be able to look at it.)

  19. devkaiwang commented on May 31, 2019

    @devkaiwang

    For a standard float widget, when the users release they mouse after dragging or finished entering some number by return key, we should regard the operation as an intended editing. It seems to be the best we can do.

    For a color picker, if we regard every movement on the open picker as a valid editing, it will be a mess. But if we choose user's closing picker as a confirmation, we get the same clean result as a float widget.

    Additionally, we have to select multiple times to get a valid color on the picker, e.g. first hue, then alpha... and you get a color you want.

  20. eliasdaler commented on May 31, 2019

    @eliasdaler
    Contributor

    Yeah, I understand now. It looks like ideally IsItemActivated should happen when you click on color and open picking widget, and IsItemDeactivatedAfterEdit IsItemDeactivated should happen when you click on some other widget (which closes the picking widget).

    What is the current behaviour?

  21. devkaiwang commented on Jun 3, 2019

    @devkaiwang

    @eliasdaler

    I don't have my testing code now, however, generally, current behavior is that IsItemDeactivatedAfterEdit happens after you clicked on the widgets of ColorEdit or moved your mouse on the color wheel.

  22. kudaba commented on Dec 17, 2019

    @kudaba
    Contributor

    I noticed another small issue with IsItemDeactivatedAfterEdit. If you have a single item (i.e. InputInt) in a window and try to tab out, since the active control doesn't change, it won't trigger a deactivate.

  23. JakubLukas commented on Oct 5, 2021

    @JakubLukas

    I also noticed small problem with IsItemDeactivatedAfterEdit when used after slider widget.
    IsItemDeactivatedAfterEdit returns true in frame when there is mouse up (so io.MouseDown[0] is false) but in that frame slider do not calculate value, so out parameter (e.g. float* v of SliderFloat) is default value.
    That means that if I want to apply value on IsItemDeactivatedAfterEdit, nothing changes.
    Possible fix would be removing pointed line in SliderBehaviorT

    if (!g.IO.MouseDown[0])
                {
                    ClearActiveID();
                }
                else // <--- removing this line /////////////////////////////////////////
                {
                    const float mouse_abs_pos = g.IO.MousePos[axis];
                    clicked_t = (slider_usable_sz > 0.0f) ? ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f) : 0.0f;
                    if (axis == ImGuiAxis_Y)
                        clicked_t = 1.0f - clicked_t;
                    set_new_value = true;
                }
    
  24. ocornut commented on Nov 24, 2021

    @ocornut
    Owner

    When investigating and working on a solution for #4714 I came up with an issue:

    {
        static ImVec4 color0(1.0f, 0.0f, 0.0f, 1.0f);
        static ImVec4 color1(0.0f, 1.0f, 0.0f, 1.0f);
        static int edited_ret_frame = -1;
        static int edited_ret_field = 0;
        static int edited_query_frame = -1;
        static int edited_query_field = 0;
        static int deactivated_frame = -1;
        static int deactivated_field = 0;
    
        if (ImGui::ColorEdit4("color0", &color0.x)) { edited_ret_frame = ImGui::GetFrameCount(); edited_ret_field = 0; }
        if (ImGui::IsItemEdited()) { edited_query_frame = ImGui::GetFrameCount(); edited_query_field = 0; }
        if (ImGui::IsItemDeactivatedAfterEdit()) { deactivated_frame = ImGui::GetFrameCount(); deactivated_field = 0; }
    
        if (ImGui::ColorEdit4("color1", &color1.x)) { edited_ret_frame = ImGui::GetFrameCount(); edited_ret_field = 1; }
        if (ImGui::IsItemEdited()) { edited_query_frame = ImGui::GetFrameCount(); edited_query_field = 1; }
        if (ImGui::IsItemDeactivatedAfterEdit()) { deactivated_frame = ImGui::GetFrameCount(); deactivated_field = 1; }
    
        ImGui::Text("Edited (ret) frame %d, field %d", edited_ret_frame, edited_ret_field);
        ImGui::Text("Edited (query) frame %d, field %d", edited_query_frame, edited_query_field);
        ImGui::Text("Deactivated frame %d, field %d", deactivated_frame, deactivated_field);
    }

    When you drag a color into another it writes into a different item without that written item being ever activated.
    As a result IsItemDeactivatedAfterEdit() never returns true there:

    deactivated_after_edit_on_drop

    While #4714 (after upcoming fix) would not suffer from this, a drag and drop target would.

  25. ocornut commented on Jan 20, 2025

    @ocornut
    Owner

    Closing this ancient issue.
    Many issues have been fixed with IsItemDeactivated(), IsItemDeactivatedAfterEdit() over the years. (#5184, #5904, #6766, #8303, #8004, #8149, #4714 and more).
    I am not ruling this that there might still be issues, but the reality is that this particular topic here has too many messages going in many directions and it's hard to make sense of it consider many changes have been made since then.
    If you or anyone has further issues implementing an undo/redo system please open a new issue. Thank you!

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      ⌂ 换网址