imgui: Context recovery / graceful handling of bad state

I’m using vanilla Dear Imgui v1.60 WIP.

I have an app that exposes imgui API to plugins using a scripting language. Now, in my own code I can be sure that I am “well-behaved” - for example, I match calls to ImGui::Begin() with calls to ImGui::End(). But I can’t be sure that plugins will be the same. I also have live reloading of plugin scripts, and sometimes I end up trying to load plugin code that won’t compile (I can keep using the last-known-good version in this case) or worse: plugin code that isn’t well-behaved with respect to imgui API. Consider a plugin that consists entirely of [the scrip equivalent of] the following:

ImGui::Begin("This won't end well.");

I end up hitting this assertion:

IM_ASSERT(g.CurrentWindowStack.Size == 1);    // Mismatched Begin()/End() calls

As a feature request, is it possible to consider supporting more graceful failures? I don’t have a solid idea in mind, but you can see my use case above. It could be something like D3D12’s command lists, where the CloseCommandList() function returns a status code indicating whether this was a valid or malformed command list - maybe ImGui::EndFrame() could return a similar value and just drop the frame altogether, or render as much of it as it can [and I realize how this is a fuzzy concept - I’m just thinking out loud here].

Is there some other way to do this that I’m missing? I wouldn’t mind running the plugin code in its own imgui context (multiple context support rocks!), but currently that doesn’t seem to solve the problem I have.

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Reactions: 3
  • Comments: 52 (28 by maintainers)

Commits related to this issue

Most upvoted comments

Pushed this in master as 9712bff Note this is technically undocumented/internals api so come with little guarantee and won’t be widely advertised but we’ve been using it in the TestEngine.

I’m working on a few things error_handling 2

The great bit is that if you use ImGuiErrorFlags_NoAssert you can get away with a tooltip:

#if 0
    if (ImGui::Begin("Error 1"))
    {
        ImGui::Text("This window calls End() inside the if (Begin()) block!");
        ImGui::End();
    }
    else
    {
        printf("");
    }
#endif
#if 1
    if (ImGui::Begin("Error 2"))
    {
        ImGui::Text("This window calls PushID() without popping!");
        ImGui::PushID("Hello");
    }
    ImGui::End();

Edit:final API/names are different but essentially similar features.

// Macros used by Recoverable Error handling
// - Only dispatch error if _EXPR: evaluate as assert (similar to an assert macro).
// - The message will always be a string literal, in order to increase likelihood of being display by an assert handler.
// - The intent is that you may rewire this macro to dispatch dynamically:
//   - On programmers machines, when debugger is attached, on direct imgui API usage error: always assert!
//   - On exception recovery and script language recovery: you may decide to error log.
#ifndef IM_ASSERT_USER_ERROR
#define IM_ASSERT_USER_ERROR(_EXPR,_MSG)    do { if (!(_EXPR) && ImGui::ErrorLog(_MSG)) { IM_ASSERT((_EXPR) && _MSG); } } while (0)    // Recoverable User Error
#endif

// - Error recovery is provided as a way to facilitate recovery from errors in e.g. scripting languages, or after specific exceptions handlers.
// - Error recovery is not perfect nor guaranteed! You are not supposed to rely on it in the course of a normal application run.
// - Always ensure that on programmers seat you have at minimum Asserts or Tooltips enabled when making direct imgui API call,
//   and especially in native code. Otherwise it would severely hinder your ability to catch and correct mistakes!
// - (1) Programmer seats: default path is:
//   - Recoverable errors will call IM_ASSERT_USER_ERROR(), leading to IM_ASSERT() being executed.
//   - Recovery will generally be performed, assuming you can resume from your assert.
// - (2) Programmer seats: if you disable Asserts (either via ImGuiErrorFlags_NoAssert either via a disabled IM_ASSERT macros) but keep Tooltips:
//   - Recoverable errors will be visible in a tooltip.
//   - Programmer is prompted to press F1 to enable asserts.
//   - THIS IMPLICITLY RELY ON RECOVERY BEING 100% FUNCTIONAL WHICH IS NOT GUARANTEED. A FEW CASES MIGHT PROBABLY STILL CRASH/ASSERTS.
//   - THIS IMPLICITLY RELY ON 'F1' KEY BEING AVAILABLE WITHOUT CAUSING MUCH HARM IN YOUR APP. // FIXME-ERRORHANDLING: Need to find a solution for this.
// - (3) What you might want to setup on non-programmers seats:
//   - Use ImGuiErrorFlags_NoAssert, but make sure log entries are well visible or reported somewhere.
//   - If errors are not well resurfaced to programmers, it may hinder your ability to prevent errors from staying/spreading in the codebase. Use with caution!
// - (4) If you offer the ability to write Dear ImGui code via e.g. scripting language, you may want to:
//   - Use ErrorRecoveryStoreState() to record stack sizes before running the script interpreter.
//   - Use ImGuiErrorFlags_NoAssert but only while in the context of the script interpreter.
//   - Maybe trigger a script break from your ErrorCallback if you can.
//   - Ensure that e.g ImGuiErrorFlags_NoTooltip is NOT set, and that log entries are well surfaced and visible somewhere.
// - (5) To handle resuming code execution after an exception:
//   - Use ErrorRecoveryStoreState() to record stack sizes before your try {} block.
//   - Temporary adjust settings (e.g. disable assert, set a log callback).
//   - Call ErrorRecoveryTryToRecoverState()
//   - Restore settings.
// FIXME-ERRORHANDLING: recover may log many times and assert once?
enum ImGuiErrorFlags_
{
    ImGuiErrorFlags_None                = 0,
    ImGuiErrorFlags_EnableRecovery      = 1 << 0,   // Enable recovery attempts. Some errors won't be detected and lead to direct crashes if recovery is disabled.
    ImGuiErrorFlags_NoDebugLog          = 1 << 1,   // Disable debug log on error.
    ImGuiErrorFlags_NoAssert            = 1 << 2,   // Disable asserts on error. Otherwise: we call IM_ASSERT() when returning from a failing IM_ASSERT_USER_ERROR()
    ImGuiErrorFlags_NoTooltip           = 1 << 3,   // Disable tooltip on error. The tooltip will display a keyboard shortcut to enable asserts if they were disabled!
};

typedef void (*ImGuiErrorCallback)(ImGuiContext* ctx, void* user_data, const char* msg);
// Error Handling [EXPERIMENTAL]
// (this will eventually be moved to public ImGuiIO when we are happy with the feature)
ImGuiErrorFlags         ErrorFlags;                             // = Assert+DebugLog+Tooltip. See ImGuiErrorHandlingFlags_
ImGuiErrorCallback      ErrorCallback;                          // = NULL
void*                   ErrorCallbackUserData;                  // = NULL

Branch https://github.com/ocornut/imgui/compare/features/error_recovery?expand=1

I need to stress that it is unlikely that recovery is going to be 100% perfect all the time but I believe if it handles 99% of realistic error cases then we may be good. This is not merged yet. Curious if you have feedback on whether this can be useful to your case.

The only feature “regression” is that if you are to disable _EnableRecovery it doesn’t get you exactly the same asserts as before.

I believe if the feature works it should be a non-issue, but I would need to see how it behave in real world vs my few tests.

(I think I may simultaneously start working on official scoped/raii helpers so people have them in a a separate header, even if I don’t fancy them)

Could you open an issue with those two, for tracking, preferably with a basic most repro? Thank you.

Now that we’ve shipped our major update and I’ve had a bit of time to breathe, I’m finally migrating Pioneer from ImGui 1.89.9 to 1.91.9b.

Feedback regarding error handling:

  • As documented, recovery inside of a tab bar (for example, protecting the contents of a singular tab with an ErrorRecoveryState) isn’t functional at the moment. That’s an area that would be eminently useful, as Pioneer has hot-reloadable debug tools (and game UI) living inside a tab bar.
  • Am I correct in thinking that using ErrorRecoveryTryToRecoverState inside a table before a valid call to EndTable() would prematurely end that table? I know it’s a very specialized scenario, and I personally don’t have an organic repro case in the Pioneer codebase, but I think it’s worth considering.

In general, the error recovery feature works very well and neatly replaces the existing cobbled-together error handling we’ve been carrying.

(By asking questions or posting self-answer it is essentially asking me to interact which defeat the purpose of create new issues to silo or track things. I’m answering here assuming this is a closure on this topic. It’s my fault for not reacting to your first post which nicely actually asked “Is this still the correct issue to post on?”).

As per https://github.com/ocornut/imgui/wiki/Error-Handling, the idea is that you can call ErrorRecoveryTryToRecoverState() yourself right after your script execution without waiting for EndFrame(). So you have a finer control of when things are recovered/logged and with which flags. Also useful if you need to differentiate one script from another when handling errors.

One additional concern for your consideration is that the recovery feature may also be usable / extremely useful in a “graceful exit” scenario in the presence of external error handling.

We’re currently using a slightly patched and integrated version of ImGui 1.89.8’s ErrorCheckEndWindowRecover in Pioneer Space Sim as a way to ensure ImGui is left in a sane state if Lua code (the main user of the ImGui API) throws an error; when entering a protected call an ImGuiStackSizes object is filled and saved and if an error is thrown the error handler unwinds the various ImGui stacks.

Of note, we’ve had to patch ImGuiStackSizes to add an additional SizeOfTabBarStack variable - from my off-hand skimming at the moment I think the error handling code in 1.89.8 will produce an invalid result if running ErrorCheckEndWindowRecover in a child window nested inside a tab bar item. We also recover the IDStack to its saved state rather than a depth of 1, and I suspect the TreeDepth state also should be saved and recovered for completeness.

The proposed TryToRecoverWindowState function I believe would be extremely useful to this specific use case, in addition to the other changes in that branch - we’d definitely benefit from the ability to have IM_ASSERT_USER_ERROR log errors rather than remaining unhandled and leading to a segfault at worst.

We’ve been using that function for a long time in the test engine. It’s not perfect but doesn’t make things worse, and recovers many cases.

The way we’ve been handling stack unrolling on error in Pioneer has been to save a copy of the stack sizes, including the CurrentWindowStackSize, when entering a protected call (try {} catch-equivalent) and to then handle the necessary End/Pops if an error occurred during the protected call. Looking at ErrorCheckEndFrameRecover, this appears to be very similar to what we are doing; however ImGui’s function unwinds the entire stack instead of supporting mid-frame unrolling.

Would you be interested in a pull request that allows unrolling to a “known state” (implemented with ImGuiStackSizes) mid-frame? It would need a few minutes to detach from Pioneer’s logging system but is otherwise based on the existing ImGui functionality with a few extra variables to enable unrolling to a “mid-window” state.