Advertisement
Guest User

Untitled

a guest
Oct 24th, 2017
437
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 441.52 KB | None | 0 0
  1. // dear imgui, v1.52 WIP
  2. // (main code and documentation)
  3.  
  4. // See ImGui::ShowTestWindow() in imgui_demo.cpp for demo code.
  5. // Newcomers, read 'Programmer guide' below for notes on how to setup ImGui in your codebase.
  6. // Get latest version at https://github.com/ocornut/imgui
  7. // Releases change-log at https://github.com/ocornut/imgui/releases
  8. // Gallery (please post your screenshots/video there!): https://github.com/ocornut/imgui/issues/1269
  9. // Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
  10. // This library is free but I need your support to sustain development and maintenance.
  11. // If you work for a company, please consider financial support, e.g: https://www.patreon.com/imgui
  12.  
  13. /*
  14.  
  15. Index
  16. - MISSION STATEMENT
  17. - END-USER GUIDE
  18. - PROGRAMMER GUIDE (read me!)
  19. - Read first
  20. - How to update to a newer version of ImGui
  21. - Getting started with integrating ImGui in your code/engine
  22. - API BREAKING CHANGES (read me when you update!)
  23. - ISSUES & TODO LIST
  24. - FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
  25. - How can I help?
  26. - What is ImTextureID and how do I display an image?
  27. - I integrated ImGui in my engine and the text or lines are blurry..
  28. - I integrated ImGui in my engine and some elements are clipping or disappearing when I move windows around..
  29. - How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on labels/IDs.
  30. - How can I tell when ImGui wants my mouse/keyboard inputs VS when I can pass them to my application?
  31. - How can I load a different font than the default?
  32. - How can I easily use icons in my application?
  33. - How can I load multiple fonts?
  34. - How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic?
  35. - How can I preserve my ImGui context across reloading a DLL? (loss of the global/static variables)
  36. - How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
  37. - ISSUES & TODO-LIST
  38. - CODE
  39.  
  40.  
  41. MISSION STATEMENT
  42. =================
  43.  
  44. - Easy to use to create code-driven and data-driven tools
  45. - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools
  46. - Easy to hack and improve
  47. - Minimize screen real-estate usage
  48. - Minimize setup and maintenance
  49. - Minimize state storage on user side
  50. - Portable, minimize dependencies, run on target (consoles, phones, etc.)
  51. - Efficient runtime and memory consumption (NB- we do allocate when "growing" content - creating a window / opening a tree node for the first time, etc. - but a typical frame won't allocate anything)
  52.  
  53. Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes:
  54. - Doesn't look fancy, doesn't animate
  55. - Limited layout features, intricate layouts are typically crafted in code
  56.  
  57.  
  58. END-USER GUIDE
  59. ==============
  60.  
  61. - Double-click title bar to collapse window
  62. - Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin()
  63. - Click and drag on lower right corner to resize window
  64. - Click and drag on any empty space to move window
  65. - Double-click/double-tap on lower right corner grip to auto-fit to content
  66. - TAB/SHIFT+TAB to cycle through keyboard editable fields
  67. - Use mouse wheel to scroll
  68. - Use CTRL+mouse wheel to zoom window contents (if io.FontAllowScaling is true)
  69. - CTRL+Click on a slider or drag box to input value as text
  70. - Text editor:
  71. - Hold SHIFT or use mouse to select text.
  72. - CTRL+Left/Right to word jump
  73. - CTRL+Shift+Left/Right to select words
  74. - CTRL+A our Double-Click to select all
  75. - CTRL+X,CTRL+C,CTRL+V to use OS clipboard
  76. - CTRL+Z,CTRL+Y to undo/redo
  77. - ESCAPE to revert text to its original value
  78. - You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!)
  79. - Controls are automatically adjusted for OSX to match standard OSX text editing operations.
  80.  
  81.  
  82. PROGRAMMER GUIDE
  83. ================
  84.  
  85. READ FIRST
  86.  
  87. - Read the FAQ below this section!
  88. - Your code creates the UI, if your code doesn't run the UI is gone! == very dynamic UI, no construction/destructions steps, less data retention on your side, no state duplication, less sync, less bugs.
  89. - Call and read ImGui::ShowTestWindow() for demo code demonstrating most features.
  90. - You can learn about immediate-mode gui principles at http://www.johno.se/book/imgui.html or watch http://mollyrocket.com/861
  91.  
  92. HOW TO UPDATE TO A NEWER VERSION OF IMGUI
  93.  
  94. - Overwrite all the sources files except for imconfig.h (if you have made modification to your copy of imconfig.h)
  95. - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
  96. If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed from the public API.
  97. If you have a problem with a missing function/symbols, search for its name in the code, there will likely be a comment about it.
  98. Please report any issue to the GitHub page!
  99. - Try to keep your copy of dear imgui reasonably up to date.
  100.  
  101. GETTING STARTED WITH INTEGRATING IMGUI IN YOUR CODE/ENGINE
  102.  
  103. - Add the ImGui source files to your projects, using your preferred build system. It is recommended you build the .cpp files as part of your project and not as a library.
  104. - You can later customize the imconfig.h file to tweak some compilation time behavior, such as integrating imgui types with your own maths types.
  105. - See examples/ folder for standalone sample applications. To understand the integration process, you can read examples/opengl2_example/ because it is short,
  106. then switch to the one more appropriate to your use case.
  107. - You may be able to grab and copy a ready made imgui_impl_*** file from the examples/.
  108. - When using ImGui, your programming IDE if your friend: follow the declaration of variables, functions and types to find comments about them.
  109.  
  110. - Init: retrieve the ImGuiIO structure with ImGui::GetIO() and fill the fields marked 'Settings': at minimum you need to set io.DisplaySize (application resolution).
  111. Later on you will fill your keyboard mapping, clipboard handlers, and other advanced features but for a basic integration you don't need to worry about it all.
  112. - Init: call io.Fonts->GetTexDataAsRGBA32(...), it will build the font atlas texture, then load the texture pixels into graphics memory.
  113. - Every frame:
  114. - In your main loop as early a possible, fill the IO fields marked 'Input' (e.g. mouse position, buttons, keyboard info, etc.)
  115. - Call ImGui::NewFrame() to begin the imgui frame
  116. - You can use any ImGui function you want between NewFrame() and Render()
  117. - Call ImGui::Render() as late as you can to end the frame and finalize render data. it will call your io.RenderDrawListFn handler.
  118. (if you don't need to render, you still need to call Render() and ignore the callback, or call EndFrame() instead. if you call neither some aspects of windows focusing/moving will appear broken.)
  119. - All rendering information are stored into command-lists until ImGui::Render() is called.
  120. - ImGui never touches or knows about your GPU state. the only function that knows about GPU is the RenderDrawListFn handler that you provide.
  121. - Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render" phases of your own application.
  122. - Refer to the examples applications in the examples/ folder for instruction on how to setup your code.
  123. - A minimal application skeleton may be:
  124.  
  125. // Application init
  126. ImGuiIO& io = ImGui::GetIO();
  127. io.DisplaySize.x = 1920.0f;
  128. io.DisplaySize.y = 1280.0f;
  129. io.RenderDrawListsFn = MyRenderFunction; // Setup a render function, or set to NULL and call GetDrawData() after Render() to access the render data.
  130. // TODO: Fill others settings of the io structure later.
  131.  
  132. // Load texture atlas (there is a default font so you don't need to care about choosing a font yet)
  133. unsigned char* pixels;
  134. int width, height;
  135. io.Fonts->GetTexDataAsRGBA32(pixels, &width, &height);
  136. // TODO: At this points you've got the texture data and you need to upload that your your graphic system:
  137. MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA)
  138. // TODO: Store your texture pointer/identifier (whatever your engine uses) in 'io.Fonts->TexID'. This will be passed back to your via the renderer.
  139. io.Fonts->TexID = (void*)texture;
  140.  
  141. // Application main loop
  142. while (true)
  143. {
  144. // Setup low-level inputs (e.g. on Win32, GetKeyboardState(), or write to those fields from your Windows message loop handlers, etc.)
  145. ImGuiIO& io = ImGui::GetIO();
  146. io.DeltaTime = 1.0f/60.0f;
  147. io.MousePos = mouse_pos;
  148. io.MouseDown[0] = mouse_button_0;
  149. io.MouseDown[1] = mouse_button_1;
  150.  
  151. // Call NewFrame(), after this point you can use ImGui::* functions anytime
  152. ImGui::NewFrame();
  153.  
  154. // Most of your application code here
  155. MyGameUpdate(); // may use any ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
  156. MyGameRender(); // may use any ImGui functions as well!
  157.  
  158. // Render & swap video buffers
  159. ImGui::Render();
  160. SwapBuffers();
  161. }
  162.  
  163. - A minimal render function skeleton may be:
  164.  
  165. void void MyRenderFunction(ImDrawData* draw_data)(ImDrawData* draw_data)
  166. {
  167. // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
  168. // TODO: Setup viewport, orthographic projection matrix
  169. // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
  170. for (int n = 0; n < draw_data->CmdListsCount; n++)
  171. {
  172. const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by ImGui
  173. const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by ImGui
  174. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  175. {
  176. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  177. if (pcmd->UserCallback)
  178. {
  179. pcmd->UserCallback(cmd_list, pcmd);
  180. }
  181. else
  182. {
  183. // Render 'pcmd->ElemCount/3' texture triangles
  184. MyEngineBindTexture(pcmd->TextureId);
  185. MyEngineScissor((int)pcmd->ClipRect.x, (int)pcmd->ClipRect.y, (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
  186. MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer, vtx_buffer);
  187. }
  188. idx_buffer += pcmd->ElemCount;
  189. }
  190. }
  191. }
  192.  
  193. - The examples/ folders contains many functional implementation of the pseudo-code above.
  194. - When calling NewFrame(), the 'io.WantCaptureMouse'/'io.WantCaptureKeyboard'/'io.WantTextInput' flags are updated.
  195. They tell you if ImGui intends to use your inputs. So for example, if 'io.WantCaptureMouse' is set you would typically want to hide
  196. mouse inputs from the rest of your application. Read the FAQ below for more information about those flags.
  197.  
  198.  
  199.  
  200. API BREAKING CHANGES
  201. ====================
  202.  
  203. Occasionally introducing changes that are breaking the API. The breakage are generally minor and easy to fix.
  204. Here is a change-log of API breaking changes, if you are using one of the functions listed, expect to have to fix some code.
  205. Also read releases logs https://github.com/ocornut/imgui/releases for more details.
  206.  
  207. - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your binding if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
  208. - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete).
  209. - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
  210. - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
  211. - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
  212. - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
  213. - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame.
  214. - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
  215. - 2017/08/13 (1.51) - renamed ImGuiCol_Columns*** to ImGuiCol_Separator***. Kept redirection enums (will obsolete).
  216. - 2017/08/11 (1.51) - renamed ImGuiSetCond_*** types and flags to ImGuiCond_***. Kept redirection enums (will obsolete).
  217. - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
  218. - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
  219. - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
  220. - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0))'
  221. - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
  222. - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
  223. - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
  224. - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetId() and use it instead of passing string to BeginChild().
  225. - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
  226. - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
  227. - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully breakage should be minimal.
  228. - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
  229. If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you.
  230. However if your TitleBg/TitleBgActive alpha was <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
  231. This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color.
  232. ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col)
  233. {
  234. float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a;
  235. return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a);
  236. }
  237. If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
  238. - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
  239. - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
  240. - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
  241. - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDraw::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
  242. - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref github issue #337).
  243. - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
  244. - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
  245. - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
  246. - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
  247. - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
  248. - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
  249. - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
  250. GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
  251. GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
  252. - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
  253. - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
  254. - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
  255. - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
  256. you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
  257. - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
  258. this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
  259. - if you are using a vanilla copy of one of the imgui_impl_XXXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
  260. - the signature of the io.RenderDrawListsFn handler has changed!
  261. ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
  262. became:
  263. ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
  264. argument 'cmd_lists' -> 'draw_data->CmdLists'
  265. argument 'cmd_lists_count' -> 'draw_data->CmdListsCount'
  266. ImDrawList 'commands' -> 'CmdBuffer'
  267. ImDrawList 'vtx_buffer' -> 'VtxBuffer'
  268. ImDrawList n/a -> 'IdxBuffer' (new)
  269. ImDrawCmd 'vtx_count' -> 'ElemCount'
  270. ImDrawCmd 'clip_rect' -> 'ClipRect'
  271. ImDrawCmd 'user_callback' -> 'UserCallback'
  272. ImDrawCmd 'texture_id' -> 'TextureId'
  273. - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
  274. - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
  275. - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
  276. - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
  277. - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
  278. - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
  279. - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
  280. - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely be used. Sorry!
  281. - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
  282. - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
  283. - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
  284. - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
  285. - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
  286. - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
  287. - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
  288. - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
  289. - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
  290. - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
  291. - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
  292. - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
  293. - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
  294. - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
  295. - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
  296. - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
  297. - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
  298. - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
  299. - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
  300. - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
  301. - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
  302. (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
  303. this sequence:
  304. const void* png_data;
  305. unsigned int png_size;
  306. ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size);
  307. // <Copy to GPU>
  308. became:
  309. unsigned char* pixels;
  310. int width, height;
  311. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  312. // <Copy to GPU>
  313. io.Fonts->TexID = (your_texture_identifier);
  314. you now have much more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs.
  315. it is now recommended that you sample the font texture with bilinear interpolation.
  316. (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID.
  317. (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
  318. (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
  319. - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
  320. - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
  321. - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
  322. - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
  323. - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
  324. - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
  325. - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
  326. - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
  327. - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
  328. - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
  329. - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
  330.  
  331.  
  332. ISSUES & TODO-LIST
  333. ==================
  334. See TODO.txt
  335.  
  336.  
  337. FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
  338. ======================================
  339.  
  340. Q: How can I help?
  341. A: - If you are experienced enough with ImGui and with C/C++, look at the todo list and see how you want/can help!
  342. - Become a Patron/donate! Convince your company to become a Patron or provide serious funding for development time! See http://www.patreon.com/imgui
  343.  
  344. Q: What is ImTextureID and how do I display an image?
  345. A: ImTextureID is a void* used to pass renderer-agnostic texture references around until it hits your render function.
  346. ImGui knows nothing about what those bits represent, it just passes them around. It is up to you to decide what you want the void* to carry!
  347. It could be an identifier to your OpenGL texture (cast GLuint to void*), a pointer to your custom engine material (cast MyMaterial* to void*), etc.
  348. At the end of the chain, your renderer takes this void* to cast it back into whatever it needs to select a current texture to render.
  349. Refer to examples applications, where each renderer (in a imgui_impl_xxxx.cpp file) is treating ImTextureID as a different thing.
  350. (c++ tip: OpenGL uses integers to identify textures. You can safely store an integer into a void*, just cast it to void*, don't take it's address!)
  351. To display a custom image/texture within an ImGui window, you may use ImGui::Image(), ImGui::ImageButton(), ImDrawList::AddImage() functions.
  352. ImGui will generate the geometry and draw calls using the ImTextureID that you passed and which your renderer can use.
  353. It is your responsibility to get textures uploaded to your GPU.
  354.  
  355. Q: I integrated ImGui in my engine and the text or lines are blurry..
  356. A: In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f).
  357. Also make sure your orthographic projection matrix and io.DisplaySize matches your actual framebuffer dimension.
  358.  
  359. Q: I integrated ImGui in my engine and some elements are clipping or disappearing when I move windows around..
  360. A: Most likely you are mishandling the clipping rectangles in your render function. Rectangles provided by ImGui are defined as (x1=left,y1=top,x2=right,y2=bottom) and NOT as (x1,y1,width,height).
  361.  
  362. Q: Can I have multiple widgets with the same label? Can I have widget without a label?
  363. A: Yes. A primer on the use of labels/IDs in ImGui..
  364.  
  365. - Elements that are not clickable, such as Text() items don't need an ID.
  366.  
  367. - Interactive widgets require state to be carried over multiple frames (most typically ImGui often needs to remember what is the "active" widget).
  368. to do so they need a unique ID. unique ID are typically derived from a string label, an integer index or a pointer.
  369.  
  370. Button("OK"); // Label = "OK", ID = hash of "OK"
  371. Button("Cancel"); // Label = "Cancel", ID = hash of "Cancel"
  372.  
  373. - ID are uniquely scoped within windows, tree nodes, etc. so no conflict can happen if you have two buttons called "OK" in two different windows
  374. or in two different locations of a tree.
  375.  
  376. - If you have a same ID twice in the same location, you'll have a conflict:
  377.  
  378. Button("OK");
  379. Button("OK"); // ID collision! Both buttons will be treated as the same.
  380.  
  381. Fear not! this is easy to solve and there are many ways to solve it!
  382.  
  383. - When passing a label you can optionally specify extra unique ID information within string itself. This helps solving the simpler collision cases.
  384. use "##" to pass a complement to the ID that won't be visible to the end-user:
  385.  
  386. Button("Play"); // Label = "Play", ID = hash of "Play"
  387. Button("Play##foo1"); // Label = "Play", ID = hash of "Play##foo1" (different from above)
  388. Button("Play##foo2"); // Label = "Play", ID = hash of "Play##foo2" (different from above)
  389.  
  390. - If you want to completely hide the label, but still need an ID:
  391.  
  392. Checkbox("##On", &b); // Label = "", ID = hash of "##On" (no label!)
  393.  
  394. - Occasionally/rarely you might want change a label while preserving a constant ID. This allows you to animate labels.
  395. For example you may want to include varying information in a window title bar (and windows are uniquely identified by their ID.. obviously)
  396. Use "###" to pass a label that isn't part of ID:
  397.  
  398. Button("Hello###ID"; // Label = "Hello", ID = hash of "ID"
  399. Button("World###ID"; // Label = "World", ID = hash of "ID" (same as above)
  400.  
  401. sprintf(buf, "My game (%f FPS)###MyGame");
  402. Begin(buf); // Variable label, ID = hash of "MyGame"
  403.  
  404. - Use PushID() / PopID() to create scopes and avoid ID conflicts within the same Window.
  405. This is the most convenient way of distinguishing ID if you are iterating and creating many UI elements.
  406. You can push a pointer, a string or an integer value. Remember that ID are formed from the concatenation of everything in the ID stack!
  407.  
  408. for (int i = 0; i < 100; i++)
  409. {
  410. PushID(i);
  411. Button("Click"); // Label = "Click", ID = hash of integer + "label" (unique)
  412. PopID();
  413. }
  414.  
  415. for (int i = 0; i < 100; i++)
  416. {
  417. MyObject* obj = Objects[i];
  418. PushID(obj);
  419. Button("Click"); // Label = "Click", ID = hash of pointer + "label" (unique)
  420. PopID();
  421. }
  422.  
  423. for (int i = 0; i < 100; i++)
  424. {
  425. MyObject* obj = Objects[i];
  426. PushID(obj->Name);
  427. Button("Click"); // Label = "Click", ID = hash of string + "label" (unique)
  428. PopID();
  429. }
  430.  
  431. - More example showing that you can stack multiple prefixes into the ID stack:
  432.  
  433. Button("Click"); // Label = "Click", ID = hash of "Click"
  434. PushID("node");
  435. Button("Click"); // Label = "Click", ID = hash of "node" + "Click"
  436. PushID(my_ptr);
  437. Button("Click"); // Label = "Click", ID = hash of "node" + ptr + "Click"
  438. PopID();
  439. PopID();
  440.  
  441. - Tree nodes implicitly creates a scope for you by calling PushID().
  442.  
  443. Button("Click"); // Label = "Click", ID = hash of "Click"
  444. if (TreeNode("node"))
  445. {
  446. Button("Click"); // Label = "Click", ID = hash of "node" + "Click"
  447. TreePop();
  448. }
  449.  
  450. - When working with trees, ID are used to preserve the open/close state of each tree node.
  451. Depending on your use cases you may want to use strings, indices or pointers as ID.
  452. e.g. when displaying a single object that may change over time (1-1 relationship), using a static string as ID will preserve your node open/closed state when the targeted object change.
  453. e.g. when displaying a list of objects, using indices or pointers as ID will preserve the node open/closed state differently. experiment and see what makes more sense!
  454.  
  455. Q: How can I tell when ImGui wants my mouse/keyboard inputs VS when I can pass them to my application?
  456. A: You can read the 'io.WantCaptureMouse'/'io.WantCaptureKeyboard'/'ioWantTextInput' flags from the ImGuiIO structure.
  457. - When 'io.WantCaptureMouse' or 'io.WantCaptureKeyboard' flags are set you may want to discard/hide the inputs from the rest of your application.
  458. - When 'io.WantTextInput' is set to may want to notify your OS to popup an on-screen keyboard, if available (e.g. on a mobile phone, or console without a keyboard).
  459. Preferably read the flags after calling ImGui::NewFrame() to avoid them lagging by one frame. But reading those flags before calling NewFrame() is also generally ok,
  460. as the bool toggles fairly rarely and you don't generally expect to interact with either ImGui or your application during the same frame when that transition occurs.
  461. ImGui is tracking dragging and widget activity that may occur outside the boundary of a window, so 'io.WantCaptureMouse' is more accurate and correct than checking if a window is hovered.
  462. (Advanced note: text input releases focus on Return 'KeyDown', so the following Return 'KeyUp' event that your application receive will typically have 'io.WantCaptureKeyboard=false'.
  463. Depending on your application logic it may or not be inconvenient. You might want to track which key-downs were for ImGui (e.g. with an array of bool) and filter out the corresponding key-ups.)
  464.  
  465. Q: How can I load a different font than the default? (default is an embedded version of ProggyClean.ttf, rendered at size 13)
  466. A: Use the font atlas to load the TTF/OTF file you want:
  467.  
  468. ImGuiIO& io = ImGui::GetIO();
  469. io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
  470. io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
  471.  
  472. Q: How can I easily use icons in my application?
  473. A: The most convenient and practical way is to merge an icon font such as FontAwesome inside you main font. Then you can refer to icons within your strings.
  474. Read 'How can I load multiple fonts?' and the file 'extra_fonts/README.txt' for instructions.
  475.  
  476. Q: How can I load multiple fonts?
  477. A: Use the font atlas to pack them into a single texture:
  478. (Read extra_fonts/README.txt and the code in ImFontAtlas for more details.)
  479.  
  480. ImGuiIO& io = ImGui::GetIO();
  481. ImFont* font0 = io.Fonts->AddFontDefault();
  482. ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
  483. ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels);
  484. io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
  485. // the first loaded font gets used by default
  486. // use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime
  487.  
  488. // Options
  489. ImFontConfig config;
  490. config.OversampleH = 3;
  491. config.OversampleV = 1;
  492. config.GlyphOffset.y -= 2.0f; // Move everything by 2 pixels up
  493. config.GlyphExtraSpacing.x = 1.0f; // Increase spacing between characters
  494. io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, &config);
  495.  
  496. // Combine multiple fonts into one (e.g. for icon fonts)
  497. ImWchar ranges[] = { 0xf000, 0xf3ff, 0 };
  498. ImFontConfig config;
  499. config.MergeMode = true;
  500. io.Fonts->AddFontDefault();
  501. io.Fonts->LoadFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges); // Merge icon font
  502. io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, NULL, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge japanese glyphs
  503.  
  504. Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
  505. A: When loading a font, pass custom Unicode ranges to specify the glyphs to load.
  506.  
  507. // Add default Japanese ranges
  508. io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese());
  509.  
  510. // Or create your own custom ranges (e.g. for a game you can feed your entire game script and only build the characters the game need)
  511. ImVector<ImWchar> ranges;
  512. ImFontAtlas::GlyphRangesBuilder builder;
  513. builder.AddText("Hello world"); // Add a string (here "Hello world" contains 7 unique characters)
  514. builder.AddChar(0x7262); // Add a specific character
  515. builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); // Add one of the default ranges
  516. builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted)
  517. io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, ranges.Data);
  518.  
  519. All your strings needs to use UTF-8 encoding. In C++11 you can encode a string literal in UTF-8 by using the u8"hello" syntax.
  520. Specifying literal in your source code using a local code page (such as CP-923 for Japanese or CP-1251 for Cyrillic) will NOT work!
  521. Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8.
  522.  
  523. Text input: it is up to your application to pass the right character code to io.AddInputCharacter(). The applications in examples/ are doing that.
  524. For languages using IME, on Windows you can copy the Hwnd of your application to io.ImeWindowHandle. The default implementation of io.ImeSetInputScreenPosFn() on Windows will set your IME position correctly.
  525.  
  526. Q: How can I preserve my ImGui context across reloading a DLL? (loss of the global/static variables)
  527. A: Create your own context 'ctx = CreateContext()' + 'SetCurrentContext(ctx)' and your own font atlas 'ctx->GetIO().Fonts = new ImFontAtlas()' so you don't rely on the default globals.
  528.  
  529. Q: How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
  530. A: The easiest way is to create a dummy window. Call Begin() with NoTitleBar|NoResize|NoMove|NoScrollbar|NoSavedSettings|NoInputs flag, zero background alpha,
  531. then retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like.
  532. You can also perfectly create a standalone ImDrawList instance _but_ you need ImGui to be initialized because ImDrawList pulls from ImGui data to retrieve the coordinates of the white pixel.
  533.  
  534. - tip: the construct 'IMGUI_ONCE_UPON_A_FRAME { ... }' will run the block of code only once a frame. You can use it to quickly add custom UI in the middle of a deep nested inner loop in your code.
  535. - tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug"
  536. - tip: you can call Begin() multiple times with the same name during the same frame, it will keep appending to the same window. this is also useful to set yourself in the context of another window (to get/set other settings)
  537. - tip: you can call Render() multiple times (e.g for VR renders).
  538. - tip: call and read the ShowTestWindow() code in imgui_demo.cpp for more example of how to use ImGui!
  539.  
  540. */
  541.  
  542. #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
  543. #define _CRT_SECURE_NO_WARNINGS
  544. #endif
  545.  
  546. #include "imgui.h"
  547. #define IMGUI_DEFINE_MATH_OPERATORS
  548. #define IMGUI_DEFINE_PLACEMENT_NEW
  549. #include "imgui_internal.h"
  550.  
  551. #include <ctype.h> // toupper, isprint
  552. #include <stdlib.h> // NULL, malloc, free, qsort, atoi
  553. #include <stdio.h> // vsnprintf, sscanf, printf
  554. #include <limits.h> // INT_MIN, INT_MAX
  555. #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
  556. #include <stddef.h> // intptr_t
  557. #else
  558. #include <stdint.h> // intptr_t
  559. #endif
  560.  
  561. #ifdef _MSC_VER
  562. #pragma warning (disable: 4127) // condition expression is constant
  563. #pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff)
  564. #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
  565. #endif
  566.  
  567. // Clang warnings with -Weverything
  568. #ifdef __clang__
  569. #pragma clang diagnostic ignored "-Wunknown-pragmas" // warning : unknown warning group '-Wformat-pedantic *' // not all warnings are known by all clang versions.. so ignoring warnings triggers new warnings on some configuration. great!
  570. #pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse.
  571. #pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
  572. #pragma clang diagnostic ignored "-Wformat-nonliteral" // warning : format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
  573. #pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
  574. #pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it.
  575. #pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness //
  576. #pragma clang diagnostic ignored "-Wformat-pedantic" // warning : format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
  577. #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int' //
  578. #elif defined(__GNUC__)
  579. #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
  580. #pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
  581. #pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
  582. #pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
  583. #pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
  584. #pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'xxxx' to type 'xxxx' casts away qualifiers
  585. #pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
  586. #endif
  587.  
  588. //-------------------------------------------------------------------------
  589. // Forward Declarations
  590. //-------------------------------------------------------------------------
  591.  
  592. static void LogRenderedText(const ImVec2& ref_pos, const char* text, const char* text_end = NULL);
  593.  
  594. static void PushMultiItemsWidths(int components, float w_full = 0.0f);
  595. static float GetDraggedColumnOffset(int column_index);
  596.  
  597. static bool IsKeyPressedMap(ImGuiKey key, bool repeat = true);
  598.  
  599. static ImFont* GetDefaultFont();
  600. static void SetCurrentFont(ImFont* font);
  601. static void SetCurrentWindow(ImGuiWindow* window);
  602. static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y);
  603. static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond);
  604. static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond);
  605. static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond);
  606. static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs);
  607. static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags);
  608. static inline bool IsWindowContentHoverable(ImGuiWindow* window);
  609. static void ClearSetNextWindowData();
  610. static void CheckStacksSize(ImGuiWindow* window, bool write);
  611. static void Scrollbar(ImGuiWindow* window, bool horizontal);
  612. static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
  613.  
  614. static void AddDrawListToRenderList(ImVector<ImDrawList*>& out_render_list, ImDrawList* draw_list);
  615. static void AddWindowToRenderList(ImVector<ImDrawList*>& out_render_list, ImGuiWindow* window);
  616. static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>& out_sorted_windows, ImGuiWindow* window);
  617.  
  618. static ImGuiIniData* FindWindowSettings(const char* name);
  619. static ImGuiIniData* AddWindowSettings(const char* name);
  620. static void LoadIniSettingsFromDisk(const char* ini_filename);
  621. static void SaveIniSettingsToDisk(const char* ini_filename);
  622. static void MarkIniSettingsDirty(ImGuiWindow* window);
  623.  
  624. static ImRect GetVisibleRect();
  625.  
  626. static bool BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags);
  627. static void CloseInactivePopups();
  628. static void ClosePopupToLevel(int remaining);
  629. static void ClosePopup(ImGuiID id);
  630. static ImGuiWindow* GetFrontMostModalRootWindow();
  631. static ImVec2 FindBestPopupWindowPos(const ImVec2& base_pos, const ImVec2& size, int* last_dir, const ImRect& rect_to_avoid);
  632.  
  633. static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data);
  634. static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end);
  635. static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining = NULL, ImVec2* out_offset = NULL, bool stop_on_new_line = false);
  636.  
  637. static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size);
  638. static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size);
  639. static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2);
  640. static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format);
  641.  
  642. //-----------------------------------------------------------------------------
  643. // Platform dependent default implementations
  644. //-----------------------------------------------------------------------------
  645.  
  646. static const char* GetClipboardTextFn_DefaultImpl(void* user_data);
  647. static void SetClipboardTextFn_DefaultImpl(void* user_data, const char* text);
  648. static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y);
  649.  
  650. //-----------------------------------------------------------------------------
  651. // Context
  652. //-----------------------------------------------------------------------------
  653.  
  654. // Default font atlas storage.
  655. // New contexts always point by default to this font atlas. It can be changed by reassigning the GetIO().Fonts variable.
  656. static ImFontAtlas GImDefaultFontAtlas;
  657.  
  658. // Default context storage + current context pointer.
  659. // Implicitely used by all ImGui functions. Always assumed to be != NULL. Change to a different context by calling ImGui::SetCurrentContext()
  660. // If you are hot-reloading this code in a DLL you will lose the static/global variables. Create your own context+font atlas instead of relying on those default (see FAQ entry "How can I preserve my ImGui context across reloading a DLL?").
  661. // ImGui is currently not thread-safe because of this variable. If you want thread-safety to allow N threads to access N different contexts, you might work around it by:
  662. // - Having multiple instances of the ImGui code compiled inside different namespace (easiest/safest, if you have a finite number of contexts)
  663. // - or: Changing this variable to be TLS. You may #define GImGui in imconfig.h for further custom hackery. Future development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
  664. #ifndef GImGui
  665. static ImGuiContext GImDefaultContext;
  666. ImGuiContext* GImGui = &GImDefaultContext;
  667. #endif
  668.  
  669. //-----------------------------------------------------------------------------
  670. // User facing structures
  671. //-----------------------------------------------------------------------------
  672.  
  673. ImGuiStyle::ImGuiStyle()
  674. {
  675. Alpha = 1.0f; // Global alpha applies to everything in ImGui
  676. WindowPadding = ImVec2(8, 8); // Padding within a window
  677. WindowMinSize = ImVec2(32, 32); // Minimum window size
  678. WindowRounding = 9.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows
  679. WindowTitleAlign = ImVec2(0.0f, 0.5f);// Alignment for title bar text
  680. ChildWindowRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
  681. FramePadding = ImVec2(4, 3); // Padding within a framed rectangle (used by most widgets)
  682. FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
  683. ItemSpacing = ImVec2(8, 4); // Horizontal and vertical spacing between widgets/lines
  684. ItemInnerSpacing = ImVec2(4, 4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
  685. TouchExtraPadding = ImVec2(0, 0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
  686. IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
  687. ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns
  688. ScrollbarSize = 16.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
  689. ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
  690. GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar
  691. GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
  692. ButtonTextAlign = ImVec2(0.5f, 0.5f);// Alignment of button text when button is larger than text.
  693. DisplayWindowPadding = ImVec2(22, 22); // Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows.
  694. DisplaySafeAreaPadding = ImVec2(4, 4); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
  695. AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU.
  696. AntiAliasedShapes = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
  697. CurveTessellationTol = 1.25f; // Tessellation tolerance. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
  698.  
  699. Colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);
  700. Colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f);
  701. Colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.70f);
  702. Colors[ImGuiCol_ChildWindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
  703. Colors[ImGuiCol_PopupBg] = ImVec4(0.05f, 0.05f, 0.10f, 0.90f);
  704. Colors[ImGuiCol_Border] = ImVec4(0.70f, 0.70f, 0.70f, 0.40f);
  705. Colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
  706. Colors[ImGuiCol_FrameBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.30f); // Background of checkbox, radio button, plot, slider, text input
  707. Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.90f, 0.80f, 0.80f, 0.40f);
  708. Colors[ImGuiCol_FrameBgActive] = ImVec4(0.90f, 0.65f, 0.65f, 0.45f);
  709. Colors[ImGuiCol_TitleBg] = ImVec4(0.27f, 0.27f, 0.54f, 0.83f);
  710. Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.40f, 0.80f, 0.20f);
  711. Colors[ImGuiCol_TitleBgActive] = ImVec4(0.32f, 0.32f, 0.63f, 0.87f);
  712. Colors[ImGuiCol_MenuBarBg] = ImVec4(0.40f, 0.40f, 0.55f, 0.80f);
  713. Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.20f, 0.25f, 0.30f, 0.60f);
  714. Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.40f, 0.40f, 0.80f, 0.30f);
  715. Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.40f, 0.40f, 0.80f, 0.40f);
  716. Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 0.40f);
  717. Colors[ImGuiCol_ComboBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.99f);
  718. Colors[ImGuiCol_CheckMark] = ImVec4(0.90f, 0.90f, 0.90f, 0.50f);
  719. Colors[ImGuiCol_SliderGrab] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f);
  720. Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f);
  721. Colors[ImGuiCol_Button] = ImVec4(0.67f, 0.40f, 0.40f, 0.60f);
  722. Colors[ImGuiCol_ButtonHovered] = ImVec4(0.67f, 0.40f, 0.40f, 1.00f);
  723. Colors[ImGuiCol_ButtonActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f);
  724. Colors[ImGuiCol_Header] = ImVec4(0.40f, 0.40f, 0.90f, 0.45f);
  725. Colors[ImGuiCol_HeaderHovered] = ImVec4(0.45f, 0.45f, 0.90f, 0.80f);
  726. Colors[ImGuiCol_HeaderActive] = ImVec4(0.53f, 0.53f, 0.87f, 0.80f);
  727. Colors[ImGuiCol_Separator] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);
  728. Colors[ImGuiCol_SeparatorHovered] = ImVec4(0.60f, 0.60f, 0.70f, 1.00f);
  729. Colors[ImGuiCol_SeparatorActive] = ImVec4(0.70f, 0.70f, 0.90f, 1.00f);
  730. Colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f);
  731. Colors[ImGuiCol_ResizeGripHovered] = ImVec4(1.00f, 1.00f, 1.00f, 0.60f);
  732. Colors[ImGuiCol_ResizeGripActive] = ImVec4(1.00f, 1.00f, 1.00f, 0.90f);
  733. Colors[ImGuiCol_CloseButton] = ImVec4(0.50f, 0.50f, 0.90f, 0.50f);
  734. Colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.70f, 0.70f, 0.90f, 0.60f);
  735. Colors[ImGuiCol_CloseButtonActive] = ImVec4(0.70f, 0.70f, 0.70f, 1.00f);
  736. Colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
  737. Colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
  738. Colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
  739. Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f);
  740. Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f);
  741. Colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f);
  742. }
  743.  
  744. ImGuiIO::ImGuiIO()
  745. {
  746. // Most fields are initialized with zero
  747. memset(this, 0, sizeof(*this));
  748.  
  749. // Settings
  750. DisplaySize = ImVec2(-1.0f, -1.0f);
  751. DeltaTime = 1.0f / 60.0f;
  752. IniSavingRate = 5.0f;
  753. IniFilename = "imgui.ini";
  754. LogFilename = "imgui_log.txt";
  755. MouseDoubleClickTime = 0.30f;
  756. MouseDoubleClickMaxDist = 6.0f;
  757. for (int i = 0; i < ImGuiKey_COUNT; i++)
  758. KeyMap[i] = -1;
  759. KeyRepeatDelay = 0.250f;
  760. KeyRepeatRate = 0.050f;
  761. UserData = NULL;
  762.  
  763. Fonts = &GImDefaultFontAtlas;
  764. FontGlobalScale = 1.0f;
  765. FontDefault = NULL;
  766. FontAllowUserScaling = false;
  767. DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
  768. DisplayVisibleMin = DisplayVisibleMax = ImVec2(0.0f, 0.0f);
  769.  
  770. // User functions
  771. RenderDrawListsFn = NULL;
  772. MemAllocFn = malloc;
  773. MemFreeFn = free;
  774. GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
  775. SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
  776. ClipboardUserData = NULL;
  777. ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl;
  778. ImeWindowHandle = NULL;
  779.  
  780. // Input (NB: we already have memset zero the entire structure)
  781. MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
  782. MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
  783. MouseDragThreshold = 6.0f;
  784. for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
  785. for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f;
  786.  
  787. // Set OS X style defaults based on __APPLE__ compile time flag
  788. #ifdef __APPLE__
  789. OSXBehaviors = true;
  790. #endif
  791. }
  792.  
  793. // Pass in translated ASCII characters for text input.
  794. // - with glfw you can get those from the callback set in glfwSetCharCallback()
  795. // - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
  796. void ImGuiIO::AddInputCharacter(ImWchar c)
  797. {
  798. const int n = ImStrlenW(InputCharacters);
  799. if (n + 1 < IM_ARRAYSIZE(InputCharacters))
  800. {
  801. InputCharacters[n] = c;
  802. InputCharacters[n + 1] = '\0';
  803. }
  804. }
  805.  
  806. void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
  807. {
  808. // We can't pass more wchars than ImGuiIO::InputCharacters[] can hold so don't convert more
  809. const int wchars_buf_len = sizeof(ImGuiIO::InputCharacters) / sizeof(ImWchar);
  810. ImWchar wchars[wchars_buf_len];
  811. ImTextStrFromUtf8(wchars, wchars_buf_len, utf8_chars, NULL);
  812. for (int i = 0; i < wchars_buf_len && wchars[i] != 0; i++)
  813. AddInputCharacter(wchars[i]);
  814. }
  815.  
  816. //-----------------------------------------------------------------------------
  817. // HELPERS
  818. //-----------------------------------------------------------------------------
  819.  
  820. #define IM_F32_TO_INT8_UNBOUND(_VAL) ((int)((_VAL) * 255.0f + ((_VAL)>=0 ? 0.5f : -0.5f))) // Unsaturated, for display purpose
  821. #define IM_F32_TO_INT8_SAT(_VAL) ((int)(ImSaturate(_VAL) * 255.0f + 0.5f)) // Saturated, always output 0..255
  822.  
  823. // Play it nice with Windows users. Notepad in 2015 still doesn't display text data with Unix-style \n.
  824. #ifdef _WIN32
  825. #define IM_NEWLINE "\r\n"
  826. #else
  827. #define IM_NEWLINE "\n"
  828. #endif
  829.  
  830. ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
  831. {
  832. ImVec2 ap = p - a;
  833. ImVec2 ab_dir = b - a;
  834. float ab_len = sqrtf(ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y);
  835. ab_dir *= 1.0f / ab_len;
  836. float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
  837. if (dot < 0.0f)
  838. return a;
  839. if (dot > ab_len)
  840. return b;
  841. return a + ab_dir * dot;
  842. }
  843.  
  844. bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
  845. {
  846. bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
  847. bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
  848. bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
  849. return ((b1 == b2) && (b2 == b3));
  850. }
  851.  
  852. void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
  853. {
  854. ImVec2 v0 = b - a;
  855. ImVec2 v1 = c - a;
  856. ImVec2 v2 = p - a;
  857. const float denom = v0.x * v1.y - v1.x * v0.y;
  858. out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
  859. out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
  860. out_u = 1.0f - out_v - out_w;
  861. }
  862.  
  863. ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
  864. {
  865. ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
  866. ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
  867. ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
  868. float dist2_ab = ImLengthSqr(p - proj_ab);
  869. float dist2_bc = ImLengthSqr(p - proj_bc);
  870. float dist2_ca = ImLengthSqr(p - proj_ca);
  871. float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
  872. if (m == dist2_ab)
  873. return proj_ab;
  874. if (m == dist2_bc)
  875. return proj_bc;
  876. return proj_ca;
  877. }
  878.  
  879. int ImStricmp(const char* str1, const char* str2)
  880. {
  881. int d;
  882. while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; }
  883. return d;
  884. }
  885.  
  886. int ImStrnicmp(const char* str1, const char* str2, int count)
  887. {
  888. int d = 0;
  889. while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
  890. return d;
  891. }
  892.  
  893. void ImStrncpy(char* dst, const char* src, int count)
  894. {
  895. if (count < 1) return;
  896. strncpy(dst, src, (size_t)count);
  897. dst[count - 1] = 0;
  898. }
  899.  
  900. char* ImStrdup(const char *str)
  901. {
  902. size_t len = strlen(str) + 1;
  903. void* buff = ImGui::MemAlloc(len);
  904. return (char*)memcpy(buff, (const void*)str, len);
  905. }
  906.  
  907. int ImStrlenW(const ImWchar* str)
  908. {
  909. int n = 0;
  910. while (*str++) n++;
  911. return n;
  912. }
  913.  
  914. const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
  915. {
  916. while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
  917. buf_mid_line--;
  918. return buf_mid_line;
  919. }
  920.  
  921. const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
  922. {
  923. if (!needle_end)
  924. needle_end = needle + strlen(needle);
  925.  
  926. const char un0 = (char)toupper(*needle);
  927. while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
  928. {
  929. if (toupper(*haystack) == un0)
  930. {
  931. const char* b = needle + 1;
  932. for (const char* a = haystack + 1; b < needle_end; a++, b++)
  933. if (toupper(*a) != toupper(*b))
  934. break;
  935. if (b == needle_end)
  936. return haystack;
  937. }
  938. haystack++;
  939. }
  940. return NULL;
  941. }
  942.  
  943. static const char* ImAtoi(const char* src, int* output)
  944. {
  945. int negative = 0;
  946. if (*src == '-') { negative = 1; src++; }
  947. if (*src == '+') { src++; }
  948. int v = 0;
  949. while (*src >= '0' && *src <= '9')
  950. v = (v * 10) + (*src++ - '0');
  951. *output = negative ? -v : v;
  952. return src;
  953. }
  954.  
  955. // MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
  956. // Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
  957. int ImFormatString(char* buf, int buf_size, const char* fmt, ...)
  958. {
  959. IM_ASSERT(buf_size > 0);
  960. va_list args;
  961. va_start(args, fmt);
  962. int w = vsnprintf(buf, buf_size, fmt, args);
  963. va_end(args);
  964. if (w == -1 || w >= buf_size)
  965. w = buf_size - 1;
  966. buf[w] = 0;
  967. return w;
  968. }
  969.  
  970. int ImFormatStringV(char* buf, int buf_size, const char* fmt, va_list args)
  971. {
  972. IM_ASSERT(buf_size > 0);
  973. int w = vsnprintf(buf, buf_size, fmt, args);
  974. if (w == -1 || w >= buf_size)
  975. w = buf_size - 1;
  976. buf[w] = 0;
  977. return w;
  978. }
  979.  
  980. // Pass data_size==0 for zero-terminated strings
  981. // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
  982. ImU32 ImHash(const void* data, int data_size, ImU32 seed)
  983. {
  984. static ImU32 crc32_lut[256] = { 0 };
  985. if (!crc32_lut[1])
  986. {
  987. const ImU32 polynomial = 0xEDB88320;
  988. for (ImU32 i = 0; i < 256; i++)
  989. {
  990. ImU32 crc = i;
  991. for (ImU32 j = 0; j < 8; j++)
  992. crc = (crc >> 1) ^ (ImU32(-int(crc & 1)) & polynomial);
  993. crc32_lut[i] = crc;
  994. }
  995. }
  996.  
  997. seed = ~seed;
  998. ImU32 crc = seed;
  999. const unsigned char* current = (const unsigned char*)data;
  1000.  
  1001. if (data_size > 0)
  1002. {
  1003. // Known size
  1004. while (data_size--)
  1005. crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *current++];
  1006. }
  1007. else
  1008. {
  1009. // Zero-terminated string
  1010. while (unsigned char c = *current++)
  1011. {
  1012. // We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
  1013. // Because this syntax is rarely used we are optimizing for the common case.
  1014. // - If we reach ### in the string we discard the hash so far and reset to the seed.
  1015. // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller.
  1016. if (c == '#' && current[0] == '#' && current[1] == '#')
  1017. crc = seed;
  1018. crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
  1019. }
  1020. }
  1021. return ~crc;
  1022. }
  1023.  
  1024. //-----------------------------------------------------------------------------
  1025. // ImText* helpers
  1026. //-----------------------------------------------------------------------------
  1027.  
  1028. // Convert UTF-8 to 32-bits character, process single character input.
  1029. // Based on stb_from_utf8() from github.com/nothings/stb/
  1030. // We handle UTF-8 decoding error by skipping forward.
  1031. int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
  1032. {
  1033. unsigned int c = (unsigned int)-1;
  1034. const unsigned char* str = (const unsigned char*)in_text;
  1035. if (!(*str & 0x80))
  1036. {
  1037. c = (unsigned int)(*str++);
  1038. *out_char = c;
  1039. return 1;
  1040. }
  1041. if ((*str & 0xe0) == 0xc0)
  1042. {
  1043. *out_char = 0xFFFD; // will be invalid but not end of string
  1044. if (in_text_end && in_text_end - (const char*)str < 2) return 1;
  1045. if (*str < 0xc2) return 2;
  1046. c = (unsigned int)((*str++ & 0x1f) << 6);
  1047. if ((*str & 0xc0) != 0x80) return 2;
  1048. c += (*str++ & 0x3f);
  1049. *out_char = c;
  1050. return 2;
  1051. }
  1052. if ((*str & 0xf0) == 0xe0)
  1053. {
  1054. *out_char = 0xFFFD; // will be invalid but not end of string
  1055. if (in_text_end && in_text_end - (const char*)str < 3) return 1;
  1056. if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3;
  1057. if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below
  1058. c = (unsigned int)((*str++ & 0x0f) << 12);
  1059. if ((*str & 0xc0) != 0x80) return 3;
  1060. c += (unsigned int)((*str++ & 0x3f) << 6);
  1061. if ((*str & 0xc0) != 0x80) return 3;
  1062. c += (*str++ & 0x3f);
  1063. *out_char = c;
  1064. return 3;
  1065. }
  1066. if ((*str & 0xf8) == 0xf0)
  1067. {
  1068. *out_char = 0xFFFD; // will be invalid but not end of string
  1069. if (in_text_end && in_text_end - (const char*)str < 4) return 1;
  1070. if (*str > 0xf4) return 4;
  1071. if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4;
  1072. if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below
  1073. c = (unsigned int)((*str++ & 0x07) << 18);
  1074. if ((*str & 0xc0) != 0x80) return 4;
  1075. c += (unsigned int)((*str++ & 0x3f) << 12);
  1076. if ((*str & 0xc0) != 0x80) return 4;
  1077. c += (unsigned int)((*str++ & 0x3f) << 6);
  1078. if ((*str & 0xc0) != 0x80) return 4;
  1079. c += (*str++ & 0x3f);
  1080. // utf-8 encodings of values used in surrogate pairs are invalid
  1081. if ((c & 0xFFFFF800) == 0xD800) return 4;
  1082. *out_char = c;
  1083. return 4;
  1084. }
  1085. *out_char = 0;
  1086. return 0;
  1087. }
  1088.  
  1089. int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
  1090. {
  1091. ImWchar* buf_out = buf;
  1092. ImWchar* buf_end = buf + buf_size;
  1093. while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
  1094. {
  1095. unsigned int c;
  1096. in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
  1097. if (c == 0)
  1098. break;
  1099. if (c < 0x10000) // FIXME: Losing characters that don't fit in 2 bytes
  1100. *buf_out++ = (ImWchar)c;
  1101. }
  1102. *buf_out = 0;
  1103. if (in_text_remaining)
  1104. *in_text_remaining = in_text;
  1105. return (int)(buf_out - buf);
  1106. }
  1107.  
  1108. int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
  1109. {
  1110. int char_count = 0;
  1111. while ((!in_text_end || in_text < in_text_end) && *in_text)
  1112. {
  1113. unsigned int c;
  1114. in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
  1115. if (c == 0)
  1116. break;
  1117. if (c < 0x10000)
  1118. char_count++;
  1119. }
  1120. return char_count;
  1121. }
  1122.  
  1123. // Based on stb_to_utf8() from github.com/nothings/stb/
  1124. static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c)
  1125. {
  1126. if (c < 0x80)
  1127. {
  1128. buf[0] = (char)c;
  1129. return 1;
  1130. }
  1131. if (c < 0x800)
  1132. {
  1133. if (buf_size < 2) return 0;
  1134. buf[0] = (char)(0xc0 + (c >> 6));
  1135. buf[1] = (char)(0x80 + (c & 0x3f));
  1136. return 2;
  1137. }
  1138. if (c >= 0xdc00 && c < 0xe000)
  1139. {
  1140. return 0;
  1141. }
  1142. if (c >= 0xd800 && c < 0xdc00)
  1143. {
  1144. if (buf_size < 4) return 0;
  1145. buf[0] = (char)(0xf0 + (c >> 18));
  1146. buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
  1147. buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
  1148. buf[3] = (char)(0x80 + ((c) & 0x3f));
  1149. return 4;
  1150. }
  1151. //else if (c < 0x10000)
  1152. {
  1153. if (buf_size < 3) return 0;
  1154. buf[0] = (char)(0xe0 + (c >> 12));
  1155. buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
  1156. buf[2] = (char)(0x80 + ((c) & 0x3f));
  1157. return 3;
  1158. }
  1159. }
  1160.  
  1161. static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
  1162. {
  1163. if (c < 0x80) return 1;
  1164. if (c < 0x800) return 2;
  1165. if (c >= 0xdc00 && c < 0xe000) return 0;
  1166. if (c >= 0xd800 && c < 0xdc00) return 4;
  1167. return 3;
  1168. }
  1169.  
  1170. int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
  1171. {
  1172. char* buf_out = buf;
  1173. const char* buf_end = buf + buf_size;
  1174. while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
  1175. {
  1176. unsigned int c = (unsigned int)(*in_text++);
  1177. if (c < 0x80)
  1178. *buf_out++ = (char)c;
  1179. else
  1180. buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end - buf_out - 1), c);
  1181. }
  1182. *buf_out = 0;
  1183. return (int)(buf_out - buf);
  1184. }
  1185.  
  1186. int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
  1187. {
  1188. int bytes_count = 0;
  1189. while ((!in_text_end || in_text < in_text_end) && *in_text)
  1190. {
  1191. unsigned int c = (unsigned int)(*in_text++);
  1192. if (c < 0x80)
  1193. bytes_count++;
  1194. else
  1195. bytes_count += ImTextCountUtf8BytesFromChar(c);
  1196. }
  1197. return bytes_count;
  1198. }
  1199.  
  1200. ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
  1201. {
  1202. float s = 1.0f / 255.0f;
  1203. return ImVec4(
  1204. ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
  1205. ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
  1206. ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
  1207. ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
  1208. }
  1209.  
  1210. ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
  1211. {
  1212. ImU32 out;
  1213. out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
  1214. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
  1215. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
  1216. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
  1217. return out;
  1218. }
  1219.  
  1220. ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
  1221. {
  1222. ImGuiStyle& style = GImGui->Style;
  1223. ImVec4 c = style.Colors[idx];
  1224. c.w *= style.Alpha * alpha_mul;
  1225. return ColorConvertFloat4ToU32(c);
  1226. }
  1227.  
  1228. ImU32 ImGui::GetColorU32(const ImVec4& col)
  1229. {
  1230. ImGuiStyle& style = GImGui->Style;
  1231. ImVec4 c = col;
  1232. c.w *= style.Alpha;
  1233. return ColorConvertFloat4ToU32(c);
  1234. }
  1235.  
  1236. const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
  1237. {
  1238. ImGuiStyle& style = GImGui->Style;
  1239. return style.Colors[idx];
  1240. }
  1241.  
  1242. ImU32 ImGui::GetColorU32(ImU32 col)
  1243. {
  1244. float style_alpha = GImGui->Style.Alpha;
  1245. if (style_alpha >= 1.0f)
  1246. return col;
  1247. int a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
  1248. a = (int)(a * style_alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
  1249. return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
  1250. }
  1251.  
  1252. // Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
  1253. // Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
  1254. void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
  1255. {
  1256. float K = 0.f;
  1257. if (g < b)
  1258. {
  1259. ImSwap(g, b);
  1260. K = -1.f;
  1261. }
  1262. if (r < g)
  1263. {
  1264. ImSwap(r, g);
  1265. K = -2.f / 6.f - K;
  1266. }
  1267.  
  1268. const float chroma = r - (g < b ? g : b);
  1269. out_h = fabsf(K + (g - b) / (6.f * chroma + 1e-20f));
  1270. out_s = chroma / (r + 1e-20f);
  1271. out_v = r;
  1272. }
  1273.  
  1274. // Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
  1275. // also http://en.wikipedia.org/wiki/HSL_and_HSV
  1276. void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
  1277. {
  1278. if (s == 0.0f)
  1279. {
  1280. // gray
  1281. out_r = out_g = out_b = v;
  1282. return;
  1283. }
  1284.  
  1285. h = fmodf(h, 1.0f) / (60.0f / 360.0f);
  1286. int i = (int)h;
  1287. float f = h - (float)i;
  1288. float p = v * (1.0f - s);
  1289. float q = v * (1.0f - s * f);
  1290. float t = v * (1.0f - s * (1.0f - f));
  1291.  
  1292. switch (i)
  1293. {
  1294. case 0: out_r = v; out_g = t; out_b = p; break;
  1295. case 1: out_r = q; out_g = v; out_b = p; break;
  1296. case 2: out_r = p; out_g = v; out_b = t; break;
  1297. case 3: out_r = p; out_g = q; out_b = v; break;
  1298. case 4: out_r = t; out_g = p; out_b = v; break;
  1299. case 5: default: out_r = v; out_g = p; out_b = q; break;
  1300. }
  1301. }
  1302.  
  1303. bool ImGui::ColorPicker(const char* label, float* col)
  1304. {
  1305. const int EDGE_SIZE = 200; // = int( ImGui::GetWindowWidth() * 0.75f );
  1306. const ImVec2 SV_PICKER_SIZE = ImVec2(EDGE_SIZE, EDGE_SIZE);
  1307. const float SPACING = ImGui::GetStyle().ItemInnerSpacing.x;
  1308. const float HUE_PICKER_WIDTH = 20.f;
  1309. const float CROSSHAIR_SIZE = 7.0f;
  1310.  
  1311. ImColor color(col[0], col[1], col[2]);
  1312. bool value_changed = false;
  1313.  
  1314. ImDrawList* draw_list = ImGui::GetWindowDrawList();
  1315.  
  1316. // setup
  1317.  
  1318. ImVec2 picker_pos = ImGui::GetCursorScreenPos();
  1319.  
  1320. float hue, saturation, value;
  1321. ImGui::ColorConvertRGBtoHSV(
  1322. color.Value.x, color.Value.y, color.Value.z, hue, saturation, value);
  1323.  
  1324. // draw hue bar
  1325.  
  1326. ImColor colors[] = { ImColor(255, 0, 0),
  1327. ImColor(255, 255, 0),
  1328. ImColor(0, 255, 0),
  1329. ImColor(0, 255, 255),
  1330. ImColor(0, 0, 255),
  1331. ImColor(255, 0, 255),
  1332. ImColor(255, 0, 0) };
  1333.  
  1334. for (int i = 0; i < 6; ++i)
  1335. {
  1336. draw_list->AddRectFilledMultiColor(
  1337. ImVec2(picker_pos.x + SV_PICKER_SIZE.x + SPACING, picker_pos.y + i * (SV_PICKER_SIZE.y / 6)),
  1338. ImVec2(picker_pos.x + SV_PICKER_SIZE.x + SPACING + HUE_PICKER_WIDTH,
  1339. picker_pos.y + (i + 1) * (SV_PICKER_SIZE.y / 6)),
  1340. colors[i],
  1341. colors[i],
  1342. colors[i + 1],
  1343. colors[i + 1]);
  1344. }
  1345.  
  1346. draw_list->AddLine(
  1347. ImVec2(picker_pos.x + SV_PICKER_SIZE.x + SPACING - 2, picker_pos.y + hue * SV_PICKER_SIZE.y),
  1348. ImVec2(picker_pos.x + SV_PICKER_SIZE.x + SPACING + 2 + HUE_PICKER_WIDTH, picker_pos.y + hue * SV_PICKER_SIZE.y),
  1349. ImColor(255, 255, 255));
  1350.  
  1351. // draw color matrix
  1352.  
  1353. {
  1354. const ImU32 c_oColorBlack = ImGui::ColorConvertFloat4ToU32(ImVec4(0.f, 0.f, 0.f, 1.f));
  1355. const ImU32 c_oColorBlackTransparent = ImGui::ColorConvertFloat4ToU32(ImVec4(0.f, 0.f, 0.f, 0.f));
  1356. const ImU32 c_oColorWhite = ImGui::ColorConvertFloat4ToU32(ImVec4(1.f, 1.f, 1.f, 1.f));
  1357.  
  1358. ImVec4 cHueValue(1, 1, 1, 1);
  1359. ImGui::ColorConvertHSVtoRGB(hue, 1, 1, cHueValue.x, cHueValue.y, cHueValue.z);
  1360. ImU32 oHueColor = ImGui::ColorConvertFloat4ToU32(cHueValue);
  1361.  
  1362. draw_list->AddRectFilledMultiColor(
  1363. ImVec2(picker_pos.x, picker_pos.y),
  1364. ImVec2(picker_pos.x + SV_PICKER_SIZE.x, picker_pos.y + SV_PICKER_SIZE.y),
  1365. c_oColorWhite,
  1366. oHueColor,
  1367. oHueColor,
  1368. c_oColorWhite
  1369. );
  1370.  
  1371. draw_list->AddRectFilledMultiColor(
  1372. ImVec2(picker_pos.x, picker_pos.y),
  1373. ImVec2(picker_pos.x + SV_PICKER_SIZE.x, picker_pos.y + SV_PICKER_SIZE.y),
  1374. c_oColorBlackTransparent,
  1375. c_oColorBlackTransparent,
  1376. c_oColorBlack,
  1377. c_oColorBlack
  1378. );
  1379. }
  1380.  
  1381. // draw cross-hair
  1382.  
  1383. float x = saturation * SV_PICKER_SIZE.x;
  1384. float y = (1 - value) * SV_PICKER_SIZE.y;
  1385. ImVec2 p(picker_pos.x + x, picker_pos.y + y);
  1386. draw_list->AddLine(ImVec2(p.x - CROSSHAIR_SIZE, p.y), ImVec2(p.x - 2, p.y), ImColor(255, 255, 255));
  1387. draw_list->AddLine(ImVec2(p.x + CROSSHAIR_SIZE, p.y), ImVec2(p.x + 2, p.y), ImColor(255, 255, 255));
  1388. draw_list->AddLine(ImVec2(p.x, p.y + CROSSHAIR_SIZE), ImVec2(p.x, p.y + 2), ImColor(255, 255, 255));
  1389. draw_list->AddLine(ImVec2(p.x, p.y - CROSSHAIR_SIZE), ImVec2(p.x, p.y - 2), ImColor(255, 255, 255));
  1390.  
  1391. // color matrix logic
  1392.  
  1393. ImGui::InvisibleButton("saturation_value_selector", SV_PICKER_SIZE);
  1394.  
  1395. if (ImGui::IsItemActive() && ImGui::GetIO().MouseDown[0])
  1396. {
  1397. ImVec2 mouse_pos_in_canvas = ImVec2(
  1398. ImGui::GetIO().MousePos.x - picker_pos.x, ImGui::GetIO().MousePos.y - picker_pos.y);
  1399.  
  1400. /**/ if (mouse_pos_in_canvas.x < 0) mouse_pos_in_canvas.x = 0;
  1401. else if (mouse_pos_in_canvas.x >= SV_PICKER_SIZE.x - 1) mouse_pos_in_canvas.x = SV_PICKER_SIZE.x - 1;
  1402.  
  1403. /**/ if (mouse_pos_in_canvas.y < 0) mouse_pos_in_canvas.y = 0;
  1404. else if (mouse_pos_in_canvas.y >= SV_PICKER_SIZE.y - 1) mouse_pos_in_canvas.y = SV_PICKER_SIZE.y - 1;
  1405.  
  1406. value = 1 - (mouse_pos_in_canvas.y / (SV_PICKER_SIZE.y - 1));
  1407. saturation = mouse_pos_in_canvas.x / (SV_PICKER_SIZE.x - 1);
  1408. value_changed = true;
  1409. }
  1410.  
  1411. // hue bar logic
  1412.  
  1413. ImGui::SetCursorScreenPos(ImVec2(picker_pos.x + SPACING + SV_PICKER_SIZE.x, picker_pos.y));
  1414. ImGui::InvisibleButton("hue_selector", ImVec2(HUE_PICKER_WIDTH, SV_PICKER_SIZE.y));
  1415.  
  1416. if (ImGui::GetIO().MouseDown[0] && (ImGui::IsItemHovered() || ImGui::IsItemActive()))
  1417. {
  1418. ImVec2 mouse_pos_in_canvas = ImVec2(
  1419. ImGui::GetIO().MousePos.x - picker_pos.x, ImGui::GetIO().MousePos.y - picker_pos.y);
  1420.  
  1421. /**/ if (mouse_pos_in_canvas.y < 0) mouse_pos_in_canvas.y = 0;
  1422. else if (mouse_pos_in_canvas.y >= SV_PICKER_SIZE.y - 1) mouse_pos_in_canvas.y = SV_PICKER_SIZE.y - 1;
  1423.  
  1424. hue = mouse_pos_in_canvas.y / (SV_PICKER_SIZE.y - 1);
  1425. value_changed = true;
  1426. }
  1427.  
  1428. // R,G,B or H,S,V color editor
  1429.  
  1430. //color = ImColor::HSV(hue >= 1 ? hue - 10 * 1e-6 : hue, saturation > 0 ? saturation : 10 * 1e-6, value > 0 ? value : 1e-6);
  1431. color = ImColor::HSV(hue, saturation, value);
  1432. col[0] = color.Value.x;
  1433. col[1] = color.Value.y;
  1434. col[2] = color.Value.z;
  1435.  
  1436. return value_changed;
  1437. }
  1438.  
  1439. FILE* ImFileOpen(const char* filename, const char* mode)
  1440. {
  1441. #if defined(_WIN32) && !defined(__CYGWIN__)
  1442. // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames. Converting both strings from UTF-8 to wchar format (using a single allocation, because we can)
  1443. const int filename_wsize = ImTextCountCharsFromUtf8(filename, NULL) + 1;
  1444. const int mode_wsize = ImTextCountCharsFromUtf8(mode, NULL) + 1;
  1445. ImVector<ImWchar> buf;
  1446. buf.resize(filename_wsize + mode_wsize);
  1447. ImTextStrFromUtf8(&buf[0], filename_wsize, filename, NULL);
  1448. ImTextStrFromUtf8(&buf[filename_wsize], mode_wsize, mode, NULL);
  1449. return _wfopen((wchar_t*)&buf[0], (wchar_t*)&buf[filename_wsize]);
  1450. #else
  1451. return fopen(filename, mode);
  1452. #endif
  1453. }
  1454.  
  1455. // Load file content into memory
  1456. // Memory allocated with ImGui::MemAlloc(), must be freed by user using ImGui::MemFree()
  1457. void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, int* out_file_size, int padding_bytes)
  1458. {
  1459. IM_ASSERT(filename && file_open_mode);
  1460. if (out_file_size)
  1461. *out_file_size = 0;
  1462.  
  1463. FILE* f;
  1464. if ((f = ImFileOpen(filename, file_open_mode)) == NULL)
  1465. return NULL;
  1466.  
  1467. long file_size_signed;
  1468. if (fseek(f, 0, SEEK_END) || (file_size_signed = ftell(f)) == -1 || fseek(f, 0, SEEK_SET))
  1469. {
  1470. fclose(f);
  1471. return NULL;
  1472. }
  1473.  
  1474. int file_size = (int)file_size_signed;
  1475. void* file_data = ImGui::MemAlloc(file_size + padding_bytes);
  1476. if (file_data == NULL)
  1477. {
  1478. fclose(f);
  1479. return NULL;
  1480. }
  1481. if (fread(file_data, 1, (size_t)file_size, f) != (size_t)file_size)
  1482. {
  1483. fclose(f);
  1484. ImGui::MemFree(file_data);
  1485. return NULL;
  1486. }
  1487. if (padding_bytes > 0)
  1488. memset((void *)(((char*)file_data) + file_size), 0, padding_bytes);
  1489.  
  1490. fclose(f);
  1491. if (out_file_size)
  1492. *out_file_size = file_size;
  1493.  
  1494. return file_data;
  1495. }
  1496.  
  1497. //-----------------------------------------------------------------------------
  1498. // ImGuiStorage
  1499. //-----------------------------------------------------------------------------
  1500.  
  1501. // Helper: Key->value storage
  1502. void ImGuiStorage::Clear()
  1503. {
  1504. Data.clear();
  1505. }
  1506.  
  1507. // std::lower_bound but without the bullshit
  1508. static ImVector<ImGuiStorage::Pair>::iterator LowerBound(ImVector<ImGuiStorage::Pair>& data, ImGuiID key)
  1509. {
  1510. ImVector<ImGuiStorage::Pair>::iterator first = data.begin();
  1511. ImVector<ImGuiStorage::Pair>::iterator last = data.end();
  1512. int count = (int)(last - first);
  1513. while (count > 0)
  1514. {
  1515. int count2 = count / 2;
  1516. ImVector<ImGuiStorage::Pair>::iterator mid = first + count2;
  1517. if (mid->key < key)
  1518. {
  1519. first = ++mid;
  1520. count -= count2 + 1;
  1521. }
  1522. else
  1523. {
  1524. count = count2;
  1525. }
  1526. }
  1527. return first;
  1528. }
  1529.  
  1530. int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
  1531. {
  1532. ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
  1533. if (it == Data.end() || it->key != key)
  1534. return default_val;
  1535. return it->val_i;
  1536. }
  1537.  
  1538. bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
  1539. {
  1540. return GetInt(key, default_val ? 1 : 0) != 0;
  1541. }
  1542.  
  1543. float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
  1544. {
  1545. ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
  1546. if (it == Data.end() || it->key != key)
  1547. return default_val;
  1548. return it->val_f;
  1549. }
  1550.  
  1551. void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
  1552. {
  1553. ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
  1554. if (it == Data.end() || it->key != key)
  1555. return NULL;
  1556. return it->val_p;
  1557. }
  1558.  
  1559. // References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
  1560. int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
  1561. {
  1562. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1563. if (it == Data.end() || it->key != key)
  1564. it = Data.insert(it, Pair(key, default_val));
  1565. return &it->val_i;
  1566. }
  1567.  
  1568. bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
  1569. {
  1570. return (bool*)GetIntRef(key, default_val ? 1 : 0);
  1571. }
  1572.  
  1573. float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
  1574. {
  1575. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1576. if (it == Data.end() || it->key != key)
  1577. it = Data.insert(it, Pair(key, default_val));
  1578. return &it->val_f;
  1579. }
  1580.  
  1581. void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
  1582. {
  1583. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1584. if (it == Data.end() || it->key != key)
  1585. it = Data.insert(it, Pair(key, default_val));
  1586. return &it->val_p;
  1587. }
  1588.  
  1589. // FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
  1590. void ImGuiStorage::SetInt(ImGuiID key, int val)
  1591. {
  1592. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1593. if (it == Data.end() || it->key != key)
  1594. {
  1595. Data.insert(it, Pair(key, val));
  1596. return;
  1597. }
  1598. it->val_i = val;
  1599. }
  1600.  
  1601. void ImGuiStorage::SetBool(ImGuiID key, bool val)
  1602. {
  1603. SetInt(key, val ? 1 : 0);
  1604. }
  1605.  
  1606. void ImGuiStorage::SetFloat(ImGuiID key, float val)
  1607. {
  1608. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1609. if (it == Data.end() || it->key != key)
  1610. {
  1611. Data.insert(it, Pair(key, val));
  1612. return;
  1613. }
  1614. it->val_f = val;
  1615. }
  1616.  
  1617. void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
  1618. {
  1619. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1620. if (it == Data.end() || it->key != key)
  1621. {
  1622. Data.insert(it, Pair(key, val));
  1623. return;
  1624. }
  1625. it->val_p = val;
  1626. }
  1627.  
  1628. void ImGuiStorage::SetAllInt(int v)
  1629. {
  1630. for (int i = 0; i < Data.Size; i++)
  1631. Data[i].val_i = v;
  1632. }
  1633.  
  1634. //-----------------------------------------------------------------------------
  1635. // ImGuiTextFilter
  1636. //-----------------------------------------------------------------------------
  1637.  
  1638. // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
  1639. ImGuiTextFilter::ImGuiTextFilter(const char* default_filter)
  1640. {
  1641. if (default_filter)
  1642. {
  1643. ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
  1644. Build();
  1645. }
  1646. else
  1647. {
  1648. InputBuf[0] = 0;
  1649. CountGrep = 0;
  1650. }
  1651. }
  1652.  
  1653. bool ImGuiTextFilter::Draw(const char* label, float width)
  1654. {
  1655. if (width != 0.0f)
  1656. ImGui::PushItemWidth(width);
  1657. bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
  1658. if (width != 0.0f)
  1659. ImGui::PopItemWidth();
  1660. if (value_changed)
  1661. Build();
  1662. return value_changed;
  1663. }
  1664.  
  1665. void ImGuiTextFilter::TextRange::split(char separator, ImVector<TextRange>& out)
  1666. {
  1667. out.resize(0);
  1668. const char* wb = b;
  1669. const char* we = wb;
  1670. while (we < e)
  1671. {
  1672. if (*we == separator)
  1673. {
  1674. out.push_back(TextRange(wb, we));
  1675. wb = we + 1;
  1676. }
  1677. we++;
  1678. }
  1679. if (wb != we)
  1680. out.push_back(TextRange(wb, we));
  1681. }
  1682.  
  1683. void ImGuiTextFilter::Build()
  1684. {
  1685. Filters.resize(0);
  1686. TextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
  1687. input_range.split(',', Filters);
  1688.  
  1689. CountGrep = 0;
  1690. for (int i = 0; i != Filters.Size; i++)
  1691. {
  1692. Filters[i].trim_blanks();
  1693. if (Filters[i].empty())
  1694. continue;
  1695. if (Filters[i].front() != '-')
  1696. CountGrep += 1;
  1697. }
  1698. }
  1699.  
  1700. bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
  1701. {
  1702. if (Filters.empty())
  1703. return true;
  1704.  
  1705. if (text == NULL)
  1706. text = "";
  1707.  
  1708. for (int i = 0; i != Filters.Size; i++)
  1709. {
  1710. const TextRange& f = Filters[i];
  1711. if (f.empty())
  1712. continue;
  1713. if (f.front() == '-')
  1714. {
  1715. // Subtract
  1716. if (ImStristr(text, text_end, f.begin() + 1, f.end()) != NULL)
  1717. return false;
  1718. }
  1719. else
  1720. {
  1721. // Grep
  1722. if (ImStristr(text, text_end, f.begin(), f.end()) != NULL)
  1723. return true;
  1724. }
  1725. }
  1726.  
  1727. // Implicit * grep
  1728. if (CountGrep == 0)
  1729. return true;
  1730.  
  1731. return false;
  1732. }
  1733.  
  1734. //-----------------------------------------------------------------------------
  1735. // ImGuiTextBuffer
  1736. //-----------------------------------------------------------------------------
  1737.  
  1738. // On some platform vsnprintf() takes va_list by reference and modifies it.
  1739. // va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
  1740. #ifndef va_copy
  1741. #define va_copy(dest, src) (dest = src)
  1742. #endif
  1743.  
  1744. // Helper: Text buffer for logging/accumulating text
  1745. void ImGuiTextBuffer::appendv(const char* fmt, va_list args)
  1746. {
  1747. va_list args_copy;
  1748. va_copy(args_copy, args);
  1749.  
  1750. int len = vsnprintf(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
  1751. if (len <= 0)
  1752. return;
  1753.  
  1754. const int write_off = Buf.Size;
  1755. const int needed_sz = write_off + len;
  1756. if (write_off + len >= Buf.Capacity)
  1757. {
  1758. int double_capacity = Buf.Capacity * 2;
  1759. Buf.reserve(needed_sz > double_capacity ? needed_sz : double_capacity);
  1760. }
  1761.  
  1762. Buf.resize(needed_sz);
  1763. ImFormatStringV(&Buf[write_off] - 1, len + 1, fmt, args_copy);
  1764. }
  1765.  
  1766. void ImGuiTextBuffer::append(const char* fmt, ...)
  1767. {
  1768. va_list args;
  1769. va_start(args, fmt);
  1770. appendv(fmt, args);
  1771. va_end(args);
  1772. }
  1773.  
  1774. //-----------------------------------------------------------------------------
  1775. // ImGuiSimpleColumns
  1776. //-----------------------------------------------------------------------------
  1777.  
  1778. ImGuiSimpleColumns::ImGuiSimpleColumns()
  1779. {
  1780. Count = 0;
  1781. Spacing = Width = NextWidth = 0.0f;
  1782. memset(Pos, 0, sizeof(Pos));
  1783. memset(NextWidths, 0, sizeof(NextWidths));
  1784. }
  1785.  
  1786. void ImGuiSimpleColumns::Update(int count, float spacing, bool clear)
  1787. {
  1788. IM_ASSERT(Count <= IM_ARRAYSIZE(Pos));
  1789. Count = count;
  1790. Width = NextWidth = 0.0f;
  1791. Spacing = spacing;
  1792. if (clear) memset(NextWidths, 0, sizeof(NextWidths));
  1793. for (int i = 0; i < Count; i++)
  1794. {
  1795. if (i > 0 && NextWidths[i] > 0.0f)
  1796. Width += Spacing;
  1797. Pos[i] = (float)(int)Width;
  1798. Width += NextWidths[i];
  1799. NextWidths[i] = 0.0f;
  1800. }
  1801. }
  1802.  
  1803. float ImGuiSimpleColumns::DeclColumns(float w0, float w1, float w2) // not using va_arg because they promote float to double
  1804. {
  1805. NextWidth = 0.0f;
  1806. NextWidths[0] = ImMax(NextWidths[0], w0);
  1807. NextWidths[1] = ImMax(NextWidths[1], w1);
  1808. NextWidths[2] = ImMax(NextWidths[2], w2);
  1809. for (int i = 0; i < 3; i++)
  1810. NextWidth += NextWidths[i] + ((i > 0 && NextWidths[i] > 0.0f) ? Spacing : 0.0f);
  1811. return ImMax(Width, NextWidth);
  1812. }
  1813.  
  1814. float ImGuiSimpleColumns::CalcExtraSpace(float avail_w)
  1815. {
  1816. return ImMax(0.0f, avail_w - Width);
  1817. }
  1818.  
  1819. //-----------------------------------------------------------------------------
  1820. // ImGuiListClipper
  1821. //-----------------------------------------------------------------------------
  1822.  
  1823. static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height)
  1824. {
  1825. // Set cursor position and a few other things so that SetScrollHere() and Columns() can work when seeking cursor.
  1826. // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue. Consider moving within SetCursorXXX functions?
  1827. ImGui::SetCursorPosY(pos_y);
  1828. ImGuiWindow* window = ImGui::GetCurrentWindow();
  1829. window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHere() can properly function after the end of our clipper usage.
  1830. window->DC.PrevLineHeight = (line_height - GImGui->Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
  1831. if (window->DC.ColumnsCount > 1)
  1832. window->DC.ColumnsCellMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
  1833. }
  1834.  
  1835. // Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1
  1836. // Use case B: Begin() called from constructor with items_height>0
  1837. // FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style.
  1838. void ImGuiListClipper::Begin(int count, float items_height)
  1839. {
  1840. StartPosY = ImGui::GetCursorPosY();
  1841. ItemsHeight = items_height;
  1842. ItemsCount = count;
  1843. StepNo = 0;
  1844. DisplayEnd = DisplayStart = -1;
  1845. if (ItemsHeight > 0.0f)
  1846. {
  1847. ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display
  1848. if (DisplayStart > 0)
  1849. SetCursorPosYAndSetupDummyPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor
  1850. StepNo = 2;
  1851. }
  1852. }
  1853.  
  1854. void ImGuiListClipper::End()
  1855. {
  1856. if (ItemsCount < 0)
  1857. return;
  1858. // In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user.
  1859. if (ItemsCount < INT_MAX)
  1860. SetCursorPosYAndSetupDummyPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor
  1861. ItemsCount = -1;
  1862. StepNo = 3;
  1863. }
  1864.  
  1865. bool ImGuiListClipper::Step()
  1866. {
  1867. if (ItemsCount == 0 || ImGui::GetCurrentWindowRead()->SkipItems)
  1868. {
  1869. ItemsCount = -1;
  1870. return false;
  1871. }
  1872. if (StepNo == 0) // Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height.
  1873. {
  1874. DisplayStart = 0;
  1875. DisplayEnd = 1;
  1876. StartPosY = ImGui::GetCursorPosY();
  1877. StepNo = 1;
  1878. return true;
  1879. }
  1880. if (StepNo == 1) // Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element.
  1881. {
  1882. if (ItemsCount == 1) { ItemsCount = -1; return false; }
  1883. float items_height = ImGui::GetCursorPosY() - StartPosY;
  1884. IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically
  1885. Begin(ItemsCount - 1, items_height);
  1886. DisplayStart++;
  1887. DisplayEnd++;
  1888. StepNo = 3;
  1889. return true;
  1890. }
  1891. if (StepNo == 2) // Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3.
  1892. {
  1893. IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0);
  1894. StepNo = 3;
  1895. return true;
  1896. }
  1897. if (StepNo == 3) // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop.
  1898. End();
  1899. return false;
  1900. }
  1901.  
  1902. //-----------------------------------------------------------------------------
  1903. // ImGuiWindow
  1904. //-----------------------------------------------------------------------------
  1905.  
  1906. ImGuiWindow::ImGuiWindow(const char* name)
  1907. {
  1908. Name = ImStrdup(name);
  1909. ID = ImHash(name, 0);
  1910. IDStack.push_back(ID);
  1911. Flags = 0;
  1912. OrderWithinParent = 0;
  1913. PosFloat = Pos = ImVec2(0.0f, 0.0f);
  1914. Size = SizeFull = ImVec2(0.0f, 0.0f);
  1915. SizeContents = SizeContentsExplicit = ImVec2(0.0f, 0.0f);
  1916. WindowPadding = ImVec2(0.0f, 0.0f);
  1917. MoveId = GetID("#MOVE");
  1918. Scroll = ImVec2(0.0f, 0.0f);
  1919. ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
  1920. ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
  1921. ScrollbarX = ScrollbarY = false;
  1922. ScrollbarSizes = ImVec2(0.0f, 0.0f);
  1923. BorderSize = 0.0f;
  1924. Active = WasActive = false;
  1925. Accessed = false;
  1926. Collapsed = false;
  1927. SkipItems = false;
  1928. BeginCount = 0;
  1929. PopupId = 0;
  1930. AutoFitFramesX = AutoFitFramesY = -1;
  1931. AutoFitOnlyGrows = false;
  1932. AutoFitChildAxises = 0x00;
  1933. AutoPosLastDirection = -1;
  1934. HiddenFrames = 0;
  1935. SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
  1936. SetWindowPosCenterWanted = false;
  1937.  
  1938. LastFrameActive = -1;
  1939. ItemWidthDefault = 0.0f;
  1940. FontWindowScale = 1.0f;
  1941.  
  1942. DrawList = (ImDrawList*)ImGui::MemAlloc(sizeof(ImDrawList));
  1943. IM_PLACEMENT_NEW(DrawList) ImDrawList();
  1944. DrawList->_OwnerName = Name;
  1945. ParentWindow = NULL;
  1946. RootWindow = NULL;
  1947. RootNonPopupWindow = NULL;
  1948.  
  1949. FocusIdxAllCounter = FocusIdxTabCounter = -1;
  1950. FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = INT_MAX;
  1951. FocusIdxAllRequestNext = FocusIdxTabRequestNext = INT_MAX;
  1952. }
  1953.  
  1954. ImGuiWindow::~ImGuiWindow()
  1955. {
  1956. DrawList->~ImDrawList();
  1957. ImGui::MemFree(DrawList);
  1958. DrawList = NULL;
  1959. ImGui::MemFree(Name);
  1960. Name = NULL;
  1961. }
  1962.  
  1963. ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
  1964. {
  1965. ImGuiID seed = IDStack.back();
  1966. ImGuiID id = ImHash(str, str_end ? (int)(str_end - str) : 0, seed);
  1967. ImGui::KeepAliveID(id);
  1968. return id;
  1969. }
  1970.  
  1971. ImGuiID ImGuiWindow::GetID(const void* ptr)
  1972. {
  1973. ImGuiID seed = IDStack.back();
  1974. ImGuiID id = ImHash(&ptr, sizeof(void*), seed);
  1975. ImGui::KeepAliveID(id);
  1976. return id;
  1977. }
  1978.  
  1979. ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end)
  1980. {
  1981. ImGuiID seed = IDStack.back();
  1982. return ImHash(str, str_end ? (int)(str_end - str) : 0, seed);
  1983. }
  1984.  
  1985. //-----------------------------------------------------------------------------
  1986. // Internal API exposed in imgui_internal.h
  1987. //-----------------------------------------------------------------------------
  1988.  
  1989. static void SetCurrentWindow(ImGuiWindow* window)
  1990. {
  1991. ImGuiContext& g = *GImGui;
  1992. g.CurrentWindow = window;
  1993. if (window)
  1994. g.FontSize = window->CalcFontSize();
  1995. }
  1996.  
  1997. ImGuiWindow* ImGui::GetParentWindow()
  1998. {
  1999. ImGuiContext& g = *GImGui;
  2000. IM_ASSERT(g.CurrentWindowStack.Size >= 2);
  2001. return g.CurrentWindowStack[(unsigned int)g.CurrentWindowStack.Size - 2];
  2002. }
  2003.  
  2004. void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
  2005. {
  2006. ImGuiContext& g = *GImGui;
  2007. g.ActiveIdIsJustActivated = (g.ActiveId != id);
  2008. g.ActiveId = id;
  2009. g.ActiveIdAllowOverlap = false;
  2010. g.ActiveIdIsAlive |= (id != 0);
  2011. g.ActiveIdWindow = window;
  2012. }
  2013.  
  2014. void ImGui::ClearActiveID()
  2015. {
  2016. SetActiveID(0, NULL);
  2017. }
  2018.  
  2019. void ImGui::SetHoveredID(ImGuiID id)
  2020. {
  2021. ImGuiContext& g = *GImGui;
  2022. g.HoveredId = id;
  2023. g.HoveredIdAllowOverlap = false;
  2024. }
  2025.  
  2026. void ImGui::KeepAliveID(ImGuiID id)
  2027. {
  2028. ImGuiContext& g = *GImGui;
  2029. if (g.ActiveId == id)
  2030. g.ActiveIdIsAlive = true;
  2031. }
  2032.  
  2033. // Advance cursor given item size for layout.
  2034. void ImGui::ItemSize(const ImVec2& size, float text_offset_y)
  2035. {
  2036. ImGuiWindow* window = GetCurrentWindow();
  2037. if (window->SkipItems)
  2038. return;
  2039.  
  2040. // Always align ourselves on pixel boundaries
  2041. ImGuiContext& g = *GImGui;
  2042. const float line_height = ImMax(window->DC.CurrentLineHeight, size.y);
  2043. const float text_base_offset = ImMax(window->DC.CurrentLineTextBaseOffset, text_offset_y);
  2044. window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x + size.x, window->DC.CursorPos.y);
  2045. window->DC.CursorPos = ImVec2((float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX), (float)(int)(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y));
  2046. window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
  2047. window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
  2048.  
  2049. //window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // Debug
  2050.  
  2051. window->DC.PrevLineHeight = line_height;
  2052. window->DC.PrevLineTextBaseOffset = text_base_offset;
  2053. window->DC.CurrentLineHeight = window->DC.CurrentLineTextBaseOffset = 0.0f;
  2054. }
  2055.  
  2056. void ImGui::ItemSize(const ImRect& bb, float text_offset_y)
  2057. {
  2058. ItemSize(bb.GetSize(), text_offset_y);
  2059. }
  2060.  
  2061. // Declare item bounding box for clipping and interaction.
  2062. // Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
  2063. // declares their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd().
  2064. bool ImGui::ItemAdd(const ImRect& bb, const ImGuiID* id)
  2065. {
  2066. ImGuiContext& g = *GImGui;
  2067. ImGuiWindow* window = g.CurrentWindow;
  2068. window->DC.LastItemId = id ? *id : 0;
  2069. window->DC.LastItemRect = bb;
  2070. window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = false;
  2071. if (IsClippedEx(bb, id, false))
  2072. return false;
  2073.  
  2074. // Setting LastItemHoveredAndUsable for IsItemHovered(). This is a sensible default, but widgets are free to override it.
  2075. if (IsMouseHoveringRect(bb.Min, bb.Max))
  2076. {
  2077. // Matching the behavior of IsHovered() but allow if ActiveId==window->MoveID (we clicked on the window background)
  2078. // So that clicking on items with no active id such as Text() still returns true with IsItemHovered()
  2079. window->DC.LastItemHoveredRect = true;
  2080. if (g.HoveredRootWindow == window->RootWindow)
  2081. if (g.ActiveId == 0 || (id && g.ActiveId == *id) || g.ActiveIdAllowOverlap || (g.ActiveId == window->MoveId))
  2082. if (IsWindowContentHoverable(window))
  2083. window->DC.LastItemHoveredAndUsable = true;
  2084. }
  2085.  
  2086. return true;
  2087. }
  2088.  
  2089. bool ImGui::IsClippedEx(const ImRect& bb, const ImGuiID* id, bool clip_even_when_logged)
  2090. {
  2091. ImGuiContext& g = *GImGui;
  2092. ImGuiWindow* window = GetCurrentWindowRead();
  2093. if (!bb.Overlaps(window->ClipRect))
  2094. if (!id || *id != GImGui->ActiveId)
  2095. if (clip_even_when_logged || !g.LogEnabled)
  2096. return true;
  2097. return false;
  2098. }
  2099.  
  2100. // NB: This is an internal helper. The user-facing IsItemHovered() is using data emitted from ItemAdd(), with a slightly different logic.
  2101. bool ImGui::IsHovered(const ImRect& bb, ImGuiID id, bool flatten_childs)
  2102. {
  2103. ImGuiContext& g = *GImGui;
  2104. if (g.HoveredId == 0 || g.HoveredId == id || g.HoveredIdAllowOverlap)
  2105. {
  2106. ImGuiWindow* window = GetCurrentWindowRead();
  2107. if (g.HoveredWindow == window || (flatten_childs && g.HoveredRootWindow == window->RootWindow))
  2108. if ((g.ActiveId == 0 || g.ActiveId == id || g.ActiveIdAllowOverlap) && IsMouseHoveringRect(bb.Min, bb.Max))
  2109. if (IsWindowContentHoverable(g.HoveredRootWindow))
  2110. return true;
  2111. }
  2112. return false;
  2113. }
  2114.  
  2115. bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id, bool tab_stop)
  2116. {
  2117. ImGuiContext& g = *GImGui;
  2118.  
  2119. const bool allow_keyboard_focus = window->DC.AllowKeyboardFocus;
  2120. window->FocusIdxAllCounter++;
  2121. if (allow_keyboard_focus)
  2122. window->FocusIdxTabCounter++;
  2123.  
  2124. // Process keyboard input at this point: TAB/Shift-TAB to tab out of the currently focused item.
  2125. // Note that we can always TAB out of a widget that doesn't allow tabbing in.
  2126. if (tab_stop && (g.ActiveId == id) && window->FocusIdxAllRequestNext == INT_MAX && window->FocusIdxTabRequestNext == INT_MAX && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab))
  2127. window->FocusIdxTabRequestNext = window->FocusIdxTabCounter + (g.IO.KeyShift ? (allow_keyboard_focus ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items.
  2128.  
  2129. if (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent)
  2130. return true;
  2131.  
  2132. if (allow_keyboard_focus)
  2133. if (window->FocusIdxTabCounter == window->FocusIdxTabRequestCurrent)
  2134. return true;
  2135.  
  2136. return false;
  2137. }
  2138.  
  2139. void ImGui::FocusableItemUnregister(ImGuiWindow* window)
  2140. {
  2141. window->FocusIdxAllCounter--;
  2142. window->FocusIdxTabCounter--;
  2143. }
  2144.  
  2145. ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_x, float default_y)
  2146. {
  2147. ImGuiContext& g = *GImGui;
  2148. ImVec2 content_max;
  2149. if (size.x < 0.0f || size.y < 0.0f)
  2150. content_max = g.CurrentWindow->Pos + GetContentRegionMax();
  2151. if (size.x <= 0.0f)
  2152. size.x = (size.x == 0.0f) ? default_x : ImMax(content_max.x - g.CurrentWindow->DC.CursorPos.x, 4.0f) + size.x;
  2153. if (size.y <= 0.0f)
  2154. size.y = (size.y == 0.0f) ? default_y : ImMax(content_max.y - g.CurrentWindow->DC.CursorPos.y, 4.0f) + size.y;
  2155. return size;
  2156. }
  2157.  
  2158. float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
  2159. {
  2160. if (wrap_pos_x < 0.0f)
  2161. return 0.0f;
  2162.  
  2163. ImGuiWindow* window = GetCurrentWindowRead();
  2164. if (wrap_pos_x == 0.0f)
  2165. wrap_pos_x = GetContentRegionMax().x + window->Pos.x;
  2166. else if (wrap_pos_x > 0.0f)
  2167. wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
  2168.  
  2169. return ImMax(wrap_pos_x - pos.x, 1.0f);
  2170. }
  2171.  
  2172. //-----------------------------------------------------------------------------
  2173.  
  2174. void* ImGui::MemAlloc(size_t sz)
  2175. {
  2176. GImGui->IO.MetricsAllocs++;
  2177. return GImGui->IO.MemAllocFn(sz);
  2178. }
  2179.  
  2180. void ImGui::MemFree(void* ptr)
  2181. {
  2182. if (ptr) GImGui->IO.MetricsAllocs--;
  2183. return GImGui->IO.MemFreeFn(ptr);
  2184. }
  2185.  
  2186. const char* ImGui::GetClipboardText()
  2187. {
  2188. return GImGui->IO.GetClipboardTextFn ? GImGui->IO.GetClipboardTextFn(GImGui->IO.ClipboardUserData) : "";
  2189. }
  2190.  
  2191. void ImGui::SetClipboardText(const char* text)
  2192. {
  2193. if (GImGui->IO.SetClipboardTextFn)
  2194. GImGui->IO.SetClipboardTextFn(GImGui->IO.ClipboardUserData, text);
  2195. }
  2196.  
  2197. const char* ImGui::GetVersion()
  2198. {
  2199. return IMGUI_VERSION;
  2200. }
  2201.  
  2202. // Internal state access - if you want to share ImGui state between modules (e.g. DLL) or allocate it yourself
  2203. // Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
  2204. ImGuiContext* ImGui::GetCurrentContext()
  2205. {
  2206. return GImGui;
  2207. }
  2208.  
  2209. void ImGui::SetCurrentContext(ImGuiContext* ctx)
  2210. {
  2211. #ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
  2212. IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
  2213. #else
  2214. GImGui = ctx;
  2215. #endif
  2216. }
  2217.  
  2218. ImGuiContext* ImGui::CreateContext(void* (*malloc_fn)(size_t), void(*free_fn)(void*))
  2219. {
  2220. if (!malloc_fn) malloc_fn = malloc;
  2221. ImGuiContext* ctx = (ImGuiContext*)malloc_fn(sizeof(ImGuiContext));
  2222. IM_PLACEMENT_NEW(ctx) ImGuiContext();
  2223. ctx->IO.MemAllocFn = malloc_fn;
  2224. ctx->IO.MemFreeFn = free_fn ? free_fn : free;
  2225. return ctx;
  2226. }
  2227.  
  2228. void ImGui::DestroyContext(ImGuiContext* ctx)
  2229. {
  2230. void(*free_fn)(void*) = ctx->IO.MemFreeFn;
  2231. ctx->~ImGuiContext();
  2232. free_fn(ctx);
  2233. if (GImGui == ctx)
  2234. SetCurrentContext(NULL);
  2235. }
  2236.  
  2237. ImGuiIO& ImGui::GetIO()
  2238. {
  2239. return GImGui->IO;
  2240. }
  2241.  
  2242. ImGuiStyle& ImGui::GetStyle()
  2243. {
  2244. return GImGui->Style;
  2245. }
  2246.  
  2247. // Same value as passed to your RenderDrawListsFn() function. valid after Render() and until the next call to NewFrame()
  2248. ImDrawData* ImGui::GetDrawData()
  2249. {
  2250. return GImGui->RenderDrawData.Valid ? &GImGui->RenderDrawData : NULL;
  2251. }
  2252.  
  2253. float ImGui::GetTime()
  2254. {
  2255. return GImGui->Time;
  2256. }
  2257.  
  2258. int ImGui::GetFrameCount()
  2259. {
  2260. return GImGui->FrameCount;
  2261. }
  2262.  
  2263. void ImGui::NewFrame()
  2264. {
  2265. ImGuiContext& g = *GImGui;
  2266.  
  2267. // Check user data
  2268. IM_ASSERT(g.IO.DeltaTime >= 0.0f); // Need a positive DeltaTime (zero is tolerated but will cause some timing issues)
  2269. IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f);
  2270. IM_ASSERT(g.IO.Fonts->Fonts.Size > 0); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
  2271. IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
  2272. IM_ASSERT(g.Style.CurveTessellationTol > 0.0f); // Invalid style setting
  2273. IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f); // Invalid style setting. Alpha cannot be negative (allows us to avoid a few clamps in color computations)
  2274.  
  2275. // Initialize on first frame
  2276. if (!g.Initialized)
  2277. ImGui::Initialize();
  2278.  
  2279. SetCurrentFont(GetDefaultFont());
  2280. IM_ASSERT(g.Font->IsLoaded());
  2281.  
  2282. g.Time += g.IO.DeltaTime;
  2283. g.FrameCount += 1;
  2284. g.TooltipOverrideCount = 0;
  2285. g.OverlayDrawList.Clear();
  2286. g.OverlayDrawList.PushTextureID(g.IO.Fonts->TexID);
  2287. g.OverlayDrawList.PushClipRectFullScreen();
  2288.  
  2289. // Mark rendering data as invalid to prevent user who may have a handle on it to use it
  2290. g.RenderDrawData.Valid = false;
  2291. g.RenderDrawData.CmdLists = NULL;
  2292. g.RenderDrawData.CmdListsCount = g.RenderDrawData.TotalVtxCount = g.RenderDrawData.TotalIdxCount = 0;
  2293.  
  2294. // Clear reference to active widget if the widget isn't alive anymore
  2295. g.HoveredIdPreviousFrame = g.HoveredId;
  2296. g.HoveredId = 0;
  2297. g.HoveredIdAllowOverlap = false;
  2298. if (!g.ActiveIdIsAlive && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0)
  2299. ClearActiveID();
  2300. g.ActiveIdPreviousFrame = g.ActiveId;
  2301. g.ActiveIdIsAlive = false;
  2302. g.ActiveIdIsJustActivated = false;
  2303. if (g.ScalarAsInputTextId && g.ActiveId != g.ScalarAsInputTextId)
  2304. g.ScalarAsInputTextId = 0;
  2305.  
  2306. // Update keyboard input state
  2307. memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration));
  2308. for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++)
  2309. g.IO.KeysDownDuration[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownDuration[i] < 0.0f ? 0.0f : g.IO.KeysDownDuration[i] + g.IO.DeltaTime) : -1.0f;
  2310.  
  2311. // Update mouse input state
  2312. // If mouse just appeared or disappeared (usually denoted by -FLT_MAX component, but in reality we test for -256000.0f) we cancel out movement in MouseDelta
  2313. if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MousePosPrev))
  2314. g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev;
  2315. else
  2316. g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
  2317. g.IO.MousePosPrev = g.IO.MousePos;
  2318. for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
  2319. {
  2320. g.IO.MouseClicked[i] = g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] < 0.0f;
  2321. g.IO.MouseReleased[i] = !g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] >= 0.0f;
  2322. g.IO.MouseDownDurationPrev[i] = g.IO.MouseDownDuration[i];
  2323. g.IO.MouseDownDuration[i] = g.IO.MouseDown[i] ? (g.IO.MouseDownDuration[i] < 0.0f ? 0.0f : g.IO.MouseDownDuration[i] + g.IO.DeltaTime) : -1.0f;
  2324. g.IO.MouseDoubleClicked[i] = false;
  2325. if (g.IO.MouseClicked[i])
  2326. {
  2327. if (g.Time - g.IO.MouseClickedTime[i] < g.IO.MouseDoubleClickTime)
  2328. {
  2329. if (ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i]) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist)
  2330. g.IO.MouseDoubleClicked[i] = true;
  2331. g.IO.MouseClickedTime[i] = -FLT_MAX; // so the third click isn't turned into a double-click
  2332. }
  2333. else
  2334. {
  2335. g.IO.MouseClickedTime[i] = g.Time;
  2336. }
  2337. g.IO.MouseClickedPos[i] = g.IO.MousePos;
  2338. g.IO.MouseDragMaxDistanceSqr[i] = 0.0f;
  2339. }
  2340. else if (g.IO.MouseDown[i])
  2341. {
  2342. g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i]));
  2343. }
  2344. }
  2345.  
  2346. // Calculate frame-rate for the user, as a purely luxurious feature
  2347. g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
  2348. g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
  2349. g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
  2350. g.IO.Framerate = 1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame));
  2351.  
  2352. // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering). Only valid for root windows.
  2353. if (g.MovedWindowMoveId && g.MovedWindowMoveId == g.ActiveId)
  2354. {
  2355. KeepAliveID(g.MovedWindowMoveId);
  2356. IM_ASSERT(g.MovedWindow && g.MovedWindow->RootWindow);
  2357. IM_ASSERT(g.MovedWindow->RootWindow->MoveId == g.MovedWindowMoveId);
  2358. if (g.IO.MouseDown[0])
  2359. {
  2360. if (!(g.MovedWindow->Flags & ImGuiWindowFlags_NoMove))
  2361. {
  2362. g.MovedWindow->PosFloat += g.IO.MouseDelta;
  2363. if (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f)
  2364. MarkIniSettingsDirty(g.MovedWindow);
  2365. }
  2366. FocusWindow(g.MovedWindow);
  2367. }
  2368. else
  2369. {
  2370. ClearActiveID();
  2371. g.MovedWindow = NULL;
  2372. g.MovedWindowMoveId = 0;
  2373. }
  2374. }
  2375. else
  2376. {
  2377. g.MovedWindow = NULL;
  2378. g.MovedWindowMoveId = 0;
  2379. }
  2380.  
  2381. // Delay saving settings so we don't spam disk too much
  2382. if (g.SettingsDirtyTimer > 0.0f)
  2383. {
  2384. g.SettingsDirtyTimer -= g.IO.DeltaTime;
  2385. if (g.SettingsDirtyTimer <= 0.0f)
  2386. SaveIniSettingsToDisk(g.IO.IniFilename);
  2387. }
  2388.  
  2389. // Find the window we are hovering. Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow
  2390. g.HoveredWindow = g.MovedWindow ? g.MovedWindow : FindHoveredWindow(g.IO.MousePos, false);
  2391. if (g.HoveredWindow && (g.HoveredWindow->Flags & ImGuiWindowFlags_ChildWindow))
  2392. g.HoveredRootWindow = g.HoveredWindow->RootWindow;
  2393. else
  2394. g.HoveredRootWindow = g.MovedWindow ? g.MovedWindow->RootWindow : FindHoveredWindow(g.IO.MousePos, true);
  2395.  
  2396. if (ImGuiWindow* modal_window = GetFrontMostModalRootWindow())
  2397. {
  2398. g.ModalWindowDarkeningRatio = ImMin(g.ModalWindowDarkeningRatio + g.IO.DeltaTime * 6.0f, 1.0f);
  2399. ImGuiWindow* window = g.HoveredRootWindow;
  2400. while (window && window != modal_window)
  2401. window = window->ParentWindow;
  2402. if (!window)
  2403. g.HoveredRootWindow = g.HoveredWindow = NULL;
  2404. }
  2405. else
  2406. {
  2407. g.ModalWindowDarkeningRatio = 0.0f;
  2408. }
  2409.  
  2410. // Are we using inputs? Tell user so they can capture/discard the inputs away from the rest of their application.
  2411. // When clicking outside of a window we assume the click is owned by the application and won't request capture. We need to track click ownership.
  2412. int mouse_earliest_button_down = -1;
  2413. bool mouse_any_down = false;
  2414. for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
  2415. {
  2416. if (g.IO.MouseClicked[i])
  2417. g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (!g.OpenPopupStack.empty());
  2418. mouse_any_down |= g.IO.MouseDown[i];
  2419. if (g.IO.MouseDown[i])
  2420. if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[mouse_earliest_button_down] > g.IO.MouseClickedTime[i])
  2421. mouse_earliest_button_down = i;
  2422. }
  2423. bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down];
  2424. if (g.CaptureMouseNextFrame != -1)
  2425. g.IO.WantCaptureMouse = (g.CaptureMouseNextFrame != 0);
  2426. else
  2427. g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (g.ActiveId != 0) || (!g.OpenPopupStack.empty());
  2428. g.IO.WantCaptureKeyboard = (g.CaptureKeyboardNextFrame != -1) ? (g.CaptureKeyboardNextFrame != 0) : (g.ActiveId != 0);
  2429. g.IO.WantTextInput = (g.ActiveId != 0 && g.InputTextState.Id == g.ActiveId);
  2430. g.MouseCursor = ImGuiMouseCursor_Arrow;
  2431. g.CaptureMouseNextFrame = g.CaptureKeyboardNextFrame = -1;
  2432. g.OsImePosRequest = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default
  2433.  
  2434. // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
  2435. if (!mouse_avail_to_imgui)
  2436. g.HoveredWindow = g.HoveredRootWindow = NULL;
  2437.  
  2438. // Scale & Scrolling
  2439. if (g.HoveredWindow && g.IO.MouseWheel != 0.0f && !g.HoveredWindow->Collapsed)
  2440. {
  2441. ImGuiWindow* window = g.HoveredWindow;
  2442. if (g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
  2443. {
  2444. // Zoom / Scale window
  2445. const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
  2446. const float scale = new_font_scale / window->FontWindowScale;
  2447. window->FontWindowScale = new_font_scale;
  2448.  
  2449. const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
  2450. window->Pos += offset;
  2451. window->PosFloat += offset;
  2452. window->Size *= scale;
  2453. window->SizeFull *= scale;
  2454. }
  2455. else if (!g.IO.KeyCtrl && !(window->Flags & ImGuiWindowFlags_NoScrollWithMouse))
  2456. {
  2457. // Scroll
  2458. const int scroll_lines = (window->Flags & ImGuiWindowFlags_ComboBox) ? 3 : 5;
  2459. SetWindowScrollY(window, window->Scroll.y - g.IO.MouseWheel * window->CalcFontSize() * scroll_lines);
  2460. }
  2461. }
  2462.  
  2463. // Pressing TAB activate widget focus
  2464. // NB: Don't discard FocusedWindow if it isn't active, so that a window that go on/off programatically won't lose its keyboard focus.
  2465. if (g.ActiveId == 0 && g.NavWindow != NULL && g.NavWindow->Active && IsKeyPressedMap(ImGuiKey_Tab, false))
  2466. g.NavWindow->FocusIdxTabRequestNext = 0;
  2467.  
  2468. // Mark all windows as not visible
  2469. for (int i = 0; i != g.Windows.Size; i++)
  2470. {
  2471. ImGuiWindow* window = g.Windows[i];
  2472. window->WasActive = window->Active;
  2473. window->Active = false;
  2474. window->Accessed = false;
  2475. }
  2476.  
  2477. // Closing the focused window restore focus to the first active root window in descending z-order
  2478. if (g.NavWindow && !g.NavWindow->WasActive)
  2479. for (int i = g.Windows.Size - 1; i >= 0; i--)
  2480. if (g.Windows[i]->WasActive && !(g.Windows[i]->Flags & ImGuiWindowFlags_ChildWindow))
  2481. {
  2482. FocusWindow(g.Windows[i]);
  2483. break;
  2484. }
  2485.  
  2486. // No window should be open at the beginning of the frame.
  2487. // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
  2488. g.CurrentWindowStack.resize(0);
  2489. g.CurrentPopupStack.resize(0);
  2490. CloseInactivePopups();
  2491.  
  2492. // Create implicit window - we will only render it if the user has added something to it.
  2493. ImGui::SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
  2494. ImGui::Begin("Debug");
  2495. }
  2496.  
  2497. void ImGui::Initialize()
  2498. {
  2499. ImGuiContext& g = *GImGui;
  2500. g.LogClipboard = (ImGuiTextBuffer*)ImGui::MemAlloc(sizeof(ImGuiTextBuffer));
  2501. IM_PLACEMENT_NEW(g.LogClipboard) ImGuiTextBuffer();
  2502.  
  2503. IM_ASSERT(g.Settings.empty());
  2504. LoadIniSettingsFromDisk(g.IO.IniFilename);
  2505. g.Initialized = true;
  2506. }
  2507.  
  2508. // This function is merely here to free heap allocations.
  2509. void ImGui::Shutdown()
  2510. {
  2511. ImGuiContext& g = *GImGui;
  2512.  
  2513. // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
  2514. if (g.IO.Fonts) // Testing for NULL to allow user to NULLify in case of running Shutdown() on multiple contexts. Bit hacky.
  2515. g.IO.Fonts->Clear();
  2516.  
  2517. // Cleanup of other data are conditional on actually having initialize ImGui.
  2518. if (!g.Initialized)
  2519. return;
  2520.  
  2521. SaveIniSettingsToDisk(g.IO.IniFilename);
  2522.  
  2523. for (int i = 0; i < g.Windows.Size; i++)
  2524. {
  2525. g.Windows[i]->~ImGuiWindow();
  2526. ImGui::MemFree(g.Windows[i]);
  2527. }
  2528. g.Windows.clear();
  2529. g.WindowsSortBuffer.clear();
  2530. g.CurrentWindow = NULL;
  2531. g.CurrentWindowStack.clear();
  2532. g.NavWindow = NULL;
  2533. g.HoveredWindow = NULL;
  2534. g.HoveredRootWindow = NULL;
  2535. g.ActiveIdWindow = NULL;
  2536. g.MovedWindow = NULL;
  2537. for (int i = 0; i < g.Settings.Size; i++)
  2538. ImGui::MemFree(g.Settings[i].Name);
  2539. g.Settings.clear();
  2540. g.ColorModifiers.clear();
  2541. g.StyleModifiers.clear();
  2542. g.FontStack.clear();
  2543. g.OpenPopupStack.clear();
  2544. g.CurrentPopupStack.clear();
  2545. g.SetNextWindowSizeConstraintCallback = NULL;
  2546. g.SetNextWindowSizeConstraintCallbackUserData = NULL;
  2547. for (int i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
  2548. g.RenderDrawLists[i].clear();
  2549. g.OverlayDrawList.ClearFreeMemory();
  2550. g.PrivateClipboard.clear();
  2551. g.InputTextState.Text.clear();
  2552. g.InputTextState.InitialText.clear();
  2553. g.InputTextState.TempTextBuffer.clear();
  2554.  
  2555. if (g.LogFile && g.LogFile != stdout)
  2556. {
  2557. fclose(g.LogFile);
  2558. g.LogFile = NULL;
  2559. }
  2560. if (g.LogClipboard)
  2561. {
  2562. g.LogClipboard->~ImGuiTextBuffer();
  2563. ImGui::MemFree(g.LogClipboard);
  2564. }
  2565.  
  2566. g.Initialized = false;
  2567. }
  2568.  
  2569. static ImGuiIniData* FindWindowSettings(const char* name)
  2570. {
  2571. ImGuiContext& g = *GImGui;
  2572. ImGuiID id = ImHash(name, 0);
  2573. for (int i = 0; i != g.Settings.Size; i++)
  2574. {
  2575. ImGuiIniData* ini = &g.Settings[i];
  2576. if (ini->Id == id)
  2577. return ini;
  2578. }
  2579. return NULL;
  2580. }
  2581.  
  2582. static ImGuiIniData* AddWindowSettings(const char* name)
  2583. {
  2584. GImGui->Settings.resize(GImGui->Settings.Size + 1);
  2585. ImGuiIniData* ini = &GImGui->Settings.back();
  2586. ini->Name = ImStrdup(name);
  2587. ini->Id = ImHash(name, 0);
  2588. ini->Collapsed = false;
  2589. ini->Pos = ImVec2(FLT_MAX, FLT_MAX);
  2590. ini->Size = ImVec2(0, 0);
  2591. return ini;
  2592. }
  2593.  
  2594. // Zero-tolerance, poor-man .ini parsing
  2595. // FIXME: Write something less rubbish
  2596. static void LoadIniSettingsFromDisk(const char* ini_filename)
  2597. {
  2598. ImGuiContext& g = *GImGui;
  2599. if (!ini_filename)
  2600. return;
  2601.  
  2602. int file_size;
  2603. char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_size, 1);
  2604. if (!file_data)
  2605. return;
  2606.  
  2607. ImGuiIniData* settings = NULL;
  2608. const char* buf_end = file_data + file_size;
  2609. for (const char* line_start = file_data; line_start < buf_end; )
  2610. {
  2611. const char* line_end = line_start;
  2612. while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
  2613. line_end++;
  2614.  
  2615. if (line_start[0] == '[' && line_end > line_start && line_end[-1] == ']')
  2616. {
  2617. char name[64];
  2618. ImFormatString(name, IM_ARRAYSIZE(name), "%.*s", (int)(line_end - line_start - 2), line_start + 1);
  2619. settings = FindWindowSettings(name);
  2620. if (!settings)
  2621. settings = AddWindowSettings(name);
  2622. }
  2623. else if (settings)
  2624. {
  2625. float x, y;
  2626. int i;
  2627. if (sscanf(line_start, "Pos=%f,%f", &x, &y) == 2)
  2628. settings->Pos = ImVec2(x, y);
  2629. else if (sscanf(line_start, "Size=%f,%f", &x, &y) == 2)
  2630. settings->Size = ImMax(ImVec2(x, y), g.Style.WindowMinSize);
  2631. else if (sscanf(line_start, "Collapsed=%d", &i) == 1)
  2632. settings->Collapsed = (i != 0);
  2633. }
  2634.  
  2635. line_start = line_end + 1;
  2636. }
  2637.  
  2638. ImGui::MemFree(file_data);
  2639. }
  2640.  
  2641. static void SaveIniSettingsToDisk(const char* ini_filename)
  2642. {
  2643. ImGuiContext& g = *GImGui;
  2644. g.SettingsDirtyTimer = 0.0f;
  2645. if (!ini_filename)
  2646. return;
  2647.  
  2648. // Gather data from windows that were active during this session
  2649. for (int i = 0; i != g.Windows.Size; i++)
  2650. {
  2651. ImGuiWindow* window = g.Windows[i];
  2652. if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
  2653. continue;
  2654. ImGuiIniData* settings = FindWindowSettings(window->Name);
  2655. if (!settings) // This will only return NULL in the rare instance where the window was first created with ImGuiWindowFlags_NoSavedSettings then had the flag disabled later on. We don't bind settings in this case (bug #1000).
  2656. continue;
  2657. settings->Pos = window->Pos;
  2658. settings->Size = window->SizeFull;
  2659. settings->Collapsed = window->Collapsed;
  2660. }
  2661.  
  2662. // Write .ini file
  2663. // If a window wasn't opened in this session we preserve its settings
  2664. FILE* f = ImFileOpen(ini_filename, "wt");
  2665. if (!f)
  2666. return;
  2667. for (int i = 0; i != g.Settings.Size; i++)
  2668. {
  2669. const ImGuiIniData* settings = &g.Settings[i];
  2670. if (settings->Pos.x == FLT_MAX)
  2671. continue;
  2672. const char* name = settings->Name;
  2673. if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
  2674. name = p;
  2675. fprintf(f, "[%s]\n", name);
  2676. fprintf(f, "Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y);
  2677. fprintf(f, "Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y);
  2678. fprintf(f, "Collapsed=%d\n", settings->Collapsed);
  2679. fprintf(f, "\n");
  2680. }
  2681.  
  2682. fclose(f);
  2683. }
  2684.  
  2685. static void MarkIniSettingsDirty(ImGuiWindow* window)
  2686. {
  2687. ImGuiContext& g = *GImGui;
  2688. if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
  2689. if (g.SettingsDirtyTimer <= 0.0f)
  2690. g.SettingsDirtyTimer = g.IO.IniSavingRate;
  2691. }
  2692.  
  2693. // FIXME: Add a more explicit sort order in the window structure.
  2694. static int ChildWindowComparer(const void* lhs, const void* rhs)
  2695. {
  2696. const ImGuiWindow* a = *(const ImGuiWindow**)lhs;
  2697. const ImGuiWindow* b = *(const ImGuiWindow**)rhs;
  2698. if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
  2699. return d;
  2700. if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
  2701. return d;
  2702. if (int d = (a->Flags & ImGuiWindowFlags_ComboBox) - (b->Flags & ImGuiWindowFlags_ComboBox))
  2703. return d;
  2704. return (a->OrderWithinParent - b->OrderWithinParent);
  2705. }
  2706.  
  2707. static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>& out_sorted_windows, ImGuiWindow* window)
  2708. {
  2709. out_sorted_windows.push_back(window);
  2710. if (window->Active)
  2711. {
  2712. int count = window->DC.ChildWindows.Size;
  2713. if (count > 1)
  2714. qsort(window->DC.ChildWindows.begin(), (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
  2715. for (int i = 0; i < count; i++)
  2716. {
  2717. ImGuiWindow* child = window->DC.ChildWindows[i];
  2718. if (child->Active)
  2719. AddWindowToSortedBuffer(out_sorted_windows, child);
  2720. }
  2721. }
  2722. }
  2723.  
  2724. static void AddDrawListToRenderList(ImVector<ImDrawList*>& out_render_list, ImDrawList* draw_list)
  2725. {
  2726. if (draw_list->CmdBuffer.empty())
  2727. return;
  2728.  
  2729. // Remove trailing command if unused
  2730. ImDrawCmd& last_cmd = draw_list->CmdBuffer.back();
  2731. if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL)
  2732. {
  2733. draw_list->CmdBuffer.pop_back();
  2734. if (draw_list->CmdBuffer.empty())
  2735. return;
  2736. }
  2737.  
  2738. // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. May trigger for you if you are using PrimXXX functions incorrectly.
  2739. IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
  2740. IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
  2741. IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
  2742.  
  2743. // Check that draw_list doesn't use more vertices than indexable in a single draw call (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per window)
  2744. // If this assert triggers because you are drawing lots of stuff manually, you can:
  2745. // A) Add '#define ImDrawIdx unsigned int' in imconfig.h to set the index size to 4 bytes. You'll need to handle the 4-bytes indices to your renderer.
  2746. // For example, the OpenGL example code detect index size at compile-time by doing:
  2747. // 'glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);'
  2748. // Your own engine or render API may use different parameters or function calls to specify index sizes. 2 and 4 bytes indices are generally supported by most API.
  2749. // B) If for some reason you cannot use 4 bytes indices or don't want to, a workaround is to call BeginChild()/EndChild() before reaching the 64K limit to split your draw commands in multiple draw lists.
  2750. IM_ASSERT(((ImU64)draw_list->_VtxCurrentIdx >> (sizeof(ImDrawIdx) * 8)) == 0); // Too many vertices in same ImDrawList. See comment above.
  2751.  
  2752. out_render_list.push_back(draw_list);
  2753. GImGui->IO.MetricsRenderVertices += draw_list->VtxBuffer.Size;
  2754. GImGui->IO.MetricsRenderIndices += draw_list->IdxBuffer.Size;
  2755. }
  2756.  
  2757. static void AddWindowToRenderList(ImVector<ImDrawList*>& out_render_list, ImGuiWindow* window)
  2758. {
  2759. AddDrawListToRenderList(out_render_list, window->DrawList);
  2760. for (int i = 0; i < window->DC.ChildWindows.Size; i++)
  2761. {
  2762. ImGuiWindow* child = window->DC.ChildWindows[i];
  2763. if (!child->Active) // clipped children may have been marked not active
  2764. continue;
  2765. if ((child->Flags & ImGuiWindowFlags_Popup) && child->HiddenFrames > 0)
  2766. continue;
  2767. AddWindowToRenderList(out_render_list, child);
  2768. }
  2769. }
  2770.  
  2771. static void AddWindowToRenderListSelectLayer(ImGuiWindow* window)
  2772. {
  2773. // FIXME: Generalize this with a proper layering system so e.g. user can draw in specific layers, below text, ..
  2774. ImGuiContext& g = *GImGui;
  2775. g.IO.MetricsActiveWindows++;
  2776. if (window->Flags & ImGuiWindowFlags_Popup)
  2777. AddWindowToRenderList(g.RenderDrawLists[1], window);
  2778. else if (window->Flags & ImGuiWindowFlags_Tooltip)
  2779. AddWindowToRenderList(g.RenderDrawLists[2], window);
  2780. else
  2781. AddWindowToRenderList(g.RenderDrawLists[0], window);
  2782. }
  2783.  
  2784. // When using this function it is sane to ensure that float are perfectly rounded to integer values, to that e.g. (int)(max.x-min.x) in user's render produce correct result.
  2785. void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
  2786. {
  2787. ImGuiWindow* window = GetCurrentWindow();
  2788. window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
  2789. window->ClipRect = window->DrawList->_ClipRectStack.back();
  2790. }
  2791.  
  2792. void ImGui::PopClipRect()
  2793. {
  2794. ImGuiWindow* window = GetCurrentWindow();
  2795. window->DrawList->PopClipRect();
  2796. window->ClipRect = window->DrawList->_ClipRectStack.back();
  2797. }
  2798.  
  2799. // This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
  2800. void ImGui::EndFrame()
  2801. {
  2802. ImGuiContext& g = *GImGui;
  2803. IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame()
  2804. IM_ASSERT(g.FrameCountEnded != g.FrameCount); // ImGui::EndFrame() called multiple times, or forgot to call ImGui::NewFrame() again
  2805.  
  2806. // Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
  2807. if (g.IO.ImeSetInputScreenPosFn && ImLengthSqr(g.OsImePosRequest - g.OsImePosSet) > 0.0001f)
  2808. {
  2809. g.IO.ImeSetInputScreenPosFn((int)g.OsImePosRequest.x, (int)g.OsImePosRequest.y);
  2810. g.OsImePosSet = g.OsImePosRequest;
  2811. }
  2812.  
  2813. // Hide implicit "Debug" window if it hasn't been used
  2814. IM_ASSERT(g.CurrentWindowStack.Size == 1); // Mismatched Begin()/End() calls
  2815. if (g.CurrentWindow && !g.CurrentWindow->Accessed)
  2816. g.CurrentWindow->Active = false;
  2817. ImGui::End();
  2818.  
  2819. // Click to focus window and start moving (after we're done with all our widgets)
  2820. if (g.ActiveId == 0 && g.HoveredId == 0 && g.IO.MouseClicked[0])
  2821. {
  2822. if (!(g.NavWindow && !g.NavWindow->WasActive && g.NavWindow->Active)) // Unless we just made a popup appear
  2823. {
  2824. if (g.HoveredRootWindow != NULL)
  2825. {
  2826. FocusWindow(g.HoveredWindow);
  2827. if (!(g.HoveredWindow->Flags & ImGuiWindowFlags_NoMove))
  2828. {
  2829. g.MovedWindow = g.HoveredWindow;
  2830. g.MovedWindowMoveId = g.HoveredRootWindow->MoveId;
  2831. SetActiveID(g.MovedWindowMoveId, g.HoveredRootWindow);
  2832. }
  2833. }
  2834. else if (g.NavWindow != NULL && GetFrontMostModalRootWindow() == NULL)
  2835. {
  2836. // Clicking on void disable focus
  2837. FocusWindow(NULL);
  2838. }
  2839. }
  2840. }
  2841.  
  2842. // Sort the window list so that all child windows are after their parent
  2843. // We cannot do that on FocusWindow() because childs may not exist yet
  2844. g.WindowsSortBuffer.resize(0);
  2845. g.WindowsSortBuffer.reserve(g.Windows.Size);
  2846. for (int i = 0; i != g.Windows.Size; i++)
  2847. {
  2848. ImGuiWindow* window = g.Windows[i];
  2849. if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
  2850. continue;
  2851. AddWindowToSortedBuffer(g.WindowsSortBuffer, window);
  2852. }
  2853.  
  2854. IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size); // we done something wrong
  2855. g.Windows.swap(g.WindowsSortBuffer);
  2856.  
  2857. // Clear Input data for next frame
  2858. g.IO.MouseWheel = 0.0f;
  2859. memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters));
  2860.  
  2861. g.FrameCountEnded = g.FrameCount;
  2862. }
  2863.  
  2864. void ImGui::Render()
  2865. {
  2866. ImGuiContext& g = *GImGui;
  2867. IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame()
  2868.  
  2869. if (g.FrameCountEnded != g.FrameCount)
  2870. ImGui::EndFrame();
  2871. g.FrameCountRendered = g.FrameCount;
  2872.  
  2873. // Skip render altogether if alpha is 0.0
  2874. // Note that vertex buffers have been created and are wasted, so it is best practice that you don't create windows in the first place, or consistently respond to Begin() returning false.
  2875. if (g.Style.Alpha > 0.0f)
  2876. {
  2877. // Gather windows to render
  2878. g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsActiveWindows = 0;
  2879. for (int i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
  2880. g.RenderDrawLists[i].resize(0);
  2881. for (int i = 0; i != g.Windows.Size; i++)
  2882. {
  2883. ImGuiWindow* window = g.Windows[i];
  2884. if (window->Active && window->HiddenFrames <= 0 && (window->Flags & (ImGuiWindowFlags_ChildWindow)) == 0)
  2885. AddWindowToRenderListSelectLayer(window);
  2886. }
  2887.  
  2888. // Flatten layers
  2889. int n = g.RenderDrawLists[0].Size;
  2890. int flattened_size = n;
  2891. for (int i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
  2892. flattened_size += g.RenderDrawLists[i].Size;
  2893. g.RenderDrawLists[0].resize(flattened_size);
  2894. for (int i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
  2895. {
  2896. ImVector<ImDrawList*>& layer = g.RenderDrawLists[i];
  2897. if (layer.empty())
  2898. continue;
  2899. memcpy(&g.RenderDrawLists[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
  2900. n += layer.Size;
  2901. }
  2902.  
  2903. // Draw software mouse cursor if requested
  2904. if (g.IO.MouseDrawCursor)
  2905. {
  2906. const ImGuiMouseCursorData& cursor_data = g.MouseCursorData[g.MouseCursor];
  2907. const ImVec2 pos = g.IO.MousePos - cursor_data.HotOffset;
  2908. const ImVec2 size = cursor_data.Size;
  2909. const ImTextureID tex_id = g.IO.Fonts->TexID;
  2910. g.OverlayDrawList.PushTextureID(tex_id);
  2911. g.OverlayDrawList.AddImage(tex_id, pos + ImVec2(1, 0), pos + ImVec2(1, 0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], IM_COL32(0, 0, 0, 48)); // Shadow
  2912. g.OverlayDrawList.AddImage(tex_id, pos + ImVec2(2, 0), pos + ImVec2(2, 0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], IM_COL32(0, 0, 0, 48)); // Shadow
  2913. g.OverlayDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], IM_COL32(0, 0, 0, 255)); // Black border
  2914. g.OverlayDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[0], cursor_data.TexUvMax[0], IM_COL32(255, 255, 255, 255)); // White fill
  2915. g.OverlayDrawList.PopTextureID();
  2916. }
  2917. if (!g.OverlayDrawList.VtxBuffer.empty())
  2918. AddDrawListToRenderList(g.RenderDrawLists[0], &g.OverlayDrawList);
  2919.  
  2920. // Setup draw data
  2921. g.RenderDrawData.Valid = true;
  2922. g.RenderDrawData.CmdLists = (g.RenderDrawLists[0].Size > 0) ? &g.RenderDrawLists[0][0] : NULL;
  2923. g.RenderDrawData.CmdListsCount = g.RenderDrawLists[0].Size;
  2924. g.RenderDrawData.TotalVtxCount = g.IO.MetricsRenderVertices;
  2925. g.RenderDrawData.TotalIdxCount = g.IO.MetricsRenderIndices;
  2926.  
  2927. // Render. If user hasn't set a callback then they may retrieve the draw data via GetDrawData()
  2928. if (g.RenderDrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL)
  2929. g.IO.RenderDrawListsFn(&g.RenderDrawData);
  2930. }
  2931. }
  2932.  
  2933. const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
  2934. {
  2935. const char* text_display_end = text;
  2936. if (!text_end)
  2937. text_end = (const char*)-1;
  2938.  
  2939. while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
  2940. text_display_end++;
  2941. return text_display_end;
  2942. }
  2943.  
  2944. // Pass text data straight to log (without being displayed)
  2945. void ImGui::LogText(const char* fmt, ...)
  2946. {
  2947. ImGuiContext& g = *GImGui;
  2948. if (!g.LogEnabled)
  2949. return;
  2950.  
  2951. va_list args;
  2952. va_start(args, fmt);
  2953. if (g.LogFile)
  2954. {
  2955. vfprintf(g.LogFile, fmt, args);
  2956. }
  2957. else
  2958. {
  2959. g.LogClipboard->appendv(fmt, args);
  2960. }
  2961. va_end(args);
  2962. }
  2963.  
  2964. // Internal version that takes a position to decide on newline placement and pad items according to their depth.
  2965. // We split text into individual lines to add current tree level padding
  2966. static void LogRenderedText(const ImVec2& ref_pos, const char* text, const char* text_end)
  2967. {
  2968. ImGuiContext& g = *GImGui;
  2969. ImGuiWindow* window = ImGui::GetCurrentWindowRead();
  2970.  
  2971. if (!text_end)
  2972. text_end = ImGui::FindRenderedTextEnd(text, text_end);
  2973.  
  2974. const bool log_new_line = ref_pos.y > window->DC.LogLinePosY + 1;
  2975. window->DC.LogLinePosY = ref_pos.y;
  2976.  
  2977. const char* text_remaining = text;
  2978. if (g.LogStartDepth > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth
  2979. g.LogStartDepth = window->DC.TreeDepth;
  2980. const int tree_depth = (window->DC.TreeDepth - g.LogStartDepth);
  2981. for (;;)
  2982. {
  2983. // Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry.
  2984. const char* line_end = text_remaining;
  2985. while (line_end < text_end)
  2986. if (*line_end == '\n')
  2987. break;
  2988. else
  2989. line_end++;
  2990. if (line_end >= text_end)
  2991. line_end = NULL;
  2992.  
  2993. const bool is_first_line = (text == text_remaining);
  2994. bool is_last_line = false;
  2995. if (line_end == NULL)
  2996. {
  2997. is_last_line = true;
  2998. line_end = text_end;
  2999. }
  3000. if (line_end != NULL && !(is_last_line && (line_end - text_remaining) == 0))
  3001. {
  3002. const int char_count = (int)(line_end - text_remaining);
  3003. if (log_new_line || !is_first_line)
  3004. ImGui::LogText(IM_NEWLINE "%*s%.*s", tree_depth * 4, "", char_count, text_remaining);
  3005. else
  3006. ImGui::LogText(" %.*s", char_count, text_remaining);
  3007. }
  3008.  
  3009. if (is_last_line)
  3010. break;
  3011. text_remaining = line_end + 1;
  3012. }
  3013. }
  3014.  
  3015. // Internal ImGui functions to render text
  3016. // RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
  3017. void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
  3018. {
  3019. ImGuiContext& g = *GImGui;
  3020. ImGuiWindow* window = GetCurrentWindow();
  3021.  
  3022. // Hide anything after a '##' string
  3023. const char* text_display_end;
  3024. if (hide_text_after_hash)
  3025. {
  3026. text_display_end = FindRenderedTextEnd(text, text_end);
  3027. }
  3028. else
  3029. {
  3030. if (!text_end)
  3031. text_end = text + strlen(text); // FIXME-OPT
  3032. text_display_end = text_end;
  3033. }
  3034.  
  3035. const int text_len = (int)(text_display_end - text);
  3036. if (text_len > 0)
  3037. {
  3038. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
  3039. if (g.LogEnabled)
  3040. LogRenderedText(pos, text, text_display_end);
  3041. }
  3042. }
  3043.  
  3044. void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
  3045. {
  3046. ImGuiContext& g = *GImGui;
  3047. ImGuiWindow* window = GetCurrentWindow();
  3048.  
  3049. if (!text_end)
  3050. text_end = text + strlen(text); // FIXME-OPT
  3051.  
  3052. const int text_len = (int)(text_end - text);
  3053. if (text_len > 0)
  3054. {
  3055. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
  3056. if (g.LogEnabled)
  3057. LogRenderedText(pos, text, text_end);
  3058. }
  3059. }
  3060.  
  3061. // Default clip_rect uses (pos_min,pos_max)
  3062. // Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
  3063. void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect, bool tab, bool selected)
  3064. {
  3065. // Hide anything after a '##' string
  3066. const char* text_display_end = FindRenderedTextEnd(text, text_end);
  3067. const int text_len = (int)(text_display_end - text);
  3068. if (text_len == 0)
  3069. return;
  3070.  
  3071. ImGuiContext& g = *GImGui;
  3072. ImGuiWindow* window = GetCurrentWindow();
  3073.  
  3074. // Perform CPU side clipping for single clipped element to avoid using scissor state
  3075. ImVec2 pos = pos_min;
  3076. const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
  3077.  
  3078. const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
  3079. const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
  3080. bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
  3081. if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
  3082. need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
  3083.  
  3084. // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
  3085. if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
  3086. if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
  3087.  
  3088. // Render
  3089. if (need_clipping)
  3090. {
  3091. ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
  3092. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(tab ? selected ? ImGuiCol_TabTextActive : ImGuiCol_TabText : ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
  3093. }
  3094. else
  3095. {
  3096. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(tab ? selected ? ImGuiCol_TabTextActive : ImGuiCol_TabText : ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
  3097. }
  3098. if (g.LogEnabled)
  3099. LogRenderedText(pos, text, text_display_end);
  3100. }
  3101.  
  3102.  
  3103. // Render a rectangle shaped with optional rounding and borders
  3104. void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
  3105. {
  3106. ImGuiWindow* window = GetCurrentWindow();
  3107.  
  3108. window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
  3109. if (border && (window->Flags & ImGuiWindowFlags_ShowBorders))
  3110. {
  3111. window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding);
  3112. window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding);
  3113. }
  3114. }
  3115.  
  3116. void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
  3117. {
  3118. ImGuiWindow* window = GetCurrentWindow();
  3119. if (window->Flags & ImGuiWindowFlags_ShowBorders)
  3120. {
  3121. window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding);
  3122. window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding);
  3123. }
  3124. }
  3125.  
  3126. // Render a triangle to denote expanded/collapsed state
  3127. void ImGui::RenderCollapseTriangle(ImVec2 p_min, bool is_open, float scale)
  3128. {
  3129. ImGuiContext& g = *GImGui;
  3130. ImGuiWindow* window = GetCurrentWindow();
  3131.  
  3132. const float h = g.FontSize * 1.00f;
  3133. const float r = h * 0.40f * scale;
  3134. ImVec2 center = p_min + ImVec2(h*0.50f, h*0.50f*scale);
  3135.  
  3136. ImVec2 a, b, c;
  3137. if (is_open)
  3138. {
  3139. center.y -= r*0.25f;
  3140. a = center + ImVec2(0, 1)*r;
  3141. b = center + ImVec2(-0.866f, -0.5f)*r;
  3142. c = center + ImVec2(0.866f, -0.5f)*r;
  3143. }
  3144. else
  3145. {
  3146. a = center + ImVec2(1, 0)*r;
  3147. b = center + ImVec2(-0.500f, 0.866f)*r;
  3148. c = center + ImVec2(-0.500f, -0.866f)*r;
  3149. }
  3150.  
  3151. window->DrawList->AddTriangleFilled(a, b, c, GetColorU32(ImGuiCol_Text));
  3152. }
  3153.  
  3154. void ImGui::RenderBullet(ImVec2 pos)
  3155. {
  3156. ImGuiWindow* window = GetCurrentWindow();
  3157. window->DrawList->AddCircleFilled(pos, GImGui->FontSize*0.20f, GetColorU32(ImGuiCol_Text), 8);
  3158. }
  3159.  
  3160. void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col)
  3161. {
  3162. ImGuiContext& g = *GImGui;
  3163. ImGuiWindow* window = GetCurrentWindow();
  3164. float start_x = (float)(int)(g.FontSize * 0.307f + 0.5f);
  3165. float rem_third = (float)(int)((g.FontSize - start_x) / 3.0f);
  3166. float bx = pos.x + 0.5f + start_x + rem_third;
  3167. float by = pos.y - 1.0f + (float)(int)(g.Font->Ascent * (g.FontSize / g.Font->FontSize) + 0.5f) + (float)(int)(g.Font->DisplayOffset.y);
  3168. window->DrawList->PathLineTo(ImVec2(bx - rem_third, by - rem_third));
  3169. window->DrawList->PathLineTo(ImVec2(bx, by));
  3170. window->DrawList->PathLineTo(ImVec2(bx + rem_third * 2, by - rem_third * 2));
  3171. window->DrawList->PathStroke(col, false);
  3172. }
  3173.  
  3174. // Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
  3175. // CalcTextSize("") should return ImVec2(0.0f, GImGui->FontSize)
  3176. ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
  3177. {
  3178. ImGuiContext& g = *GImGui;
  3179.  
  3180. const char* text_display_end;
  3181. if (hide_text_after_double_hash)
  3182. text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string
  3183. else
  3184. text_display_end = text_end;
  3185.  
  3186. ImFont* font = g.Font;
  3187. const float font_size = g.FontSize;
  3188. if (text == text_display_end)
  3189. return ImVec2(0.0f, font_size);
  3190. ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
  3191.  
  3192. // Cancel out character spacing for the last character of a line (it is baked into glyph->XAdvance field)
  3193. const float font_scale = font_size / font->FontSize;
  3194. const float character_spacing_x = 1.0f * font_scale;
  3195. if (text_size.x > 0.0f)
  3196. text_size.x -= character_spacing_x;
  3197. text_size.x = (float)(int)(text_size.x + 0.95f);
  3198.  
  3199. return text_size;
  3200. }
  3201.  
  3202. // Helper to calculate coarse clipping of large list of evenly sized items.
  3203. // NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern.
  3204. // NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX
  3205. void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
  3206. {
  3207. ImGuiContext& g = *GImGui;
  3208. ImGuiWindow* window = GetCurrentWindowRead();
  3209. if (g.LogEnabled)
  3210. {
  3211. // If logging is active, do not perform any clipping
  3212. *out_items_display_start = 0;
  3213. *out_items_display_end = items_count;
  3214. return;
  3215. }
  3216. if (window->SkipItems)
  3217. {
  3218. *out_items_display_start = *out_items_display_end = 0;
  3219. return;
  3220. }
  3221.  
  3222. const ImVec2 pos = window->DC.CursorPos;
  3223. int start = (int)((window->ClipRect.Min.y - pos.y) / items_height);
  3224. int end = (int)((window->ClipRect.Max.y - pos.y) / items_height);
  3225. start = ImClamp(start, 0, items_count);
  3226. end = ImClamp(end + 1, start, items_count);
  3227. *out_items_display_start = start;
  3228. *out_items_display_end = end;
  3229. }
  3230.  
  3231. // Find window given position, search front-to-back
  3232. // FIXME: Note that we have a lag here because WindowRectClipped is updated in Begin() so windows moved by user via SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is called, aka before the next Begin(). Moving window thankfully isn't affected.
  3233. static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs)
  3234. {
  3235. ImGuiContext& g = *GImGui;
  3236. for (int i = g.Windows.Size - 1; i >= 0; i--)
  3237. {
  3238. ImGuiWindow* window = g.Windows[i];
  3239. if (!window->Active)
  3240. continue;
  3241. if (window->Flags & ImGuiWindowFlags_NoInputs)
  3242. continue;
  3243. if (excluding_childs && (window->Flags & ImGuiWindowFlags_ChildWindow) != 0)
  3244. continue;
  3245.  
  3246. // Using the clipped AABB so a child window will typically be clipped by its parent.
  3247. ImRect bb(window->WindowRectClipped.Min - g.Style.TouchExtraPadding, window->WindowRectClipped.Max + g.Style.TouchExtraPadding);
  3248. if (bb.Contains(pos))
  3249. return window;
  3250. }
  3251. return NULL;
  3252. }
  3253.  
  3254. // Test if mouse cursor is hovering given rectangle
  3255. // NB- Rectangle is clipped by our current clip setting
  3256. // NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
  3257. bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
  3258. {
  3259. ImGuiContext& g = *GImGui;
  3260. ImGuiWindow* window = GetCurrentWindowRead();
  3261.  
  3262. // Clip
  3263. ImRect rect_clipped(r_min, r_max);
  3264. if (clip)
  3265. rect_clipped.ClipWith(window->ClipRect);
  3266.  
  3267. // Expand for touch input
  3268. const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
  3269. return rect_for_touch.Contains(g.IO.MousePos);
  3270. }
  3271.  
  3272. bool ImGui::IsAnyWindowHovered()
  3273. {
  3274. ImGuiContext& g = *GImGui;
  3275. return g.HoveredWindow != NULL;
  3276. }
  3277.  
  3278. static bool IsKeyPressedMap(ImGuiKey key, bool repeat)
  3279. {
  3280. const int key_index = GImGui->IO.KeyMap[key];
  3281. return (key_index >= 0) ? ImGui::IsKeyPressed(key_index, repeat) : false;
  3282. }
  3283.  
  3284. int ImGui::GetKeyIndex(ImGuiKey imgui_key)
  3285. {
  3286. IM_ASSERT(imgui_key >= 0 && imgui_key < ImGuiKey_COUNT);
  3287. return GImGui->IO.KeyMap[imgui_key];
  3288. }
  3289.  
  3290. // Note that imgui doesn't know the semantic of each entry of io.KeyDown[]. Use your own indices/enums according to how your backend/engine stored them into KeyDown[]!
  3291. bool ImGui::IsKeyDown(int user_key_index)
  3292. {
  3293. if (user_key_index < 0) return false;
  3294. IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(GImGui->IO.KeysDown));
  3295. return GImGui->IO.KeysDown[user_key_index];
  3296. }
  3297.  
  3298. int ImGui::CalcTypematicPressedRepeatAmount(float t, float t_prev, float repeat_delay, float repeat_rate)
  3299. {
  3300. if (t == 0.0f)
  3301. return 1;
  3302. if (t <= repeat_delay || repeat_rate <= 0.0f)
  3303. return 0;
  3304. const int count = (int)((t - repeat_delay) / repeat_rate) - (int)((t_prev - repeat_delay) / repeat_rate);
  3305. return (count > 0) ? count : 0;
  3306. }
  3307.  
  3308. int ImGui::GetKeyPressedAmount(int key_index, float repeat_delay, float repeat_rate)
  3309. {
  3310. ImGuiContext& g = *GImGui;
  3311. if (key_index < 0) return false;
  3312. IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown));
  3313. const float t = g.IO.KeysDownDuration[key_index];
  3314. return CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, repeat_delay, repeat_rate);
  3315. }
  3316.  
  3317. bool ImGui::IsKeyPressed(int user_key_index, bool repeat)
  3318. {
  3319. ImGuiContext& g = *GImGui;
  3320. if (user_key_index < 0) return false;
  3321. IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
  3322. const float t = g.IO.KeysDownDuration[user_key_index];
  3323. if (t == 0.0f)
  3324. return true;
  3325. if (repeat && t > g.IO.KeyRepeatDelay)
  3326. return GetKeyPressedAmount(user_key_index, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0;
  3327. return false;
  3328. }
  3329.  
  3330. bool ImGui::IsKeyReleased(int user_key_index)
  3331. {
  3332. ImGuiContext& g = *GImGui;
  3333. if (user_key_index < 0) return false;
  3334. IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
  3335. if (g.IO.KeysDownDurationPrev[user_key_index] >= 0.0f && !g.IO.KeysDown[user_key_index])
  3336. return true;
  3337. return false;
  3338. }
  3339.  
  3340. bool ImGui::IsMouseDown(int button)
  3341. {
  3342. ImGuiContext& g = *GImGui;
  3343. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3344. return g.IO.MouseDown[button];
  3345. }
  3346.  
  3347. bool ImGui::IsMouseClicked(int button, bool repeat)
  3348. {
  3349. ImGuiContext& g = *GImGui;
  3350. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3351. const float t = g.IO.MouseDownDuration[button];
  3352. if (t == 0.0f)
  3353. return true;
  3354.  
  3355. if (repeat && t > g.IO.KeyRepeatDelay)
  3356. {
  3357. float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate;
  3358. if ((fmodf(t - delay, rate) > rate*0.5f) != (fmodf(t - delay - g.IO.DeltaTime, rate) > rate*0.5f))
  3359. return true;
  3360. }
  3361.  
  3362. return false;
  3363. }
  3364.  
  3365. bool ImGui::IsMouseReleased(int button)
  3366. {
  3367. ImGuiContext& g = *GImGui;
  3368. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3369. return g.IO.MouseReleased[button];
  3370. }
  3371.  
  3372. bool ImGui::IsMouseDoubleClicked(int button)
  3373. {
  3374. ImGuiContext& g = *GImGui;
  3375. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3376. return g.IO.MouseDoubleClicked[button];
  3377. }
  3378.  
  3379. bool ImGui::IsMouseDragging(int button, float lock_threshold)
  3380. {
  3381. ImGuiContext& g = *GImGui;
  3382. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3383. if (!g.IO.MouseDown[button])
  3384. return false;
  3385. if (lock_threshold < 0.0f)
  3386. lock_threshold = g.IO.MouseDragThreshold;
  3387. return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
  3388. }
  3389.  
  3390. ImVec2 ImGui::GetMousePos()
  3391. {
  3392. return GImGui->IO.MousePos;
  3393. }
  3394.  
  3395. // NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
  3396. ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
  3397. {
  3398. ImGuiContext& g = *GImGui;
  3399. if (g.CurrentPopupStack.Size > 0)
  3400. return g.OpenPopupStack[g.CurrentPopupStack.Size - 1].MousePosOnOpen;
  3401. return g.IO.MousePos;
  3402. }
  3403.  
  3404. // We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position
  3405. bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
  3406. {
  3407. if (mouse_pos == NULL)
  3408. mouse_pos = &GImGui->IO.MousePos;
  3409. const float MOUSE_INVALID = -256000.0f;
  3410. return mouse_pos->x >= MOUSE_INVALID && mouse_pos->y >= MOUSE_INVALID;
  3411. }
  3412.  
  3413. ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold)
  3414. {
  3415. ImGuiContext& g = *GImGui;
  3416. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3417. if (lock_threshold < 0.0f)
  3418. lock_threshold = g.IO.MouseDragThreshold;
  3419. if (g.IO.MouseDown[button])
  3420. if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
  3421. return g.IO.MousePos - g.IO.MouseClickedPos[button]; // Assume we can only get active with left-mouse button (at the moment).
  3422. return ImVec2(0.0f, 0.0f);
  3423. }
  3424.  
  3425. void ImGui::ResetMouseDragDelta(int button)
  3426. {
  3427. ImGuiContext& g = *GImGui;
  3428. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3429. // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
  3430. g.IO.MouseClickedPos[button] = g.IO.MousePos;
  3431. }
  3432.  
  3433. ImGuiMouseCursor ImGui::GetMouseCursor()
  3434. {
  3435. return GImGui->MouseCursor;
  3436. }
  3437.  
  3438. void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
  3439. {
  3440. GImGui->MouseCursor = cursor_type;
  3441. }
  3442.  
  3443. void ImGui::CaptureKeyboardFromApp(bool capture)
  3444. {
  3445. GImGui->CaptureKeyboardNextFrame = capture ? 1 : 0;
  3446. }
  3447.  
  3448. void ImGui::CaptureMouseFromApp(bool capture)
  3449. {
  3450. GImGui->CaptureMouseNextFrame = capture ? 1 : 0;
  3451. }
  3452.  
  3453. bool ImGui::IsItemHovered()
  3454. {
  3455. ImGuiWindow* window = GetCurrentWindowRead();
  3456. return window->DC.LastItemHoveredAndUsable;
  3457. }
  3458.  
  3459. bool ImGui::IsItemRectHovered()
  3460. {
  3461. ImGuiWindow* window = GetCurrentWindowRead();
  3462. return window->DC.LastItemHoveredRect;
  3463. }
  3464.  
  3465. bool ImGui::IsItemActive()
  3466. {
  3467. ImGuiContext& g = *GImGui;
  3468. if (g.ActiveId)
  3469. {
  3470. ImGuiWindow* window = GetCurrentWindowRead();
  3471. return g.ActiveId == window->DC.LastItemId;
  3472. }
  3473. return false;
  3474. }
  3475.  
  3476. bool ImGui::IsItemClicked(int mouse_button)
  3477. {
  3478. return IsMouseClicked(mouse_button) && IsItemHovered();
  3479. }
  3480.  
  3481. bool ImGui::IsAnyItemHovered()
  3482. {
  3483. return GImGui->HoveredId != 0 || GImGui->HoveredIdPreviousFrame != 0;
  3484. }
  3485.  
  3486. bool ImGui::IsAnyItemActive()
  3487. {
  3488. return GImGui->ActiveId != 0;
  3489. }
  3490.  
  3491. bool ImGui::IsItemVisible()
  3492. {
  3493. ImGuiWindow* window = GetCurrentWindowRead();
  3494. return window->ClipRect.Overlaps(window->DC.LastItemRect);
  3495. }
  3496.  
  3497. // Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
  3498. void ImGui::SetItemAllowOverlap()
  3499. {
  3500. ImGuiContext& g = *GImGui;
  3501. if (g.HoveredId == g.CurrentWindow->DC.LastItemId)
  3502. g.HoveredIdAllowOverlap = true;
  3503. if (g.ActiveId == g.CurrentWindow->DC.LastItemId)
  3504. g.ActiveIdAllowOverlap = true;
  3505. }
  3506.  
  3507. ImVec2 ImGui::GetItemRectMin()
  3508. {
  3509. ImGuiWindow* window = GetCurrentWindowRead();
  3510. return window->DC.LastItemRect.Min;
  3511. }
  3512.  
  3513. ImVec2 ImGui::GetItemRectMax()
  3514. {
  3515. ImGuiWindow* window = GetCurrentWindowRead();
  3516. return window->DC.LastItemRect.Max;
  3517. }
  3518.  
  3519. ImVec2 ImGui::GetItemRectSize()
  3520. {
  3521. ImGuiWindow* window = GetCurrentWindowRead();
  3522. return window->DC.LastItemRect.GetSize();
  3523. }
  3524.  
  3525. ImVec2 ImGui::CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge, float outward)
  3526. {
  3527. ImGuiWindow* window = GetCurrentWindowRead();
  3528. ImRect rect = window->DC.LastItemRect;
  3529. rect.Expand(outward);
  3530. return rect.GetClosestPoint(pos, on_edge);
  3531. }
  3532.  
  3533. static ImRect GetVisibleRect()
  3534. {
  3535. ImGuiContext& g = *GImGui;
  3536. if (g.IO.DisplayVisibleMin.x != g.IO.DisplayVisibleMax.x && g.IO.DisplayVisibleMin.y != g.IO.DisplayVisibleMax.y)
  3537. return ImRect(g.IO.DisplayVisibleMin, g.IO.DisplayVisibleMax);
  3538. return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
  3539. }
  3540.  
  3541. // Not exposed publicly as BeginTooltip() because bool parameters are evil. Let's see if other needs arise first.
  3542. static void BeginTooltipEx(bool override_previous_tooltip)
  3543. {
  3544. ImGuiContext& g = *GImGui;
  3545. char window_name[16];
  3546. ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip%02d", g.TooltipOverrideCount);
  3547. if (override_previous_tooltip)
  3548. if (ImGuiWindow* window = ImGui::FindWindowByName(window_name))
  3549. if (window->Active)
  3550. {
  3551. // Hide previous tooltips. We can't easily "reset" the content of a window so we create a new one.
  3552. window->HiddenFrames = 1;
  3553. ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip%02d", ++g.TooltipOverrideCount);
  3554. }
  3555. ImGui::Begin(window_name, NULL, ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize);
  3556. }
  3557.  
  3558. void ImGui::SetTooltipV(const char* fmt, va_list args)
  3559. {
  3560. BeginTooltipEx(true);
  3561. TextV(fmt, args);
  3562. EndTooltip();
  3563. }
  3564.  
  3565. void ImGui::SetTooltip(const char* fmt, ...)
  3566. {
  3567. va_list args;
  3568. va_start(args, fmt);
  3569. SetTooltipV(fmt, args);
  3570. va_end(args);
  3571. }
  3572.  
  3573. void ImGui::BeginTooltip()
  3574. {
  3575. BeginTooltipEx(false);
  3576. }
  3577.  
  3578. void ImGui::EndTooltip()
  3579. {
  3580. IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
  3581. ImGui::End();
  3582. }
  3583.  
  3584. // Mark popup as open (toggle toward open state).
  3585. // Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
  3586. // Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
  3587. // One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
  3588. void ImGui::OpenPopupEx(ImGuiID id, bool reopen_existing)
  3589. {
  3590. ImGuiContext& g = *GImGui;
  3591. ImGuiWindow* window = g.CurrentWindow;
  3592. int current_stack_size = g.CurrentPopupStack.Size;
  3593. ImGuiPopupRef popup_ref = ImGuiPopupRef(id, window, window->GetID("##menus"), g.IO.MousePos); // Tagged as new ref because constructor sets Window to NULL (we are passing the ParentWindow info here)
  3594. if (g.OpenPopupStack.Size < current_stack_size + 1)
  3595. g.OpenPopupStack.push_back(popup_ref);
  3596. else if (reopen_existing || g.OpenPopupStack[current_stack_size].PopupId != id)
  3597. {
  3598. g.OpenPopupStack.resize(current_stack_size + 1);
  3599. g.OpenPopupStack[current_stack_size] = popup_ref;
  3600. }
  3601. }
  3602.  
  3603. void ImGui::OpenPopup(const char* str_id)
  3604. {
  3605. ImGuiContext& g = *GImGui;
  3606. OpenPopupEx(g.CurrentWindow->GetID(str_id), false);
  3607. }
  3608.  
  3609. static void CloseInactivePopups()
  3610. {
  3611. ImGuiContext& g = *GImGui;
  3612. if (g.OpenPopupStack.empty())
  3613. return;
  3614.  
  3615. // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
  3616. // Don't close our own child popup windows
  3617. int n = 0;
  3618. if (g.NavWindow)
  3619. {
  3620. for (n = 0; n < g.OpenPopupStack.Size; n++)
  3621. {
  3622. ImGuiPopupRef& popup = g.OpenPopupStack[n];
  3623. if (!popup.Window)
  3624. continue;
  3625. IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
  3626. if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
  3627. continue;
  3628.  
  3629. bool has_focus = false;
  3630. for (int m = n; m < g.OpenPopupStack.Size && !has_focus; m++)
  3631. has_focus = (g.OpenPopupStack[m].Window && g.OpenPopupStack[m].Window->RootWindow == g.NavWindow->RootWindow);
  3632. if (!has_focus)
  3633. break;
  3634. }
  3635. }
  3636. if (n < g.OpenPopupStack.Size) // This test is not required but it allows to set a useful breakpoint on the line below
  3637. g.OpenPopupStack.resize(n);
  3638. }
  3639.  
  3640. static ImGuiWindow* GetFrontMostModalRootWindow()
  3641. {
  3642. ImGuiContext& g = *GImGui;
  3643. for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
  3644. if (ImGuiWindow* front_most_popup = g.OpenPopupStack.Data[n].Window)
  3645. if (front_most_popup->Flags & ImGuiWindowFlags_Modal)
  3646. return front_most_popup;
  3647. return NULL;
  3648. }
  3649.  
  3650. static void ClosePopupToLevel(int remaining)
  3651. {
  3652. ImGuiContext& g = *GImGui;
  3653. if (remaining > 0)
  3654. ImGui::FocusWindow(g.OpenPopupStack[remaining - 1].Window);
  3655. else
  3656. ImGui::FocusWindow(g.OpenPopupStack[0].ParentWindow);
  3657. g.OpenPopupStack.resize(remaining);
  3658. }
  3659.  
  3660. static void ClosePopup(ImGuiID id)
  3661. {
  3662. if (!ImGui::IsPopupOpen(id))
  3663. return;
  3664. ImGuiContext& g = *GImGui;
  3665. ClosePopupToLevel(g.OpenPopupStack.Size - 1);
  3666. }
  3667.  
  3668. // Close the popup we have begin-ed into.
  3669. void ImGui::CloseCurrentPopup()
  3670. {
  3671. ImGuiContext& g = *GImGui;
  3672. int popup_idx = g.CurrentPopupStack.Size - 1;
  3673. if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.CurrentPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
  3674. return;
  3675. while (popup_idx > 0 && g.OpenPopupStack[popup_idx].Window && (g.OpenPopupStack[popup_idx].Window->Flags & ImGuiWindowFlags_ChildMenu))
  3676. popup_idx--;
  3677. ClosePopupToLevel(popup_idx);
  3678. }
  3679.  
  3680. static inline void ClearSetNextWindowData()
  3681. {
  3682. // FIXME-OPT
  3683. ImGuiContext& g = *GImGui;
  3684. g.SetNextWindowPosCond = g.SetNextWindowSizeCond = g.SetNextWindowContentSizeCond = g.SetNextWindowCollapsedCond = 0;
  3685. g.SetNextWindowSizeConstraint = g.SetNextWindowFocus = false;
  3686. }
  3687.  
  3688. static bool BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags)
  3689. {
  3690. ImGuiContext& g = *GImGui;
  3691. ImGuiWindow* window = g.CurrentWindow;
  3692. if (!ImGui::IsPopupOpen(id))
  3693. {
  3694. ClearSetNextWindowData(); // We behave like Begin() and need to consume those values
  3695. return false;
  3696. }
  3697.  
  3698. ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
  3699. ImGuiWindowFlags flags = extra_flags | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize;
  3700.  
  3701. char name[20];
  3702. if (flags & ImGuiWindowFlags_ChildMenu)
  3703. ImFormatString(name, IM_ARRAYSIZE(name), "##menu_%d", g.CurrentPopupStack.Size); // Recycle windows based on depth
  3704. else
  3705. ImFormatString(name, IM_ARRAYSIZE(name), "##popup_%08x", id); // Not recycling, so we can close/open during the same frame
  3706.  
  3707. bool is_open = ImGui::Begin(name, NULL, flags);
  3708. if (!(window->Flags & ImGuiWindowFlags_ShowBorders))
  3709. g.CurrentWindow->Flags &= ~ImGuiWindowFlags_ShowBorders;
  3710. if (!is_open) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
  3711. ImGui::EndPopup();
  3712.  
  3713. return is_open;
  3714. }
  3715.  
  3716. bool ImGui::BeginPopup(const char* str_id)
  3717. {
  3718. ImGuiContext& g = *GImGui;
  3719. if (g.OpenPopupStack.Size <= g.CurrentPopupStack.Size) // Early out for performance
  3720. {
  3721. ClearSetNextWindowData(); // We behave like Begin() and need to consume those values
  3722. return false;
  3723. }
  3724. return BeginPopupEx(g.CurrentWindow->GetID(str_id), ImGuiWindowFlags_ShowBorders);
  3725. }
  3726.  
  3727. bool ImGui::IsPopupOpen(ImGuiID id)
  3728. {
  3729. ImGuiContext& g = *GImGui;
  3730. return g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupId == id;
  3731. }
  3732.  
  3733. bool ImGui::IsPopupOpen(const char* str_id)
  3734. {
  3735. ImGuiContext& g = *GImGui;
  3736. return g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupId == g.CurrentWindow->GetID(str_id);
  3737. }
  3738.  
  3739. bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags extra_flags)
  3740. {
  3741. ImGuiContext& g = *GImGui;
  3742. ImGuiWindow* window = g.CurrentWindow;
  3743. const ImGuiID id = window->GetID(name);
  3744. if (!IsPopupOpen(id))
  3745. {
  3746. ClearSetNextWindowData(); // We behave like Begin() and need to consume those values
  3747. return false;
  3748. }
  3749.  
  3750. ImGuiWindowFlags flags = extra_flags | ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings;
  3751. bool is_open = ImGui::Begin(name, p_open, flags);
  3752. if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
  3753. {
  3754. ImGui::EndPopup();
  3755. if (is_open)
  3756. ClosePopup(id);
  3757. return false;
  3758. }
  3759.  
  3760. return is_open;
  3761. }
  3762.  
  3763. void ImGui::EndPopup()
  3764. {
  3765. ImGuiWindow* window = GetCurrentWindow();
  3766. IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
  3767. IM_ASSERT(GImGui->CurrentPopupStack.Size > 0);
  3768. ImGui::End();
  3769. if (!(window->Flags & ImGuiWindowFlags_Modal))
  3770. ImGui::PopStyleVar();
  3771. }
  3772.  
  3773. // This is a helper to handle the most simple case of associating one named popup to one given widget.
  3774. // 1. If you have many possible popups (for different "instances" of a same widget, or for wholly different widgets), you may be better off handling
  3775. // this yourself so you can store data relative to the widget that opened the popup instead of choosing different popup identifiers.
  3776. // 2. If you want right-clicking on the same item to reopen the popup at new location, use the same code replacing IsItemHovered() with IsItemRectHovered()
  3777. // and passing true to the OpenPopupEx().
  3778. // Because: hovering an item in a window below the popup won't normally trigger is hovering behavior/coloring. The pattern of ignoring the fact that
  3779. // the item can be interacted with (because it is blocked by the active popup) may useful in some situation when e.g. large canvas as one item, content of menu
  3780. // driven by click position.
  3781. bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button)
  3782. {
  3783. if (IsItemHovered() && IsMouseClicked(mouse_button))
  3784. OpenPopupEx(GImGui->CurrentWindow->GetID(str_id), false);
  3785. return BeginPopup(str_id);
  3786. }
  3787.  
  3788. bool ImGui::BeginPopupContextWindow(const char* str_id, int mouse_button, bool also_over_items)
  3789. {
  3790. if (!str_id)
  3791. str_id = "window_context";
  3792. if (IsWindowRectHovered() && IsMouseClicked(mouse_button))
  3793. if (also_over_items || !IsAnyItemHovered())
  3794. OpenPopupEx(GImGui->CurrentWindow->GetID(str_id), true);
  3795. return BeginPopup(str_id);
  3796. }
  3797.  
  3798. bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button)
  3799. {
  3800. if (!str_id)
  3801. str_id = "void_context";
  3802. if (!IsAnyWindowHovered() && IsMouseClicked(mouse_button))
  3803. OpenPopupEx(GImGui->CurrentWindow->GetID(str_id), true);
  3804. return BeginPopup(str_id);
  3805. }
  3806.  
  3807. static bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
  3808. {
  3809. ImGuiWindow* parent_window = ImGui::GetCurrentWindow();
  3810. ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_ChildWindow;
  3811.  
  3812. const ImVec2 content_avail = ImGui::GetContentRegionAvail();
  3813. ImVec2 size = ImFloor(size_arg);
  3814. const int auto_fit_axises = ((size.x == 0.0f) ? 0x01 : 0x00) | ((size.y == 0.0f) ? 0x02 : 0x00);
  3815. if (size.x <= 0.0f)
  3816. size.x = ImMax(content_avail.x, 4.0f) - fabsf(size.x); // Arbitrary minimum zero-ish child size of 4.0f (0.0f causing too much issues)
  3817. if (size.y <= 0.0f)
  3818. size.y = ImMax(content_avail.y, 4.0f) - fabsf(size.y);
  3819. if (border)
  3820. flags |= ImGuiWindowFlags_ShowBorders;
  3821. flags |= extra_flags;
  3822.  
  3823. char title[256];
  3824. if (name)
  3825. ImFormatString(title, IM_ARRAYSIZE(title), "%s.%s.%08X", parent_window->Name, name, id);
  3826. else
  3827. ImFormatString(title, IM_ARRAYSIZE(title), "%s.%08X", parent_window->Name, id);
  3828.  
  3829. bool ret = ImGui::Begin(title, NULL, size, -1.0f, flags);
  3830. ImGuiWindow* child_window = ImGui::GetCurrentWindow();
  3831. child_window->AutoFitChildAxises = auto_fit_axises;
  3832. if (!(parent_window->Flags & ImGuiWindowFlags_ShowBorders))
  3833. child_window->Flags &= ~ImGuiWindowFlags_ShowBorders;
  3834.  
  3835. return ret;
  3836. }
  3837.  
  3838. bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
  3839. {
  3840. ImGuiWindow* window = GetCurrentWindow();
  3841. return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);
  3842. }
  3843.  
  3844. bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
  3845. {
  3846. return BeginChildEx(NULL, id, size_arg, border, extra_flags);
  3847. }
  3848.  
  3849. void ImGui::EndChild()
  3850. {
  3851. ImGuiWindow* window = GetCurrentWindow();
  3852.  
  3853. IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss
  3854. if ((window->Flags & ImGuiWindowFlags_ComboBox) || window->BeginCount > 1)
  3855. {
  3856. ImGui::End();
  3857. }
  3858. else
  3859. {
  3860. // When using auto-filling child window, we don't provide full width/height to ItemSize so that it doesn't feed back into automatic size-fitting.
  3861. ImVec2 sz = GetWindowSize();
  3862. if (window->AutoFitChildAxises & 0x01) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
  3863. sz.x = ImMax(4.0f, sz.x);
  3864. if (window->AutoFitChildAxises & 0x02)
  3865. sz.y = ImMax(4.0f, sz.y);
  3866. ImGui::End();
  3867.  
  3868. ImGuiWindow* parent_window = GetCurrentWindow();
  3869. ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
  3870. ItemSize(sz);
  3871. ItemAdd(bb, NULL);
  3872. }
  3873. }
  3874.  
  3875. // Helper to create a child window / scrolling region that looks like a normal widget frame.
  3876. bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
  3877. {
  3878. ImGuiContext& g = *GImGui;
  3879. const ImGuiStyle& style = g.Style;
  3880. ImGui::PushStyleColor(ImGuiCol_ChildWindowBg, style.Colors[ImGuiCol_FrameBg]);
  3881. ImGui::PushStyleVar(ImGuiStyleVar_ChildWindowRounding, style.FrameRounding);
  3882. ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
  3883. return ImGui::BeginChild(id, size, (g.CurrentWindow->Flags & ImGuiWindowFlags_ShowBorders) ? true : false, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
  3884. }
  3885.  
  3886. void ImGui::EndChildFrame()
  3887. {
  3888. ImGui::EndChild();
  3889. ImGui::PopStyleVar(2);
  3890. ImGui::PopStyleColor();
  3891. }
  3892.  
  3893. // Save and compare stack sizes on Begin()/End() to detect usage errors
  3894. static void CheckStacksSize(ImGuiWindow* window, bool write)
  3895. {
  3896. // NOT checking: DC.ItemWidth, DC.AllowKeyboardFocus, DC.ButtonRepeat, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
  3897. ImGuiContext& g = *GImGui;
  3898. int* p_backup = &window->DC.StackSizesBackup[0];
  3899. { int current = window->IDStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushID/PopID or TreeNode/TreePop Mismatch!"); p_backup++; } // Too few or too many PopID()/TreePop()
  3900. { int current = window->DC.GroupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // Too few or too many EndGroup()
  3901. { int current = g.CurrentPopupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch"); p_backup++;}// Too few or too many EndMenu()/EndPopup()
  3902. { int current = g.ColorModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleColor/PopStyleColor Mismatch!"); p_backup++; } // Too few or too many PopStyleColor()
  3903. { int current = g.StyleModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleVar/PopStyleVar Mismatch!"); p_backup++; } // Too few or too many PopStyleVar()
  3904. { int current = g.FontStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushFont/PopFont Mismatch!"); p_backup++; } // Too few or too many PopFont()
  3905. IM_ASSERT(p_backup == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup));
  3906. }
  3907.  
  3908. static ImVec2 FindBestPopupWindowPos(const ImVec2& base_pos, const ImVec2& size, int* last_dir, const ImRect& r_inner)
  3909. {
  3910. const ImGuiStyle& style = GImGui->Style;
  3911.  
  3912. // Clamp into visible area while not overlapping the cursor. Safety padding is optional if our popup size won't fit without it.
  3913. ImVec2 safe_padding = style.DisplaySafeAreaPadding;
  3914. ImRect r_outer(GetVisibleRect());
  3915. r_outer.Expand(ImVec2((size.x - r_outer.GetWidth() > safe_padding.x * 2) ? -safe_padding.x : 0.0f, (size.y - r_outer.GetHeight() > safe_padding.y * 2) ? -safe_padding.y : 0.0f));
  3916. ImVec2 base_pos_clamped = ImClamp(base_pos, r_outer.Min, r_outer.Max - size);
  3917.  
  3918. for (int n = (*last_dir != -1) ? -1 : 0; n < 4; n++) // Last, Right, down, up, left. (Favor last used direction).
  3919. {
  3920. const int dir = (n == -1) ? *last_dir : n;
  3921. ImRect rect(dir == 0 ? r_inner.Max.x : r_outer.Min.x, dir == 1 ? r_inner.Max.y : r_outer.Min.y, dir == 3 ? r_inner.Min.x : r_outer.Max.x, dir == 2 ? r_inner.Min.y : r_outer.Max.y);
  3922. if (rect.GetWidth() < size.x || rect.GetHeight() < size.y)
  3923. continue;
  3924. *last_dir = dir;
  3925. return ImVec2(dir == 0 ? r_inner.Max.x : dir == 3 ? r_inner.Min.x - size.x : base_pos_clamped.x, dir == 1 ? r_inner.Max.y : dir == 2 ? r_inner.Min.y - size.y : base_pos_clamped.y);
  3926. }
  3927.  
  3928. // Fallback, try to keep within display
  3929. *last_dir = -1;
  3930. ImVec2 pos = base_pos;
  3931. pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
  3932. pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
  3933. return pos;
  3934. }
  3935.  
  3936. ImGuiWindow* ImGui::FindWindowByName(const char* name)
  3937. {
  3938. // FIXME-OPT: Store sorted hashes -> pointers so we can do a bissection in a contiguous block
  3939. ImGuiContext& g = *GImGui;
  3940. ImGuiID id = ImHash(name, 0);
  3941. for (int i = 0; i < g.Windows.Size; i++)
  3942. if (g.Windows[i]->ID == id)
  3943. return g.Windows[i];
  3944. return NULL;
  3945. }
  3946.  
  3947. static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags)
  3948. {
  3949. ImGuiContext& g = *GImGui;
  3950.  
  3951. // Create window the first time
  3952. ImGuiWindow* window = (ImGuiWindow*)ImGui::MemAlloc(sizeof(ImGuiWindow));
  3953. IM_PLACEMENT_NEW(window) ImGuiWindow(name);
  3954. window->Flags = flags;
  3955.  
  3956. if (flags & ImGuiWindowFlags_NoSavedSettings)
  3957. {
  3958. // User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
  3959. window->Size = window->SizeFull = size;
  3960. }
  3961. else
  3962. {
  3963. // Retrieve settings from .ini file
  3964. // Use SetWindowPos() or SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
  3965. window->PosFloat = ImVec2(60, 60);
  3966. window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
  3967.  
  3968. ImGuiIniData* settings = FindWindowSettings(name);
  3969. if (!settings)
  3970. {
  3971. settings = AddWindowSettings(name);
  3972. }
  3973. else
  3974. {
  3975. window->SetWindowPosAllowFlags &= ~ImGuiCond_FirstUseEver;
  3976. window->SetWindowSizeAllowFlags &= ~ImGuiCond_FirstUseEver;
  3977. window->SetWindowCollapsedAllowFlags &= ~ImGuiCond_FirstUseEver;
  3978. }
  3979.  
  3980. if (settings->Pos.x != FLT_MAX)
  3981. {
  3982. window->PosFloat = settings->Pos;
  3983. window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
  3984. window->Collapsed = settings->Collapsed;
  3985. }
  3986.  
  3987. if (ImLengthSqr(settings->Size) > 0.00001f)
  3988. size = settings->Size;
  3989. window->Size = window->SizeFull = size;
  3990. }
  3991.  
  3992. if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
  3993. {
  3994. window->AutoFitFramesX = window->AutoFitFramesY = 2;
  3995. window->AutoFitOnlyGrows = false;
  3996. }
  3997. else
  3998. {
  3999. if (window->Size.x <= 0.0f)
  4000. window->AutoFitFramesX = 2;
  4001. if (window->Size.y <= 0.0f)
  4002. window->AutoFitFramesY = 2;
  4003. window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
  4004. }
  4005.  
  4006. if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
  4007. g.Windows.insert(g.Windows.begin(), window); // Quite slow but rare and only once
  4008. else
  4009. g.Windows.push_back(window);
  4010. return window;
  4011. }
  4012.  
  4013. static void ApplySizeFullWithConstraint(ImGuiWindow* window, ImVec2 new_size)
  4014. {
  4015. ImGuiContext& g = *GImGui;
  4016. if (g.SetNextWindowSizeConstraint)
  4017. {
  4018. // Using -1,-1 on either X/Y axis to preserve the current size.
  4019. ImRect cr = g.SetNextWindowSizeConstraintRect;
  4020. new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
  4021. new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
  4022. if (g.SetNextWindowSizeConstraintCallback)
  4023. {
  4024. ImGuiSizeConstraintCallbackData data;
  4025. data.UserData = g.SetNextWindowSizeConstraintCallbackUserData;
  4026. data.Pos = window->Pos;
  4027. data.CurrentSize = window->SizeFull;
  4028. data.DesiredSize = new_size;
  4029. g.SetNextWindowSizeConstraintCallback(&data);
  4030. new_size = data.DesiredSize;
  4031. }
  4032. }
  4033. if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
  4034. new_size = ImMax(new_size, g.Style.WindowMinSize);
  4035. window->SizeFull = new_size;
  4036. }
  4037.  
  4038. static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
  4039. {
  4040. ImVec2 scroll = window->Scroll;
  4041. float cr_x = window->ScrollTargetCenterRatio.x;
  4042. float cr_y = window->ScrollTargetCenterRatio.y;
  4043. if (window->ScrollTarget.x < FLT_MAX)
  4044. scroll.x = window->ScrollTarget.x - cr_x * (window->SizeFull.x - window->ScrollbarSizes.x);
  4045. if (window->ScrollTarget.y < FLT_MAX)
  4046. scroll.y = window->ScrollTarget.y - (1.0f - cr_y) * (window->TitleBarHeight() + window->MenuBarHeight()) - cr_y * (window->SizeFull.y - window->ScrollbarSizes.y);
  4047. scroll = ImMax(scroll, ImVec2(0.0f, 0.0f));
  4048. if (!window->Collapsed && !window->SkipItems)
  4049. {
  4050. scroll.x = ImMin(scroll.x, ImMax(0.0f, window->SizeContents.x - (window->SizeFull.x - window->ScrollbarSizes.x))); // == GetScrollMaxX for that window
  4051. scroll.y = ImMin(scroll.y, ImMax(0.0f, window->SizeContents.y - (window->SizeFull.y - window->ScrollbarSizes.y))); // == GetScrollMaxY for that window
  4052. }
  4053. return scroll;
  4054. }
  4055.  
  4056. // Push a new ImGui window to add widgets to.
  4057. // - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
  4058. // - Begin/End can be called multiple times during the frame with the same window name to append content.
  4059. // - 'size_on_first_use' for a regular window denote the initial size for first-time creation (no saved data) and isn't that useful. Use SetNextWindowSize() prior to calling Begin() for more flexible window manipulation.
  4060. // - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
  4061. // You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
  4062. // - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
  4063. // - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
  4064. // - Passing non-zero 'size' is roughly equivalent to calling SetNextWindowSize(size, ImGuiCond_FirstUseEver) prior to calling Begin().
  4065. bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
  4066. {
  4067. return ImGui::Begin(name, p_open, ImVec2(0.f, 0.f), -1.0f, flags);
  4068. }
  4069.  
  4070. bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha, ImGuiWindowFlags flags)
  4071. {
  4072. ImGuiContext& g = *GImGui;
  4073. const ImGuiStyle& style = g.Style;
  4074. IM_ASSERT(name != NULL); // Window name required
  4075. IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame()
  4076. IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
  4077.  
  4078. if (flags & ImGuiWindowFlags_NoInputs)
  4079. flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
  4080.  
  4081. // Find or create
  4082. bool window_is_new = false;
  4083. ImGuiWindow* window = FindWindowByName(name);
  4084. if (!window)
  4085. {
  4086. window = CreateNewWindow(name, size_on_first_use, flags);
  4087. window_is_new = true;
  4088. }
  4089.  
  4090. const int current_frame = ImGui::GetFrameCount();
  4091. const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
  4092. if (first_begin_of_the_frame)
  4093. window->Flags = (ImGuiWindowFlags)flags;
  4094. else
  4095. flags = window->Flags;
  4096.  
  4097. // Add to stack
  4098. ImGuiWindow* parent_window = !g.CurrentWindowStack.empty() ? g.CurrentWindowStack.back() : NULL;
  4099. g.CurrentWindowStack.push_back(window);
  4100. SetCurrentWindow(window);
  4101. CheckStacksSize(window, true);
  4102. IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
  4103.  
  4104. bool window_was_active = (window->LastFrameActive == current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
  4105. if (flags & ImGuiWindowFlags_Popup)
  4106. {
  4107. ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size];
  4108. window_was_active &= (window->PopupId == popup_ref.PopupId);
  4109. window_was_active &= (window == popup_ref.Window);
  4110. popup_ref.Window = window;
  4111. g.CurrentPopupStack.push_back(popup_ref);
  4112. window->PopupId = popup_ref.PopupId;
  4113. }
  4114.  
  4115. const bool window_appearing_after_being_hidden = (window->HiddenFrames == 1);
  4116.  
  4117. // Process SetNextWindow***() calls
  4118. bool window_pos_set_by_api = false, window_size_set_by_api = false;
  4119. if (g.SetNextWindowPosCond)
  4120. {
  4121. const ImVec2 backup_cursor_pos = window->DC.CursorPos; // FIXME: not sure of the exact reason of this saving/restore anymore :( need to look into that.
  4122. if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowPosAllowFlags |= ImGuiCond_Appearing;
  4123. window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.SetNextWindowPosCond) != 0;
  4124. if (window_pos_set_by_api && ImLengthSqr(g.SetNextWindowPosVal - ImVec2(-FLT_MAX, -FLT_MAX)) < 0.001f)
  4125. {
  4126. window->SetWindowPosCenterWanted = true; // May be processed on the next frame if this is our first frame and we are measuring size
  4127. window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  4128. }
  4129. else
  4130. {
  4131. SetWindowPos(window, g.SetNextWindowPosVal, g.SetNextWindowPosCond);
  4132. }
  4133. window->DC.CursorPos = backup_cursor_pos;
  4134. g.SetNextWindowPosCond = 0;
  4135. }
  4136. if (g.SetNextWindowSizeCond)
  4137. {
  4138. if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowSizeAllowFlags |= ImGuiCond_Appearing;
  4139. window_size_set_by_api = (window->SetWindowSizeAllowFlags & g.SetNextWindowSizeCond) != 0;
  4140. SetWindowSize(window, g.SetNextWindowSizeVal, g.SetNextWindowSizeCond);
  4141. g.SetNextWindowSizeCond = 0;
  4142. }
  4143. if (g.SetNextWindowContentSizeCond)
  4144. {
  4145. window->SizeContentsExplicit = g.SetNextWindowContentSizeVal;
  4146. g.SetNextWindowContentSizeCond = 0;
  4147. }
  4148. else if (first_begin_of_the_frame)
  4149. {
  4150. window->SizeContentsExplicit = ImVec2(0.0f, 0.0f);
  4151. }
  4152. if (g.SetNextWindowCollapsedCond)
  4153. {
  4154. if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowCollapsedAllowFlags |= ImGuiCond_Appearing;
  4155. SetWindowCollapsed(window, g.SetNextWindowCollapsedVal, g.SetNextWindowCollapsedCond);
  4156. g.SetNextWindowCollapsedCond = 0;
  4157. }
  4158. if (g.SetNextWindowFocus)
  4159. {
  4160. ImGui::SetWindowFocus();
  4161. g.SetNextWindowFocus = false;
  4162. }
  4163.  
  4164. // Update known root window (if we are a child window, otherwise window == window->RootWindow)
  4165. int root_idx, root_non_popup_idx;
  4166. for (root_idx = g.CurrentWindowStack.Size - 1; root_idx > 0; root_idx--)
  4167. if (!(g.CurrentWindowStack[root_idx]->Flags & ImGuiWindowFlags_ChildWindow))
  4168. break;
  4169. for (root_non_popup_idx = root_idx; root_non_popup_idx > 0; root_non_popup_idx--)
  4170. if (!(g.CurrentWindowStack[root_non_popup_idx]->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) || (g.CurrentWindowStack[root_non_popup_idx]->Flags & ImGuiWindowFlags_Modal))
  4171. break;
  4172. window->ParentWindow = parent_window;
  4173. window->RootWindow = g.CurrentWindowStack[root_idx];
  4174. window->RootNonPopupWindow = g.CurrentWindowStack[root_non_popup_idx]; // Used to display TitleBgActive color and for selecting which window to use for NavWindowing
  4175.  
  4176.  
  4177. // When reusing window again multiple times a frame, just append content (don't need to setup again)
  4178. if (first_begin_of_the_frame)
  4179. {
  4180. window->Active = true;
  4181. window->OrderWithinParent = 0;
  4182. window->BeginCount = 0;
  4183. window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
  4184. window->LastFrameActive = current_frame;
  4185. window->IDStack.resize(1);
  4186.  
  4187. // Clear draw list, setup texture, outer clipping rectangle
  4188. window->DrawList->Clear();
  4189. window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
  4190. ImRect fullscreen_rect(GetVisibleRect());
  4191. if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_ComboBox | ImGuiWindowFlags_Popup)))
  4192. PushClipRect(parent_window->ClipRect.Min, parent_window->ClipRect.Max, true);
  4193. else
  4194. PushClipRect(fullscreen_rect.Min, fullscreen_rect.Max, true);
  4195.  
  4196. if (!window_was_active)
  4197. {
  4198. // Popup first latch mouse position, will position itself when it appears next frame
  4199. window->AutoPosLastDirection = -1;
  4200. if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api)
  4201. window->PosFloat = g.IO.MousePos;
  4202. }
  4203.  
  4204. // Collapse window by double-clicking on title bar
  4205. // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
  4206. if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse))
  4207. {
  4208. ImRect title_bar_rect = window->TitleBarRect();
  4209. if (g.HoveredWindow == window && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0])
  4210. {
  4211. window->Collapsed = !window->Collapsed;
  4212. MarkIniSettingsDirty(window);
  4213. FocusWindow(window);
  4214. }
  4215. }
  4216. else
  4217. {
  4218. window->Collapsed = false;
  4219. }
  4220.  
  4221. // SIZE
  4222.  
  4223. // Save contents size from last frame for auto-fitting (unless explicitly specified)
  4224. window->SizeContents.x = (float)(int)((window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : ((window_is_new ? 0.0f : window->DC.CursorMaxPos.x - window->Pos.x) + window->Scroll.x));
  4225. window->SizeContents.y = (float)(int)((window->SizeContentsExplicit.y != 0.0f) ? window->SizeContentsExplicit.y : ((window_is_new ? 0.0f : window->DC.CursorMaxPos.y - window->Pos.y) + window->Scroll.y));
  4226.  
  4227. // Hide popup/tooltip window when first appearing while we measure size (because we recycle them)
  4228. if (window->HiddenFrames > 0)
  4229. window->HiddenFrames--;
  4230. if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0 && !window_was_active)
  4231. {
  4232. window->HiddenFrames = 1;
  4233. if (flags & ImGuiWindowFlags_AlwaysAutoResize)
  4234. {
  4235. if (!window_size_set_by_api)
  4236. window->Size = window->SizeFull = ImVec2(0.f, 0.f);
  4237. window->SizeContents = ImVec2(0.f, 0.f);
  4238. }
  4239. }
  4240.  
  4241. // Lock window padding so that altering the ShowBorders flag for children doesn't have side-effects.
  4242. window->WindowPadding = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_ShowBorders | ImGuiWindowFlags_ComboBox | ImGuiWindowFlags_Popup))) ? ImVec2(0, 0) : style.WindowPadding;
  4243.  
  4244. // Calculate auto-fit size
  4245. ImVec2 size_auto_fit;
  4246. if ((flags & ImGuiWindowFlags_Tooltip) != 0)
  4247. {
  4248. // Tooltip always resize. We keep the spacing symmetric on both axises for aesthetic purpose.
  4249. size_auto_fit = window->SizeContents + window->WindowPadding - ImVec2(0.0f, style.ItemSpacing.y);
  4250. }
  4251. else
  4252. {
  4253. size_auto_fit = ImClamp(window->SizeContents + window->WindowPadding, style.WindowMinSize, ImMax(style.WindowMinSize, g.IO.DisplaySize - g.Style.DisplaySafeAreaPadding));
  4254.  
  4255. // Handling case of auto fit window not fitting in screen on one axis, we are growing auto fit size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than DisplaySize-WindowPadding.
  4256. if (size_auto_fit.x < window->SizeContents.x && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar))
  4257. size_auto_fit.y += style.ScrollbarSize;
  4258. if (size_auto_fit.y < window->SizeContents.y && !(flags & ImGuiWindowFlags_NoScrollbar))
  4259. size_auto_fit.x += style.ScrollbarSize;
  4260. size_auto_fit.y = ImMax(size_auto_fit.y - style.ItemSpacing.y, 0.0f);
  4261. }
  4262.  
  4263. // Handle automatic resize
  4264. if (window->Collapsed)
  4265. {
  4266. // We still process initial auto-fit on collapsed windows to get a window width,
  4267. // But otherwise we don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
  4268. if (window->AutoFitFramesX > 0)
  4269. window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
  4270. if (window->AutoFitFramesY > 0)
  4271. window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
  4272. }
  4273. else
  4274. {
  4275. if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window_size_set_by_api)
  4276. {
  4277. window->SizeFull = size_auto_fit;
  4278. }
  4279. else if ((window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) && !window_size_set_by_api)
  4280. {
  4281. // Auto-fit only grows during the first few frames
  4282. if (window->AutoFitFramesX > 0)
  4283. window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
  4284. if (window->AutoFitFramesY > 0)
  4285. window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
  4286. MarkIniSettingsDirty(window);
  4287. }
  4288. }
  4289.  
  4290. // Apply minimum/maximum window size constraints and final size
  4291. ApplySizeFullWithConstraint(window, window->SizeFull);
  4292. window->Size = window->Collapsed ? window->TitleBarRect().GetSize() : window->SizeFull;
  4293.  
  4294. // POSITION
  4295.  
  4296. // Position child window
  4297. if (flags & ImGuiWindowFlags_ChildWindow)
  4298. {
  4299. window->OrderWithinParent = parent_window->DC.ChildWindows.Size;
  4300. parent_window->DC.ChildWindows.push_back(window);
  4301. }
  4302. if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup))
  4303. {
  4304. window->Pos = window->PosFloat = parent_window->DC.CursorPos;
  4305. window->Size = window->SizeFull = size_on_first_use; // NB: argument name 'size_on_first_use' misleading here, it's really just 'size' as provided by user passed via BeginChild()->Begin().
  4306. }
  4307.  
  4308. bool window_pos_center = false;
  4309. window_pos_center |= (window->SetWindowPosCenterWanted && window->HiddenFrames == 0);
  4310. window_pos_center |= ((flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api && window_appearing_after_being_hidden);
  4311. if (window_pos_center)
  4312. {
  4313. // Center (any sort of window)
  4314. SetWindowPos(window, ImMax(style.DisplaySafeAreaPadding, fullscreen_rect.GetCenter() - window->SizeFull * 0.5f), 0);
  4315. }
  4316. else if (flags & ImGuiWindowFlags_ChildMenu)
  4317. {
  4318. // Child menus typically request _any_ position within the parent menu item, and then our FindBestPopupWindowPos() function will move the new menu outside the parent bounds.
  4319. // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
  4320. IM_ASSERT(window_pos_set_by_api);
  4321. float horizontal_overlap = style.ItemSpacing.x; // We want some overlap to convey the relative depth of each popup (currently the amount of overlap it is hard-coded to style.ItemSpacing.x, may need to introduce another style value).
  4322. ImRect rect_to_avoid;
  4323. if (parent_window->DC.MenuBarAppending)
  4324. rect_to_avoid = ImRect(-FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight(), FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight() + parent_window->MenuBarHeight());
  4325. else
  4326. rect_to_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
  4327. window->PosFloat = FindBestPopupWindowPos(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
  4328. }
  4329. else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_appearing_after_being_hidden)
  4330. {
  4331. ImRect rect_to_avoid(window->PosFloat.x - 1, window->PosFloat.y - 1, window->PosFloat.x + 1, window->PosFloat.y + 1);
  4332. window->PosFloat = FindBestPopupWindowPos(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
  4333. }
  4334.  
  4335. // Position tooltip (always follows mouse)
  4336. if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api)
  4337. {
  4338. ImVec2 ref_pos = g.IO.MousePos;
  4339. ImRect rect_to_avoid(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24, ref_pos.y + 24); // FIXME: Completely hard-coded. Perhaps center on cursor hit-point instead?
  4340. window->PosFloat = FindBestPopupWindowPos(ref_pos, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
  4341. if (window->AutoPosLastDirection == -1)
  4342. window->PosFloat = ref_pos + ImVec2(2, 2); // If there's not enough room, for tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
  4343. }
  4344.  
  4345. // Clamp position so it stays visible
  4346. if (!(flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
  4347. {
  4348. if (!window_pos_set_by_api && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && g.IO.DisplaySize.x > 0.0f && g.IO.DisplaySize.y > 0.0f) // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
  4349. {
  4350. ImVec2 padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
  4351. window->PosFloat = ImMax(window->PosFloat + window->Size, padding) - window->Size;
  4352. window->PosFloat = ImMin(window->PosFloat, g.IO.DisplaySize - padding);
  4353. }
  4354. }
  4355. window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
  4356.  
  4357. // Default item width. Make it proportional to window size if window manually resizes
  4358. if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
  4359. window->ItemWidthDefault = (float)(int)(window->Size.x * 0.65f);
  4360. else
  4361. window->ItemWidthDefault = (float)(int)(g.FontSize * 16.0f);
  4362.  
  4363. // Prepare for focus requests
  4364. window->FocusIdxAllRequestCurrent = (window->FocusIdxAllRequestNext == INT_MAX || window->FocusIdxAllCounter == -1) ? INT_MAX : (window->FocusIdxAllRequestNext + (window->FocusIdxAllCounter + 1)) % (window->FocusIdxAllCounter + 1);
  4365. window->FocusIdxTabRequestCurrent = (window->FocusIdxTabRequestNext == INT_MAX || window->FocusIdxTabCounter == -1) ? INT_MAX : (window->FocusIdxTabRequestNext + (window->FocusIdxTabCounter + 1)) % (window->FocusIdxTabCounter + 1);
  4366. window->FocusIdxAllCounter = window->FocusIdxTabCounter = -1;
  4367. window->FocusIdxAllRequestNext = window->FocusIdxTabRequestNext = INT_MAX;
  4368.  
  4369. // Apply scrolling
  4370. window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
  4371. window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
  4372.  
  4373. // Modal window darkens what is behind them
  4374. if ((flags & ImGuiWindowFlags_Modal) != 0 && window == GetFrontMostModalRootWindow())
  4375. window->DrawList->AddRectFilled(fullscreen_rect.Min, fullscreen_rect.Max, GetColorU32(ImGuiCol_ModalWindowDarkening, g.ModalWindowDarkeningRatio));
  4376.  
  4377. // Draw window + handle manual resize
  4378. ImRect title_bar_rect = window->TitleBarRect();
  4379. const float window_rounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildWindowRounding : style.WindowRounding;
  4380. if (window->Collapsed)
  4381. {
  4382. // Title bar only
  4383. RenderFrame(title_bar_rect.GetTL(), title_bar_rect.GetBR(), GetColorU32(ImGuiCol_TitleBgCollapsed), true, window_rounding);
  4384. }
  4385. else
  4386. {
  4387. ImU32 resize_col = 0;
  4388. const float resize_corner_size = ImMax(g.FontSize * 1.35f, window_rounding + 1.0f + g.FontSize * 0.2f);
  4389. if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && !(flags & ImGuiWindowFlags_NoResize))
  4390. {
  4391. // Manual resize
  4392. const ImVec2 br = window->Rect().GetBR();
  4393. const ImRect resize_rect(br - ImVec2(resize_corner_size * 0.75f, resize_corner_size * 0.75f), br);
  4394. const ImGuiID resize_id = window->GetID("#RESIZE");
  4395. bool hovered, held;
  4396. ButtonBehavior(resize_rect, resize_id, &hovered, &held, ImGuiButtonFlags_FlattenChilds);
  4397. resize_col = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
  4398. if (hovered || held)
  4399. g.MouseCursor = ImGuiMouseCursor_ResizeNWSE;
  4400.  
  4401. ImVec2 size_target(FLT_MAX, FLT_MAX);
  4402. if (g.HoveredWindow == window && held && g.IO.MouseDoubleClicked[0])
  4403. {
  4404. // Manual auto-fit when double-clicking
  4405. size_target = size_auto_fit;
  4406. ClearActiveID();
  4407. }
  4408. else if (held)
  4409. {
  4410. // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
  4411. size_target = (g.IO.MousePos - g.ActiveIdClickOffset + resize_rect.GetSize()) - window->Pos;
  4412. }
  4413.  
  4414. if (size_target.x != FLT_MAX && size_target.y != FLT_MAX)
  4415. {
  4416. ApplySizeFullWithConstraint(window, size_target);
  4417. MarkIniSettingsDirty(window);
  4418. }
  4419. window->Size = window->SizeFull;
  4420. title_bar_rect = window->TitleBarRect();
  4421. }
  4422.  
  4423. // Scrollbars
  4424. window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->SizeContents.y > window->Size.y + style.ItemSpacing.y) && !(flags & ImGuiWindowFlags_NoScrollbar));
  4425. window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->SizeContents.x > window->Size.x - (window->ScrollbarY ? style.ScrollbarSize : 0.0f) - window->WindowPadding.x) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
  4426. if (window->ScrollbarX && !window->ScrollbarY)
  4427. window->ScrollbarY = (window->SizeContents.y > window->Size.y + style.ItemSpacing.y - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar);
  4428. window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
  4429. window->BorderSize = (flags & ImGuiWindowFlags_ShowBorders) ? 1.0f : 0.0f;
  4430.  
  4431. // Window background, Default Alpha
  4432. ImGuiCol bg_color_idx = ImGuiCol_WindowBg;
  4433. if ((flags & ImGuiWindowFlags_ComboBox) != 0)
  4434. bg_color_idx = ImGuiCol_ComboBg;
  4435. else if ((flags & ImGuiWindowFlags_Tooltip) != 0 || (flags & ImGuiWindowFlags_Popup) != 0)
  4436. bg_color_idx = ImGuiCol_PopupBg;
  4437. else if ((flags & ImGuiWindowFlags_ChildWindow) != 0)
  4438. bg_color_idx = ImGuiCol_ChildWindowBg;
  4439. ImVec4 bg_color = style.Colors[bg_color_idx]; // We don't use GetColorU32() because bg_alpha is assigned (not multiplied) below
  4440. if (bg_alpha >= 0.0f)
  4441. bg_color.w = bg_alpha;
  4442. bg_color.w *= style.Alpha;
  4443. if (bg_color.w > 0.0f)
  4444. window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, ColorConvertFloat4ToU32(bg_color), window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImGuiCorner_All : ImGuiCorner_BotLeft | ImGuiCorner_BotRight);
  4445.  
  4446. // Title bar
  4447. const bool is_focused = g.NavWindow && window->RootNonPopupWindow == g.NavWindow->RootNonPopupWindow;
  4448. if (!(flags & ImGuiWindowFlags_NoTitleBar))
  4449. window->DrawList->AddRectFilled(title_bar_rect.GetTL(), title_bar_rect.GetBR(), GetColorU32(is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg), window_rounding, ImGuiCorner_TopLeft | ImGuiCorner_TopRight);
  4450.  
  4451. // Menu bar
  4452. if (flags & ImGuiWindowFlags_MenuBar)
  4453. {
  4454. ImRect menu_bar_rect = window->MenuBarRect();
  4455. if (flags & ImGuiWindowFlags_ShowBorders)
  4456. window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border));
  4457. window->DrawList->AddRectFilled(menu_bar_rect.GetTL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImGuiCorner_TopLeft | ImGuiCorner_TopRight);
  4458. }
  4459.  
  4460. // Scrollbars
  4461. if (window->ScrollbarX)
  4462. Scrollbar(window, true);
  4463. if (window->ScrollbarY)
  4464. Scrollbar(window, false);
  4465.  
  4466. // Render resize grip
  4467. // (after the input handling so we don't have a frame of latency)
  4468. if (!(flags & ImGuiWindowFlags_NoResize))
  4469. {
  4470. const ImVec2 br = window->Rect().GetBR();
  4471. window->DrawList->PathLineTo(br + ImVec2(-resize_corner_size, -window->BorderSize));
  4472. window->DrawList->PathLineTo(br + ImVec2(-window->BorderSize, -resize_corner_size));
  4473. window->DrawList->PathArcToFast(ImVec2(br.x - window_rounding - window->BorderSize, br.y - window_rounding - window->BorderSize), window_rounding, 0, 3);
  4474. window->DrawList->PathFillConvex(resize_col);
  4475. }
  4476.  
  4477. // Borders
  4478. if (flags & ImGuiWindowFlags_ShowBorders)
  4479. {
  4480. window->DrawList->AddRect(window->Pos + ImVec2(1, 1), window->Pos + window->Size + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), window_rounding);
  4481. window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), window_rounding);
  4482. if (!(flags & ImGuiWindowFlags_NoTitleBar))
  4483. window->DrawList->AddLine(title_bar_rect.GetBL() + ImVec2(1, 0), title_bar_rect.GetBR() - ImVec2(1, 0), GetColorU32(ImGuiCol_Border));
  4484. }
  4485. }
  4486.  
  4487. // Update ContentsRegionMax. All the variable it depends on are set above in this function.
  4488. window->ContentsRegionRect.Min.x = -window->Scroll.x + window->WindowPadding.x;
  4489. window->ContentsRegionRect.Min.y = -window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight();
  4490. window->ContentsRegionRect.Max.x = -window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x));
  4491. window->ContentsRegionRect.Max.y = -window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y));
  4492.  
  4493. // Setup drawing context
  4494. window->DC.IndentX = 0.0f + window->WindowPadding.x - window->Scroll.x;
  4495. window->DC.GroupOffsetX = 0.0f;
  4496. window->DC.ColumnsOffsetX = 0.0f;
  4497. window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.IndentX + window->DC.ColumnsOffsetX, window->TitleBarHeight() + window->MenuBarHeight() + window->WindowPadding.y - window->Scroll.y);
  4498. window->DC.CursorPos = window->DC.CursorStartPos;
  4499. window->DC.CursorPosPrevLine = window->DC.CursorPos;
  4500. window->DC.CursorMaxPos = window->DC.CursorStartPos;
  4501. window->DC.CurrentLineHeight = window->DC.PrevLineHeight = 0.0f;
  4502. window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
  4503. window->DC.MenuBarAppending = false;
  4504. window->DC.MenuBarOffsetX = ImMax(window->WindowPadding.x, style.ItemSpacing.x);
  4505. window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
  4506. window->DC.ChildWindows.resize(0);
  4507. window->DC.LayoutType = ImGuiLayoutType_Vertical;
  4508. window->DC.ItemWidth = window->ItemWidthDefault;
  4509. window->DC.TextWrapPos = -1.0f; // disabled
  4510. window->DC.AllowKeyboardFocus = true;
  4511. window->DC.ButtonRepeat = false;
  4512. window->DC.ItemWidthStack.resize(0);
  4513. window->DC.AllowKeyboardFocusStack.resize(0);
  4514. window->DC.ButtonRepeatStack.resize(0);
  4515. window->DC.TextWrapPosStack.resize(0);
  4516. window->DC.ColumnsCurrent = 0;
  4517. window->DC.ColumnsCount = 1;
  4518. window->DC.ColumnsStartPosY = window->DC.CursorPos.y;
  4519. window->DC.ColumnsStartMaxPosX = window->DC.CursorMaxPos.x;
  4520. window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.ColumnsStartPosY;
  4521. window->DC.TreeDepth = 0;
  4522. window->DC.StateStorage = &window->StateStorage;
  4523. window->DC.GroupStack.resize(0);
  4524. window->MenuColumns.Update(3, style.ItemSpacing.x, !window_was_active);
  4525.  
  4526. if (window->AutoFitFramesX > 0)
  4527. window->AutoFitFramesX--;
  4528. if (window->AutoFitFramesY > 0)
  4529. window->AutoFitFramesY--;
  4530.  
  4531. // New windows appears in front (we need to do that AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
  4532. if (!window_was_active && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
  4533. if (!(flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) || (flags & ImGuiWindowFlags_Popup))
  4534. FocusWindow(window);
  4535.  
  4536. // Title bar
  4537. if (!(flags & ImGuiWindowFlags_NoTitleBar))
  4538. {
  4539. // Close button
  4540. if (p_open != NULL)
  4541. {
  4542. const float PAD = 2.0f;
  4543. const float rad = (window->TitleBarHeight() - PAD*2.0f) * 0.5f;
  4544. if (CloseButton(window->GetID("#CLOSE"), window->Rect().GetTR() + ImVec2(-PAD - rad, PAD + rad), rad))
  4545. *p_open = false;
  4546. }
  4547.  
  4548. const ImVec2 text_size = CalcTextSize(name, NULL, true);
  4549. if (!(flags & ImGuiWindowFlags_NoCollapse))
  4550. RenderCollapseTriangle(window->Pos + style.FramePadding, !window->Collapsed, 1.0f);
  4551.  
  4552. ImVec2 text_min = window->Pos;
  4553. ImVec2 text_max = window->Pos + ImVec2(window->Size.x, style.FramePadding.y * 2 + text_size.y);
  4554. ImRect clip_rect;
  4555. clip_rect.Max = ImVec2(window->Pos.x + window->Size.x - (p_open ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x), text_max.y); // Match the size of CloseWindowButton()
  4556. float pad_left = (flags & ImGuiWindowFlags_NoCollapse) == 0 ? (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x) : style.FramePadding.x;
  4557. float pad_right = (p_open != NULL) ? (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x) : style.FramePadding.x;
  4558. if (style.WindowTitleAlign.x > 0.0f) pad_right = ImLerp(pad_right, pad_left, style.WindowTitleAlign.x);
  4559. text_min.x += pad_left;
  4560. text_max.x -= pad_right;
  4561. clip_rect.Min = ImVec2(text_min.x, window->Pos.y);
  4562. RenderTextClipped(text_min, text_max, name, NULL, &text_size, style.WindowTitleAlign, &clip_rect);
  4563. }
  4564.  
  4565. // Save clipped aabb so we can access it in constant-time in FindHoveredWindow()
  4566. window->WindowRectClipped = window->Rect();
  4567. window->WindowRectClipped.ClipWith(window->ClipRect);
  4568.  
  4569. // Pressing CTRL+C while holding on a window copy its content to the clipboard
  4570. // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
  4571. // Maybe we can support CTRL+C on every element?
  4572. /*
  4573. if (g.ActiveId == move_id)
  4574. if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C))
  4575. ImGui::LogToClipboard();
  4576. */
  4577. }
  4578.  
  4579. // Inner clipping rectangle
  4580. // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame
  4581. // Note that if our window is collapsed we will end up with a null clipping rectangle which is the correct behavior.
  4582. const ImRect title_bar_rect = window->TitleBarRect();
  4583. const float border_size = window->BorderSize;
  4584. // Force round to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
  4585. ImRect clip_rect;
  4586. clip_rect.Min.x = ImFloor(0.5f + title_bar_rect.Min.x + ImMax(border_size, ImFloor(window->WindowPadding.x*0.5f)));
  4587. clip_rect.Min.y = ImFloor(0.5f + title_bar_rect.Max.y + window->MenuBarHeight() + border_size);
  4588. clip_rect.Max.x = ImFloor(0.5f + window->Pos.x + window->Size.x - window->ScrollbarSizes.x - ImMax(border_size, ImFloor(window->WindowPadding.x*0.5f)));
  4589. clip_rect.Max.y = ImFloor(0.5f + window->Pos.y + window->Size.y - window->ScrollbarSizes.y - border_size);
  4590. PushClipRect(clip_rect.Min, clip_rect.Max, true);
  4591.  
  4592. // Clear 'accessed' flag last thing
  4593. if (first_begin_of_the_frame)
  4594. window->Accessed = false;
  4595. window->BeginCount++;
  4596. g.SetNextWindowSizeConstraint = false;
  4597.  
  4598. // Child window can be out of sight and have "negative" clip windows.
  4599. // Mark them as collapsed so commands are skipped earlier (we can't manually collapse because they have no title bar).
  4600. if (flags & ImGuiWindowFlags_ChildWindow)
  4601. {
  4602. IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0);
  4603. window->Collapsed = parent_window && parent_window->Collapsed;
  4604.  
  4605. if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
  4606. window->Collapsed |= (window->WindowRectClipped.Min.x >= window->WindowRectClipped.Max.x || window->WindowRectClipped.Min.y >= window->WindowRectClipped.Max.y);
  4607.  
  4608. // We also hide the window from rendering because we've already added its border to the command list.
  4609. // (we could perform the check earlier in the function but it is simpler at this point)
  4610. if (window->Collapsed)
  4611. window->Active = false;
  4612. }
  4613. if (style.Alpha <= 0.0f)
  4614. window->Active = false;
  4615.  
  4616. // Return false if we don't intend to display anything to allow user to perform an early out optimization
  4617. window->SkipItems = (window->Collapsed || !window->Active) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0;
  4618. return !window->SkipItems;
  4619. }
  4620.  
  4621. void ImGui::End()
  4622. {
  4623. ImGuiContext& g = *GImGui;
  4624. ImGuiWindow* window = g.CurrentWindow;
  4625.  
  4626. if (window->DC.ColumnsCount != 1) // close columns set if any is open
  4627. EndColumns();
  4628. PopClipRect(); // inner window clip rectangle
  4629.  
  4630. // Stop logging
  4631. if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging
  4632. LogFinish();
  4633.  
  4634. // Pop
  4635. // NB: we don't clear 'window->RootWindow'. The pointer is allowed to live until the next call to Begin().
  4636. g.CurrentWindowStack.pop_back();
  4637. if (window->Flags & ImGuiWindowFlags_Popup)
  4638. g.CurrentPopupStack.pop_back();
  4639. CheckStacksSize(window, false);
  4640. SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back());
  4641. }
  4642.  
  4643. // Vertical scrollbar
  4644. // The entire piece of code below is rather confusing because:
  4645. // - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab)
  4646. // - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar
  4647. // - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal.
  4648. static void Scrollbar(ImGuiWindow* window, bool horizontal)
  4649. {
  4650. ImGuiContext& g = *GImGui;
  4651. const ImGuiStyle& style = g.Style;
  4652. const ImGuiID id = window->GetID(horizontal ? "#SCROLLX" : "#SCROLLY");
  4653.  
  4654. // Render background
  4655. bool other_scrollbar = (horizontal ? window->ScrollbarY : window->ScrollbarX);
  4656. float other_scrollbar_size_w = other_scrollbar ? style.ScrollbarSize : 0.0f;
  4657. const ImRect window_rect = window->Rect();
  4658. const float border_size = window->BorderSize;
  4659. ImRect bb = horizontal
  4660. ? ImRect(window->Pos.x + border_size, window_rect.Max.y - style.ScrollbarSize, window_rect.Max.x - other_scrollbar_size_w - border_size, window_rect.Max.y - border_size)
  4661. : ImRect(window_rect.Max.x - style.ScrollbarSize, window->Pos.y + border_size, window_rect.Max.x - border_size, window_rect.Max.y - other_scrollbar_size_w - border_size);
  4662. if (!horizontal)
  4663. bb.Min.y += window->TitleBarHeight() + ((window->Flags & ImGuiWindowFlags_MenuBar) ? window->MenuBarHeight() : 0.0f);
  4664. if (bb.GetWidth() <= 0.0f || bb.GetHeight() <= 0.0f)
  4665. return;
  4666.  
  4667. float window_rounding = (window->Flags & ImGuiWindowFlags_ChildWindow) ? style.ChildWindowRounding : style.WindowRounding;
  4668. int window_rounding_corners;
  4669. if (horizontal)
  4670. window_rounding_corners = ImGuiCorner_BotLeft | (other_scrollbar ? 0 : ImGuiCorner_BotRight);
  4671. else
  4672. window_rounding_corners = (((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImGuiCorner_TopRight : 0) | (other_scrollbar ? 0 : ImGuiCorner_BotRight);
  4673. window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_ScrollbarBg), window_rounding, window_rounding_corners);
  4674. bb.Expand(ImVec2(-ImClamp((float)(int)((bb.Max.x - bb.Min.x - 2.0f) * 0.5f), 0.0f, 3.0f), -ImClamp((float)(int)((bb.Max.y - bb.Min.y - 2.0f) * 0.5f), 0.0f, 3.0f)));
  4675.  
  4676. // V denote the main, longer axis of the scrollbar (= height for a vertical scrollbar)
  4677. float scrollbar_size_v = horizontal ? bb.GetWidth() : bb.GetHeight();
  4678. float scroll_v = horizontal ? window->Scroll.x : window->Scroll.y;
  4679. float win_size_avail_v = (horizontal ? window->SizeFull.x : window->SizeFull.y) - other_scrollbar_size_w;
  4680. float win_size_contents_v = horizontal ? window->SizeContents.x : window->SizeContents.y;
  4681.  
  4682. // Calculate the height of our grabbable box. It generally represent the amount visible (vs the total scrollable amount)
  4683. // But we maintain a minimum size in pixel to allow for the user to still aim inside.
  4684. IM_ASSERT(ImMax(win_size_contents_v, win_size_avail_v) > 0.0f); // Adding this assert to check if the ImMax(XXX,1.0f) is still needed. PLEASE CONTACT ME if this triggers.
  4685. const float win_size_v = ImMax(ImMax(win_size_contents_v, win_size_avail_v), 1.0f);
  4686. const float grab_h_pixels = ImClamp(scrollbar_size_v * (win_size_avail_v / win_size_v), style.GrabMinSize, scrollbar_size_v);
  4687. const float grab_h_norm = grab_h_pixels / scrollbar_size_v;
  4688.  
  4689. // Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar().
  4690. bool held = false;
  4691. bool hovered = false;
  4692. const bool previously_held = (g.ActiveId == id);
  4693. ImGui::ButtonBehavior(bb, id, &hovered, &held);
  4694.  
  4695. float scroll_max = ImMax(1.0f, win_size_contents_v - win_size_avail_v);
  4696. float scroll_ratio = ImSaturate(scroll_v / scroll_max);
  4697. float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v;
  4698. if (held && grab_h_norm < 1.0f)
  4699. {
  4700. float scrollbar_pos_v = horizontal ? bb.Min.x : bb.Min.y;
  4701. float mouse_pos_v = horizontal ? g.IO.MousePos.x : g.IO.MousePos.y;
  4702. float* click_delta_to_grab_center_v = horizontal ? &g.ScrollbarClickDeltaToGrabCenter.x : &g.ScrollbarClickDeltaToGrabCenter.y;
  4703.  
  4704. // Click position in scrollbar normalized space (0.0f->1.0f)
  4705. const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v);
  4706. ImGui::SetHoveredID(id);
  4707.  
  4708. bool seek_absolute = false;
  4709. if (!previously_held)
  4710. {
  4711. // On initial click calculate the distance between mouse and the center of the grab
  4712. if (clicked_v_norm >= grab_v_norm && clicked_v_norm <= grab_v_norm + grab_h_norm)
  4713. {
  4714. *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f;
  4715. }
  4716. else
  4717. {
  4718. seek_absolute = true;
  4719. *click_delta_to_grab_center_v = 0.0f;
  4720. }
  4721. }
  4722.  
  4723. // Apply scroll
  4724. // It is ok to modify Scroll here because we are being called in Begin() after the calculation of SizeContents and before setting up our starting position
  4725. const float scroll_v_norm = ImSaturate((clicked_v_norm - *click_delta_to_grab_center_v - grab_h_norm*0.5f) / (1.0f - grab_h_norm));
  4726. scroll_v = (float)(int)(0.5f + scroll_v_norm * scroll_max);//(win_size_contents_v - win_size_v));
  4727. if (horizontal)
  4728. window->Scroll.x = scroll_v;
  4729. else
  4730. window->Scroll.y = scroll_v;
  4731.  
  4732. // Update values for rendering
  4733. scroll_ratio = ImSaturate(scroll_v / scroll_max);
  4734. grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v;
  4735.  
  4736. // Update distance to grab now that we have seeked and saturated
  4737. if (seek_absolute)
  4738. *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f;
  4739. }
  4740.  
  4741. // Render
  4742. const ImU32 grab_col = ImGui::GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab);
  4743. if (horizontal)
  4744. window->DrawList->AddRectFilled(ImVec2(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y), ImVec2(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, bb.Max.y), grab_col, style.ScrollbarRounding);
  4745. else
  4746. window->DrawList->AddRectFilled(ImVec2(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm)), ImVec2(bb.Max.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels), grab_col, style.ScrollbarRounding);
  4747. }
  4748.  
  4749. // Moving window to front of display (which happens to be back of our sorted list)
  4750. void ImGui::FocusWindow(ImGuiWindow* window)
  4751. {
  4752. ImGuiContext& g = *GImGui;
  4753.  
  4754. // Always mark the window we passed as focused. This is used for keyboard interactions such as tabbing.
  4755. g.NavWindow = window;
  4756.  
  4757. // Passing NULL allow to disable keyboard focus
  4758. if (!window)
  4759. return;
  4760.  
  4761. // And move its root window to the top of the pile
  4762. if (window->RootWindow)
  4763. window = window->RootWindow;
  4764.  
  4765. // Steal focus on active widgets
  4766. if (window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement should be unnecessary. Need further testing before removing it..
  4767. if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != window)
  4768. ClearActiveID();
  4769.  
  4770. // Bring to front
  4771. if ((window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) || g.Windows.back() == window)
  4772. return;
  4773. for (int i = 0; i < g.Windows.Size; i++)
  4774. if (g.Windows[i] == window)
  4775. {
  4776. g.Windows.erase(g.Windows.begin() + i);
  4777. break;
  4778. }
  4779. g.Windows.push_back(window);
  4780. }
  4781.  
  4782. void ImGui::PushItemWidth(float item_width)
  4783. {
  4784. ImGuiWindow* window = GetCurrentWindow();
  4785. window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
  4786. window->DC.ItemWidthStack.push_back(window->DC.ItemWidth);
  4787. }
  4788.  
  4789. static void PushMultiItemsWidths(int components, float w_full)
  4790. {
  4791. ImGuiWindow* window = ImGui::GetCurrentWindow();
  4792. const ImGuiStyle& style = GImGui->Style;
  4793. if (w_full <= 0.0f)
  4794. w_full = ImGui::CalcItemWidth();
  4795. const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components));
  4796. const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components - 1)));
  4797. window->DC.ItemWidthStack.push_back(w_item_last);
  4798. for (int i = 0; i < components - 1; i++)
  4799. window->DC.ItemWidthStack.push_back(w_item_one);
  4800. window->DC.ItemWidth = window->DC.ItemWidthStack.back();
  4801. }
  4802.  
  4803. void ImGui::PopItemWidth()
  4804. {
  4805. ImGuiWindow* window = GetCurrentWindow();
  4806. window->DC.ItemWidthStack.pop_back();
  4807. window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back();
  4808. }
  4809.  
  4810. float ImGui::CalcItemWidth()
  4811. {
  4812. ImGuiWindow* window = GetCurrentWindowRead();
  4813. float w = window->DC.ItemWidth;
  4814. if (w < 0.0f)
  4815. {
  4816. // Align to a right-side limit. We include 1 frame padding in the calculation because this is how the width is always used (we add 2 frame padding to it), but we could move that responsibility to the widget as well.
  4817. float width_to_right_edge = GetContentRegionAvail().x;
  4818. w = ImMax(1.0f, width_to_right_edge + w);
  4819. }
  4820. w = (float)(int)w;
  4821. return w;
  4822. }
  4823.  
  4824. static ImFont* GetDefaultFont()
  4825. {
  4826. ImGuiContext& g = *GImGui;
  4827. return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0];
  4828. }
  4829.  
  4830. static void SetCurrentFont(ImFont* font)
  4831. {
  4832. ImGuiContext& g = *GImGui;
  4833. IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
  4834. IM_ASSERT(font->Scale > 0.0f);
  4835. g.Font = font;
  4836. g.FontBaseSize = g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale;
  4837. g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
  4838. g.FontTexUvWhitePixel = g.Font->ContainerAtlas->TexUvWhitePixel;
  4839. }
  4840.  
  4841. void ImGui::PushFont(ImFont* font)
  4842. {
  4843. ImGuiContext& g = *GImGui;
  4844. if (!font)
  4845. font = GetDefaultFont();
  4846. SetCurrentFont(font);
  4847. g.FontStack.push_back(font);
  4848. g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
  4849. }
  4850.  
  4851. void ImGui::PopFont()
  4852. {
  4853. ImGuiContext& g = *GImGui;
  4854. g.CurrentWindow->DrawList->PopTextureID();
  4855. g.FontStack.pop_back();
  4856. SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
  4857. }
  4858.  
  4859. void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
  4860. {
  4861. ImGuiWindow* window = GetCurrentWindow();
  4862. window->DC.AllowKeyboardFocus = allow_keyboard_focus;
  4863. window->DC.AllowKeyboardFocusStack.push_back(allow_keyboard_focus);
  4864. }
  4865.  
  4866. void ImGui::PopAllowKeyboardFocus()
  4867. {
  4868. ImGuiWindow* window = GetCurrentWindow();
  4869. window->DC.AllowKeyboardFocusStack.pop_back();
  4870. window->DC.AllowKeyboardFocus = window->DC.AllowKeyboardFocusStack.empty() ? true : window->DC.AllowKeyboardFocusStack.back();
  4871. }
  4872.  
  4873. void ImGui::PushButtonRepeat(bool repeat)
  4874. {
  4875. ImGuiWindow* window = GetCurrentWindow();
  4876. window->DC.ButtonRepeat = repeat;
  4877. window->DC.ButtonRepeatStack.push_back(repeat);
  4878. }
  4879.  
  4880. void ImGui::PopButtonRepeat()
  4881. {
  4882. ImGuiWindow* window = GetCurrentWindow();
  4883. window->DC.ButtonRepeatStack.pop_back();
  4884. window->DC.ButtonRepeat = window->DC.ButtonRepeatStack.empty() ? false : window->DC.ButtonRepeatStack.back();
  4885. }
  4886.  
  4887. void ImGui::PushTextWrapPos(float wrap_pos_x)
  4888. {
  4889. ImGuiWindow* window = GetCurrentWindow();
  4890. window->DC.TextWrapPos = wrap_pos_x;
  4891. window->DC.TextWrapPosStack.push_back(wrap_pos_x);
  4892. }
  4893.  
  4894. void ImGui::PopTextWrapPos()
  4895. {
  4896. ImGuiWindow* window = GetCurrentWindow();
  4897. window->DC.TextWrapPosStack.pop_back();
  4898. window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back();
  4899. }
  4900.  
  4901. // FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
  4902. void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
  4903. {
  4904. ImGuiContext& g = *GImGui;
  4905. ImGuiColMod backup;
  4906. backup.Col = idx;
  4907. backup.BackupValue = g.Style.Colors[idx];
  4908. g.ColorModifiers.push_back(backup);
  4909. g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
  4910. }
  4911.  
  4912. void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
  4913. {
  4914. ImGuiContext& g = *GImGui;
  4915. ImGuiColMod backup;
  4916. backup.Col = idx;
  4917. backup.BackupValue = g.Style.Colors[idx];
  4918. g.ColorModifiers.push_back(backup);
  4919. g.Style.Colors[idx] = col;
  4920. }
  4921.  
  4922. void ImGui::PopStyleColor(int count)
  4923. {
  4924. ImGuiContext& g = *GImGui;
  4925. while (count > 0)
  4926. {
  4927. ImGuiColMod& backup = g.ColorModifiers.back();
  4928. g.Style.Colors[backup.Col] = backup.BackupValue;
  4929. g.ColorModifiers.pop_back();
  4930. count--;
  4931. }
  4932. }
  4933.  
  4934. struct ImGuiStyleVarInfo
  4935. {
  4936. ImGuiDataType Type;
  4937. ImU32 Offset;
  4938. void* GetVarPtr() const { return (void*)((unsigned char*)&GImGui->Style + Offset); }
  4939. };
  4940.  
  4941. static const ImGuiStyleVarInfo GStyleVarInfo[ImGuiStyleVar_Count_] =
  4942. {
  4943. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
  4944. { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
  4945. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
  4946. { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
  4947. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildWindowRounding) }, // ImGuiStyleVar_ChildWindowRounding
  4948. { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
  4949. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
  4950. { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
  4951. { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
  4952. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
  4953. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
  4954. { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
  4955. };
  4956.  
  4957. static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)
  4958. {
  4959. IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_Count_);
  4960. return &GStyleVarInfo[idx];
  4961. }
  4962.  
  4963. void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
  4964. {
  4965. const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
  4966. if (var_info->Type == ImGuiDataType_Float)
  4967. {
  4968. float* pvar = (float*)var_info->GetVarPtr();
  4969. GImGui->StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
  4970. *pvar = val;
  4971. return;
  4972. }
  4973. IM_ASSERT(0); // Called function with wrong-type? Variable is not a float.
  4974. }
  4975.  
  4976. void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
  4977. {
  4978. const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
  4979. if (var_info->Type == ImGuiDataType_Float2)
  4980. {
  4981. ImVec2* pvar = (ImVec2*)var_info->GetVarPtr();
  4982. GImGui->StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
  4983. *pvar = val;
  4984. return;
  4985. }
  4986. IM_ASSERT(0); // Called function with wrong-type? Variable is not a ImVec2.
  4987. }
  4988.  
  4989. void ImGui::PopStyleVar(int count)
  4990. {
  4991. ImGuiContext& g = *GImGui;
  4992. while (count > 0)
  4993. {
  4994. ImGuiStyleMod& backup = g.StyleModifiers.back();
  4995. const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx);
  4996. if (info->Type == ImGuiDataType_Float) (*(float*)info->GetVarPtr()) = backup.BackupFloat[0];
  4997. else if (info->Type == ImGuiDataType_Float2) (*(ImVec2*)info->GetVarPtr()) = ImVec2(backup.BackupFloat[0], backup.BackupFloat[1]);
  4998. else if (info->Type == ImGuiDataType_Int) (*(int*)info->GetVarPtr()) = backup.BackupInt[0];
  4999. g.StyleModifiers.pop_back();
  5000. count--;
  5001. }
  5002. }
  5003.  
  5004. const char* ImGui::GetStyleColorName(ImGuiCol idx)
  5005. {
  5006. // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
  5007. switch (idx)
  5008. {
  5009. case ImGuiCol_Text: return "Text";
  5010. case ImGuiCol_TextDisabled: return "TextDisabled";
  5011. case ImGuiCol_WindowBg: return "WindowBg";
  5012. case ImGuiCol_ChildWindowBg: return "ChildWindowBg";
  5013. case ImGuiCol_PopupBg: return "PopupBg";
  5014. case ImGuiCol_Border: return "Border";
  5015. case ImGuiCol_BorderShadow: return "BorderShadow";
  5016. case ImGuiCol_FrameBg: return "FrameBg";
  5017. case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
  5018. case ImGuiCol_FrameBgActive: return "FrameBgActive";
  5019. case ImGuiCol_TitleBg: return "TitleBg";
  5020. case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
  5021. case ImGuiCol_TitleBgActive: return "TitleBgActive";
  5022. case ImGuiCol_MenuBarBg: return "MenuBarBg";
  5023. case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
  5024. case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
  5025. case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
  5026. case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
  5027. case ImGuiCol_ComboBg: return "ComboBg";
  5028. case ImGuiCol_CheckMark: return "CheckMark";
  5029. case ImGuiCol_SliderGrab: return "SliderGrab";
  5030. case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
  5031. case ImGuiCol_Button: return "Button";
  5032. case ImGuiCol_ButtonHovered: return "ButtonHovered";
  5033. case ImGuiCol_ButtonActive: return "ButtonActive";
  5034. case ImGuiCol_Header: return "Header";
  5035. case ImGuiCol_HeaderHovered: return "HeaderHovered";
  5036. case ImGuiCol_HeaderActive: return "HeaderActive";
  5037. case ImGuiCol_Separator: return "Separator";
  5038. case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
  5039. case ImGuiCol_SeparatorActive: return "SeparatorActive";
  5040. case ImGuiCol_ResizeGrip: return "ResizeGrip";
  5041. case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
  5042. case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
  5043. case ImGuiCol_CloseButton: return "CloseButton";
  5044. case ImGuiCol_CloseButtonHovered: return "CloseButtonHovered";
  5045. case ImGuiCol_CloseButtonActive: return "CloseButtonActive";
  5046. case ImGuiCol_PlotLines: return "PlotLines";
  5047. case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
  5048. case ImGuiCol_PlotHistogram: return "PlotHistogram";
  5049. case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
  5050. case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
  5051. case ImGuiCol_ModalWindowDarkening: return "ModalWindowDarkening";
  5052. }
  5053. IM_ASSERT(0);
  5054. return "Unknown";
  5055. }
  5056.  
  5057. bool ImGui::IsWindowHovered()
  5058. {
  5059. ImGuiContext& g = *GImGui;
  5060. return g.HoveredWindow == g.CurrentWindow && IsWindowContentHoverable(g.HoveredRootWindow);
  5061. }
  5062.  
  5063. bool ImGui::IsWindowRectHovered()
  5064. {
  5065. ImGuiContext& g = *GImGui;
  5066. return g.HoveredWindow == g.CurrentWindow;
  5067. }
  5068.  
  5069. bool ImGui::IsWindowFocused()
  5070. {
  5071. ImGuiContext& g = *GImGui;
  5072. return g.NavWindow == g.CurrentWindow;
  5073. }
  5074.  
  5075. bool ImGui::IsRootWindowFocused()
  5076. {
  5077. ImGuiContext& g = *GImGui;
  5078. return g.NavWindow == g.CurrentWindow->RootWindow;
  5079. }
  5080.  
  5081. bool ImGui::IsRootWindowOrAnyChildFocused()
  5082. {
  5083. ImGuiContext& g = *GImGui;
  5084. return g.NavWindow && g.NavWindow->RootWindow == g.CurrentWindow->RootWindow;
  5085. }
  5086.  
  5087. bool ImGui::IsRootWindowOrAnyChildHovered()
  5088. {
  5089. ImGuiContext& g = *GImGui;
  5090. return g.HoveredRootWindow && (g.HoveredRootWindow == g.CurrentWindow->RootWindow) && IsWindowContentHoverable(g.HoveredRootWindow);
  5091. }
  5092.  
  5093. float ImGui::GetWindowWidth()
  5094. {
  5095. ImGuiWindow* window = GImGui->CurrentWindow;
  5096. return window->Size.x;
  5097. }
  5098.  
  5099. float ImGui::GetWindowHeight()
  5100. {
  5101. ImGuiWindow* window = GImGui->CurrentWindow;
  5102. return window->Size.y;
  5103. }
  5104.  
  5105. ImVec2 ImGui::GetWindowPos()
  5106. {
  5107. ImGuiContext& g = *GImGui;
  5108. ImGuiWindow* window = g.CurrentWindow;
  5109. return window->Pos;
  5110. }
  5111.  
  5112. static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y)
  5113. {
  5114. window->DC.CursorMaxPos.y += window->Scroll.y; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it.
  5115. window->Scroll.y = new_scroll_y;
  5116. window->DC.CursorMaxPos.y -= window->Scroll.y;
  5117. }
  5118.  
  5119. static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
  5120. {
  5121. // Test condition (NB: bit 0 is always true) and clear flags for next time
  5122. if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
  5123. return;
  5124. window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  5125. window->SetWindowPosCenterWanted = false;
  5126.  
  5127. // Set
  5128. const ImVec2 old_pos = window->Pos;
  5129. window->PosFloat = pos;
  5130. window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
  5131. window->DC.CursorPos += (window->Pos - old_pos); // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
  5132. window->DC.CursorMaxPos += (window->Pos - old_pos); // And more importantly we need to adjust this so size calculation doesn't get affected.
  5133. }
  5134.  
  5135. void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
  5136. {
  5137. ImGuiWindow* window = GetCurrentWindowRead();
  5138. SetWindowPos(window, pos, cond);
  5139. }
  5140.  
  5141. void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
  5142. {
  5143. if (ImGuiWindow* window = FindWindowByName(name))
  5144. SetWindowPos(window, pos, cond);
  5145. }
  5146.  
  5147. ImVec2 ImGui::GetWindowSize()
  5148. {
  5149. ImGuiWindow* window = GetCurrentWindowRead();
  5150. return window->Size;
  5151. }
  5152.  
  5153. static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
  5154. {
  5155. // Test condition (NB: bit 0 is always true) and clear flags for next time
  5156. if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
  5157. return;
  5158. window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  5159.  
  5160. // Set
  5161. if (size.x > 0.0f)
  5162. {
  5163. window->AutoFitFramesX = 0;
  5164. window->SizeFull.x = size.x;
  5165. }
  5166. else
  5167. {
  5168. window->AutoFitFramesX = 2;
  5169. window->AutoFitOnlyGrows = false;
  5170. }
  5171. if (size.y > 0.0f)
  5172. {
  5173. window->AutoFitFramesY = 0;
  5174. window->SizeFull.y = size.y;
  5175. }
  5176. else
  5177. {
  5178. window->AutoFitFramesY = 2;
  5179. window->AutoFitOnlyGrows = false;
  5180. }
  5181. }
  5182.  
  5183. void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
  5184. {
  5185. SetWindowSize(GImGui->CurrentWindow, size, cond);
  5186. }
  5187.  
  5188. void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
  5189. {
  5190. ImGuiWindow* window = FindWindowByName(name);
  5191. if (window)
  5192. SetWindowSize(window, size, cond);
  5193. }
  5194.  
  5195. static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
  5196. {
  5197. // Test condition (NB: bit 0 is always true) and clear flags for next time
  5198. if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
  5199. return;
  5200. window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
  5201.  
  5202. // Set
  5203. window->Collapsed = collapsed;
  5204. }
  5205.  
  5206. void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
  5207. {
  5208. SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
  5209. }
  5210.  
  5211. bool ImGui::IsWindowCollapsed()
  5212. {
  5213. return GImGui->CurrentWindow->Collapsed;
  5214. }
  5215.  
  5216. void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
  5217. {
  5218. ImGuiWindow* window = FindWindowByName(name);
  5219. if (window)
  5220. SetWindowCollapsed(window, collapsed, cond);
  5221. }
  5222.  
  5223. void ImGui::SetWindowFocus()
  5224. {
  5225. FocusWindow(GImGui->CurrentWindow);
  5226. }
  5227.  
  5228. void ImGui::SetWindowFocus(const char* name)
  5229. {
  5230. if (name)
  5231. {
  5232. if (ImGuiWindow* window = FindWindowByName(name))
  5233. FocusWindow(window);
  5234. }
  5235. else
  5236. {
  5237. FocusWindow(NULL);
  5238. }
  5239. }
  5240.  
  5241. void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond)
  5242. {
  5243. ImGuiContext& g = *GImGui;
  5244. g.SetNextWindowPosVal = pos;
  5245. g.SetNextWindowPosCond = cond ? cond : ImGuiCond_Always;
  5246. }
  5247.  
  5248. void ImGui::SetNextWindowPosCenter(ImGuiCond cond)
  5249. {
  5250. ImGuiContext& g = *GImGui;
  5251. g.SetNextWindowPosVal = ImVec2(-FLT_MAX, -FLT_MAX);
  5252. g.SetNextWindowPosCond = cond ? cond : ImGuiCond_Always;
  5253. }
  5254.  
  5255. void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
  5256. {
  5257. ImGuiContext& g = *GImGui;
  5258. g.SetNextWindowSizeVal = size;
  5259. g.SetNextWindowSizeCond = cond ? cond : ImGuiCond_Always;
  5260. }
  5261.  
  5262. void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeConstraintCallback custom_callback, void* custom_callback_user_data)
  5263. {
  5264. ImGuiContext& g = *GImGui;
  5265. g.SetNextWindowSizeConstraint = true;
  5266. g.SetNextWindowSizeConstraintRect = ImRect(size_min, size_max);
  5267. g.SetNextWindowSizeConstraintCallback = custom_callback;
  5268. g.SetNextWindowSizeConstraintCallbackUserData = custom_callback_user_data;
  5269. }
  5270.  
  5271. void ImGui::SetNextWindowContentSize(const ImVec2& size)
  5272. {
  5273. ImGuiContext& g = *GImGui;
  5274. g.SetNextWindowContentSizeVal = size;
  5275. g.SetNextWindowContentSizeCond = ImGuiCond_Always;
  5276. }
  5277.  
  5278. void ImGui::SetNextWindowContentWidth(float width)
  5279. {
  5280. ImGuiContext& g = *GImGui;
  5281. g.SetNextWindowContentSizeVal = ImVec2(width, g.SetNextWindowContentSizeCond ? g.SetNextWindowContentSizeVal.y : 0.0f);
  5282. g.SetNextWindowContentSizeCond = ImGuiCond_Always;
  5283. }
  5284.  
  5285. void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
  5286. {
  5287. ImGuiContext& g = *GImGui;
  5288. g.SetNextWindowCollapsedVal = collapsed;
  5289. g.SetNextWindowCollapsedCond = cond ? cond : ImGuiCond_Always;
  5290. }
  5291.  
  5292. void ImGui::SetNextWindowFocus()
  5293. {
  5294. ImGuiContext& g = *GImGui;
  5295. g.SetNextWindowFocus = true;
  5296. }
  5297.  
  5298. // In window space (not screen space!)
  5299. ImVec2 ImGui::GetContentRegionMax()
  5300. {
  5301. ImGuiWindow* window = GetCurrentWindowRead();
  5302. ImVec2 mx = window->ContentsRegionRect.Max;
  5303. if (window->DC.ColumnsCount != 1)
  5304. mx.x = GetColumnOffset(window->DC.ColumnsCurrent + 1) - window->WindowPadding.x;
  5305. return mx;
  5306. }
  5307.  
  5308. ImVec2 ImGui::GetContentRegionAvail()
  5309. {
  5310. ImGuiWindow* window = GetCurrentWindowRead();
  5311. return GetContentRegionMax() - (window->DC.CursorPos - window->Pos);
  5312. }
  5313.  
  5314. float ImGui::GetContentRegionAvailWidth()
  5315. {
  5316. return GetContentRegionAvail().x;
  5317. }
  5318.  
  5319. // In window space (not screen space!)
  5320. ImVec2 ImGui::GetWindowContentRegionMin()
  5321. {
  5322. ImGuiWindow* window = GetCurrentWindowRead();
  5323. return window->ContentsRegionRect.Min;
  5324. }
  5325.  
  5326. ImVec2 ImGui::GetWindowContentRegionMax()
  5327. {
  5328. ImGuiWindow* window = GetCurrentWindowRead();
  5329. return window->ContentsRegionRect.Max;
  5330. }
  5331.  
  5332. float ImGui::GetWindowContentRegionWidth()
  5333. {
  5334. ImGuiWindow* window = GetCurrentWindowRead();
  5335. return window->ContentsRegionRect.Max.x - window->ContentsRegionRect.Min.x;
  5336. }
  5337.  
  5338. float ImGui::GetTextLineHeight()
  5339. {
  5340. ImGuiContext& g = *GImGui;
  5341. return g.FontSize;
  5342. }
  5343.  
  5344. float ImGui::GetTextLineHeightWithSpacing()
  5345. {
  5346. ImGuiContext& g = *GImGui;
  5347. return g.FontSize + g.Style.ItemSpacing.y;
  5348. }
  5349.  
  5350. float ImGui::GetItemsLineHeightWithSpacing()
  5351. {
  5352. ImGuiContext& g = *GImGui;
  5353. return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
  5354. }
  5355.  
  5356. ImDrawList* ImGui::GetWindowDrawList()
  5357. {
  5358. ImGuiWindow* window = GetCurrentWindow();
  5359. return window->DrawList;
  5360. }
  5361.  
  5362. ImFont* ImGui::GetFont()
  5363. {
  5364. return GImGui->Font;
  5365. }
  5366.  
  5367. float ImGui::GetFontSize()
  5368. {
  5369. return GImGui->FontSize;
  5370. }
  5371.  
  5372. ImVec2 ImGui::GetFontTexUvWhitePixel()
  5373. {
  5374. return GImGui->FontTexUvWhitePixel;
  5375. }
  5376.  
  5377. void ImGui::SetWindowFontScale(float scale)
  5378. {
  5379. ImGuiContext& g = *GImGui;
  5380. ImGuiWindow* window = GetCurrentWindow();
  5381. window->FontWindowScale = scale;
  5382. g.FontSize = window->CalcFontSize();
  5383. }
  5384.  
  5385. // User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
  5386. // Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
  5387. ImVec2 ImGui::GetCursorPos()
  5388. {
  5389. ImGuiWindow* window = GetCurrentWindowRead();
  5390. return window->DC.CursorPos - window->Pos + window->Scroll;
  5391. }
  5392.  
  5393. float ImGui::GetCursorPosX()
  5394. {
  5395. ImGuiWindow* window = GetCurrentWindowRead();
  5396. return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
  5397. }
  5398.  
  5399. float ImGui::GetCursorPosY()
  5400. {
  5401. ImGuiWindow* window = GetCurrentWindowRead();
  5402. return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
  5403. }
  5404.  
  5405. void ImGui::SetCursorPos(const ImVec2& local_pos)
  5406. {
  5407. ImGuiWindow* window = GetCurrentWindow();
  5408. window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
  5409. window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
  5410. }
  5411.  
  5412. void ImGui::SetCursorPosX(float x)
  5413. {
  5414. ImGuiWindow* window = GetCurrentWindow();
  5415. window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
  5416. window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
  5417. }
  5418.  
  5419. void ImGui::SetCursorPosY(float y)
  5420. {
  5421. ImGuiWindow* window = GetCurrentWindow();
  5422. window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
  5423. window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
  5424. }
  5425.  
  5426. ImVec2 ImGui::GetCursorStartPos()
  5427. {
  5428. ImGuiWindow* window = GetCurrentWindowRead();
  5429. return window->DC.CursorStartPos - window->Pos;
  5430. }
  5431.  
  5432. ImVec2 ImGui::GetCursorScreenPos()
  5433. {
  5434. ImGuiWindow* window = GetCurrentWindowRead();
  5435. return window->DC.CursorPos;
  5436. }
  5437.  
  5438. void ImGui::SetCursorScreenPos(const ImVec2& screen_pos)
  5439. {
  5440. ImGuiWindow* window = GetCurrentWindow();
  5441. window->DC.CursorPos = screen_pos;
  5442. window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
  5443. }
  5444.  
  5445. float ImGui::GetScrollX()
  5446. {
  5447. return GImGui->CurrentWindow->Scroll.x;
  5448. }
  5449.  
  5450. float ImGui::GetScrollY()
  5451. {
  5452. return GImGui->CurrentWindow->Scroll.y;
  5453. }
  5454.  
  5455. float ImGui::GetScrollMaxX()
  5456. {
  5457. ImGuiWindow* window = GetCurrentWindowRead();
  5458. return ImMax(0.0f, window->SizeContents.x - (window->SizeFull.x - window->ScrollbarSizes.x));
  5459. }
  5460.  
  5461. float ImGui::GetScrollMaxY()
  5462. {
  5463. ImGuiWindow* window = GetCurrentWindowRead();
  5464. return ImMax(0.0f, window->SizeContents.y - (window->SizeFull.y - window->ScrollbarSizes.y));
  5465. }
  5466.  
  5467. void ImGui::SetScrollX(float scroll_x)
  5468. {
  5469. ImGuiWindow* window = GetCurrentWindow();
  5470. window->ScrollTarget.x = scroll_x;
  5471. window->ScrollTargetCenterRatio.x = 0.0f;
  5472. }
  5473.  
  5474. void ImGui::SetScrollY(float scroll_y)
  5475. {
  5476. ImGuiWindow* window = GetCurrentWindow();
  5477. window->ScrollTarget.y = scroll_y + window->TitleBarHeight() + window->MenuBarHeight(); // title bar height canceled out when using ScrollTargetRelY
  5478. window->ScrollTargetCenterRatio.y = 0.0f;
  5479. }
  5480.  
  5481. void ImGui::SetScrollFromPosY(float pos_y, float center_y_ratio)
  5482. {
  5483. // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size
  5484. ImGuiWindow* window = GetCurrentWindow();
  5485. IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
  5486. window->ScrollTarget.y = (float)(int)(pos_y + window->Scroll.y);
  5487. if (center_y_ratio <= 0.0f && window->ScrollTarget.y <= window->WindowPadding.y) // Minor hack to make "scroll to top" take account of WindowPadding, else it would scroll to (WindowPadding.y - ItemSpacing.y)
  5488. window->ScrollTarget.y = 0.0f;
  5489. window->ScrollTargetCenterRatio.y = center_y_ratio;
  5490. }
  5491.  
  5492. // center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
  5493. void ImGui::SetScrollHere(float center_y_ratio)
  5494. {
  5495. ImGuiWindow* window = GetCurrentWindow();
  5496. float target_y = window->DC.CursorPosPrevLine.y - window->Pos.y; // Top of last item, in window space
  5497. target_y += (window->DC.PrevLineHeight * center_y_ratio) + (GImGui->Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line.
  5498. SetScrollFromPosY(target_y, center_y_ratio);
  5499. }
  5500.  
  5501. void ImGui::SetKeyboardFocusHere(int offset)
  5502. {
  5503. ImGuiWindow* window = GetCurrentWindow();
  5504. window->FocusIdxAllRequestNext = window->FocusIdxAllCounter + 1 + offset;
  5505. window->FocusIdxTabRequestNext = INT_MAX;
  5506. }
  5507.  
  5508. void ImGui::SetStateStorage(ImGuiStorage* tree)
  5509. {
  5510. ImGuiWindow* window = GetCurrentWindow();
  5511. window->DC.StateStorage = tree ? tree : &window->StateStorage;
  5512. }
  5513.  
  5514. ImGuiStorage* ImGui::GetStateStorage()
  5515. {
  5516. ImGuiWindow* window = GetCurrentWindowRead();
  5517. return window->DC.StateStorage;
  5518. }
  5519.  
  5520. void ImGui::TextV(const char* fmt, va_list args)
  5521. {
  5522. ImGuiWindow* window = GetCurrentWindow();
  5523. if (window->SkipItems)
  5524. return;
  5525.  
  5526. ImGuiContext& g = *GImGui;
  5527. const char* text_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
  5528. TextUnformatted(g.TempBuffer, text_end);
  5529. }
  5530.  
  5531. void ImGui::Text(const char* fmt, ...)
  5532. {
  5533. va_list args;
  5534. va_start(args, fmt);
  5535. TextV(fmt, args);
  5536. va_end(args);
  5537. }
  5538.  
  5539. void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args)
  5540. {
  5541. PushStyleColor(ImGuiCol_Text, col);
  5542. TextV(fmt, args);
  5543. PopStyleColor();
  5544. }
  5545.  
  5546. void ImGui::TextColored(const ImVec4& col, const char* fmt, ...)
  5547. {
  5548. va_list args;
  5549. va_start(args, fmt);
  5550. TextColoredV(col, fmt, args);
  5551. va_end(args);
  5552. }
  5553.  
  5554. void ImGui::TextDisabledV(const char* fmt, va_list args)
  5555. {
  5556. PushStyleColor(ImGuiCol_Text, GImGui->Style.Colors[ImGuiCol_TextDisabled]);
  5557. TextV(fmt, args);
  5558. PopStyleColor();
  5559. }
  5560.  
  5561. void ImGui::TextDisabled(const char* fmt, ...)
  5562. {
  5563. va_list args;
  5564. va_start(args, fmt);
  5565. TextDisabledV(fmt, args);
  5566. va_end(args);
  5567. }
  5568.  
  5569. void ImGui::TextWrappedV(const char* fmt, va_list args)
  5570. {
  5571. bool need_wrap = (GImGui->CurrentWindow->DC.TextWrapPos < 0.0f); // Keep existing wrap position is one ia already set
  5572. if (need_wrap) PushTextWrapPos(0.0f);
  5573. TextV(fmt, args);
  5574. if (need_wrap) PopTextWrapPos();
  5575. }
  5576.  
  5577. void ImGui::TextWrapped(const char* fmt, ...)
  5578. {
  5579. va_list args;
  5580. va_start(args, fmt);
  5581. TextWrappedV(fmt, args);
  5582. va_end(args);
  5583. }
  5584.  
  5585. void ImGui::TextUnformatted(const char* text, const char* text_end)
  5586. {
  5587. ImGuiWindow* window = GetCurrentWindow();
  5588. if (window->SkipItems)
  5589. return;
  5590.  
  5591. ImGuiContext& g = *GImGui;
  5592. IM_ASSERT(text != NULL);
  5593. const char* text_begin = text;
  5594. if (text_end == NULL)
  5595. text_end = text + strlen(text); // FIXME-OPT
  5596.  
  5597. const float wrap_pos_x = window->DC.TextWrapPos;
  5598. const bool wrap_enabled = wrap_pos_x >= 0.0f;
  5599. if (text_end - text > 2000 && !wrap_enabled)
  5600. {
  5601. // Long text!
  5602. // Perform manual coarse clipping to optimize for long multi-line text
  5603. // From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled.
  5604. // We also don't vertically center the text within the line full height, which is unlikely to matter because we are likely the biggest and only item on the line.
  5605. const char* line = text;
  5606. const float line_height = GetTextLineHeight();
  5607. const ImVec2 text_pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrentLineTextBaseOffset);
  5608. const ImRect clip_rect = window->ClipRect;
  5609. ImVec2 text_size(0, 0);
  5610.  
  5611. if (text_pos.y <= clip_rect.Max.y)
  5612. {
  5613. ImVec2 pos = text_pos;
  5614.  
  5615. // Lines to skip (can't skip when logging text)
  5616. if (!g.LogEnabled)
  5617. {
  5618. int lines_skippable = (int)((clip_rect.Min.y - text_pos.y) / line_height);
  5619. if (lines_skippable > 0)
  5620. {
  5621. int lines_skipped = 0;
  5622. while (line < text_end && lines_skipped < lines_skippable)
  5623. {
  5624. const char* line_end = strchr(line, '\n');
  5625. if (!line_end)
  5626. line_end = text_end;
  5627. line = line_end + 1;
  5628. lines_skipped++;
  5629. }
  5630. pos.y += lines_skipped * line_height;
  5631. }
  5632. }
  5633.  
  5634. // Lines to render
  5635. if (line < text_end)
  5636. {
  5637. ImRect line_rect(pos, pos + ImVec2(FLT_MAX, line_height));
  5638. while (line < text_end)
  5639. {
  5640. const char* line_end = strchr(line, '\n');
  5641. if (IsClippedEx(line_rect, NULL, false))
  5642. break;
  5643.  
  5644. const ImVec2 line_size = CalcTextSize(line, line_end, false);
  5645. text_size.x = ImMax(text_size.x, line_size.x);
  5646. RenderText(pos, line, line_end, false);
  5647. if (!line_end)
  5648. line_end = text_end;
  5649. line = line_end + 1;
  5650. line_rect.Min.y += line_height;
  5651. line_rect.Max.y += line_height;
  5652. pos.y += line_height;
  5653. }
  5654.  
  5655. // Count remaining lines
  5656. int lines_skipped = 0;
  5657. while (line < text_end)
  5658. {
  5659. const char* line_end = strchr(line, '\n');
  5660. if (!line_end)
  5661. line_end = text_end;
  5662. line = line_end + 1;
  5663. lines_skipped++;
  5664. }
  5665. pos.y += lines_skipped * line_height;
  5666. }
  5667.  
  5668. text_size.y += (pos - text_pos).y;
  5669. }
  5670.  
  5671. ImRect bb(text_pos, text_pos + text_size);
  5672. ItemSize(bb);
  5673. ItemAdd(bb, NULL);
  5674. }
  5675. else
  5676. {
  5677. const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f;
  5678. const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width);
  5679.  
  5680. // Account of baseline offset
  5681. ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrentLineTextBaseOffset);
  5682. ImRect bb(text_pos, text_pos + text_size);
  5683. ItemSize(text_size);
  5684. if (!ItemAdd(bb, NULL))
  5685. return;
  5686.  
  5687. // Render (we don't hide text after ## in this end-user function)
  5688. RenderTextWrapped(bb.Min, text_begin, text_end, wrap_width);
  5689. }
  5690. }
  5691.  
  5692. void ImGui::AlignFirstTextHeightToWidgets()
  5693. {
  5694. ImGuiWindow* window = GetCurrentWindow();
  5695. if (window->SkipItems)
  5696. return;
  5697.  
  5698. // Declare a dummy item size to that upcoming items that are smaller will center-align on the newly expanded line height.
  5699. ImGuiContext& g = *GImGui;
  5700. ItemSize(ImVec2(0, g.FontSize + g.Style.FramePadding.y * 2), g.Style.FramePadding.y);
  5701. SameLine(0, 0);
  5702. }
  5703.  
  5704. // Add a label+text combo aligned to other label+value widgets
  5705. void ImGui::LabelTextV(const char* label, const char* fmt, va_list args)
  5706. {
  5707. ImGuiWindow* window = GetCurrentWindow();
  5708. if (window->SkipItems)
  5709. return;
  5710.  
  5711. ImGuiContext& g = *GImGui;
  5712. const ImGuiStyle& style = g.Style;
  5713. const float w = CalcItemWidth();
  5714.  
  5715. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  5716. const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2));
  5717. const ImRect total_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + (label_size.x > 0.0f ? style.ItemInnerSpacing.x : 0.0f), style.FramePadding.y * 2) + label_size);
  5718. ItemSize(total_bb, style.FramePadding.y);
  5719. if (!ItemAdd(total_bb, NULL))
  5720. return;
  5721.  
  5722. // Render
  5723. const char* value_text_begin = &g.TempBuffer[0];
  5724. const char* value_text_end = value_text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
  5725. RenderTextClipped(value_bb.Min, value_bb.Max, value_text_begin, value_text_end, NULL, ImVec2(0.0f, 0.5f));
  5726. if (label_size.x > 0.0f)
  5727. RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label);
  5728. }
  5729.  
  5730. void ImGui::LabelText(const char* label, const char* fmt, ...)
  5731. {
  5732. va_list args;
  5733. va_start(args, fmt);
  5734. LabelTextV(label, fmt, args);
  5735. va_end(args);
  5736. }
  5737.  
  5738. static inline bool IsWindowContentHoverable(ImGuiWindow* window)
  5739. {
  5740. // An active popup disable hovering on other windows (apart from its own children)
  5741. // FIXME-OPT: This could be cached/stored within the window.
  5742. ImGuiContext& g = *GImGui;
  5743. if (g.NavWindow)
  5744. if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindow)
  5745. if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) != 0 && focused_root_window->WasActive && focused_root_window != window->RootWindow)
  5746. return false;
  5747.  
  5748. return true;
  5749. }
  5750.  
  5751. bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags)
  5752. {
  5753. ImGuiContext& g = *GImGui;
  5754. ImGuiWindow* window = GetCurrentWindow();
  5755.  
  5756. if (flags & ImGuiButtonFlags_Disabled)
  5757. {
  5758. if (out_hovered) *out_hovered = false;
  5759. if (out_held) *out_held = false;
  5760. if (g.ActiveId == id) ClearActiveID();
  5761. return false;
  5762. }
  5763.  
  5764. // Default behavior requires click+release on same spot
  5765. if ((flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick)) == 0)
  5766. flags |= ImGuiButtonFlags_PressedOnClickRelease;
  5767.  
  5768. bool pressed = false;
  5769. bool hovered = IsHovered(bb, id, (flags & ImGuiButtonFlags_FlattenChilds) != 0);
  5770. if (hovered)
  5771. {
  5772. SetHoveredID(id);
  5773. if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt))
  5774. {
  5775. // | CLICKING | HOLDING with ImGuiButtonFlags_Repeat
  5776. // PressedOnClickRelease | <on release>* | <on repeat> <on repeat> .. (NOT on release) <-- MOST COMMON! (*) only if both click/release were over bounds
  5777. // PressedOnClick | <on click> | <on click> <on repeat> <on repeat> ..
  5778. // PressedOnRelease | <on release> | <on repeat> <on repeat> .. (NOT on release)
  5779. // PressedOnDoubleClick | <on dclick> | <on dclick> <on repeat> <on repeat> ..
  5780. if ((flags & ImGuiButtonFlags_PressedOnClickRelease) && g.IO.MouseClicked[0])
  5781. {
  5782. SetActiveID(id, window); // Hold on ID
  5783. FocusWindow(window);
  5784. g.ActiveIdClickOffset = g.IO.MousePos - bb.Min;
  5785. }
  5786. if (((flags & ImGuiButtonFlags_PressedOnClick) && g.IO.MouseClicked[0]) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDoubleClicked[0]))
  5787. {
  5788. pressed = true;
  5789. ClearActiveID();
  5790. FocusWindow(window);
  5791. }
  5792. if ((flags & ImGuiButtonFlags_PressedOnRelease) && g.IO.MouseReleased[0])
  5793. {
  5794. if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps <on release>
  5795. pressed = true;
  5796. ClearActiveID();
  5797. }
  5798.  
  5799. // 'Repeat' mode acts when held regardless of _PressedOn flags (see table above).
  5800. // Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings.
  5801. if ((flags & ImGuiButtonFlags_Repeat) && g.ActiveId == id && g.IO.MouseDownDuration[0] > 0.0f && IsMouseClicked(0, true))
  5802. pressed = true;
  5803. }
  5804. }
  5805.  
  5806. bool held = false;
  5807. if (g.ActiveId == id)
  5808. {
  5809. if (g.IO.MouseDown[0])
  5810. {
  5811. held = true;
  5812. }
  5813. else
  5814. {
  5815. if (hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease))
  5816. if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps <on release>
  5817. pressed = true;
  5818. ClearActiveID();
  5819. }
  5820. }
  5821.  
  5822. // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match. This allows using patterns where a later submitted widget overlaps a previous one.
  5823. if (hovered && (flags & ImGuiButtonFlags_AllowOverlapMode) && (g.HoveredIdPreviousFrame != id && g.HoveredIdPreviousFrame != 0))
  5824. hovered = pressed = held = false;
  5825.  
  5826. if (out_hovered) *out_hovered = hovered;
  5827. if (out_held) *out_held = held;
  5828.  
  5829. return pressed;
  5830. }
  5831.  
  5832. bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags, bool tab, bool selected)
  5833. {
  5834. ImGuiWindow* window = GetCurrentWindow();
  5835. if (window->SkipItems)
  5836. return false;
  5837.  
  5838. ImGuiContext& g = *GImGui;
  5839. const ImGuiStyle& style = g.Style;
  5840. const ImGuiID id = window->GetID(label);
  5841. const ImVec2 label_size = CalcTextSize(label, NULL, true, -1.0F);
  5842.  
  5843. ImVec2 pos = window->DC.CursorPos;
  5844. if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrentLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag)
  5845. pos.y += window->DC.CurrentLineTextBaseOffset - style.FramePadding.y;
  5846. ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f);
  5847.  
  5848. const ImRect bb(pos, pos + size);
  5849. ItemSize(bb, style.FramePadding.y);
  5850. if (!ItemAdd(bb, &id))
  5851. return false;
  5852.  
  5853. if (window->DC.ButtonRepeat) flags |= ImGuiButtonFlags_Repeat;
  5854. bool hovered, held;
  5855. bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
  5856.  
  5857. // Render
  5858. ImU32 col;
  5859. if (tab)
  5860. col = GetColorU32(selected ? ImGuiCol_TabSelected : ((hovered && held) ? ImGuiCol_TabActive : hovered ? ImGuiCol_TabHovered : ImGuiCol_Tab));
  5861. else
  5862. col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
  5863. //if (tab) RenderFrame(ImVec2(bb.Min.x - 3, bb.Min.y - 3), ImVec2(bb.Max.x + 3, bb.Max.y + 3), GetColorU32(ImVec4(0, 0, 0, 1)), true, style.FrameRounding);
  5864. RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
  5865. RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb, tab, selected);
  5866.  
  5867. // Automatically close popups
  5868. //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
  5869. // CloseCurrentPopup();
  5870.  
  5871. return pressed;
  5872. }
  5873.  
  5874. bool ImGui::Button(const char* label, const ImVec2& size_arg)
  5875. {
  5876. return ButtonEx(label, size_arg, 0);
  5877. }
  5878.  
  5879. // Small buttons fits within text without additional vertical spacing.
  5880. bool ImGui::SmallButton(const char* label)
  5881. {
  5882. ImGuiContext& g = *GImGui;
  5883. float backup_padding_y = g.Style.FramePadding.y;
  5884. g.Style.FramePadding.y = 0.0f;
  5885. bool pressed = ButtonEx(label, ImVec2(0, 0), ImGuiButtonFlags_AlignTextBaseLine);
  5886. g.Style.FramePadding.y = backup_padding_y;
  5887. return pressed;
  5888. }
  5889.  
  5890. // Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack.
  5891. // Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id)
  5892. bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg)
  5893. {
  5894. ImGuiWindow* window = GetCurrentWindow();
  5895. if (window->SkipItems)
  5896. return false;
  5897.  
  5898. const ImGuiID id = window->GetID(str_id);
  5899. ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f);
  5900. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
  5901. ItemSize(bb);
  5902. if (!ItemAdd(bb, &id))
  5903. return false;
  5904.  
  5905. bool hovered, held;
  5906. bool pressed = ButtonBehavior(bb, id, &hovered, &held);
  5907.  
  5908. return pressed;
  5909. }
  5910.  
  5911. // Upper-right button to close a window.
  5912. bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos, float radius)
  5913. {
  5914. ImGuiWindow* window = GetCurrentWindow();
  5915.  
  5916. const ImRect bb(pos - ImVec2(radius, radius), pos + ImVec2(radius, radius));
  5917.  
  5918. bool hovered, held;
  5919. bool pressed = ButtonBehavior(bb, id, &hovered, &held);
  5920.  
  5921. // Render
  5922. const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_CloseButtonActive : hovered ? ImGuiCol_CloseButtonHovered : ImGuiCol_CloseButton);
  5923. const ImVec2 center = bb.GetCenter();
  5924. window->DrawList->AddCircleFilled(center, ImMax(2.0f, radius), col, 12);
  5925.  
  5926. const float cross_extent = (radius * 0.7071f) - 1.0f;
  5927. if (hovered)
  5928. {
  5929. window->DrawList->AddLine(center + ImVec2(+cross_extent, +cross_extent), center + ImVec2(-cross_extent, -cross_extent), GetColorU32(ImGuiCol_Text));
  5930. window->DrawList->AddLine(center + ImVec2(+cross_extent, -cross_extent), center + ImVec2(-cross_extent, +cross_extent), GetColorU32(ImGuiCol_Text));
  5931. }
  5932.  
  5933. return pressed;
  5934. }
  5935.  
  5936. void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col)
  5937. {
  5938. ImGuiWindow* window = GetCurrentWindow();
  5939. if (window->SkipItems)
  5940. return;
  5941.  
  5942. ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
  5943. if (border_col.w > 0.0f)
  5944. bb.Max += ImVec2(2, 2);
  5945. ItemSize(bb);
  5946. if (!ItemAdd(bb, NULL))
  5947. return;
  5948.  
  5949. if (border_col.w > 0.0f)
  5950. {
  5951. window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(border_col), 0.0f);
  5952. window->DrawList->AddImage(user_texture_id, bb.Min + ImVec2(1, 1), bb.Max - ImVec2(1, 1), uv0, uv1, GetColorU32(tint_col));
  5953. }
  5954. else
  5955. {
  5956. window->DrawList->AddImage(user_texture_id, bb.Min, bb.Max, uv0, uv1, GetColorU32(tint_col));
  5957. }
  5958. }
  5959.  
  5960. // frame_padding < 0: uses FramePadding from style (default)
  5961. // frame_padding = 0: no framing
  5962. // frame_padding > 0: set framing size
  5963. // The color used are the button colors.
  5964. bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col)
  5965. {
  5966. ImGuiWindow* window = GetCurrentWindow();
  5967. if (window->SkipItems)
  5968. return false;
  5969.  
  5970. ImGuiContext& g = *GImGui;
  5971. const ImGuiStyle& style = g.Style;
  5972.  
  5973. // Default to using texture ID as ID. User can still push string/integer prefixes.
  5974. // We could hash the size/uv to create a unique ID but that would prevent the user from animating UV.
  5975. PushID((void *)user_texture_id);
  5976. const ImGuiID id = window->GetID("#image");
  5977. PopID();
  5978.  
  5979. const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : style.FramePadding;
  5980. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size + padding * 2);
  5981. const ImRect image_bb(window->DC.CursorPos + padding, window->DC.CursorPos + padding + size);
  5982. ItemSize(bb);
  5983. if (!ItemAdd(bb, &id))
  5984. return false;
  5985.  
  5986. bool hovered, held;
  5987. bool pressed = ButtonBehavior(bb, id, &hovered, &held);
  5988.  
  5989. // Render
  5990. const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
  5991. RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, style.FrameRounding));
  5992. if (bg_col.w > 0.0f)
  5993. window->DrawList->AddRectFilled(image_bb.Min, image_bb.Max, GetColorU32(bg_col));
  5994. window->DrawList->AddImage(user_texture_id, image_bb.Min, image_bb.Max, uv0, uv1, GetColorU32(tint_col));
  5995.  
  5996. return pressed;
  5997. }
  5998.  
  5999. // Start logging ImGui output to TTY
  6000. void ImGui::LogToTTY(int max_depth)
  6001. {
  6002. ImGuiContext& g = *GImGui;
  6003. if (g.LogEnabled)
  6004. return;
  6005. ImGuiWindow* window = GetCurrentWindowRead();
  6006.  
  6007. g.LogEnabled = true;
  6008. g.LogFile = stdout;
  6009. g.LogStartDepth = window->DC.TreeDepth;
  6010. if (max_depth >= 0)
  6011. g.LogAutoExpandMaxDepth = max_depth;
  6012. }
  6013.  
  6014. // Start logging ImGui output to given file
  6015. void ImGui::LogToFile(int max_depth, const char* filename)
  6016. {
  6017. ImGuiContext& g = *GImGui;
  6018. if (g.LogEnabled)
  6019. return;
  6020. ImGuiWindow* window = GetCurrentWindowRead();
  6021.  
  6022. if (!filename)
  6023. {
  6024. filename = g.IO.LogFilename;
  6025. if (!filename)
  6026. return;
  6027. }
  6028.  
  6029. g.LogFile = ImFileOpen(filename, "ab");
  6030. if (!g.LogFile)
  6031. {
  6032. IM_ASSERT(g.LogFile != NULL); // Consider this an error
  6033. return;
  6034. }
  6035. g.LogEnabled = true;
  6036. g.LogStartDepth = window->DC.TreeDepth;
  6037. if (max_depth >= 0)
  6038. g.LogAutoExpandMaxDepth = max_depth;
  6039. }
  6040.  
  6041. // Start logging ImGui output to clipboard
  6042. void ImGui::LogToClipboard(int max_depth)
  6043. {
  6044. ImGuiContext& g = *GImGui;
  6045. if (g.LogEnabled)
  6046. return;
  6047. ImGuiWindow* window = GetCurrentWindowRead();
  6048.  
  6049. g.LogEnabled = true;
  6050. g.LogFile = NULL;
  6051. g.LogStartDepth = window->DC.TreeDepth;
  6052. if (max_depth >= 0)
  6053. g.LogAutoExpandMaxDepth = max_depth;
  6054. }
  6055.  
  6056. void ImGui::LogFinish()
  6057. {
  6058. ImGuiContext& g = *GImGui;
  6059. if (!g.LogEnabled)
  6060. return;
  6061.  
  6062. LogText(IM_NEWLINE);
  6063. g.LogEnabled = false;
  6064. if (g.LogFile != NULL)
  6065. {
  6066. if (g.LogFile == stdout)
  6067. fflush(g.LogFile);
  6068. else
  6069. fclose(g.LogFile);
  6070. g.LogFile = NULL;
  6071. }
  6072. if (g.LogClipboard->size() > 1)
  6073. {
  6074. SetClipboardText(g.LogClipboard->begin());
  6075. g.LogClipboard->clear();
  6076. }
  6077. }
  6078.  
  6079. // Helper to display logging buttons
  6080. void ImGui::LogButtons()
  6081. {
  6082. ImGuiContext& g = *GImGui;
  6083.  
  6084. PushID("LogButtons");
  6085. const bool log_to_tty = Button("Log To TTY"); SameLine();
  6086. const bool log_to_file = Button("Log To File"); SameLine();
  6087. const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
  6088. PushItemWidth(80.0f);
  6089. PushAllowKeyboardFocus(false);
  6090. SliderInt("Depth", &g.LogAutoExpandMaxDepth, 0, 9, NULL);
  6091. PopAllowKeyboardFocus();
  6092. PopItemWidth();
  6093. PopID();
  6094.  
  6095. // Start logging at the end of the function so that the buttons don't appear in the log
  6096. if (log_to_tty)
  6097. LogToTTY(g.LogAutoExpandMaxDepth);
  6098. if (log_to_file)
  6099. LogToFile(g.LogAutoExpandMaxDepth, g.IO.LogFilename);
  6100. if (log_to_clipboard)
  6101. LogToClipboard(g.LogAutoExpandMaxDepth);
  6102. }
  6103.  
  6104. bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags)
  6105. {
  6106. if (flags & ImGuiTreeNodeFlags_Leaf)
  6107. return true;
  6108.  
  6109. // We only write to the tree storage if the user clicks (or explicitely use SetNextTreeNode*** functions)
  6110. ImGuiContext& g = *GImGui;
  6111. ImGuiWindow* window = g.CurrentWindow;
  6112. ImGuiStorage* storage = window->DC.StateStorage;
  6113.  
  6114. bool is_open;
  6115. if (g.SetNextTreeNodeOpenCond != 0)
  6116. {
  6117. if (g.SetNextTreeNodeOpenCond & ImGuiCond_Always)
  6118. {
  6119. is_open = g.SetNextTreeNodeOpenVal;
  6120. storage->SetInt(id, is_open);
  6121. }
  6122. else
  6123. {
  6124. // We treat ImGuiCond_Once and ImGuiCond_FirstUseEver the same because tree node state are not saved persistently.
  6125. const int stored_value = storage->GetInt(id, -1);
  6126. if (stored_value == -1)
  6127. {
  6128. is_open = g.SetNextTreeNodeOpenVal;
  6129. storage->SetInt(id, is_open);
  6130. }
  6131. else
  6132. {
  6133. is_open = stored_value != 0;
  6134. }
  6135. }
  6136. g.SetNextTreeNodeOpenCond = 0;
  6137. }
  6138. else
  6139. {
  6140. is_open = storage->GetInt(id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0;
  6141. }
  6142.  
  6143. // When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior).
  6144. // NB- If we are above max depth we still allow manually opened nodes to be logged.
  6145. if (g.LogEnabled && !(flags & ImGuiTreeNodeFlags_NoAutoOpenOnLog) && window->DC.TreeDepth < g.LogAutoExpandMaxDepth)
  6146. is_open = true;
  6147.  
  6148. return is_open;
  6149. }
  6150.  
  6151. bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end)
  6152. {
  6153. ImGuiWindow* window = GetCurrentWindow();
  6154. if (window->SkipItems)
  6155. return false;
  6156.  
  6157. ImGuiContext& g = *GImGui;
  6158. const ImGuiStyle& style = g.Style;
  6159. const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0;
  6160. const ImVec2 padding = display_frame ? style.FramePadding : ImVec2(style.FramePadding.x, 0.0f);
  6161.  
  6162. if (!label_end)
  6163. label_end = FindRenderedTextEnd(label);
  6164. const ImVec2 label_size = CalcTextSize(label, label_end, false);
  6165.  
  6166. // We vertically grow up to current line height up the typical widget height.
  6167. const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset - padding.y); // Latch before ItemSize changes it
  6168. const float frame_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + style.FramePadding.y * 2), label_size.y + padding.y * 2);
  6169. ImRect bb = ImRect(window->DC.CursorPos, ImVec2(window->Pos.x + GetContentRegionMax().x, window->DC.CursorPos.y + frame_height));
  6170. if (display_frame)
  6171. {
  6172. // Framed header expand a little outside the default padding
  6173. bb.Min.x -= (float)(int)(window->WindowPadding.x*0.5f) - 1;
  6174. bb.Max.x += (float)(int)(window->WindowPadding.x*0.5f) - 1;
  6175. }
  6176.  
  6177. const float text_offset_x = (g.FontSize + (display_frame ? padding.x * 3 : padding.x * 2)); // Collapser arrow width + Spacing
  6178. const float text_width = g.FontSize + (label_size.x > 0.0f ? label_size.x + padding.x * 2 : 0.0f); // Include collapser
  6179. ItemSize(ImVec2(text_width, frame_height), text_base_offset_y);
  6180.  
  6181. // For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing
  6182. // (Ideally we'd want to add a flag for the user to specify we want want the hit test to be done up to the right side of the content or not)
  6183. const ImRect interact_bb = display_frame ? bb : ImRect(bb.Min.x, bb.Min.y, bb.Min.x + text_width + style.ItemSpacing.x * 2, bb.Max.y);
  6184. bool is_open = TreeNodeBehaviorIsOpen(id, flags);
  6185. if (!ItemAdd(interact_bb, &id))
  6186. {
  6187. if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
  6188. TreePushRawID(id);
  6189. return is_open;
  6190. }
  6191.  
  6192. // Flags that affects opening behavior:
  6193. // - 0(default) ..................... single-click anywhere to open
  6194. // - OpenOnDoubleClick .............. double-click anywhere to open
  6195. // - OpenOnArrow .................... single-click on arrow to open
  6196. // - OpenOnDoubleClick|OpenOnArrow .. single-click on arrow or double-click anywhere to open
  6197. ImGuiButtonFlags button_flags = ImGuiButtonFlags_NoKeyModifiers | ((flags & ImGuiTreeNodeFlags_AllowOverlapMode) ? ImGuiButtonFlags_AllowOverlapMode : 0);
  6198. if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
  6199. button_flags |= ImGuiButtonFlags_PressedOnDoubleClick | ((flags & ImGuiTreeNodeFlags_OpenOnArrow) ? ImGuiButtonFlags_PressedOnClickRelease : 0);
  6200. bool hovered, held, pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags);
  6201. if (pressed && !(flags & ImGuiTreeNodeFlags_Leaf))
  6202. {
  6203. bool toggled = !(flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick));
  6204. if (flags & ImGuiTreeNodeFlags_OpenOnArrow)
  6205. toggled |= IsMouseHoveringRect(interact_bb.Min, ImVec2(interact_bb.Min.x + text_offset_x, interact_bb.Max.y));
  6206. if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
  6207. toggled |= g.IO.MouseDoubleClicked[0];
  6208. if (toggled)
  6209. {
  6210. is_open = !is_open;
  6211. window->DC.StateStorage->SetInt(id, is_open);
  6212. }
  6213. }
  6214. if (flags & ImGuiTreeNodeFlags_AllowOverlapMode)
  6215. SetItemAllowOverlap();
  6216.  
  6217. // Render
  6218. const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
  6219. const ImVec2 text_pos = bb.Min + ImVec2(text_offset_x, padding.y + text_base_offset_y);
  6220. if (display_frame)
  6221. {
  6222. // Framed type
  6223. RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
  6224. RenderCollapseTriangle(bb.Min + padding + ImVec2(0.0f, text_base_offset_y), is_open, 1.0f);
  6225. if (g.LogEnabled)
  6226. {
  6227. // NB: '##' is normally used to hide text (as a library-wide feature), so we need to specify the text range to make sure the ## aren't stripped out here.
  6228. const char log_prefix[] = "\n##";
  6229. const char log_suffix[] = "##";
  6230. LogRenderedText(text_pos, log_prefix, log_prefix + 3);
  6231. RenderTextClipped(text_pos, bb.Max, label, label_end, &label_size);
  6232. LogRenderedText(text_pos, log_suffix + 1, log_suffix + 3);
  6233. }
  6234. else
  6235. {
  6236. RenderTextClipped(text_pos, bb.Max, label, label_end, &label_size);
  6237. }
  6238. }
  6239. else
  6240. {
  6241. // Unframed typed for tree nodes
  6242. if (hovered || (flags & ImGuiTreeNodeFlags_Selected))
  6243. RenderFrame(bb.Min, bb.Max, col, false);
  6244.  
  6245. if (flags & ImGuiTreeNodeFlags_Bullet)
  6246. RenderBullet(bb.Min + ImVec2(text_offset_x * 0.5f, g.FontSize*0.50f + text_base_offset_y));
  6247. else if (!(flags & ImGuiTreeNodeFlags_Leaf))
  6248. RenderCollapseTriangle(bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), is_open, 0.70f);
  6249. if (g.LogEnabled)
  6250. LogRenderedText(text_pos, ">");
  6251. RenderText(text_pos, label, label_end, false);
  6252. }
  6253.  
  6254. if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
  6255. TreePushRawID(id);
  6256. return is_open;
  6257. }
  6258.  
  6259. // CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags_NoTreePushOnOpen flag).
  6260. // This is basically the same as calling TreeNodeEx(label, ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen). You can remove the _NoTreePushOnOpen flag if you want behavior closer to normal TreeNode().
  6261. bool ImGui::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags)
  6262. {
  6263. ImGuiWindow* window = GetCurrentWindow();
  6264. if (window->SkipItems)
  6265. return false;
  6266.  
  6267. return TreeNodeBehavior(window->GetID(label), flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen, label);
  6268. }
  6269.  
  6270. bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags)
  6271. {
  6272. ImGuiWindow* window = GetCurrentWindow();
  6273. if (window->SkipItems)
  6274. return false;
  6275.  
  6276. if (p_open && !*p_open)
  6277. return false;
  6278.  
  6279. ImGuiID id = window->GetID(label);
  6280. bool is_open = TreeNodeBehavior(id, flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen | (p_open ? ImGuiTreeNodeFlags_AllowOverlapMode : 0), label);
  6281. if (p_open)
  6282. {
  6283. // Create a small overlapping close button // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc.
  6284. ImGuiContext& g = *GImGui;
  6285. float button_sz = g.FontSize * 0.5f;
  6286. if (CloseButton(window->GetID((void*)(intptr_t)(id + 1)), ImVec2(ImMin(window->DC.LastItemRect.Max.x, window->ClipRect.Max.x) - g.Style.FramePadding.x - button_sz, window->DC.LastItemRect.Min.y + g.Style.FramePadding.y + button_sz), button_sz))
  6287. *p_open = false;
  6288. }
  6289.  
  6290. return is_open;
  6291. }
  6292.  
  6293. bool ImGui::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags)
  6294. {
  6295. ImGuiWindow* window = GetCurrentWindow();
  6296. if (window->SkipItems)
  6297. return false;
  6298.  
  6299. return TreeNodeBehavior(window->GetID(label), flags, label, NULL);
  6300. }
  6301.  
  6302. bool ImGui::TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args)
  6303. {
  6304. ImGuiWindow* window = GetCurrentWindow();
  6305. if (window->SkipItems)
  6306. return false;
  6307.  
  6308. ImGuiContext& g = *GImGui;
  6309. const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
  6310. return TreeNodeBehavior(window->GetID(str_id), flags, g.TempBuffer, label_end);
  6311. }
  6312.  
  6313. bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args)
  6314. {
  6315. ImGuiWindow* window = GetCurrentWindow();
  6316. if (window->SkipItems)
  6317. return false;
  6318.  
  6319. ImGuiContext& g = *GImGui;
  6320. const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
  6321. return TreeNodeBehavior(window->GetID(ptr_id), flags, g.TempBuffer, label_end);
  6322. }
  6323.  
  6324. bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args)
  6325. {
  6326. return TreeNodeExV(str_id, 0, fmt, args);
  6327. }
  6328.  
  6329. bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args)
  6330. {
  6331. return TreeNodeExV(ptr_id, 0, fmt, args);
  6332. }
  6333.  
  6334. bool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...)
  6335. {
  6336. va_list args;
  6337. va_start(args, fmt);
  6338. bool is_open = TreeNodeExV(str_id, flags, fmt, args);
  6339. va_end(args);
  6340. return is_open;
  6341. }
  6342.  
  6343. bool ImGui::TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...)
  6344. {
  6345. va_list args;
  6346. va_start(args, fmt);
  6347. bool is_open = TreeNodeExV(ptr_id, flags, fmt, args);
  6348. va_end(args);
  6349. return is_open;
  6350. }
  6351.  
  6352. bool ImGui::TreeNode(const char* str_id, const char* fmt, ...)
  6353. {
  6354. va_list args;
  6355. va_start(args, fmt);
  6356. bool is_open = TreeNodeExV(str_id, 0, fmt, args);
  6357. va_end(args);
  6358. return is_open;
  6359. }
  6360.  
  6361. bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...)
  6362. {
  6363. va_list args;
  6364. va_start(args, fmt);
  6365. bool is_open = TreeNodeExV(ptr_id, 0, fmt, args);
  6366. va_end(args);
  6367. return is_open;
  6368. }
  6369.  
  6370. bool ImGui::TreeNode(const char* label)
  6371. {
  6372. ImGuiWindow* window = GetCurrentWindow();
  6373. if (window->SkipItems)
  6374. return false;
  6375. return TreeNodeBehavior(window->GetID(label), 0, label, NULL);
  6376. }
  6377.  
  6378. void ImGui::TreeAdvanceToLabelPos()
  6379. {
  6380. ImGuiContext& g = *GImGui;
  6381. g.CurrentWindow->DC.CursorPos.x += GetTreeNodeToLabelSpacing();
  6382. }
  6383.  
  6384. // Horizontal distance preceding label when using TreeNode() or Bullet()
  6385. float ImGui::GetTreeNodeToLabelSpacing()
  6386. {
  6387. ImGuiContext& g = *GImGui;
  6388. return g.FontSize + (g.Style.FramePadding.x * 2.0f);
  6389. }
  6390.  
  6391. void ImGui::SetNextTreeNodeOpen(bool is_open, ImGuiCond cond)
  6392. {
  6393. ImGuiContext& g = *GImGui;
  6394. g.SetNextTreeNodeOpenVal = is_open;
  6395. g.SetNextTreeNodeOpenCond = cond ? cond : ImGuiCond_Always;
  6396. }
  6397.  
  6398. void ImGui::PushID(const char* str_id)
  6399. {
  6400. ImGuiWindow* window = GetCurrentWindowRead();
  6401. window->IDStack.push_back(window->GetID(str_id));
  6402. }
  6403.  
  6404. void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
  6405. {
  6406. ImGuiWindow* window = GetCurrentWindowRead();
  6407. window->IDStack.push_back(window->GetID(str_id_begin, str_id_end));
  6408. }
  6409.  
  6410. void ImGui::PushID(const void* ptr_id)
  6411. {
  6412. ImGuiWindow* window = GetCurrentWindowRead();
  6413. window->IDStack.push_back(window->GetID(ptr_id));
  6414. }
  6415.  
  6416. void ImGui::PushID(int int_id)
  6417. {
  6418. const void* ptr_id = (void*)(intptr_t)int_id;
  6419. ImGuiWindow* window = GetCurrentWindowRead();
  6420. window->IDStack.push_back(window->GetID(ptr_id));
  6421. }
  6422.  
  6423. void ImGui::PopID()
  6424. {
  6425. ImGuiWindow* window = GetCurrentWindowRead();
  6426. window->IDStack.pop_back();
  6427. }
  6428.  
  6429. ImGuiID ImGui::GetID(const char* str_id)
  6430. {
  6431. return GImGui->CurrentWindow->GetID(str_id);
  6432. }
  6433.  
  6434. ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
  6435. {
  6436. return GImGui->CurrentWindow->GetID(str_id_begin, str_id_end);
  6437. }
  6438.  
  6439. ImGuiID ImGui::GetID(const void* ptr_id)
  6440. {
  6441. return GImGui->CurrentWindow->GetID(ptr_id);
  6442. }
  6443.  
  6444. void ImGui::Bullet()
  6445. {
  6446. ImGuiWindow* window = GetCurrentWindow();
  6447. if (window->SkipItems)
  6448. return;
  6449.  
  6450. ImGuiContext& g = *GImGui;
  6451. const ImGuiStyle& style = g.Style;
  6452. const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y * 2), g.FontSize);
  6453. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height));
  6454. ItemSize(bb);
  6455. if (!ItemAdd(bb, NULL))
  6456. {
  6457. SameLine(0, style.FramePadding.x * 2);
  6458. return;
  6459. }
  6460.  
  6461. // Render and stay on same line
  6462. RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f));
  6463. SameLine(0, style.FramePadding.x * 2);
  6464. }
  6465.  
  6466. // Text with a little bullet aligned to the typical tree node.
  6467. void ImGui::BulletTextV(const char* fmt, va_list args)
  6468. {
  6469. ImGuiWindow* window = GetCurrentWindow();
  6470. if (window->SkipItems)
  6471. return;
  6472.  
  6473. ImGuiContext& g = *GImGui;
  6474. const ImGuiStyle& style = g.Style;
  6475.  
  6476. const char* text_begin = g.TempBuffer;
  6477. const char* text_end = text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
  6478. const ImVec2 label_size = CalcTextSize(text_begin, text_end, false);
  6479. const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it
  6480. const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y * 2), g.FontSize);
  6481. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize + (label_size.x > 0.0f ? (label_size.x + style.FramePadding.x * 2) : 0.0f), ImMax(line_height, label_size.y))); // Empty text doesn't add padding
  6482. ItemSize(bb);
  6483. if (!ItemAdd(bb, NULL))
  6484. return;
  6485.  
  6486. // Render
  6487. RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f));
  6488. RenderText(bb.Min + ImVec2(g.FontSize + style.FramePadding.x * 2, text_base_offset_y), text_begin, text_end, false);
  6489. }
  6490.  
  6491. void ImGui::BulletText(const char* fmt, ...)
  6492. {
  6493. va_list args;
  6494. va_start(args, fmt);
  6495. BulletTextV(fmt, args);
  6496. va_end(args);
  6497. }
  6498.  
  6499. static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size)
  6500. {
  6501. if (data_type == ImGuiDataType_Int)
  6502. ImFormatString(buf, buf_size, display_format, *(int*)data_ptr);
  6503. else if (data_type == ImGuiDataType_Float)
  6504. ImFormatString(buf, buf_size, display_format, *(float*)data_ptr);
  6505. }
  6506.  
  6507. static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size)
  6508. {
  6509. if (data_type == ImGuiDataType_Int)
  6510. {
  6511. if (decimal_precision < 0)
  6512. ImFormatString(buf, buf_size, "%d", *(int*)data_ptr);
  6513. else
  6514. ImFormatString(buf, buf_size, "%.*d", decimal_precision, *(int*)data_ptr);
  6515. }
  6516. else if (data_type == ImGuiDataType_Float)
  6517. {
  6518. if (decimal_precision < 0)
  6519. ImFormatString(buf, buf_size, "%f", *(float*)data_ptr); // Ideally we'd have a minimum decimal precision of 1 to visually denote that it is a float, while hiding non-significant digits?
  6520. else
  6521. ImFormatString(buf, buf_size, "%.*f", decimal_precision, *(float*)data_ptr);
  6522. }
  6523. }
  6524.  
  6525. static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2)// Store into value1
  6526. {
  6527. if (data_type == ImGuiDataType_Int)
  6528. {
  6529. if (op == '+')
  6530. *(int*)value1 = *(int*)value1 + *(const int*)value2;
  6531. else if (op == '-')
  6532. *(int*)value1 = *(int*)value1 - *(const int*)value2;
  6533. }
  6534. else if (data_type == ImGuiDataType_Float)
  6535. {
  6536. if (op == '+')
  6537. *(float*)value1 = *(float*)value1 + *(const float*)value2;
  6538. else if (op == '-')
  6539. *(float*)value1 = *(float*)value1 - *(const float*)value2;
  6540. }
  6541. }
  6542.  
  6543. // User can input math operators (e.g. +100) to edit a numerical values.
  6544. static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format)
  6545. {
  6546. while (ImCharIsSpace(*buf))
  6547. buf++;
  6548.  
  6549. // We don't support '-' op because it would conflict with inputing negative value.
  6550. // Instead you can use +-100 to subtract from an existing value
  6551. char op = buf[0];
  6552. if (op == '+' || op == '*' || op == '/')
  6553. {
  6554. buf++;
  6555. while (ImCharIsSpace(*buf))
  6556. buf++;
  6557. }
  6558. else
  6559. {
  6560. op = 0;
  6561. }
  6562. if (!buf[0])
  6563. return false;
  6564.  
  6565. if (data_type == ImGuiDataType_Int)
  6566. {
  6567. if (!scalar_format)
  6568. scalar_format = "%d";
  6569. int* v = (int*)data_ptr;
  6570. const int old_v = *v;
  6571. int arg0i = *v;
  6572. if (op && sscanf(initial_value_buf, scalar_format, &arg0i) < 1)
  6573. return false;
  6574.  
  6575. // Store operand in a float so we can use fractional value for multipliers (*1.1), but constant always parsed as integer so we can fit big integers (e.g. 2000000003) past float precision
  6576. float arg1f = 0.0f;
  6577. if (op == '+') { if (sscanf(buf, "%f", &arg1f) == 1) *v = (int)(arg0i + arg1f); } // Add (use "+-" to subtract)
  6578. else if (op == '*') { if (sscanf(buf, "%f", &arg1f) == 1) *v = (int)(arg0i * arg1f); } // Multiply
  6579. else if (op == '/') { if (sscanf(buf, "%f", &arg1f) == 1 && arg1f != 0.0f) *v = (int)(arg0i / arg1f); }// Divide
  6580. else { if (sscanf(buf, scalar_format, &arg0i) == 1) *v = arg0i; } // Assign constant (read as integer so big values are not lossy)
  6581. return (old_v != *v);
  6582. }
  6583. else if (data_type == ImGuiDataType_Float)
  6584. {
  6585. // For floats we have to ignore format with precision (e.g. "%.2f") because sscanf doesn't take them in
  6586. scalar_format = "%f";
  6587. float* v = (float*)data_ptr;
  6588. const float old_v = *v;
  6589. float arg0f = *v;
  6590. if (op && sscanf(initial_value_buf, scalar_format, &arg0f) < 1)
  6591. return false;
  6592.  
  6593. float arg1f = 0.0f;
  6594. if (sscanf(buf, scalar_format, &arg1f) < 1)
  6595. return false;
  6596. if (op == '+') { *v = arg0f + arg1f; } // Add (use "+-" to subtract)
  6597. else if (op == '*') { *v = arg0f * arg1f; } // Multiply
  6598. else if (op == '/') { if (arg1f != 0.0f) *v = arg0f / arg1f; } // Divide
  6599. else { *v = arg1f; } // Assign constant
  6600. return (old_v != *v);
  6601. }
  6602.  
  6603. return false;
  6604. }
  6605.  
  6606. // Create text input in place of a slider (when CTRL+Clicking on slider)
  6607. // FIXME: Logic is messy and confusing.
  6608. bool ImGui::InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label, ImGuiDataType data_type, void* data_ptr, ImGuiID id, int decimal_precision)
  6609. {
  6610. ImGuiContext& g = *GImGui;
  6611. ImGuiWindow* window = GetCurrentWindow();
  6612.  
  6613. // Our replacement widget will override the focus ID (registered previously to allow for a TAB focus to happen)
  6614. SetActiveID(g.ScalarAsInputTextId, window);
  6615. SetHoveredID(0);
  6616. FocusableItemUnregister(window);
  6617.  
  6618. char buf[32];
  6619. DataTypeFormatString(data_type, data_ptr, decimal_precision, buf, IM_ARRAYSIZE(buf));
  6620. bool text_value_changed = InputTextEx(label, buf, IM_ARRAYSIZE(buf), aabb.GetSize(), ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_AutoSelectAll);
  6621. if (g.ScalarAsInputTextId == 0) // First frame we started displaying the InputText widget
  6622. {
  6623. IM_ASSERT(g.ActiveId == id); // InputText ID expected to match the Slider ID (else we'd need to store them both, which is also possible)
  6624. g.ScalarAsInputTextId = g.ActiveId;
  6625. SetHoveredID(id);
  6626. }
  6627. if (text_value_changed)
  6628. return DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, NULL);
  6629. return false;
  6630. }
  6631.  
  6632. // Parse display precision back from the display format string
  6633. int ImGui::ParseFormatPrecision(const char* fmt, int default_precision)
  6634. {
  6635. int precision = default_precision;
  6636. while ((fmt = strchr(fmt, '%')) != NULL)
  6637. {
  6638. fmt++;
  6639. if (fmt[0] == '%') { fmt++; continue; } // Ignore "%%"
  6640. while (*fmt >= '0' && *fmt <= '9')
  6641. fmt++;
  6642. if (*fmt == '.')
  6643. {
  6644. fmt = ImAtoi(fmt + 1, &precision);
  6645. if (precision < 0 || precision > 10)
  6646. precision = default_precision;
  6647. }
  6648. if (*fmt == 'e' || *fmt == 'E') // Maximum precision with scientific notation
  6649. precision = -1;
  6650. break;
  6651. }
  6652. return precision;
  6653. }
  6654.  
  6655. static float GetMinimumStepAtDecimalPrecision(int decimal_precision)
  6656. {
  6657. static const float min_steps[10] = { 1.0f, 0.1f, 0.01f, 0.001f, 0.0001f, 0.00001f, 0.000001f, 0.0000001f, 0.00000001f, 0.000000001f };
  6658. return (decimal_precision >= 0 && decimal_precision < 10) ? min_steps[decimal_precision] : powf(10.0f, (float)-decimal_precision);
  6659. }
  6660.  
  6661. float ImGui::RoundScalar(float value, int decimal_precision)
  6662. {
  6663. // Round past decimal precision
  6664. // So when our value is 1.99999 with a precision of 0.001 we'll end up rounding to 2.0
  6665. // FIXME: Investigate better rounding methods
  6666. if (decimal_precision < 0)
  6667. return value;
  6668. const float min_step = GetMinimumStepAtDecimalPrecision(decimal_precision);
  6669. bool negative = value < 0.0f;
  6670. value = fabsf(value);
  6671. float remainder = fmodf(value, min_step);
  6672. if (remainder <= min_step*0.5f)
  6673. value -= remainder;
  6674. else
  6675. value += (min_step - remainder);
  6676. return negative ? -value : value;
  6677. }
  6678.  
  6679. static inline float SliderBehaviorCalcRatioFromValue(float v, float v_min, float v_max, float power, float linear_zero_pos)
  6680. {
  6681. if (v_min == v_max)
  6682. return 0.0f;
  6683.  
  6684. const bool is_non_linear = (power < 1.0f - 0.00001f) || (power > 1.0f + 0.00001f);
  6685. const float v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min);
  6686. if (is_non_linear)
  6687. {
  6688. if (v_clamped < 0.0f)
  6689. {
  6690. const float f = 1.0f - (v_clamped - v_min) / (ImMin(0.0f, v_max) - v_min);
  6691. return (1.0f - powf(f, 1.0f / power)) * linear_zero_pos;
  6692. }
  6693. else
  6694. {
  6695. const float f = (v_clamped - ImMax(0.0f, v_min)) / (v_max - ImMax(0.0f, v_min));
  6696. return linear_zero_pos + powf(f, 1.0f / power) * (1.0f - linear_zero_pos);
  6697. }
  6698. }
  6699.  
  6700. // Linear slider
  6701. return (v_clamped - v_min) / (v_max - v_min);
  6702. }
  6703. bool ImGui::Tab(const char* label, const ImVec2& size_arg, bool selected)
  6704. {
  6705. return ButtonEx(label, size_arg, 0, true, selected);
  6706. /*int flags = 0;
  6707.  
  6708. ImGuiWindow* window = GetCurrentWindow();
  6709. if (window->SkipItems)
  6710. return false;
  6711.  
  6712. ImGuiContext& g = *GImGui;
  6713. const ImGuiStyle& style = g.Style;
  6714.  
  6715. if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1)
  6716. PopClipRect();
  6717.  
  6718. ImGuiID id = window->GetID(label);
  6719. ImVec2 label_size = CalcTextSize(label, NULL, true);
  6720. ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y);
  6721. ImVec2 pos = window->DC.CursorPos;
  6722. pos.y += window->DC.CurrentLineTextBaseOffset;
  6723. ImRect bb(pos, pos + size);
  6724. ItemSize(bb);
  6725.  
  6726. // Fill horizontal space.
  6727. ImVec2 window_padding = ImVec2(0, 0);
  6728. float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? GetWindowContentRegionMax().x : GetContentRegionMax().x;
  6729. float w_draw = ImMax(label_size.x, window->Pos.x + max_x - window_padding.x - window->DC.CursorPos.x);
  6730. ImVec2 size_draw((size_arg.x != 0 && !(flags & ImGuiSelectableFlags_DrawFillAvailWidth)) ? size_arg.x : w_draw, size_arg.y != 0.0f ? size_arg.y : size.y);
  6731. ImRect bb_with_spacing(pos, pos + size_draw);
  6732. if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_DrawFillAvailWidth))
  6733. bb_with_spacing.Max.x += window_padding.x;
  6734.  
  6735. // Selectables are tightly packed together, we extend the box to cover spacing between selectable.
  6736. float spacing_L = (float)(int)(style.ItemSpacing.x);
  6737. float spacing_U = (float)(int)(style.ItemSpacing.y);
  6738. float spacing_R = style.ItemSpacing.x - spacing_L;
  6739. float spacing_D = style.ItemSpacing.y - spacing_U;
  6740. bb_with_spacing.Min.x -= spacing_L;
  6741. bb_with_spacing.Min.y -= spacing_U;
  6742. bb_with_spacing.Max.x += spacing_R;
  6743. bb_with_spacing.Max.y += spacing_D;
  6744. if (!ItemAdd(bb_with_spacing, &id))
  6745. {
  6746. if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1)
  6747. PushColumnClipRect();
  6748. return false;
  6749. }
  6750.  
  6751. ImGuiButtonFlags button_flags = 0;
  6752. if (flags & ImGuiSelectableFlags_Menu) button_flags |= ImGuiButtonFlags_PressedOnClick;
  6753. if (flags & ImGuiSelectableFlags_MenuItem) button_flags |= ImGuiButtonFlags_PressedOnClick|ImGuiButtonFlags_PressedOnRelease;
  6754. if (flags & ImGuiSelectableFlags_Disabled) button_flags |= ImGuiButtonFlags_Disabled;
  6755. if (flags & ImGuiSelectableFlags_AllowDoubleClick) button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick;
  6756. bool hovered, held;
  6757. bool pressed = ButtonBehavior(bb_with_spacing, id, &hovered, &held, button_flags);
  6758. if (flags & ImGuiSelectableFlags_Disabled)
  6759. selected = false;
  6760.  
  6761. // Render
  6762. if (hovered || selected)
  6763. {
  6764. const ImU32 col = GetColorU32(selected ? ImGuiCol_TabSelected : (held && hovered) ? ImGuiCol_TabActive : hovered ? ImGuiCol_TabHovered : ImGuiCol_Tab);
  6765. RenderFrame(bb_with_spacing.Min, bb_with_spacing.Max, col, false, 0.0f);
  6766. if (selected)
  6767. {
  6768. RenderFrame(ImVec2(bb_with_spacing.Min.x, bb_with_spacing.Max.y - 2), bb_with_spacing.Max, GetColorU32(ImGuiCol_SelectedLine), false);
  6769. }
  6770. }
  6771.  
  6772. if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1)
  6773. {
  6774. PushColumnClipRect();
  6775. bb_with_spacing.Max.x -= (GetContentRegionMax().x - max_x);
  6776. }
  6777.  
  6778. if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
  6779. RenderTextClipped(bb.Min, bb_with_spacing.Max, label, NULL, &label_size, ImVec2(0.5f,0.5f));
  6780. if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor();
  6781.  
  6782. // Automatically close popups
  6783. if (pressed && !(flags & ImGuiSelectableFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
  6784. CloseCurrentPopup();
  6785. return pressed;*/
  6786.  
  6787. //return Selectable(label, selected, 0, size_arg);
  6788. //return ButtonEx(label, size_arg, 0, true, selected);
  6789. }
  6790. bool ImGui::SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, ImGuiSliderFlags flags)
  6791. {
  6792. ImGuiContext& g = *GImGui;
  6793. ImGuiWindow* window = GetCurrentWindow();
  6794. const ImGuiStyle& style = g.Style;
  6795.  
  6796. // Draw frame
  6797. RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
  6798.  
  6799. const bool is_non_linear = (power < 1.0f - 0.00001f) || (power > 1.0f + 0.00001f);
  6800. const bool is_horizontal = (flags & ImGuiSliderFlags_Vertical) == 0;
  6801.  
  6802. const float grab_padding = 2.0f;
  6803. const float slider_sz = is_horizontal ? (frame_bb.GetWidth() - grab_padding * 2.0f) : (frame_bb.GetHeight() - grab_padding * 2.0f);
  6804. float grab_sz;
  6805. if (decimal_precision != 0)
  6806. grab_sz = ImMin(style.GrabMinSize, slider_sz);
  6807. else
  6808. grab_sz = ImMin(ImMax(1.0f * (slider_sz / ((v_min < v_max ? v_max - v_min : v_min - v_max) + 1.0f)), style.GrabMinSize), slider_sz); // Integer sliders, if possible have the grab size represent 1 unit
  6809. const float slider_usable_sz = slider_sz - grab_sz;
  6810. const float slider_usable_pos_min = (is_horizontal ? frame_bb.Min.x : frame_bb.Min.y) + grab_padding + grab_sz*0.5f;
  6811. const float slider_usable_pos_max = (is_horizontal ? frame_bb.Max.x : frame_bb.Max.y) - grab_padding - grab_sz*0.5f;
  6812.  
  6813. // For logarithmic sliders that cross over sign boundary we want the exponential increase to be symmetric around 0.0f
  6814. float linear_zero_pos = 0.0f; // 0.0->1.0f
  6815. if (v_min * v_max < 0.0f)
  6816. {
  6817. // Different sign
  6818. const float linear_dist_min_to_0 = powf(fabsf(0.0f - v_min), 1.0f / power);
  6819. const float linear_dist_max_to_0 = powf(fabsf(v_max - 0.0f), 1.0f / power);
  6820. linear_zero_pos = linear_dist_min_to_0 / (linear_dist_min_to_0 + linear_dist_max_to_0);
  6821. }
  6822. else
  6823. {
  6824. // Same sign
  6825. linear_zero_pos = v_min < 0.0f ? 1.0f : 0.0f;
  6826. }
  6827.  
  6828. // Process clicking on the slider
  6829. bool value_changed = false;
  6830. if (g.ActiveId == id)
  6831. {
  6832. bool set_new_value = false;
  6833. float clicked_t = 0.0f;
  6834. if (g.IO.MouseDown[0])
  6835. {
  6836. const float mouse_abs_pos = is_horizontal ? g.IO.MousePos.x : g.IO.MousePos.y;
  6837. clicked_t = (slider_usable_sz > 0.0f) ? ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f) : 0.0f;
  6838. if (!is_horizontal)
  6839. clicked_t = 1.0f - clicked_t;
  6840. set_new_value = true;
  6841. }
  6842. else
  6843. {
  6844. ClearActiveID();
  6845. }
  6846.  
  6847. if (set_new_value)
  6848. {
  6849. float new_value;
  6850. if (is_non_linear)
  6851. {
  6852. // Account for logarithmic scale on both sides of the zero
  6853. if (clicked_t < linear_zero_pos)
  6854. {
  6855. // Negative: rescale to the negative range before powering
  6856. float a = 1.0f - (clicked_t / linear_zero_pos);
  6857. a = powf(a, power);
  6858. new_value = ImLerp(ImMin(v_max, 0.0f), v_min, a);
  6859. }
  6860. else
  6861. {
  6862. // Positive: rescale to the positive range before powering
  6863. float a;
  6864. if (fabsf(linear_zero_pos - 1.0f) > 1.e-6f)
  6865. a = (clicked_t - linear_zero_pos) / (1.0f - linear_zero_pos);
  6866. else
  6867. a = clicked_t;
  6868. a = powf(a, power);
  6869. new_value = ImLerp(ImMax(v_min, 0.0f), v_max, a);
  6870. }
  6871. }
  6872. else
  6873. {
  6874. // Linear slider
  6875. new_value = ImLerp(v_min, v_max, clicked_t);
  6876. }
  6877.  
  6878. // Round past decimal precision
  6879. new_value = RoundScalar(new_value, decimal_precision);
  6880. if (*v != new_value)
  6881. {
  6882. *v = new_value;
  6883. value_changed = true;
  6884. }
  6885. }
  6886. }
  6887.  
  6888. // Draw
  6889. float grab_t = SliderBehaviorCalcRatioFromValue(*v, v_min, v_max, power, linear_zero_pos);
  6890. if (!is_horizontal)
  6891. grab_t = 1.0f - grab_t;
  6892. const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t);
  6893. ImRect grab_bb;
  6894. if (is_horizontal)
  6895. grab_bb = ImRect(ImVec2(grab_pos - grab_sz*0.5f, frame_bb.Min.y + grab_padding), ImVec2(grab_pos + grab_sz*0.5f, frame_bb.Max.y - grab_padding));
  6896. else
  6897. grab_bb = ImRect(ImVec2(frame_bb.Min.x + grab_padding, grab_pos - grab_sz*0.5f), ImVec2(frame_bb.Max.x - grab_padding, grab_pos + grab_sz*0.5f));
  6898. window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding);
  6899.  
  6900. return value_changed;
  6901. }
  6902.  
  6903.  
  6904.  
  6905. // Use power!=1.0 for logarithmic sliders.
  6906. // Adjust display_format to decorate the value with a prefix or a suffix.
  6907. // "%.3f" 1.234
  6908. // "%5.2f secs" 01.23 secs
  6909. // "Gold: %.0f" Gold: 1
  6910. bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format, float power)
  6911. {
  6912. ImGuiWindow* window = GetCurrentWindow();
  6913. if (window->SkipItems)
  6914. return false;
  6915.  
  6916. ImGuiContext& g = *GImGui;
  6917. const ImGuiStyle& style = g.Style;
  6918. const ImGuiID id = window->GetID(label);
  6919. const float w = CalcItemWidth();
  6920.  
  6921. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  6922. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
  6923. const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
  6924.  
  6925. // NB- we don't call ItemSize() yet because we may turn into a text edit box below
  6926. if (!ItemAdd(total_bb, &id))
  6927. {
  6928. ItemSize(total_bb, style.FramePadding.y);
  6929. return false;
  6930. }
  6931.  
  6932. const bool hovered = IsHovered(frame_bb, id);
  6933. if (hovered)
  6934. SetHoveredID(id);
  6935.  
  6936. if (!display_format)
  6937. display_format = "%.3f";
  6938. int decimal_precision = ParseFormatPrecision(display_format, 3);
  6939.  
  6940. // Tabbing or CTRL-clicking on Slider turns it into an input box
  6941. bool start_text_input = false;
  6942. const bool tab_focus_requested = FocusableItemRegister(window, id);
  6943. if (tab_focus_requested || (hovered && g.IO.MouseClicked[0]))
  6944. {
  6945. SetActiveID(id, window);
  6946. FocusWindow(window);
  6947.  
  6948. if (tab_focus_requested || g.IO.KeyCtrl)
  6949. {
  6950. start_text_input = true;
  6951. g.ScalarAsInputTextId = 0;
  6952. }
  6953. }
  6954. if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id))
  6955. return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision);
  6956.  
  6957. // Actual slider behavior + render grab
  6958. ItemSize(total_bb, style.FramePadding.y);
  6959. const bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision);
  6960.  
  6961. // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
  6962. char value_buf[64];
  6963. const char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v);
  6964. RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f));
  6965.  
  6966. if (label_size.x > 0.0f)
  6967. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
  6968.  
  6969. return value_changed;
  6970. }
  6971.  
  6972. bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* display_format, float power)
  6973. {
  6974. ImGuiWindow* window = GetCurrentWindow();
  6975. if (window->SkipItems)
  6976. return false;
  6977.  
  6978. ImGuiContext& g = *GImGui;
  6979. const ImGuiStyle& style = g.Style;
  6980. const ImGuiID id = window->GetID(label);
  6981.  
  6982. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  6983. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size);
  6984. const ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
  6985.  
  6986. ItemSize(bb, style.FramePadding.y);
  6987. if (!ItemAdd(frame_bb, &id))
  6988. return false;
  6989.  
  6990. const bool hovered = IsHovered(frame_bb, id);
  6991. if (hovered)
  6992. SetHoveredID(id);
  6993.  
  6994. if (!display_format)
  6995. display_format = "%.3f";
  6996. int decimal_precision = ParseFormatPrecision(display_format, 3);
  6997.  
  6998. if (hovered && g.IO.MouseClicked[0])
  6999. {
  7000. SetActiveID(id, window);
  7001. FocusWindow(window);
  7002. }
  7003.  
  7004. // Actual slider behavior + render grab
  7005. bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision, ImGuiSliderFlags_Vertical);
  7006.  
  7007. // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
  7008. // For the vertical slider we allow centered text to overlap the frame padding
  7009. char value_buf[64];
  7010. char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v);
  7011. RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.0f));
  7012. if (label_size.x > 0.0f)
  7013. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
  7014.  
  7015. return value_changed;
  7016. }
  7017.  
  7018. bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max)
  7019. {
  7020. float v_deg = (*v_rad) * 360.0f / (2 * IM_PI);
  7021. bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, "%.0f deg", 1.0f);
  7022. *v_rad = v_deg * (2 * IM_PI) / 360.0f;
  7023. return value_changed;
  7024. }
  7025.  
  7026. bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* display_format)
  7027. {
  7028. if (!display_format)
  7029. display_format = "%.0f";
  7030. float v_f = (float)*v;
  7031. bool value_changed = SliderFloat(label, &v_f, (float)v_min, (float)v_max, display_format, 1.0f);
  7032. *v = (int)v_f;
  7033. return value_changed;
  7034. }
  7035.  
  7036. bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* display_format)
  7037. {
  7038. if (!display_format)
  7039. display_format = "%.0f";
  7040. float v_f = (float)*v;
  7041. bool value_changed = VSliderFloat(label, size, &v_f, (float)v_min, (float)v_max, display_format, 1.0f);
  7042. *v = (int)v_f;
  7043. return value_changed;
  7044. }
  7045.  
  7046. // Add multiple sliders on 1 line for compact edition of multiple components
  7047. bool ImGui::SliderFloatN(const char* label, float* v, int components, float v_min, float v_max, const char* display_format, float power)
  7048. {
  7049. ImGuiWindow* window = GetCurrentWindow();
  7050. if (window->SkipItems)
  7051. return false;
  7052.  
  7053. ImGuiContext& g = *GImGui;
  7054. bool value_changed = false;
  7055. BeginGroup();
  7056. PushID(label);
  7057. PushMultiItemsWidths(components);
  7058. for (int i = 0; i < components; i++)
  7059. {
  7060. PushID(i);
  7061. value_changed |= SliderFloat("##v", &v[i], v_min, v_max, display_format, power);
  7062. SameLine(0, g.Style.ItemInnerSpacing.x);
  7063. PopID();
  7064. PopItemWidth();
  7065. }
  7066. PopID();
  7067.  
  7068. TextUnformatted(label, FindRenderedTextEnd(label));
  7069. EndGroup();
  7070.  
  7071. return value_changed;
  7072. }
  7073.  
  7074. bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format, float power)
  7075. {
  7076. return SliderFloatN(label, v, 2, v_min, v_max, display_format, power);
  7077. }
  7078.  
  7079. bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format, float power)
  7080. {
  7081. return SliderFloatN(label, v, 3, v_min, v_max, display_format, power);
  7082. }
  7083.  
  7084. bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* display_format, float power)
  7085. {
  7086. return SliderFloatN(label, v, 4, v_min, v_max, display_format, power);
  7087. }
  7088.  
  7089. bool ImGui::SliderIntN(const char* label, int* v, int components, int v_min, int v_max, const char* display_format)
  7090. {
  7091. ImGuiWindow* window = GetCurrentWindow();
  7092. if (window->SkipItems)
  7093. return false;
  7094.  
  7095. ImGuiContext& g = *GImGui;
  7096. bool value_changed = false;
  7097. BeginGroup();
  7098. PushID(label);
  7099. PushMultiItemsWidths(components);
  7100. for (int i = 0; i < components; i++)
  7101. {
  7102. PushID(i);
  7103. value_changed |= SliderInt("##v", &v[i], v_min, v_max, display_format);
  7104. SameLine(0, g.Style.ItemInnerSpacing.x);
  7105. PopID();
  7106. PopItemWidth();
  7107. }
  7108. PopID();
  7109.  
  7110. TextUnformatted(label, FindRenderedTextEnd(label));
  7111. EndGroup();
  7112.  
  7113. return value_changed;
  7114. }
  7115.  
  7116. bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* display_format)
  7117. {
  7118. return SliderIntN(label, v, 2, v_min, v_max, display_format);
  7119. }
  7120.  
  7121. bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* display_format)
  7122. {
  7123. return SliderIntN(label, v, 3, v_min, v_max, display_format);
  7124. }
  7125.  
  7126. bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* display_format)
  7127. {
  7128. return SliderIntN(label, v, 4, v_min, v_max, display_format);
  7129. }
  7130.  
  7131. bool ImGui::DragBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_speed, float v_min, float v_max, int decimal_precision, float power)
  7132. {
  7133. ImGuiContext& g = *GImGui;
  7134. const ImGuiStyle& style = g.Style;
  7135.  
  7136. // Draw frame
  7137. const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
  7138. RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding);
  7139.  
  7140. bool value_changed = false;
  7141.  
  7142. // Process clicking on the drag
  7143. if (g.ActiveId == id)
  7144. {
  7145. if (g.IO.MouseDown[0])
  7146. {
  7147. if (g.ActiveIdIsJustActivated)
  7148. {
  7149. // Lock current value on click
  7150. g.DragCurrentValue = *v;
  7151. g.DragLastMouseDelta = ImVec2(0.f, 0.f);
  7152. }
  7153.  
  7154. if (v_speed == 0.0f && (v_max - v_min) != 0.0f && (v_max - v_min) < FLT_MAX)
  7155. v_speed = (v_max - v_min) * g.DragSpeedDefaultRatio;
  7156. float v_cur = g.DragCurrentValue;
  7157. const ImVec2 mouse_drag_delta = GetMouseDragDelta(0, 1.0f);
  7158. float adjust_delta = 0.0f;
  7159. //if (g.ActiveIdSource == ImGuiInputSource_Mouse)
  7160. {
  7161. adjust_delta = mouse_drag_delta.x - g.DragLastMouseDelta.x;
  7162. if (g.IO.KeyShift && g.DragSpeedScaleFast >= 0.0f)
  7163. adjust_delta *= g.DragSpeedScaleFast;
  7164. if (g.IO.KeyAlt && g.DragSpeedScaleSlow >= 0.0f)
  7165. adjust_delta *= g.DragSpeedScaleSlow;
  7166. }
  7167. adjust_delta *= v_speed;
  7168. g.DragLastMouseDelta.x = mouse_drag_delta.x;
  7169.  
  7170. if (fabsf(adjust_delta) > 0.0f)
  7171. {
  7172. if (fabsf(power - 1.0f) > 0.001f)
  7173. {
  7174. // Logarithmic curve on both side of 0.0
  7175. float v0_abs = v_cur >= 0.0f ? v_cur : -v_cur;
  7176. float v0_sign = v_cur >= 0.0f ? 1.0f : -1.0f;
  7177. float v1 = powf(v0_abs, 1.0f / power) + (adjust_delta * v0_sign);
  7178. float v1_abs = v1 >= 0.0f ? v1 : -v1;
  7179. float v1_sign = v1 >= 0.0f ? 1.0f : -1.0f; // Crossed sign line
  7180. v_cur = powf(v1_abs, power) * v0_sign * v1_sign; // Reapply sign
  7181. }
  7182. else
  7183. {
  7184. v_cur += adjust_delta;
  7185. }
  7186.  
  7187. // Clamp
  7188. if (v_min < v_max)
  7189. v_cur = ImClamp(v_cur, v_min, v_max);
  7190. g.DragCurrentValue = v_cur;
  7191. }
  7192.  
  7193. // Round to user desired precision, then apply
  7194. v_cur = RoundScalar(v_cur, decimal_precision);
  7195. if (*v != v_cur)
  7196. {
  7197. *v = v_cur;
  7198. value_changed = true;
  7199. }
  7200. }
  7201. else
  7202. {
  7203. ClearActiveID();
  7204. }
  7205. }
  7206.  
  7207. return value_changed;
  7208. }
  7209.  
  7210. bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* display_format, float power)
  7211. {
  7212. ImGuiWindow* window = GetCurrentWindow();
  7213. if (window->SkipItems)
  7214. return false;
  7215.  
  7216. ImGuiContext& g = *GImGui;
  7217. const ImGuiStyle& style = g.Style;
  7218. const ImGuiID id = window->GetID(label);
  7219. const float w = CalcItemWidth();
  7220.  
  7221. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  7222. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
  7223. const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding);
  7224. const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
  7225.  
  7226. // NB- we don't call ItemSize() yet because we may turn into a text edit box below
  7227. if (!ItemAdd(total_bb, &id))
  7228. {
  7229. ItemSize(total_bb, style.FramePadding.y);
  7230. return false;
  7231. }
  7232.  
  7233. const bool hovered = IsHovered(frame_bb, id);
  7234. if (hovered)
  7235. SetHoveredID(id);
  7236.  
  7237. if (!display_format)
  7238. display_format = "%.3f";
  7239. int decimal_precision = ParseFormatPrecision(display_format, 3);
  7240.  
  7241. // Tabbing or CTRL-clicking on Drag turns it into an input box
  7242. bool start_text_input = false;
  7243. const bool tab_focus_requested = FocusableItemRegister(window, id);
  7244. if (tab_focus_requested || (hovered && (g.IO.MouseClicked[0] | g.IO.MouseDoubleClicked[0])))
  7245. {
  7246. SetActiveID(id, window);
  7247. FocusWindow(window);
  7248.  
  7249. if (tab_focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0])
  7250. {
  7251. start_text_input = true;
  7252. g.ScalarAsInputTextId = 0;
  7253. }
  7254. }
  7255. if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id))
  7256. return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision);
  7257.  
  7258. // Actual drag behavior
  7259. ItemSize(total_bb, style.FramePadding.y);
  7260. const bool value_changed = DragBehavior(frame_bb, id, v, v_speed, v_min, v_max, decimal_precision, power);
  7261.  
  7262. // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
  7263. char value_buf[64];
  7264. const char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v);
  7265. RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f));
  7266.  
  7267. if (label_size.x > 0.0f)
  7268. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label);
  7269.  
  7270. return value_changed;
  7271. }
  7272.  
  7273. bool ImGui::DragFloatN(const char* label, float* v, int components, float v_speed, float v_min, float v_max, const char* display_format, float power)
  7274. {
  7275. ImGuiWindow* window = GetCurrentWindow();
  7276. if (window->SkipItems)
  7277. return false;
  7278.  
  7279. ImGuiContext& g = *GImGui;
  7280. bool value_changed = false;
  7281. BeginGroup();
  7282. PushID(label);
  7283. PushMultiItemsWidths(components);
  7284. for (int i = 0; i < components; i++)
  7285. {
  7286. PushID(i);
  7287. value_changed |= DragFloat("##v", &v[i], v_speed, v_min, v_max, display_format, power);
  7288. SameLine(0, g.Style.ItemInnerSpacing.x);
  7289. PopID();
  7290. PopItemWidth();
  7291. }
  7292. PopID();
  7293.  
  7294. TextUnformatted(label, FindRenderedTextEnd(label));
  7295. EndGroup();
  7296.  
  7297. return value_changed;
  7298. }
  7299.  
  7300. bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* display_format, float power)
  7301. {
  7302. return DragFloatN(label, v, 2, v_speed, v_min, v_max, display_format, power);
  7303. }
  7304.  
  7305. bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* display_format, float power)
  7306. {
  7307. return DragFloatN(label, v, 3, v_speed, v_min, v_max, display_format, power);
  7308. }
  7309.  
  7310. bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* display_format, float power)
  7311. {
  7312. return DragFloatN(label, v, 4, v_speed, v_min, v_max, display_format, power);
  7313. }
  7314.  
  7315. bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* display_format, const char* display_format_max, float power)
  7316. {
  7317. ImGuiWindow* window = GetCurrentWindow();
  7318. if (window->SkipItems)
  7319. return false;
  7320.  
  7321. ImGuiContext& g = *GImGui;
  7322. PushID(label);
  7323. BeginGroup();
  7324. PushMultiItemsWidths(2);
  7325.  
  7326. bool value_changed = DragFloat("##min", v_current_min, v_speed, (v_min >= v_max) ? -FLT_MAX : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), display_format, power);
  7327. PopItemWidth();
  7328. SameLine(0, g.Style.ItemInnerSpacing.x);
  7329. value_changed |= DragFloat("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? FLT_MAX : v_max, display_format_max ? display_format_max : display_format, power);
  7330. PopItemWidth();
  7331. SameLine(0, g.Style.ItemInnerSpacing.x);
  7332.  
  7333. TextUnformatted(label, FindRenderedTextEnd(label));
  7334. EndGroup();
  7335. PopID();
  7336.  
  7337. return value_changed;
  7338. }
  7339.  
  7340. // NB: v_speed is float to allow adjusting the drag speed with more precision
  7341. bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* display_format)
  7342. {
  7343. if (!display_format)
  7344. display_format = "%.0f";
  7345. float v_f = (float)*v;
  7346. bool value_changed = DragFloat(label, &v_f, v_speed, (float)v_min, (float)v_max, display_format);
  7347. *v = (int)v_f;
  7348. return value_changed;
  7349. }
  7350.  
  7351. bool ImGui::DragIntN(const char* label, int* v, int components, float v_speed, int v_min, int v_max, const char* display_format)
  7352. {
  7353. ImGuiWindow* window = GetCurrentWindow();
  7354. if (window->SkipItems)
  7355. return false;
  7356.  
  7357. ImGuiContext& g = *GImGui;
  7358. bool value_changed = false;
  7359. BeginGroup();
  7360. PushID(label);
  7361. PushMultiItemsWidths(components);
  7362. for (int i = 0; i < components; i++)
  7363. {
  7364. PushID(i);
  7365. value_changed |= DragInt("##v", &v[i], v_speed, v_min, v_max, display_format);
  7366. SameLine(0, g.Style.ItemInnerSpacing.x);
  7367. PopID();
  7368. PopItemWidth();
  7369. }
  7370. PopID();
  7371.  
  7372. TextUnformatted(label, FindRenderedTextEnd(label));
  7373. EndGroup();
  7374.  
  7375. return value_changed;
  7376. }
  7377.  
  7378. bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* display_format)
  7379. {
  7380. return DragIntN(label, v, 2, v_speed, v_min, v_max, display_format);
  7381. }
  7382.  
  7383. bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* display_format)
  7384. {
  7385. return DragIntN(label, v, 3, v_speed, v_min, v_max, display_format);
  7386. }
  7387.  
  7388. bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* display_format)
  7389. {
  7390. return DragIntN(label, v, 4, v_speed, v_min, v_max, display_format);
  7391. }
  7392.  
  7393. bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* display_format, const char* display_format_max)
  7394. {
  7395. ImGuiWindow* window = GetCurrentWindow();
  7396. if (window->SkipItems)
  7397. return false;
  7398.  
  7399. ImGuiContext& g = *GImGui;
  7400. PushID(label);
  7401. BeginGroup();
  7402. PushMultiItemsWidths(2);
  7403.  
  7404. bool value_changed = DragInt("##min", v_current_min, v_speed, (v_min >= v_max) ? INT_MIN : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), display_format);
  7405. PopItemWidth();
  7406. SameLine(0, g.Style.ItemInnerSpacing.x);
  7407. value_changed |= DragInt("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? INT_MAX : v_max, display_format_max ? display_format_max : display_format);
  7408. PopItemWidth();
  7409. SameLine(0, g.Style.ItemInnerSpacing.x);
  7410.  
  7411. TextUnformatted(label, FindRenderedTextEnd(label));
  7412. EndGroup();
  7413. PopID();
  7414.  
  7415. return value_changed;
  7416. }
  7417.  
  7418. void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size)
  7419. {
  7420. ImGuiWindow* window = GetCurrentWindow();
  7421. if (window->SkipItems)
  7422. return;
  7423.  
  7424. ImGuiContext& g = *GImGui;
  7425. const ImGuiStyle& style = g.Style;
  7426.  
  7427. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  7428. if (graph_size.x == 0.0f)
  7429. graph_size.x = CalcItemWidth();
  7430. if (graph_size.y == 0.0f)
  7431. graph_size.y = label_size.y + (style.FramePadding.y * 2);
  7432.  
  7433. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(graph_size.x, graph_size.y));
  7434. const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding);
  7435. const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0));
  7436. ItemSize(total_bb, style.FramePadding.y);
  7437. if (!ItemAdd(total_bb, NULL))
  7438. return;
  7439.  
  7440. // Determine scale from values if not specified
  7441. if (scale_min == FLT_MAX || scale_max == FLT_MAX)
  7442. {
  7443. float v_min = FLT_MAX;
  7444. float v_max = -FLT_MAX;
  7445. for (int i = 0; i < values_count; i++)
  7446. {
  7447. const float v = values_getter(data, i);
  7448. v_min = ImMin(v_min, v);
  7449. v_max = ImMax(v_max, v);
  7450. }
  7451. if (scale_min == FLT_MAX)
  7452. scale_min = v_min;
  7453. if (scale_max == FLT_MAX)
  7454. scale_max = v_max;
  7455. }
  7456.  
  7457. RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
  7458.  
  7459. if (values_count > 0)
  7460. {
  7461. int res_w = ImMin((int)graph_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0);
  7462. int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0);
  7463.  
  7464. // Tooltip on hover
  7465. int v_hovered = -1;
  7466. if (IsHovered(inner_bb, 0))
  7467. {
  7468. const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f);
  7469. const int v_idx = (int)(t * item_count);
  7470. IM_ASSERT(v_idx >= 0 && v_idx < values_count);
  7471.  
  7472. const float v0 = values_getter(data, (v_idx + values_offset) % values_count);
  7473. const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count);
  7474. if (plot_type == ImGuiPlotType_Lines)
  7475. SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx + 1, v1);
  7476. else if (plot_type == ImGuiPlotType_Histogram)
  7477. SetTooltip("%d: %8.4g", v_idx, v0);
  7478. v_hovered = v_idx;
  7479. }
  7480.  
  7481. const float t_step = 1.0f / (float)res_w;
  7482.  
  7483. float v0 = values_getter(data, (0 + values_offset) % values_count);
  7484. float t0 = 0.0f;
  7485. ImVec2 tp0 = ImVec2(t0, 1.0f - ImSaturate((v0 - scale_min) / (scale_max - scale_min))); // Point in the normalized space of our target rectangle
  7486. float histogram_zero_line_t = (scale_min * scale_max < 0.0f) ? (-scale_min / (scale_max - scale_min)) : (scale_min < 0.0f ? 0.0f : 1.0f); // Where does the zero line stands
  7487.  
  7488. const ImU32 col_base = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram);
  7489. const ImU32 col_hovered = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered);
  7490.  
  7491. for (int n = 0; n < res_w; n++)
  7492. {
  7493. const float t1 = t0 + t_step;
  7494. const int v1_idx = (int)(t0 * item_count + 0.5f);
  7495. IM_ASSERT(v1_idx >= 0 && v1_idx < values_count);
  7496. const float v1 = values_getter(data, (v1_idx + values_offset + 1) % values_count);
  7497. const ImVec2 tp1 = ImVec2(t1, 1.0f - ImSaturate((v1 - scale_min) / (scale_max - scale_min)));
  7498.  
  7499. // NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU.
  7500. ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0);
  7501. ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, histogram_zero_line_t));
  7502. if (plot_type == ImGuiPlotType_Lines)
  7503. {
  7504. window->DrawList->AddLine(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base);
  7505. }
  7506. else if (plot_type == ImGuiPlotType_Histogram)
  7507. {
  7508. if (pos1.x >= pos0.x + 2.0f)
  7509. pos1.x -= 1.0f;
  7510. window->DrawList->AddRectFilled(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base);
  7511. }
  7512.  
  7513. t0 = t1;
  7514. tp0 = tp1;
  7515. }
  7516. }
  7517.  
  7518. // Text overlay
  7519. if (overlay_text)
  7520. RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, NULL, NULL, ImVec2(0.5f, 0.0f));
  7521.  
  7522. if (label_size.x > 0.0f)
  7523. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label);
  7524. }
  7525.  
  7526. struct ImGuiPlotArrayGetterData
  7527. {
  7528. const float* Values;
  7529. int Stride;
  7530.  
  7531. ImGuiPlotArrayGetterData(const float* values, int stride) { Values = values; Stride = stride; }
  7532. };
  7533.  
  7534. static float Plot_ArrayGetter(void* data, int idx)
  7535. {
  7536. ImGuiPlotArrayGetterData* plot_data = (ImGuiPlotArrayGetterData*)data;
  7537. const float v = *(float*)(void*)((unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride);
  7538. return v;
  7539. }
  7540.  
  7541. void ImGui::PlotLines(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride)
  7542. {
  7543. ImGuiPlotArrayGetterData data(values, stride);
  7544. PlotEx(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
  7545. }
  7546.  
  7547. void ImGui::PlotLines(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size)
  7548. {
  7549. PlotEx(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
  7550. }
  7551.  
  7552. void ImGui::PlotHistogram(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride)
  7553. {
  7554. ImGuiPlotArrayGetterData data(values, stride);
  7555. PlotEx(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
  7556. }
  7557.  
  7558. void ImGui::PlotHistogram(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size)
  7559. {
  7560. PlotEx(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
  7561. }
  7562.  
  7563. // size_arg (for each axis) < 0.0f: align to end, 0.0f: auto, > 0.0f: specified size
  7564. void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* overlay)
  7565. {
  7566. ImGuiWindow* window = GetCurrentWindow();
  7567. if (window->SkipItems)
  7568. return;
  7569.  
  7570. ImGuiContext& g = *GImGui;
  7571. const ImGuiStyle& style = g.Style;
  7572.  
  7573. ImVec2 pos = window->DC.CursorPos;
  7574. ImRect bb(pos, pos + CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f));
  7575. ItemSize(bb, style.FramePadding.y);
  7576. if (!ItemAdd(bb, NULL))
  7577. return;
  7578.  
  7579. // Render
  7580. fraction = ImSaturate(fraction);
  7581. RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
  7582. bb.Expand(ImVec2(-window->BorderSize, -window->BorderSize));
  7583. const ImVec2 fill_br = ImVec2(ImLerp(bb.Min.x, bb.Max.x, fraction), bb.Max.y);
  7584. RenderRectFilledRangeH(window->DrawList, bb, GetColorU32(ImGuiCol_PlotHistogram), 0.0f, fraction, style.FrameRounding);
  7585.  
  7586. // Default displaying the fraction as percentage string, but user can override it
  7587. char overlay_buf[32];
  7588. if (!overlay)
  7589. {
  7590. ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction * 100 + 0.01f);
  7591. overlay = overlay_buf;
  7592. }
  7593.  
  7594. ImVec2 overlay_size = CalcTextSize(overlay, NULL);
  7595. if (overlay_size.x > 0.0f)
  7596. RenderTextClipped(ImVec2(ImClamp(fill_br.x + style.ItemSpacing.x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, NULL, &overlay_size, ImVec2(0.0f, 0.5f), &bb);
  7597. }
  7598.  
  7599. bool ImGui::Checkbox(const char* label, bool* v)
  7600. {
  7601. ImGuiWindow* window = GetCurrentWindow();
  7602. if (window->SkipItems)
  7603. return false;
  7604.  
  7605. ImGuiContext& g = *GImGui;
  7606. const ImGuiStyle& style = g.Style;
  7607. const ImGuiID id = window->GetID(label);
  7608. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  7609.  
  7610. const ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y * 2, label_size.y + style.FramePadding.y * 2));
  7611. ItemSize(check_bb, style.FramePadding.y);
  7612.  
  7613. ImRect total_bb = check_bb;
  7614. if (label_size.x > 0)
  7615. SameLine(0, style.ItemInnerSpacing.x);
  7616. const ImRect text_bb(window->DC.CursorPos + ImVec2(0, style.FramePadding.y), window->DC.CursorPos + ImVec2(0, style.FramePadding.y) + label_size);
  7617. if (label_size.x > 0)
  7618. {
  7619. ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y);
  7620. total_bb = ImRect(ImMin(check_bb.Min, text_bb.Min), ImMax(check_bb.Max, text_bb.Max));
  7621. }
  7622.  
  7623. if (!ItemAdd(total_bb, &id))
  7624. return false;
  7625.  
  7626. bool hovered, held;
  7627. bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
  7628. if (pressed)
  7629. *v = !(*v);
  7630.  
  7631. const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight());
  7632. const float check_sz2 = check_sz / 2;
  7633. const float pad = ImMax(1.0f, (float)(int)(check_sz / 4.f));
  7634. RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding);
  7635. //window->DrawList->AddRectFilled(check_bb.Min+ImVec2(pad,pad), check_bb.Max-ImVec2(pad,pad), GetColorU32(ImGuiCol_CheckMark), style.FrameRounding);
  7636. if (*v)
  7637. {
  7638. //window->DrawList->AddRectFilled(check_bb.Min+ImVec2(pad,pad), check_bb.Max-ImVec2(pad,pad), GetColorU32(ImGuiCol_CheckMark), style.FrameRounding);
  7639. ImVec2* vecs = new ImVec2[3];
  7640. vecs[0] = check_bb.Min + ImVec2(5, check_sz2 + 1);
  7641. vecs[1] = check_bb.Max - ImVec2(check_sz2 + 1, 5);
  7642. vecs[2] = check_bb.Max - ImVec2(3, check_sz2 + 3);
  7643. window->DrawList->AddPolyline(vecs, 3, IM_COL32(220, 220, 220, 255), false, 1.5f, true);
  7644. }
  7645.  
  7646. if (g.LogEnabled)
  7647. LogRenderedText(text_bb.GetTL(), *v ? "[x]" : "[ ]");
  7648. if (label_size.x > 0.0f)
  7649. RenderText(text_bb.GetTL(), label);
  7650.  
  7651. return pressed;
  7652. }
  7653.  
  7654. bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value)
  7655. {
  7656. bool v = ((*flags & flags_value) == flags_value);
  7657. bool pressed = Checkbox(label, &v);
  7658. if (pressed)
  7659. {
  7660. if (v)
  7661. *flags |= flags_value;
  7662. else
  7663. *flags &= ~flags_value;
  7664. }
  7665.  
  7666. return pressed;
  7667. }
  7668.  
  7669. bool ImGui::RadioButton(const char* label, bool active)
  7670. {
  7671. ImGuiWindow* window = GetCurrentWindow();
  7672. if (window->SkipItems)
  7673. return false;
  7674.  
  7675. ImGuiContext& g = *GImGui;
  7676. const ImGuiStyle& style = g.Style;
  7677. const ImGuiID id = window->GetID(label);
  7678. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  7679.  
  7680. const ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y * 2 - 1, label_size.y + style.FramePadding.y * 2 - 1));
  7681. ItemSize(check_bb, style.FramePadding.y);
  7682.  
  7683. ImRect total_bb = check_bb;
  7684. if (label_size.x > 0)
  7685. SameLine(0, style.ItemInnerSpacing.x);
  7686. const ImRect text_bb(window->DC.CursorPos + ImVec2(0, style.FramePadding.y), window->DC.CursorPos + ImVec2(0, style.FramePadding.y) + label_size);
  7687. if (label_size.x > 0)
  7688. {
  7689. ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y);
  7690. total_bb.Add(text_bb);
  7691. }
  7692.  
  7693. if (!ItemAdd(total_bb, &id))
  7694. return false;
  7695.  
  7696. ImVec2 center = check_bb.GetCenter();
  7697. center.x = (float)(int)center.x + 0.5f;
  7698. center.y = (float)(int)center.y + 0.5f;
  7699. const float radius = check_bb.GetHeight() * 0.5f;
  7700.  
  7701. bool hovered, held;
  7702. bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
  7703.  
  7704. window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16);
  7705. if (active)
  7706. {
  7707. const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight());
  7708. const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f));
  7709. window->DrawList->AddCircleFilled(center, radius - pad, GetColorU32(ImGuiCol_CheckMark), 16);
  7710. }
  7711.  
  7712. if (window->Flags & ImGuiWindowFlags_ShowBorders)
  7713. {
  7714. window->DrawList->AddCircle(center + ImVec2(1, 1), radius, GetColorU32(ImGuiCol_BorderShadow), 16);
  7715. window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), 16);
  7716. }
  7717.  
  7718. if (g.LogEnabled)
  7719. LogRenderedText(text_bb.GetTL(), active ? "(x)" : "( )");
  7720. if (label_size.x > 0.0f)
  7721. RenderText(text_bb.GetTL(), label);
  7722.  
  7723. return pressed;
  7724. }
  7725.  
  7726. bool ImGui::RadioButton(const char* label, int* v, int v_button)
  7727. {
  7728. const bool pressed = RadioButton(label, *v == v_button);
  7729. if (pressed)
  7730. {
  7731. *v = v_button;
  7732. }
  7733. return pressed;
  7734. }
  7735.  
  7736. static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end)
  7737. {
  7738. int line_count = 0;
  7739. const char* s = text_begin;
  7740. while (char c = *s++) // We are only matching for \n so we can ignore UTF-8 decoding
  7741. if (c == '\n')
  7742. line_count++;
  7743. s--;
  7744. if (s[0] != '\n' && s[0] != '\r')
  7745. line_count++;
  7746. *out_text_end = s;
  7747. return line_count;
  7748. }
  7749.  
  7750. static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining, ImVec2* out_offset, bool stop_on_new_line)
  7751. {
  7752. ImFont* font = GImGui->Font;
  7753. const float line_height = GImGui->FontSize;
  7754. const float scale = line_height / font->FontSize;
  7755.  
  7756. ImVec2 text_size = ImVec2(0, 0);
  7757. float line_width = 0.0f;
  7758.  
  7759. const ImWchar* s = text_begin;
  7760. while (s < text_end)
  7761. {
  7762. unsigned int c = (unsigned int)(*s++);
  7763. if (c == '\n')
  7764. {
  7765. text_size.x = ImMax(text_size.x, line_width);
  7766. text_size.y += line_height;
  7767. line_width = 0.0f;
  7768. if (stop_on_new_line)
  7769. break;
  7770. continue;
  7771. }
  7772. if (c == '\r')
  7773. continue;
  7774.  
  7775. const float char_width = font->GetCharAdvance((unsigned short)c) * scale;
  7776. line_width += char_width;
  7777. }
  7778.  
  7779. if (text_size.x < line_width)
  7780. text_size.x = line_width;
  7781.  
  7782. if (out_offset)
  7783. *out_offset = ImVec2(line_width, text_size.y + line_height); // offset allow for the possibility of sitting after a trailing \n
  7784.  
  7785. if (line_width > 0 || text_size.y == 0.0f) // whereas size.y will ignore the trailing \n
  7786. text_size.y += line_height;
  7787.  
  7788. if (remaining)
  7789. *remaining = s;
  7790.  
  7791. return text_size;
  7792. }
  7793.  
  7794. // Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar)
  7795. namespace ImGuiStb
  7796. {
  7797.  
  7798. static int STB_TEXTEDIT_STRINGLEN(const STB_TEXTEDIT_STRING* obj) { return obj->CurLenW; }
  7799. static ImWchar STB_TEXTEDIT_GETCHAR(const STB_TEXTEDIT_STRING* obj, int idx) { return obj->Text[idx]; }
  7800. static float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { ImWchar c = obj->Text[line_start_idx + char_idx]; if (c == '\n') return STB_TEXTEDIT_GETWIDTH_NEWLINE; return GImGui->Font->GetCharAdvance(c) * (GImGui->FontSize / GImGui->Font->FontSize); }
  7801. static int STB_TEXTEDIT_KEYTOTEXT(int key) { return key >= 0x10000 ? 0 : key; }
  7802. static ImWchar STB_TEXTEDIT_NEWLINE = '\n';
  7803. static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, STB_TEXTEDIT_STRING* obj, int line_start_idx)
  7804. {
  7805. const ImWchar* text = obj->Text.Data;
  7806. const ImWchar* text_remaining = NULL;
  7807. const ImVec2 size = InputTextCalcTextSizeW(text + line_start_idx, text + obj->CurLenW, &text_remaining, NULL, true);
  7808. r->x0 = 0.0f;
  7809. r->x1 = size.x;
  7810. r->baseline_y_delta = size.y;
  7811. r->ymin = 0.0f;
  7812. r->ymax = size.y;
  7813. r->num_chars = (int)(text_remaining - (text + line_start_idx));
  7814. }
  7815.  
  7816. static bool is_separator(unsigned int c) { return ImCharIsSpace(c) || c == ',' || c == ';' || c == '(' || c == ')' || c == '{' || c == '}' || c == '[' || c == ']' || c == '|'; }
  7817. static int is_word_boundary_from_right(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (is_separator(obj->Text[idx - 1]) && !is_separator(obj->Text[idx])) : 1; }
  7818. static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx--; while (idx >= 0 && !is_word_boundary_from_right(obj, idx)) idx--; return idx < 0 ? 0 : idx; }
  7819. #ifdef __APPLE__ // FIXME: Move setting to IO structure
  7820. static int is_word_boundary_from_left(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (!is_separator(obj->Text[idx - 1]) && is_separator(obj->Text[idx])) : 1; }
  7821. static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_left(obj, idx)) idx++; return idx > len ? len : idx; }
  7822. #else
  7823. static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_right(obj, idx)) idx++; return idx > len ? len : idx; }
  7824. #endif
  7825. #define STB_TEXTEDIT_MOVEWORDLEFT STB_TEXTEDIT_MOVEWORDLEFT_IMPL // They need to be #define for stb_textedit.h
  7826. #define STB_TEXTEDIT_MOVEWORDRIGHT STB_TEXTEDIT_MOVEWORDRIGHT_IMPL
  7827.  
  7828. static void STB_TEXTEDIT_DELETECHARS(STB_TEXTEDIT_STRING* obj, int pos, int n)
  7829. {
  7830. ImWchar* dst = obj->Text.Data + pos;
  7831.  
  7832. // We maintain our buffer length in both UTF-8 and wchar formats
  7833. obj->CurLenA -= ImTextCountUtf8BytesFromStr(dst, dst + n);
  7834. obj->CurLenW -= n;
  7835.  
  7836. // Offset remaining text
  7837. const ImWchar* src = obj->Text.Data + pos + n;
  7838. while (ImWchar c = *src++)
  7839. *dst++ = c;
  7840. *dst = '\0';
  7841. }
  7842.  
  7843. static bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int pos, const ImWchar* new_text, int new_text_len)
  7844. {
  7845. const int text_len = obj->CurLenW;
  7846. IM_ASSERT(pos <= text_len);
  7847. if (new_text_len + text_len + 1 > obj->Text.Size)
  7848. return false;
  7849.  
  7850. const int new_text_len_utf8 = ImTextCountUtf8BytesFromStr(new_text, new_text + new_text_len);
  7851. if (new_text_len_utf8 + obj->CurLenA + 1 > obj->BufSizeA)
  7852. return false;
  7853.  
  7854. ImWchar* text = obj->Text.Data;
  7855. if (pos != text_len)
  7856. memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos) * sizeof(ImWchar));
  7857. memcpy(text + pos, new_text, (size_t)new_text_len * sizeof(ImWchar));
  7858.  
  7859. obj->CurLenW += new_text_len;
  7860. obj->CurLenA += new_text_len_utf8;
  7861. obj->Text[obj->CurLenW] = '\0';
  7862.  
  7863. return true;
  7864. }
  7865.  
  7866. // We don't use an enum so we can build even with conflicting symbols (if another user of stb_textedit.h leak their STB_TEXTEDIT_K_* symbols)
  7867. #define STB_TEXTEDIT_K_LEFT 0x10000 // keyboard input to move cursor left
  7868. #define STB_TEXTEDIT_K_RIGHT 0x10001 // keyboard input to move cursor right
  7869. #define STB_TEXTEDIT_K_UP 0x10002 // keyboard input to move cursor up
  7870. #define STB_TEXTEDIT_K_DOWN 0x10003 // keyboard input to move cursor down
  7871. #define STB_TEXTEDIT_K_LINESTART 0x10004 // keyboard input to move cursor to start of line
  7872. #define STB_TEXTEDIT_K_LINEEND 0x10005 // keyboard input to move cursor to end of line
  7873. #define STB_TEXTEDIT_K_TEXTSTART 0x10006 // keyboard input to move cursor to start of text
  7874. #define STB_TEXTEDIT_K_TEXTEND 0x10007 // keyboard input to move cursor to end of text
  7875. #define STB_TEXTEDIT_K_DELETE 0x10008 // keyboard input to delete selection or character under cursor
  7876. #define STB_TEXTEDIT_K_BACKSPACE 0x10009 // keyboard input to delete selection or character left of cursor
  7877. #define STB_TEXTEDIT_K_UNDO 0x1000A // keyboard input to perform undo
  7878. #define STB_TEXTEDIT_K_REDO 0x1000B // keyboard input to perform redo
  7879. #define STB_TEXTEDIT_K_WORDLEFT 0x1000C // keyboard input to move cursor left one word
  7880. #define STB_TEXTEDIT_K_WORDRIGHT 0x1000D // keyboard input to move cursor right one word
  7881. #define STB_TEXTEDIT_K_SHIFT 0x20000
  7882.  
  7883. #define STB_TEXTEDIT_IMPLEMENTATION
  7884. #include "stb_textedit.h"
  7885.  
  7886. }
  7887.  
  7888. void ImGuiTextEditState::OnKeyPressed(int key)
  7889. {
  7890. stb_textedit_key(this, &StbState, key);
  7891. CursorFollow = true;
  7892. CursorAnimReset();
  7893. }
  7894.  
  7895. // Public API to manipulate UTF-8 text
  7896. // We expose UTF-8 to the user (unlike the STB_TEXTEDIT_* functions which are manipulating wchar)
  7897. // FIXME: The existence of this rarely exercised code path is a bit of a nuisance.
  7898. void ImGuiTextEditCallbackData::DeleteChars(int pos, int bytes_count)
  7899. {
  7900. IM_ASSERT(pos + bytes_count <= BufTextLen);
  7901. char* dst = Buf + pos;
  7902. const char* src = Buf + pos + bytes_count;
  7903. while (char c = *src++)
  7904. *dst++ = c;
  7905. *dst = '\0';
  7906.  
  7907. if (CursorPos + bytes_count >= pos)
  7908. CursorPos -= bytes_count;
  7909. else if (CursorPos >= pos)
  7910. CursorPos = pos;
  7911. SelectionStart = SelectionEnd = CursorPos;
  7912. BufDirty = true;
  7913. BufTextLen -= bytes_count;
  7914. }
  7915.  
  7916. void ImGuiTextEditCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end)
  7917. {
  7918. const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)strlen(new_text);
  7919. if (new_text_len + BufTextLen + 1 >= BufSize)
  7920. return;
  7921.  
  7922. if (BufTextLen != pos)
  7923. memmove(Buf + pos + new_text_len, Buf + pos, (size_t)(BufTextLen - pos));
  7924. memcpy(Buf + pos, new_text, (size_t)new_text_len * sizeof(char));
  7925. Buf[BufTextLen + new_text_len] = '\0';
  7926.  
  7927. if (CursorPos >= pos)
  7928. CursorPos += new_text_len;
  7929. SelectionStart = SelectionEnd = CursorPos;
  7930. BufDirty = true;
  7931. BufTextLen += new_text_len;
  7932. }
  7933.  
  7934. // Return false to discard a character.
  7935. static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
  7936. {
  7937. unsigned int c = *p_char;
  7938.  
  7939. if (c < 128 && c != ' ' && !isprint((int)(c & 0xFF)))
  7940. {
  7941. bool pass = false;
  7942. pass |= (c == '\n' && (flags & ImGuiInputTextFlags_Multiline));
  7943. pass |= (c == '\t' && (flags & ImGuiInputTextFlags_AllowTabInput));
  7944. if (!pass)
  7945. return false;
  7946. }
  7947.  
  7948. if (c >= 0xE000 && c <= 0xF8FF) // Filter private Unicode range. I don't imagine anybody would want to input them. GLFW on OSX seems to send private characters for special keys like arrow keys.
  7949. return false;
  7950.  
  7951. if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank))
  7952. {
  7953. if (flags & ImGuiInputTextFlags_CharsDecimal)
  7954. if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/'))
  7955. return false;
  7956.  
  7957. if (flags & ImGuiInputTextFlags_CharsHexadecimal)
  7958. if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F'))
  7959. return false;
  7960.  
  7961. if (flags & ImGuiInputTextFlags_CharsUppercase)
  7962. if (c >= 'a' && c <= 'z')
  7963. *p_char = (c += (unsigned int)('A' - 'a'));
  7964.  
  7965. if (flags & ImGuiInputTextFlags_CharsNoBlank)
  7966. if (ImCharIsSpace(c))
  7967. return false;
  7968. }
  7969.  
  7970. if (flags & ImGuiInputTextFlags_CallbackCharFilter)
  7971. {
  7972. ImGuiTextEditCallbackData callback_data;
  7973. memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData));
  7974. callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter;
  7975. callback_data.EventChar = (ImWchar)c;
  7976. callback_data.Flags = flags;
  7977. callback_data.UserData = user_data;
  7978. if (callback(&callback_data) != 0)
  7979. return false;
  7980. *p_char = callback_data.EventChar;
  7981. if (!callback_data.EventChar)
  7982. return false;
  7983. }
  7984.  
  7985. return true;
  7986. }
  7987.  
  7988. // Edit a string of text
  7989. // NB: when active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while active has no effect.
  7990. // FIXME: Rather messy function partly because we are doing UTF8 > u16 > UTF8 conversions on the go to more easily handle stb_textedit calls. Ideally we should stay in UTF-8 all the time. See https://github.com/nothings/stb/issues/188
  7991. bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
  7992. {
  7993. ImGuiWindow* window = GetCurrentWindow();
  7994. if (window->SkipItems)
  7995. return false;
  7996.  
  7997. IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys)
  7998. IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key)
  7999.  
  8000. ImGuiContext& g = *GImGui;
  8001. const ImGuiIO& io = g.IO;
  8002. const ImGuiStyle& style = g.Style;
  8003.  
  8004. const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0;
  8005. const bool is_editable = (flags & ImGuiInputTextFlags_ReadOnly) == 0;
  8006. const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0;
  8007.  
  8008. if (is_multiline) // Open group before calling GetID() because groups tracks id created during their spawn
  8009. BeginGroup();
  8010. const ImGuiID id = window->GetID(label);
  8011. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  8012. ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? GetTextLineHeight() * 8.0f : label_size.y) + style.FramePadding.y*2.0f); // Arbitrary default of 8 lines high for multi-line
  8013. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size);
  8014. const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? (style.ItemInnerSpacing.x + label_size.x) : 0.0f, 0.0f));
  8015.  
  8016. ImGuiWindow* draw_window = window;
  8017. if (is_multiline)
  8018. {
  8019. if (!BeginChildFrame(id, frame_bb.GetSize()))
  8020. {
  8021. EndChildFrame();
  8022. EndGroup();
  8023. return false;
  8024. }
  8025. draw_window = GetCurrentWindow();
  8026. size.x -= draw_window->ScrollbarSizes.x;
  8027. }
  8028. else
  8029. {
  8030. ItemSize(total_bb, style.FramePadding.y);
  8031. if (!ItemAdd(total_bb, &id))
  8032. return false;
  8033. }
  8034.  
  8035. // Password pushes a temporary font with only a fallback glyph
  8036. if (is_password)
  8037. {
  8038. const ImFont::Glyph* glyph = g.Font->FindGlyph('*');
  8039. ImFont* password_font = &g.InputTextPasswordFont;
  8040. password_font->FontSize = g.Font->FontSize;
  8041. password_font->Scale = g.Font->Scale;
  8042. password_font->DisplayOffset = g.Font->DisplayOffset;
  8043. password_font->Ascent = g.Font->Ascent;
  8044. password_font->Descent = g.Font->Descent;
  8045. password_font->ContainerAtlas = g.Font->ContainerAtlas;
  8046. password_font->FallbackGlyph = glyph;
  8047. password_font->FallbackXAdvance = glyph->XAdvance;
  8048. IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexXAdvance.empty() && password_font->IndexLookup.empty());
  8049. PushFont(password_font);
  8050. }
  8051.  
  8052. // NB: we are only allowed to access 'edit_state' if we are the active widget.
  8053. ImGuiTextEditState& edit_state = g.InputTextState;
  8054.  
  8055. const bool focus_requested = FocusableItemRegister(window, id, (flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_AllowTabInput)) == 0); // Using completion callback disable keyboard tabbing
  8056. const bool focus_requested_by_code = focus_requested && (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent);
  8057. const bool focus_requested_by_tab = focus_requested && !focus_requested_by_code;
  8058.  
  8059. const bool hovered = IsHovered(frame_bb, id);
  8060. if (hovered)
  8061. {
  8062. SetHoveredID(id);
  8063. g.MouseCursor = ImGuiMouseCursor_TextInput;
  8064. }
  8065. const bool user_clicked = hovered && io.MouseClicked[0];
  8066. const bool user_scrolled = is_multiline && g.ActiveId == 0 && edit_state.Id == id && g.ActiveIdPreviousFrame == draw_window->GetIDNoKeepAlive("#SCROLLY");
  8067.  
  8068. bool clear_active_id = false;
  8069.  
  8070. bool select_all = (g.ActiveId != id) && (flags & ImGuiInputTextFlags_AutoSelectAll) != 0;
  8071. if (focus_requested || user_clicked || user_scrolled)
  8072. {
  8073. if (g.ActiveId != id)
  8074. {
  8075. // Start edition
  8076. // Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar)
  8077. // From the moment we focused we are ignoring the content of 'buf' (unless we are in read-only mode)
  8078. const int prev_len_w = edit_state.CurLenW;
  8079. edit_state.Text.resize(buf_size + 1); // wchar count <= UTF-8 count. we use +1 to make sure that .Data isn't NULL so it doesn't crash.
  8080. edit_state.InitialText.resize(buf_size + 1); // UTF-8. we use +1 to make sure that .Data isn't NULL so it doesn't crash.
  8081. ImStrncpy(edit_state.InitialText.Data, buf, edit_state.InitialText.Size);
  8082. const char* buf_end = NULL;
  8083. edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end);
  8084. edit_state.CurLenA = (int)(buf_end - buf); // We can't get the result from ImFormatString() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8.
  8085. edit_state.CursorAnimReset();
  8086.  
  8087. // Preserve cursor position and undo/redo stack if we come back to same widget
  8088. // FIXME: We should probably compare the whole buffer to be on the safety side. Comparing buf (utf8) and edit_state.Text (wchar).
  8089. const bool recycle_state = (edit_state.Id == id) && (prev_len_w == edit_state.CurLenW);
  8090. if (recycle_state)
  8091. {
  8092. // Recycle existing cursor/selection/undo stack but clamp position
  8093. // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler.
  8094. edit_state.CursorClamp();
  8095. }
  8096. else
  8097. {
  8098. edit_state.Id = id;
  8099. edit_state.ScrollX = 0.0f;
  8100. stb_textedit_initialize_state(&edit_state.StbState, !is_multiline);
  8101. if (!is_multiline && focus_requested_by_code)
  8102. select_all = true;
  8103. }
  8104. if (flags & ImGuiInputTextFlags_AlwaysInsertMode)
  8105. edit_state.StbState.insert_mode = true;
  8106. if (!is_multiline && (focus_requested_by_tab || (user_clicked && io.KeyCtrl)))
  8107. select_all = true;
  8108. }
  8109. SetActiveID(id, window);
  8110. FocusWindow(window);
  8111. }
  8112. else if (io.MouseClicked[0])
  8113. {
  8114. // Release focus when we click outside
  8115. clear_active_id = true;
  8116. }
  8117.  
  8118. bool value_changed = false;
  8119. bool enter_pressed = false;
  8120.  
  8121. if (g.ActiveId == id)
  8122. {
  8123. if (!is_editable && !g.ActiveIdIsJustActivated)
  8124. {
  8125. // When read-only we always use the live data passed to the function
  8126. edit_state.Text.resize(buf_size + 1);
  8127. const char* buf_end = NULL;
  8128. edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end);
  8129. edit_state.CurLenA = (int)(buf_end - buf);
  8130. edit_state.CursorClamp();
  8131. }
  8132.  
  8133. edit_state.BufSizeA = buf_size;
  8134.  
  8135. // Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget.
  8136. // Down the line we should have a cleaner library-wide concept of Selected vs Active.
  8137. g.ActiveIdAllowOverlap = !io.MouseDown[0];
  8138.  
  8139. // Edit in progress
  8140. const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + edit_state.ScrollX;
  8141. const float mouse_y = (is_multiline ? (io.MousePos.y - draw_window->DC.CursorPos.y - style.FramePadding.y) : (g.FontSize*0.5f));
  8142.  
  8143. const bool osx_double_click_selects_words = io.OSXBehaviors; // OS X style: Double click selects by word instead of selecting whole text
  8144. if (select_all || (hovered && !osx_double_click_selects_words && io.MouseDoubleClicked[0]))
  8145. {
  8146. edit_state.SelectAll();
  8147. edit_state.SelectedAllMouseLock = true;
  8148. }
  8149. else if (hovered && osx_double_click_selects_words && io.MouseDoubleClicked[0])
  8150. {
  8151. // Select a word only, OS X style (by simulating keystrokes)
  8152. edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT);
  8153. edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT);
  8154. }
  8155. else if (io.MouseClicked[0] && !edit_state.SelectedAllMouseLock)
  8156. {
  8157. stb_textedit_click(&edit_state, &edit_state.StbState, mouse_x, mouse_y);
  8158. edit_state.CursorAnimReset();
  8159. }
  8160. else if (io.MouseDown[0] && !edit_state.SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f))
  8161. {
  8162. stb_textedit_drag(&edit_state, &edit_state.StbState, mouse_x, mouse_y);
  8163. edit_state.CursorAnimReset();
  8164. edit_state.CursorFollow = true;
  8165. }
  8166. if (edit_state.SelectedAllMouseLock && !io.MouseDown[0])
  8167. edit_state.SelectedAllMouseLock = false;
  8168.  
  8169. if (io.InputCharacters[0])
  8170. {
  8171. // Process text input (before we check for Return because using some IME will effectively send a Return?)
  8172. // We ignore CTRL inputs, but need to allow CTRL+ALT as some keyboards (e.g. German) use AltGR - which is Alt+Ctrl - to input certain characters.
  8173. if (!(io.KeyCtrl && !io.KeyAlt) && is_editable)
  8174. {
  8175. for (int n = 0; n < IM_ARRAYSIZE(io.InputCharacters) && io.InputCharacters[n]; n++)
  8176. if (unsigned int c = (unsigned int)io.InputCharacters[n])
  8177. {
  8178. // Insert character if they pass filtering
  8179. if (!InputTextFilterCharacter(&c, flags, callback, user_data))
  8180. continue;
  8181. edit_state.OnKeyPressed((int)c);
  8182. }
  8183. }
  8184.  
  8185. // Consume characters
  8186. memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters));
  8187. }
  8188. }
  8189.  
  8190. bool cancel_edit = false;
  8191. if (g.ActiveId == id && !g.ActiveIdIsJustActivated && !clear_active_id)
  8192. {
  8193. // Handle key-presses
  8194. const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0);
  8195. const bool is_shortcut_key_only = (io.OSXBehaviors ? (io.KeySuper && !io.KeyCtrl) : (io.KeyCtrl && !io.KeySuper)) && !io.KeyAlt && !io.KeyShift; // OS X style: Shortcuts using Cmd/Super instead of Ctrl
  8196. const bool is_wordmove_key_down = io.OSXBehaviors ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl
  8197. const bool is_startend_key_down = io.OSXBehaviors && io.KeySuper && !io.KeyCtrl && !io.KeyAlt; // OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End
  8198.  
  8199. if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINESTART : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDLEFT : STB_TEXTEDIT_K_LEFT) | k_mask); }
  8200. else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINEEND : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT : STB_TEXTEDIT_K_RIGHT) | k_mask); }
  8201. else if (IsKeyPressedMap(ImGuiKey_UpArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMax(draw_window->Scroll.y - g.FontSize, 0.0f)); else edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTSTART : STB_TEXTEDIT_K_UP) | k_mask); }
  8202. else if (IsKeyPressedMap(ImGuiKey_DownArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMin(draw_window->Scroll.y + g.FontSize, GetScrollMaxY())); else edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTEND : STB_TEXTEDIT_K_DOWN) | k_mask); }
  8203. else if (IsKeyPressedMap(ImGuiKey_Home)) { edit_state.OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); }
  8204. else if (IsKeyPressedMap(ImGuiKey_End)) { edit_state.OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); }
  8205. else if (IsKeyPressedMap(ImGuiKey_Delete) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); }
  8206. else if (IsKeyPressedMap(ImGuiKey_Backspace) && is_editable)
  8207. {
  8208. if (!edit_state.HasSelection())
  8209. {
  8210. if (is_wordmove_key_down) edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT | STB_TEXTEDIT_K_SHIFT);
  8211. else if (io.OSXBehaviors && io.KeySuper && !io.KeyAlt && !io.KeyCtrl) edit_state.OnKeyPressed(STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT);
  8212. }
  8213. edit_state.OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask);
  8214. }
  8215. else if (IsKeyPressedMap(ImGuiKey_Enter))
  8216. {
  8217. bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0;
  8218. if (!is_multiline || (ctrl_enter_for_new_line && !io.KeyCtrl) || (!ctrl_enter_for_new_line && io.KeyCtrl))
  8219. {
  8220. enter_pressed = clear_active_id = true;
  8221. }
  8222. else if (is_editable)
  8223. {
  8224. unsigned int c = '\n'; // Insert new line
  8225. if (InputTextFilterCharacter(&c, flags, callback, user_data))
  8226. edit_state.OnKeyPressed((int)c);
  8227. }
  8228. }
  8229. else if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressedMap(ImGuiKey_Tab) && !io.KeyCtrl && !io.KeyShift && !io.KeyAlt && is_editable)
  8230. {
  8231. unsigned int c = '\t'; // Insert TAB
  8232. if (InputTextFilterCharacter(&c, flags, callback, user_data))
  8233. edit_state.OnKeyPressed((int)c);
  8234. }
  8235. else if (IsKeyPressedMap(ImGuiKey_Escape)) { clear_active_id = cancel_edit = true; }
  8236. else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Z) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_UNDO); edit_state.ClearSelection(); }
  8237. else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Y) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_REDO); edit_state.ClearSelection(); }
  8238. else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_A)) { edit_state.SelectAll(); edit_state.CursorFollow = true; }
  8239. else if (is_shortcut_key_only && !is_password && ((IsKeyPressedMap(ImGuiKey_X) && is_editable) || IsKeyPressedMap(ImGuiKey_C)) && (!is_multiline || edit_state.HasSelection()))
  8240. {
  8241. // Cut, Copy
  8242. const bool cut = IsKeyPressedMap(ImGuiKey_X);
  8243. if (cut && !edit_state.HasSelection())
  8244. edit_state.SelectAll();
  8245.  
  8246. if (io.SetClipboardTextFn)
  8247. {
  8248. const int ib = edit_state.HasSelection() ? ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end) : 0;
  8249. const int ie = edit_state.HasSelection() ? ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end) : edit_state.CurLenW;
  8250. edit_state.TempTextBuffer.resize((ie - ib) * 4 + 1);
  8251. ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.Data + ib, edit_state.Text.Data + ie);
  8252. SetClipboardText(edit_state.TempTextBuffer.Data);
  8253. }
  8254.  
  8255. if (cut)
  8256. {
  8257. edit_state.CursorFollow = true;
  8258. stb_textedit_cut(&edit_state, &edit_state.StbState);
  8259. }
  8260. }
  8261. else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_V) && is_editable)
  8262. {
  8263. // Paste
  8264. if (const char* clipboard = GetClipboardText())
  8265. {
  8266. // Filter pasted buffer
  8267. const int clipboard_len = (int)strlen(clipboard);
  8268. ImWchar* clipboard_filtered = (ImWchar*)ImGui::MemAlloc((clipboard_len + 1) * sizeof(ImWchar));
  8269. int clipboard_filtered_len = 0;
  8270. for (const char* s = clipboard; *s; )
  8271. {
  8272. unsigned int c;
  8273. s += ImTextCharFromUtf8(&c, s, NULL);
  8274. if (c == 0)
  8275. break;
  8276. if (c >= 0x10000 || !InputTextFilterCharacter(&c, flags, callback, user_data))
  8277. continue;
  8278. clipboard_filtered[clipboard_filtered_len++] = (ImWchar)c;
  8279. }
  8280. clipboard_filtered[clipboard_filtered_len] = 0;
  8281. if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation
  8282. {
  8283. stb_textedit_paste(&edit_state, &edit_state.StbState, clipboard_filtered, clipboard_filtered_len);
  8284. edit_state.CursorFollow = true;
  8285. }
  8286. ImGui::MemFree(clipboard_filtered);
  8287. }
  8288. }
  8289. }
  8290.  
  8291. if (g.ActiveId == id)
  8292. {
  8293. if (cancel_edit)
  8294. {
  8295. // Restore initial value
  8296. if (is_editable)
  8297. {
  8298. ImStrncpy(buf, edit_state.InitialText.Data, buf_size);
  8299. value_changed = true;
  8300. }
  8301. }
  8302.  
  8303. // When using 'ImGuiInputTextFlags_EnterReturnsTrue' as a special case we reapply the live buffer back to the input buffer before clearing ActiveId, even though strictly speaking it wasn't modified on this frame.
  8304. // If we didn't do that, code like InputInt() with ImGuiInputTextFlags_EnterReturnsTrue would fail. Also this allows the user to use InputText() with ImGuiInputTextFlags_EnterReturnsTrue without maintaining any user-side storage.
  8305. bool apply_edit_back_to_user_buffer = !cancel_edit || (enter_pressed && (flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0);
  8306. if (apply_edit_back_to_user_buffer)
  8307. {
  8308. // Apply new value immediately - copy modified buffer back
  8309. // Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer
  8310. // FIXME: We actually always render 'buf' when calling DrawList->AddText, making the comment above incorrect.
  8311. // FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks.
  8312. if (is_editable)
  8313. {
  8314. edit_state.TempTextBuffer.resize(edit_state.Text.Size * 4);
  8315. ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.Data, NULL);
  8316. }
  8317.  
  8318. // User callback
  8319. if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackAlways)) != 0)
  8320. {
  8321. IM_ASSERT(callback != NULL);
  8322.  
  8323. // The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment.
  8324. ImGuiInputTextFlags event_flag = 0;
  8325. ImGuiKey event_key = ImGuiKey_COUNT;
  8326. if ((flags & ImGuiInputTextFlags_CallbackCompletion) != 0 && IsKeyPressedMap(ImGuiKey_Tab))
  8327. {
  8328. event_flag = ImGuiInputTextFlags_CallbackCompletion;
  8329. event_key = ImGuiKey_Tab;
  8330. }
  8331. else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_UpArrow))
  8332. {
  8333. event_flag = ImGuiInputTextFlags_CallbackHistory;
  8334. event_key = ImGuiKey_UpArrow;
  8335. }
  8336. else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_DownArrow))
  8337. {
  8338. event_flag = ImGuiInputTextFlags_CallbackHistory;
  8339. event_key = ImGuiKey_DownArrow;
  8340. }
  8341. else if (flags & ImGuiInputTextFlags_CallbackAlways)
  8342. event_flag = ImGuiInputTextFlags_CallbackAlways;
  8343.  
  8344. if (event_flag)
  8345. {
  8346. ImGuiTextEditCallbackData callback_data;
  8347. memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData));
  8348. callback_data.EventFlag = event_flag;
  8349. callback_data.Flags = flags;
  8350. callback_data.UserData = user_data;
  8351. callback_data.ReadOnly = !is_editable;
  8352.  
  8353. callback_data.EventKey = event_key;
  8354. callback_data.Buf = edit_state.TempTextBuffer.Data;
  8355. callback_data.BufTextLen = edit_state.CurLenA;
  8356. callback_data.BufSize = edit_state.BufSizeA;
  8357. callback_data.BufDirty = false;
  8358.  
  8359. // We have to convert from wchar-positions to UTF-8-positions, which can be pretty slow (an incentive to ditch the ImWchar buffer, see https://github.com/nothings/stb/issues/188)
  8360. ImWchar* text = edit_state.Text.Data;
  8361. const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.cursor);
  8362. const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_start);
  8363. const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_end);
  8364.  
  8365. // Call user code
  8366. callback(&callback_data);
  8367.  
  8368. // Read back what user may have modified
  8369. IM_ASSERT(callback_data.Buf == edit_state.TempTextBuffer.Data); // Invalid to modify those fields
  8370. IM_ASSERT(callback_data.BufSize == edit_state.BufSizeA);
  8371. IM_ASSERT(callback_data.Flags == flags);
  8372. if (callback_data.CursorPos != utf8_cursor_pos) edit_state.StbState.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos);
  8373. if (callback_data.SelectionStart != utf8_selection_start) edit_state.StbState.select_start = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart);
  8374. if (callback_data.SelectionEnd != utf8_selection_end) edit_state.StbState.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd);
  8375. if (callback_data.BufDirty)
  8376. {
  8377. IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text!
  8378. edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, callback_data.Buf, NULL);
  8379. edit_state.CurLenA = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen()
  8380. edit_state.CursorAnimReset();
  8381. }
  8382. }
  8383. }
  8384.  
  8385. // Copy back to user buffer
  8386. if (is_editable && strcmp(edit_state.TempTextBuffer.Data, buf) != 0)
  8387. {
  8388. ImStrncpy(buf, edit_state.TempTextBuffer.Data, buf_size);
  8389. value_changed = true;
  8390. }
  8391. }
  8392. }
  8393.  
  8394. // Release active ID at the end of the function (so e.g. pressing Return still does a final application of the value)
  8395. if (clear_active_id && g.ActiveId == id)
  8396. ClearActiveID();
  8397.  
  8398. // Render
  8399. // Select which buffer we are going to display. When ImGuiInputTextFlags_NoLiveEdit is set 'buf' might still be the old value. We set buf to NULL to prevent accidental usage from now on.
  8400. const char* buf_display = (g.ActiveId == id && is_editable) ? edit_state.TempTextBuffer.Data : buf; buf = NULL;
  8401.  
  8402. if (!is_multiline)
  8403. RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
  8404.  
  8405. const ImVec4 clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + size.x, frame_bb.Min.y + size.y); // Not using frame_bb.Max because we have adjusted size
  8406. ImVec2 render_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding;
  8407. ImVec2 text_size(0.f, 0.f);
  8408. const bool is_currently_scrolling = (edit_state.Id == id && is_multiline && g.ActiveId == draw_window->GetIDNoKeepAlive("#SCROLLY"));
  8409. if (g.ActiveId == id || is_currently_scrolling)
  8410. {
  8411. edit_state.CursorAnim += io.DeltaTime;
  8412.  
  8413. // This is going to be messy. We need to:
  8414. // - Display the text (this alone can be more easily clipped)
  8415. // - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation)
  8416. // - Measure text height (for scrollbar)
  8417. // We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort)
  8418. // FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8.
  8419. const ImWchar* text_begin = edit_state.Text.Data;
  8420. ImVec2 cursor_offset, select_start_offset;
  8421.  
  8422. {
  8423. // Count lines + find lines numbers straddling 'cursor' and 'select_start' position.
  8424. const ImWchar* searches_input_ptr[2];
  8425. searches_input_ptr[0] = text_begin + edit_state.StbState.cursor;
  8426. searches_input_ptr[1] = NULL;
  8427. int searches_remaining = 1;
  8428. int searches_result_line_number[2] = { -1, -999 };
  8429. if (edit_state.StbState.select_start != edit_state.StbState.select_end)
  8430. {
  8431. searches_input_ptr[1] = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end);
  8432. searches_result_line_number[1] = -1;
  8433. searches_remaining++;
  8434. }
  8435.  
  8436. // Iterate all lines to find our line numbers
  8437. // In multi-line mode, we never exit the loop until all lines are counted, so add one extra to the searches_remaining counter.
  8438. searches_remaining += is_multiline ? 1 : 0;
  8439. int line_count = 0;
  8440. for (const ImWchar* s = text_begin; *s != 0; s++)
  8441. if (*s == '\n')
  8442. {
  8443. line_count++;
  8444. if (searches_result_line_number[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_number[0] = line_count; if (--searches_remaining <= 0) break; }
  8445. if (searches_result_line_number[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_number[1] = line_count; if (--searches_remaining <= 0) break; }
  8446. }
  8447. line_count++;
  8448. if (searches_result_line_number[0] == -1) searches_result_line_number[0] = line_count;
  8449. if (searches_result_line_number[1] == -1) searches_result_line_number[1] = line_count;
  8450.  
  8451. // Calculate 2d position by finding the beginning of the line and measuring distance
  8452. cursor_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[0], text_begin), searches_input_ptr[0]).x;
  8453. cursor_offset.y = searches_result_line_number[0] * g.FontSize;
  8454. if (searches_result_line_number[1] >= 0)
  8455. {
  8456. select_start_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[1], text_begin), searches_input_ptr[1]).x;
  8457. select_start_offset.y = searches_result_line_number[1] * g.FontSize;
  8458. }
  8459.  
  8460. // Store text height (note that we haven't calculated text width at all, see GitHub issues #383, #1224)
  8461. if (is_multiline)
  8462. text_size = ImVec2(size.x, line_count * g.FontSize);
  8463. }
  8464.  
  8465. // Scroll
  8466. if (edit_state.CursorFollow)
  8467. {
  8468. // Horizontal scroll in chunks of quarter width
  8469. if (!(flags & ImGuiInputTextFlags_NoHorizontalScroll))
  8470. {
  8471. const float scroll_increment_x = size.x * 0.25f;
  8472. if (cursor_offset.x < edit_state.ScrollX)
  8473. edit_state.ScrollX = (float)(int)ImMax(0.0f, cursor_offset.x - scroll_increment_x);
  8474. else if (cursor_offset.x - size.x >= edit_state.ScrollX)
  8475. edit_state.ScrollX = (float)(int)(cursor_offset.x - size.x + scroll_increment_x);
  8476. }
  8477. else
  8478. {
  8479. edit_state.ScrollX = 0.0f;
  8480. }
  8481.  
  8482. // Vertical scroll
  8483. if (is_multiline)
  8484. {
  8485. float scroll_y = draw_window->Scroll.y;
  8486. if (cursor_offset.y - g.FontSize < scroll_y)
  8487. scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize);
  8488. else if (cursor_offset.y - size.y >= scroll_y)
  8489. scroll_y = cursor_offset.y - size.y;
  8490. draw_window->DC.CursorPos.y += (draw_window->Scroll.y - scroll_y); // To avoid a frame of lag
  8491. draw_window->Scroll.y = scroll_y;
  8492. render_pos.y = draw_window->DC.CursorPos.y;
  8493. }
  8494. }
  8495. edit_state.CursorFollow = false;
  8496. const ImVec2 render_scroll = ImVec2(edit_state.ScrollX, 0.0f);
  8497.  
  8498. // Draw selection
  8499. if (edit_state.StbState.select_start != edit_state.StbState.select_end)
  8500. {
  8501. const ImWchar* text_selected_begin = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end);
  8502. const ImWchar* text_selected_end = text_begin + ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end);
  8503.  
  8504. float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection.
  8505. float bg_offy_dn = is_multiline ? 0.0f : 2.0f;
  8506. ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg);
  8507. ImVec2 rect_pos = render_pos + select_start_offset - render_scroll;
  8508. for (const ImWchar* p = text_selected_begin; p < text_selected_end; )
  8509. {
  8510. if (rect_pos.y > clip_rect.w + g.FontSize)
  8511. break;
  8512. if (rect_pos.y < clip_rect.y)
  8513. {
  8514. while (p < text_selected_end)
  8515. if (*p++ == '\n')
  8516. break;
  8517. }
  8518. else
  8519. {
  8520. ImVec2 rect_size = InputTextCalcTextSizeW(p, text_selected_end, &p, NULL, true);
  8521. if (rect_size.x <= 0.0f) rect_size.x = (float)(int)(g.Font->GetCharAdvance((unsigned short)' ') * 0.50f); // So we can see selected empty lines
  8522. ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos + ImVec2(rect_size.x, bg_offy_dn));
  8523. rect.ClipWith(clip_rect);
  8524. if (rect.Overlaps(clip_rect))
  8525. draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color);
  8526. }
  8527. rect_pos.x = render_pos.x - render_scroll.x;
  8528. rect_pos.y += g.FontSize;
  8529. }
  8530. }
  8531.  
  8532. draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos - render_scroll, GetColorU32(ImGuiCol_Text), buf_display, buf_display + edit_state.CurLenA, 0.0f, is_multiline ? NULL : &clip_rect);
  8533.  
  8534. // Draw blinking cursor
  8535. bool cursor_is_visible = (g.InputTextState.CursorAnim <= 0.0f) || fmodf(g.InputTextState.CursorAnim, 1.20f) <= 0.80f;
  8536. ImVec2 cursor_screen_pos = render_pos + cursor_offset - render_scroll;
  8537. ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y - g.FontSize + 0.5f, cursor_screen_pos.x + 1.0f, cursor_screen_pos.y - 1.5f);
  8538. if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect))
  8539. draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text));
  8540.  
  8541. // Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.)
  8542. if (is_editable)
  8543. g.OsImePosRequest = ImVec2(cursor_screen_pos.x - 1, cursor_screen_pos.y - g.FontSize);
  8544. }
  8545. else
  8546. {
  8547. // Render text only
  8548. const char* buf_end = NULL;
  8549. if (is_multiline)
  8550. text_size = ImVec2(size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_end) * g.FontSize); // We don't need width
  8551. draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos, GetColorU32(ImGuiCol_Text), buf_display, buf_end, 0.0f, is_multiline ? NULL : &clip_rect);
  8552. }
  8553.  
  8554. if (is_multiline)
  8555. {
  8556. Dummy(text_size + ImVec2(0.0f, g.FontSize)); // Always add room to scroll an extra line
  8557. EndChildFrame();
  8558. EndGroup();
  8559. }
  8560.  
  8561. if (is_password)
  8562. PopFont();
  8563.  
  8564. // Log as text
  8565. if (g.LogEnabled && !is_password)
  8566. LogRenderedText(render_pos, buf_display, NULL);
  8567.  
  8568. if (label_size.x > 0)
  8569. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
  8570.  
  8571. if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0)
  8572. return enter_pressed;
  8573. else
  8574. return value_changed;
  8575. }
  8576.  
  8577. bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
  8578. {
  8579. IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline()
  8580. return InputTextEx(label, buf, (int)buf_size, ImVec2(0, 0), flags, callback, user_data);
  8581. }
  8582.  
  8583. bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
  8584. {
  8585. return InputTextEx(label, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data);
  8586. }
  8587.  
  8588. // NB: scalar_format here must be a simple "%xx" format string with no prefix/suffix (unlike the Drag/Slider functions "display_format" argument)
  8589. bool ImGui::InputScalarEx(const char* label, ImGuiDataType data_type, void* data_ptr, void* step_ptr, void* step_fast_ptr, const char* scalar_format, ImGuiInputTextFlags extra_flags)
  8590. {
  8591. ImGuiWindow* window = GetCurrentWindow();
  8592. if (window->SkipItems)
  8593. return false;
  8594.  
  8595. ImGuiContext& g = *GImGui;
  8596. const ImGuiStyle& style = g.Style;
  8597. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  8598.  
  8599. BeginGroup();
  8600. PushID(label);
  8601. const ImVec2 button_sz = ImVec2(g.FontSize, g.FontSize) + style.FramePadding*2.0f;
  8602. if (step_ptr)
  8603. PushItemWidth(ImMax(1.0f, CalcItemWidth() - (button_sz.x + style.ItemInnerSpacing.x) * 2));
  8604.  
  8605. char buf[64];
  8606. DataTypeFormatString(data_type, data_ptr, scalar_format, buf, IM_ARRAYSIZE(buf));
  8607.  
  8608. bool value_changed = false;
  8609. if (!(extra_flags & ImGuiInputTextFlags_CharsHexadecimal))
  8610. extra_flags |= ImGuiInputTextFlags_CharsDecimal;
  8611. extra_flags |= ImGuiInputTextFlags_AutoSelectAll;
  8612. if (InputText("", buf, IM_ARRAYSIZE(buf), extra_flags)) // PushId(label) + "" gives us the expected ID from outside point of view
  8613. value_changed = DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, scalar_format);
  8614.  
  8615. // Step buttons
  8616. if (step_ptr)
  8617. {
  8618. PopItemWidth();
  8619. SameLine(0, style.ItemInnerSpacing.x);
  8620. if (ButtonEx("-", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups))
  8621. {
  8622. DataTypeApplyOp(data_type, '-', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr);
  8623. value_changed = true;
  8624. }
  8625. SameLine(0, style.ItemInnerSpacing.x);
  8626. if (ButtonEx("+", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups))
  8627. {
  8628. DataTypeApplyOp(data_type, '+', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr);
  8629. value_changed = true;
  8630. }
  8631. }
  8632. PopID();
  8633.  
  8634. if (label_size.x > 0)
  8635. {
  8636. SameLine(0, style.ItemInnerSpacing.x);
  8637. RenderText(ImVec2(window->DC.CursorPos.x, window->DC.CursorPos.y + style.FramePadding.y), label);
  8638. ItemSize(label_size, style.FramePadding.y);
  8639. }
  8640. EndGroup();
  8641.  
  8642. return value_changed;
  8643. }
  8644.  
  8645. bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags extra_flags)
  8646. {
  8647. char display_format[16];
  8648. if (decimal_precision < 0)
  8649. strcpy(display_format, "%f"); // Ideally we'd have a minimum decimal precision of 1 to visually denote that this is a float, while hiding non-significant digits? %f doesn't have a minimum of 1
  8650. else
  8651. ImFormatString(display_format, IM_ARRAYSIZE(display_format), "%%.%df", decimal_precision);
  8652. return InputScalarEx(label, ImGuiDataType_Float, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), display_format, extra_flags);
  8653. }
  8654.  
  8655. bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags extra_flags)
  8656. {
  8657. // Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use InputText() to parse your own data, if you want to handle prefixes.
  8658. const char* scalar_format = (extra_flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d";
  8659. return InputScalarEx(label, ImGuiDataType_Int, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), scalar_format, extra_flags);
  8660. }
  8661.  
  8662. bool ImGui::InputFloatN(const char* label, float* v, int components, int decimal_precision, ImGuiInputTextFlags extra_flags)
  8663. {
  8664. ImGuiWindow* window = GetCurrentWindow();
  8665. if (window->SkipItems)
  8666. return false;
  8667.  
  8668. ImGuiContext& g = *GImGui;
  8669. bool value_changed = false;
  8670. BeginGroup();
  8671. PushID(label);
  8672. PushMultiItemsWidths(components);
  8673. for (int i = 0; i < components; i++)
  8674. {
  8675. PushID(i);
  8676. value_changed |= InputFloat("##v", &v[i], 0, 0, decimal_precision, extra_flags);
  8677. SameLine(0, g.Style.ItemInnerSpacing.x);
  8678. PopID();
  8679. PopItemWidth();
  8680. }
  8681. PopID();
  8682.  
  8683. window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y);
  8684. TextUnformatted(label, FindRenderedTextEnd(label));
  8685. EndGroup();
  8686.  
  8687. return value_changed;
  8688. }
  8689.  
  8690. bool ImGui::InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags extra_flags)
  8691. {
  8692. return InputFloatN(label, v, 2, decimal_precision, extra_flags);
  8693. }
  8694.  
  8695. bool ImGui::InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags extra_flags)
  8696. {
  8697. return InputFloatN(label, v, 3, decimal_precision, extra_flags);
  8698. }
  8699.  
  8700. bool ImGui::InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags extra_flags)
  8701. {
  8702. return InputFloatN(label, v, 4, decimal_precision, extra_flags);
  8703. }
  8704.  
  8705. bool ImGui::InputIntN(const char* label, int* v, int components, ImGuiInputTextFlags extra_flags)
  8706. {
  8707. ImGuiWindow* window = GetCurrentWindow();
  8708. if (window->SkipItems)
  8709. return false;
  8710.  
  8711. ImGuiContext& g = *GImGui;
  8712. bool value_changed = false;
  8713. BeginGroup();
  8714. PushID(label);
  8715. PushMultiItemsWidths(components);
  8716. for (int i = 0; i < components; i++)
  8717. {
  8718. PushID(i);
  8719. value_changed |= InputInt("##v", &v[i], 0, 0, extra_flags);
  8720. SameLine(0, g.Style.ItemInnerSpacing.x);
  8721. PopID();
  8722. PopItemWidth();
  8723. }
  8724. PopID();
  8725.  
  8726. window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y);
  8727. TextUnformatted(label, FindRenderedTextEnd(label));
  8728. EndGroup();
  8729.  
  8730. return value_changed;
  8731. }
  8732.  
  8733. bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags extra_flags)
  8734. {
  8735. return InputIntN(label, v, 2, extra_flags);
  8736. }
  8737.  
  8738. bool ImGui::InputInt3(const char* label, int v[3], ImGuiInputTextFlags extra_flags)
  8739. {
  8740. return InputIntN(label, v, 3, extra_flags);
  8741. }
  8742.  
  8743. bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags)
  8744. {
  8745. return InputIntN(label, v, 4, extra_flags);
  8746. }
  8747.  
  8748. static bool Items_ArrayGetter(void* data, int idx, const char** out_text)
  8749. {
  8750. const char* const* items = (const char* const*)data;
  8751. if (out_text)
  8752. *out_text = items[idx];
  8753. return true;
  8754. }
  8755.  
  8756. static bool Items_SingleStringGetter(void* data, int idx, const char** out_text)
  8757. {
  8758. // FIXME-OPT: we could pre-compute the indices to fasten this. But only 1 active combo means the waste is limited.
  8759. const char* items_separated_by_zeros = (const char*)data;
  8760. int items_count = 0;
  8761. const char* p = items_separated_by_zeros;
  8762. while (*p)
  8763. {
  8764. if (idx == items_count)
  8765. break;
  8766. p += strlen(p) + 1;
  8767. items_count++;
  8768. }
  8769. if (!*p)
  8770. return false;
  8771. if (out_text)
  8772. *out_text = p;
  8773. return true;
  8774. }
  8775.  
  8776. // Combo box helper allowing to pass an array of strings.
  8777. bool ImGui::Combo(const char* label, int* current_item, const char* const* items, int items_count, int height_in_items)
  8778. {
  8779. const bool value_changed = Combo(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_in_items);
  8780. return value_changed;
  8781. }
  8782.  
  8783. // Combo box helper allowing to pass all items in a single string.
  8784. bool ImGui::Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items)
  8785. {
  8786. int items_count = 0;
  8787. const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this, or at least only when combo is open
  8788. while (*p)
  8789. {
  8790. p += strlen(p) + 1;
  8791. items_count++;
  8792. }
  8793. bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items);
  8794. return value_changed;
  8795. }
  8796.  
  8797. // Combo box function.
  8798. bool ImGui::Combo(const char* label, int* current_item, bool(*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items)
  8799. {
  8800. ImGuiWindow* window = GetCurrentWindow();
  8801. if (window->SkipItems)
  8802. return false;
  8803.  
  8804. ImGuiContext& g = *GImGui;
  8805. const ImGuiStyle& style = g.Style;
  8806. const ImGuiID id = window->GetID(label);
  8807. const float w = CalcItemWidth();
  8808.  
  8809. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  8810. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
  8811. const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
  8812. ItemSize(total_bb, style.FramePadding.y);
  8813. if (!ItemAdd(total_bb, &id))
  8814. return false;
  8815.  
  8816. const float arrow_size = (g.FontSize + style.FramePadding.x * 2.0f);
  8817. const bool hovered = IsHovered(frame_bb, id);
  8818. bool popup_open = IsPopupOpen(id);
  8819.  
  8820. const ImRect value_bb(frame_bb.Min, frame_bb.Max - ImVec2(arrow_size, 0.0f));
  8821. RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
  8822. RenderFrame(ImVec2(frame_bb.Max.x - arrow_size, frame_bb.Min.y), frame_bb.Max, GetColorU32(popup_open || hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button), true, style.FrameRounding); // FIXME-ROUNDING
  8823. RenderCollapseTriangle(ImVec2(frame_bb.Max.x - arrow_size, frame_bb.Min.y) + style.FramePadding, true);
  8824.  
  8825. if (*current_item >= 0 && *current_item < items_count)
  8826. {
  8827. const char* item_text;
  8828. if (items_getter(data, *current_item, &item_text))
  8829. RenderTextClipped(frame_bb.Min + style.FramePadding, value_bb.Max, item_text, NULL, NULL, ImVec2(0.0f, 0.0f));
  8830. }
  8831.  
  8832. if (label_size.x > 0)
  8833. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
  8834.  
  8835. bool popup_toggled = false;
  8836. if (hovered)
  8837. {
  8838. SetHoveredID(id);
  8839. if (g.IO.MouseClicked[0])
  8840. {
  8841. ClearActiveID();
  8842. popup_toggled = true;
  8843. }
  8844. }
  8845. if (popup_toggled)
  8846. {
  8847. if (IsPopupOpen(id))
  8848. {
  8849. ClosePopup(id);
  8850. }
  8851. else
  8852. {
  8853. FocusWindow(window);
  8854. OpenPopup(label);
  8855. popup_open = true;
  8856. }
  8857. }
  8858.  
  8859. bool value_changed = false;
  8860. if (IsPopupOpen(id))
  8861. {
  8862. // Size default to hold ~7 items
  8863. if (height_in_items < 0)
  8864. height_in_items = 7;
  8865.  
  8866. float popup_height = (label_size.y + style.ItemSpacing.y) * ImMin(items_count, height_in_items) + (style.FramePadding.y * 3);
  8867. float popup_y1 = frame_bb.Max.y;
  8868. float popup_y2 = ImClamp(popup_y1 + popup_height, popup_y1, g.IO.DisplaySize.y - style.DisplaySafeAreaPadding.y);
  8869. if ((popup_y2 - popup_y1) < ImMin(popup_height, frame_bb.Min.y - style.DisplaySafeAreaPadding.y))
  8870. {
  8871. // Position our combo ABOVE because there's more space to fit! (FIXME: Handle in Begin() or use a shared helper. We have similar code in Begin() for popup placement)
  8872. popup_y1 = ImClamp(frame_bb.Min.y - popup_height, style.DisplaySafeAreaPadding.y, frame_bb.Min.y);
  8873. popup_y2 = frame_bb.Min.y;
  8874. }
  8875. ImRect popup_rect(ImVec2(frame_bb.Min.x, popup_y1), ImVec2(frame_bb.Max.x, popup_y2));
  8876. SetNextWindowPos(popup_rect.Min);
  8877. SetNextWindowSize(popup_rect.GetSize());
  8878. PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
  8879.  
  8880. const ImGuiWindowFlags flags = ImGuiWindowFlags_ComboBox | ((window->Flags & ImGuiWindowFlags_ShowBorders) ? ImGuiWindowFlags_ShowBorders : 0);
  8881. if (BeginPopupEx(id, flags))
  8882. {
  8883. // Display items
  8884. // FIXME-OPT: Use clipper
  8885. Spacing();
  8886. for (int i = 0; i < items_count; i++)
  8887. {
  8888. PushID((void*)(intptr_t)i);
  8889. const bool item_selected = (i == *current_item);
  8890. const char* item_text;
  8891. if (!items_getter(data, i, &item_text))
  8892. item_text = "*Unknown item*";
  8893. if (Selectable(item_text, item_selected))
  8894. {
  8895. ClearActiveID();
  8896. value_changed = true;
  8897. *current_item = i;
  8898. }
  8899. if (item_selected && popup_toggled)
  8900. SetScrollHere();
  8901. PopID();
  8902. }
  8903. EndPopup();
  8904. }
  8905. PopStyleVar();
  8906. }
  8907. return value_changed;
  8908. }
  8909.  
  8910. // Tip: pass an empty label (e.g. "##dummy") then you can use the space to draw other text or image.
  8911. // But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID.
  8912. bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)
  8913. {
  8914. ImGuiWindow* window = GetCurrentWindow();
  8915. if (window->SkipItems)
  8916. return false;
  8917.  
  8918. ImGuiContext& g = *GImGui;
  8919. const ImGuiStyle& style = g.Style;
  8920.  
  8921. if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1) // FIXME-OPT: Avoid if vertically clipped.
  8922. PopClipRect();
  8923.  
  8924. ImGuiID id = window->GetID(label);
  8925. ImVec2 label_size = CalcTextSize(label, NULL, true);
  8926. ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y);
  8927. ImVec2 pos = window->DC.CursorPos;
  8928. pos.y += window->DC.CurrentLineTextBaseOffset;
  8929. ImRect bb(pos, pos + size);
  8930. ItemSize(bb);
  8931.  
  8932. // Fill horizontal space.
  8933. ImVec2 window_padding = window->WindowPadding;
  8934. float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? GetWindowContentRegionMax().x : GetContentRegionMax().x;
  8935. float w_draw = ImMax(label_size.x, window->Pos.x + max_x - window_padding.x - window->DC.CursorPos.x);
  8936. ImVec2 size_draw((size_arg.x != 0 && !(flags & ImGuiSelectableFlags_DrawFillAvailWidth)) ? size_arg.x : w_draw, size_arg.y != 0.0f ? size_arg.y : size.y);
  8937. ImRect bb_with_spacing(pos, pos + size_draw);
  8938. if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_DrawFillAvailWidth))
  8939. bb_with_spacing.Max.x += window_padding.x;
  8940.  
  8941. // Selectables are tightly packed together, we extend the box to cover spacing between selectable.
  8942. float spacing_L = (float)(int)(style.ItemSpacing.x * 0.5f);
  8943. float spacing_U = (float)(int)(style.ItemSpacing.y * 0.5f);
  8944. float spacing_R = style.ItemSpacing.x - spacing_L;
  8945. float spacing_D = style.ItemSpacing.y - spacing_U;
  8946. bb_with_spacing.Min.x -= spacing_L;
  8947. bb_with_spacing.Min.y -= spacing_U;
  8948. bb_with_spacing.Max.x += spacing_R;
  8949. bb_with_spacing.Max.y += spacing_D;
  8950. if (!ItemAdd(bb_with_spacing, &id))
  8951. {
  8952. if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1)
  8953. PushColumnClipRect();
  8954. return false;
  8955. }
  8956.  
  8957. ImGuiButtonFlags button_flags = 0;
  8958. if (flags & ImGuiSelectableFlags_Menu) button_flags |= ImGuiButtonFlags_PressedOnClick;
  8959. if (flags & ImGuiSelectableFlags_MenuItem) button_flags |= ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnRelease;
  8960. if (flags & ImGuiSelectableFlags_Disabled) button_flags |= ImGuiButtonFlags_Disabled;
  8961. if (flags & ImGuiSelectableFlags_AllowDoubleClick) button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick;
  8962. bool hovered, held;
  8963. bool pressed = ButtonBehavior(bb_with_spacing, id, &hovered, &held, button_flags);
  8964. if (flags & ImGuiSelectableFlags_Disabled)
  8965. selected = false;
  8966.  
  8967. // Render
  8968. if (hovered || selected)
  8969. {
  8970. const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
  8971. RenderFrame(bb_with_spacing.Min, bb_with_spacing.Max, col, false, 0.0f);
  8972. }
  8973.  
  8974. if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1)
  8975. {
  8976. PushColumnClipRect();
  8977. bb_with_spacing.Max.x -= (GetContentRegionMax().x - max_x);
  8978. }
  8979.  
  8980. if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
  8981. RenderTextClipped(bb.Min, bb_with_spacing.Max, label, NULL, &label_size, ImVec2(0.0f, 0.0f));
  8982. if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor();
  8983.  
  8984. // Automatically close popups
  8985. if (pressed && !(flags & ImGuiSelectableFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
  8986. CloseCurrentPopup();
  8987. return pressed;
  8988. }
  8989.  
  8990. bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)
  8991. {
  8992. if (Selectable(label, *p_selected, flags, size_arg))
  8993. {
  8994. *p_selected = !*p_selected;
  8995. return true;
  8996. }
  8997. return false;
  8998. }
  8999.  
  9000. // Helper to calculate the size of a listbox and display a label on the right.
  9001. // Tip: To have a list filling the entire window width, PushItemWidth(-1) and pass an empty label "##empty"
  9002. bool ImGui::ListBoxHeader(const char* label, const ImVec2& size_arg)
  9003. {
  9004. ImGuiWindow* window = GetCurrentWindow();
  9005. if (window->SkipItems)
  9006. return false;
  9007.  
  9008. const ImGuiStyle& style = GetStyle();
  9009. const ImGuiID id = GetID(label);
  9010. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  9011.  
  9012. // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar.
  9013. ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), GetTextLineHeightWithSpacing() * 7.4f + style.ItemSpacing.y);
  9014. ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y));
  9015. ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size);
  9016. ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
  9017. window->DC.LastItemRect = bb;
  9018.  
  9019. BeginGroup();
  9020. if (label_size.x > 0)
  9021. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
  9022.  
  9023. BeginChildFrame(id, frame_bb.GetSize());
  9024. return true;
  9025. }
  9026.  
  9027. bool ImGui::ListBoxHeader(const char* label, int items_count, int height_in_items)
  9028. {
  9029. // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar.
  9030. // However we don't add +0.40f if items_count <= height_in_items. It is slightly dodgy, because it means a dynamic list of items will make the widget resize occasionally when it crosses that size.
  9031. // I am expecting that someone will come and complain about this behavior in a remote future, then we can advise on a better solution.
  9032. if (height_in_items < 0)
  9033. height_in_items = ImMin(items_count, 7);
  9034. float height_in_items_f = height_in_items < items_count ? (height_in_items + 0.40f) : (height_in_items + 0.00f);
  9035.  
  9036. // We include ItemSpacing.y so that a list sized for the exact number of items doesn't make a scrollbar appears. We could also enforce that by passing a flag to BeginChild().
  9037. ImVec2 size;
  9038. size.x = 0.0f;
  9039. size.y = GetTextLineHeightWithSpacing() * height_in_items_f + GetStyle().ItemSpacing.y;
  9040. return ListBoxHeader(label, size);
  9041. }
  9042.  
  9043. void ImGui::ListBoxFooter()
  9044. {
  9045. ImGuiWindow* parent_window = GetParentWindow();
  9046. const ImRect bb = parent_window->DC.LastItemRect;
  9047. const ImGuiStyle& style = GetStyle();
  9048.  
  9049. EndChildFrame();
  9050.  
  9051. // Redeclare item size so that it includes the label (we have stored the full size in LastItemRect)
  9052. // We call SameLine() to restore DC.CurrentLine* data
  9053. SameLine();
  9054. parent_window->DC.CursorPos = bb.Min;
  9055. ItemSize(bb, style.FramePadding.y);
  9056. EndGroup();
  9057. }
  9058.  
  9059. bool ImGui::ListBox(const char* label, int* current_item, const char* const* items, int items_count, int height_items)
  9060. {
  9061. const bool value_changed = ListBox(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_items);
  9062. return value_changed;
  9063. }
  9064.  
  9065. bool ImGui::ListBox(const char* label, int* current_item, bool(*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items)
  9066. {
  9067. if (!ListBoxHeader(label, items_count, height_in_items))
  9068. return false;
  9069.  
  9070. // Assume all items have even height (= 1 line of text). If you need items of different or variable sizes you can create a custom version of ListBox() in your code without using the clipper.
  9071. bool value_changed = false;
  9072. ImGuiListClipper clipper(items_count, GetTextLineHeightWithSpacing()); // We know exactly our line height here so we pass it as a minor optimization, but generally you don't need to.
  9073. while (clipper.Step())
  9074. for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
  9075. {
  9076. const bool item_selected = (i == *current_item);
  9077. const char* item_text;
  9078. if (!items_getter(data, i, &item_text))
  9079. item_text = "*Unknown item*";
  9080.  
  9081. PushID(i);
  9082. if (Selectable(item_text, item_selected))
  9083. {
  9084. *current_item = i;
  9085. value_changed = true;
  9086. }
  9087. PopID();
  9088. }
  9089. ListBoxFooter();
  9090. return value_changed;
  9091. }
  9092.  
  9093. bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, bool enabled)
  9094. {
  9095. ImGuiWindow* window = GetCurrentWindow();
  9096. if (window->SkipItems)
  9097. return false;
  9098.  
  9099. ImGuiContext& g = *GImGui;
  9100. ImVec2 pos = window->DC.CursorPos;
  9101. ImVec2 label_size = CalcTextSize(label, NULL, true);
  9102. ImVec2 shortcut_size = shortcut ? CalcTextSize(shortcut, NULL) : ImVec2(0.0f, 0.0f);
  9103. float w = window->MenuColumns.DeclColumns(label_size.x, shortcut_size.x, (float)(int)(g.FontSize * 1.20f)); // Feedback for next frame
  9104. float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w);
  9105.  
  9106. bool pressed = Selectable(label, false, ImGuiSelectableFlags_MenuItem | ImGuiSelectableFlags_DrawFillAvailWidth | (enabled ? 0 : ImGuiSelectableFlags_Disabled), ImVec2(w, 0.0f));
  9107. if (shortcut_size.x > 0.0f)
  9108. {
  9109. PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
  9110. RenderText(pos + ImVec2(window->MenuColumns.Pos[1] + extra_w, 0.0f), shortcut, NULL, false);
  9111. PopStyleColor();
  9112. }
  9113.  
  9114. if (selected)
  9115. RenderCheckMark(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.20f, 0.0f), GetColorU32(enabled ? ImGuiCol_Text : ImGuiCol_TextDisabled));
  9116.  
  9117. return pressed;
  9118. }
  9119.  
  9120. bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled)
  9121. {
  9122. if (MenuItem(label, shortcut, p_selected ? *p_selected : false, enabled))
  9123. {
  9124. if (p_selected)
  9125. *p_selected = !*p_selected;
  9126. return true;
  9127. }
  9128. return false;
  9129. }
  9130.  
  9131. bool ImGui::BeginMainMenuBar()
  9132. {
  9133. ImGuiContext& g = *GImGui;
  9134. SetNextWindowPos(ImVec2(0.0f, 0.0f));
  9135. SetNextWindowSize(ImVec2(g.IO.DisplaySize.x, g.FontBaseSize + g.Style.FramePadding.y * 2.0f));
  9136. PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
  9137. PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0, 0));
  9138. if (!Begin("##MainMenuBar", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_MenuBar)
  9139. || !BeginMenuBar())
  9140. {
  9141. End();
  9142. PopStyleVar(2);
  9143. return false;
  9144. }
  9145. g.CurrentWindow->DC.MenuBarOffsetX += g.Style.DisplaySafeAreaPadding.x;
  9146. return true;
  9147. }
  9148.  
  9149. void ImGui::EndMainMenuBar()
  9150. {
  9151. EndMenuBar();
  9152. End();
  9153. PopStyleVar(2);
  9154. }
  9155.  
  9156. bool ImGui::BeginMenuBar()
  9157. {
  9158. ImGuiWindow* window = GetCurrentWindow();
  9159. if (window->SkipItems)
  9160. return false;
  9161. if (!(window->Flags & ImGuiWindowFlags_MenuBar))
  9162. return false;
  9163.  
  9164. IM_ASSERT(!window->DC.MenuBarAppending);
  9165. BeginGroup(); // Save position
  9166. PushID("##menubar");
  9167. ImRect rect = window->MenuBarRect();
  9168. PushClipRect(ImVec2(ImFloor(rect.Min.x + 0.5f), ImFloor(rect.Min.y + window->BorderSize + 0.5f)), ImVec2(ImFloor(rect.Max.x + 0.5f), ImFloor(rect.Max.y + 0.5f)), false);
  9169. window->DC.CursorPos = ImVec2(rect.Min.x + window->DC.MenuBarOffsetX, rect.Min.y);// + g.Style.FramePadding.y);
  9170. window->DC.LayoutType = ImGuiLayoutType_Horizontal;
  9171. window->DC.MenuBarAppending = true;
  9172. AlignFirstTextHeightToWidgets();
  9173. return true;
  9174. }
  9175.  
  9176. void ImGui::EndMenuBar()
  9177. {
  9178. ImGuiWindow* window = GetCurrentWindow();
  9179. if (window->SkipItems)
  9180. return;
  9181.  
  9182. IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar);
  9183. IM_ASSERT(window->DC.MenuBarAppending);
  9184. PopClipRect();
  9185. PopID();
  9186. window->DC.MenuBarOffsetX = window->DC.CursorPos.x - window->MenuBarRect().Min.x;
  9187. window->DC.GroupStack.back().AdvanceCursor = false;
  9188. EndGroup();
  9189. window->DC.LayoutType = ImGuiLayoutType_Vertical;
  9190. window->DC.MenuBarAppending = false;
  9191. }
  9192.  
  9193. bool ImGui::BeginMenu(const char* label, bool enabled)
  9194. {
  9195. ImGuiWindow* window = GetCurrentWindow();
  9196. if (window->SkipItems)
  9197. return false;
  9198.  
  9199. ImGuiContext& g = *GImGui;
  9200. const ImGuiStyle& style = g.Style;
  9201. const ImGuiID id = window->GetID(label);
  9202.  
  9203. ImVec2 label_size = CalcTextSize(label, NULL, true);
  9204.  
  9205. bool pressed;
  9206. bool menu_is_open = IsPopupOpen(id);
  9207. bool menuset_is_open = !(window->Flags & ImGuiWindowFlags_Popup) && (g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].ParentMenuSet == window->GetID("##menus"));
  9208. ImGuiWindow* backed_nav_window = g.NavWindow;
  9209. if (menuset_is_open)
  9210. g.NavWindow = window; // Odd hack to allow hovering across menus of a same menu-set (otherwise we wouldn't be able to hover parent)
  9211.  
  9212. // The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu (using FindBestPopupWindowPos).
  9213. ImVec2 popup_pos, pos = window->DC.CursorPos;
  9214. if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
  9215. {
  9216. popup_pos = ImVec2(pos.x - window->WindowPadding.x, pos.y - style.FramePadding.y + window->MenuBarHeight());
  9217. window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f);
  9218. PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f);
  9219. float w = label_size.x;
  9220. pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f));
  9221. PopStyleVar();
  9222. SameLine();
  9223. window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f);
  9224. }
  9225. else
  9226. {
  9227. popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y);
  9228. float w = window->MenuColumns.DeclColumns(label_size.x, 0.0f, (float)(int)(g.FontSize * 1.20f)); // Feedback to next frame
  9229. float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w);
  9230. pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | ImGuiSelectableFlags_DrawFillAvailWidth | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f));
  9231. if (!enabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
  9232. RenderCollapseTriangle(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.20f, 0.0f), false);
  9233. if (!enabled) PopStyleColor();
  9234. }
  9235.  
  9236. bool hovered = enabled && IsHovered(window->DC.LastItemRect, id);
  9237.  
  9238. if (menuset_is_open)
  9239. g.NavWindow = backed_nav_window;
  9240.  
  9241. bool want_open = false, want_close = false;
  9242. if (window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu))
  9243. {
  9244. // Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive.
  9245. bool moving_within_opened_triangle = false;
  9246. if (g.HoveredWindow == window && g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].ParentWindow == window)
  9247. {
  9248. if (ImGuiWindow* next_window = g.OpenPopupStack[g.CurrentPopupStack.Size].Window)
  9249. {
  9250. ImRect next_window_rect = next_window->Rect();
  9251. ImVec2 ta = g.IO.MousePos - g.IO.MouseDelta;
  9252. ImVec2 tb = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetTL() : next_window_rect.GetTR();
  9253. ImVec2 tc = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetBL() : next_window_rect.GetBR();
  9254. float extra = ImClamp(fabsf(ta.x - tb.x) * 0.30f, 5.0f, 30.0f); // add a bit of extra slack.
  9255. ta.x += (window->Pos.x < next_window->Pos.x) ? -0.5f : +0.5f; // to avoid numerical issues
  9256. tb.y = ta.y + ImMax((tb.y - extra) - ta.y, -100.0f); // triangle is maximum 200 high to limit the slope and the bias toward large sub-menus // FIXME: Multiply by fb_scale?
  9257. tc.y = ta.y + ImMin((tc.y + extra) - ta.y, +100.0f);
  9258. moving_within_opened_triangle = ImTriangleContainsPoint(ta, tb, tc, g.IO.MousePos);
  9259. //window->DrawList->PushClipRectFullScreen(); window->DrawList->AddTriangleFilled(ta, tb, tc, moving_within_opened_triangle ? IM_COL32(0,128,0,128) : IM_COL32(128,0,0,128)); window->DrawList->PopClipRect(); // Debug
  9260. }
  9261. }
  9262.  
  9263. want_close = (menu_is_open && !hovered && g.HoveredWindow == window && g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrame != id && !moving_within_opened_triangle);
  9264. want_open = (!menu_is_open && hovered && !moving_within_opened_triangle) || (!menu_is_open && hovered && pressed);
  9265. }
  9266. else if (menu_is_open && pressed && menuset_is_open) // Menu bar: click an open menu again to close it
  9267. {
  9268. want_close = true;
  9269. want_open = menu_is_open = false;
  9270. }
  9271. else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // menu-bar: first click to open, then hover to open others
  9272. want_open = true;
  9273. if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu("options", has_object)) { ..use object.. }'
  9274. want_close = true;
  9275. if (want_close && IsPopupOpen(id))
  9276. ClosePopupToLevel(GImGui->CurrentPopupStack.Size);
  9277.  
  9278. if (!menu_is_open && want_open && g.OpenPopupStack.Size > g.CurrentPopupStack.Size)
  9279. {
  9280. // Don't recycle same menu level in the same frame, first close the other menu and yield for a frame.
  9281. OpenPopup(label);
  9282. return false;
  9283. }
  9284.  
  9285. menu_is_open |= want_open;
  9286. if (want_open)
  9287. OpenPopup(label);
  9288.  
  9289. if (menu_is_open)
  9290. {
  9291. SetNextWindowPos(popup_pos, ImGuiCond_Always);
  9292. ImGuiWindowFlags flags = ImGuiWindowFlags_ShowBorders | ((window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) ? ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_ChildWindow : ImGuiWindowFlags_ChildMenu);
  9293. menu_is_open = BeginPopupEx(id, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
  9294. }
  9295.  
  9296. return menu_is_open;
  9297. }
  9298.  
  9299. void ImGui::EndMenu()
  9300. {
  9301. EndPopup();
  9302. }
  9303.  
  9304. // Note: only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
  9305. void ImGui::ColorTooltip(const char* text, const float col[4], ImGuiColorEditFlags flags)
  9306. {
  9307. ImGuiContext& g = *GImGui;
  9308.  
  9309. int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]);
  9310. BeginTooltipEx(true);
  9311.  
  9312. const char* text_end = text ? FindRenderedTextEnd(text, NULL) : text;
  9313. if (text_end > text)
  9314. {
  9315. TextUnformatted(text, text_end);
  9316. Separator();
  9317. }
  9318.  
  9319. ImVec2 sz(g.FontSize * 3, g.FontSize * 3);
  9320. ColorButton("##preview", ImVec4(col[0], col[1], col[2], col[3]), (flags & (ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)) | ImGuiColorEditFlags_NoTooltip, sz);
  9321. SameLine();
  9322. if (flags & ImGuiColorEditFlags_NoAlpha)
  9323. Text("#%02X%02X%02X\nR: %d, G: %d, B: %d\n(%.3f, %.3f, %.3f)", cr, cg, cb, cr, cg, cb, col[0], col[1], col[2]);
  9324. else
  9325. Text("#%02X%02X%02X%02X\nR:%d, G:%d, B:%d, A:%d\n(%.3f, %.3f, %.3f, %.3f)", cr, cg, cb, ca, cr, cg, cb, ca, col[0], col[1], col[2], col[3]);
  9326. EndTooltip();
  9327. }
  9328.  
  9329. static inline float ColorSquareSize()
  9330. {
  9331. ImGuiContext& g = *GImGui;
  9332. return g.FontSize + g.Style.FramePadding.y * 2.0f;
  9333. }
  9334.  
  9335. static inline ImU32 ImAlphaBlendColor(ImU32 col_a, ImU32 col_b)
  9336. {
  9337. float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
  9338. int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
  9339. int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
  9340. int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
  9341. return IM_COL32(r, g, b, 0xFF);
  9342. }
  9343.  
  9344. // NB: This is rather brittle and will show artifact when rounding this enabled if rounded corners overlap multiple cells. Caller currently responsible for avoiding that.
  9345. // I spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding alltogether.
  9346. void ImGui::RenderColorRectWithAlphaCheckerboard(ImVec2 p_min, ImVec2 p_max, ImU32 col, float grid_step, ImVec2 grid_off, float rounding, int rounding_corners_flags)
  9347. {
  9348. ImGuiWindow* window = GetCurrentWindow();
  9349. if (((col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT) < 0xFF)
  9350. {
  9351. ImU32 col_bg1 = GetColorU32(ImAlphaBlendColor(IM_COL32(204, 204, 204, 255), col));
  9352. ImU32 col_bg2 = GetColorU32(ImAlphaBlendColor(IM_COL32(128, 128, 128, 255), col));
  9353. window->DrawList->AddRectFilled(p_min, p_max, col_bg1, rounding, rounding_corners_flags);
  9354.  
  9355. int yi = 0;
  9356. for (float y = p_min.y + grid_off.y; y < p_max.y; y += grid_step, yi++)
  9357. {
  9358. float y1 = ImClamp(y, p_min.y, p_max.y), y2 = ImMin(y + grid_step, p_max.y);
  9359. if (y2 <= y1)
  9360. continue;
  9361. for (float x = p_min.x + grid_off.x + (yi & 1) * grid_step; x < p_max.x; x += grid_step * 2.0f)
  9362. {
  9363. float x1 = ImClamp(x, p_min.x, p_max.x), x2 = ImMin(x + grid_step, p_max.x);
  9364. if (x2 <= x1)
  9365. continue;
  9366. int rounding_corners_flags_cell = 0;
  9367. if (y1 <= p_min.y) { if (x1 <= p_min.x) rounding_corners_flags_cell |= ImGuiCorner_TopLeft; if (x2 >= p_max.x) rounding_corners_flags_cell |= ImGuiCorner_TopRight; }
  9368. if (y2 >= p_max.y) { if (x1 <= p_min.x) rounding_corners_flags_cell |= ImGuiCorner_BotLeft; if (x2 >= p_max.x) rounding_corners_flags_cell |= ImGuiCorner_BotRight; }
  9369. rounding_corners_flags_cell &= rounding_corners_flags;
  9370. window->DrawList->AddRectFilled(ImVec2(x1, y1), ImVec2(x2, y2), col_bg2, rounding_corners_flags_cell ? rounding : 0.0f, rounding_corners_flags_cell);
  9371. }
  9372. }
  9373. }
  9374. else
  9375. {
  9376. window->DrawList->AddRectFilled(p_min, p_max, col, rounding, rounding_corners_flags);
  9377. }
  9378. }
  9379.  
  9380. void ImGui::SetColorEditOptions(ImGuiColorEditFlags flags)
  9381. {
  9382. ImGuiContext& g = *GImGui;
  9383. if ((flags & ImGuiColorEditFlags__InputsMask) == 0)
  9384. flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__InputsMask;
  9385. if ((flags & ImGuiColorEditFlags__DataTypeMask) == 0)
  9386. flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__DataTypeMask;
  9387. if ((flags & ImGuiColorEditFlags__PickerMask) == 0)
  9388. flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__PickerMask;
  9389. IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__InputsMask))); // Check only 1 option is selected
  9390. IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__DataTypeMask))); // Check only 1 option is selected
  9391. IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__PickerMask))); // Check only 1 option is selected
  9392. g.ColorEditOptions = flags;
  9393. }
  9394.  
  9395. // A little colored square. Return true when clicked.
  9396. // FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip.
  9397. // 'desc_id' is not called 'label' because we don't display it next to the button, but only in the tooltip.
  9398. bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags, ImVec2 size)
  9399. {
  9400. ImGuiWindow* window = GetCurrentWindow();
  9401. if (window->SkipItems)
  9402. return false;
  9403.  
  9404. ImGuiContext& g = *GImGui;
  9405. const ImGuiID id = window->GetID(desc_id);
  9406. float default_size = ColorSquareSize();
  9407. if (size.x == 0.0f)
  9408. size.x = default_size;
  9409. if (size.y == 0.0f)
  9410. size.y = default_size;
  9411. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
  9412. ItemSize(bb);
  9413. if (!ItemAdd(bb, &id))
  9414. return false;
  9415.  
  9416. bool hovered, held;
  9417. bool pressed = ButtonBehavior(bb, id, &hovered, &held);
  9418.  
  9419. if (flags & ImGuiColorEditFlags_NoAlpha)
  9420. flags &= ~(ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf);
  9421.  
  9422. ImVec4 col_without_alpha(col.x, col.y, col.z, 1.0f);
  9423. float grid_step = ImMin(size.x, size.y) / 2.99f;
  9424. float rounding = ImMin(g.Style.FrameRounding, grid_step * 0.5f);
  9425. if ((flags & ImGuiColorEditFlags_AlphaPreviewHalf) && col.w < 1.0f)
  9426. {
  9427. float mid_x = (float)(int)((bb.Min.x + bb.Max.x) * 0.5f + 0.5f);
  9428. RenderColorRectWithAlphaCheckerboard(ImVec2(bb.Min.x + grid_step, bb.Min.y), bb.Max, GetColorU32(col), grid_step, ImVec2(-grid_step, 0.0f), rounding, ImGuiCorner_TopRight | ImGuiCorner_BotRight);
  9429. window->DrawList->AddRectFilled(bb.Min, ImVec2(mid_x, bb.Max.y), GetColorU32(col_without_alpha), rounding, ImGuiCorner_TopLeft | ImGuiCorner_BotLeft);
  9430. }
  9431. else
  9432. {
  9433. RenderColorRectWithAlphaCheckerboard(bb.Min, bb.Max, GetColorU32((flags & ImGuiColorEditFlags_AlphaPreview) ? col : col_without_alpha), grid_step, ImVec2(0, 0), rounding);
  9434. }
  9435. if (window->Flags & ImGuiWindowFlags_ShowBorders)
  9436. RenderFrameBorder(bb.Min, bb.Max, rounding);
  9437. else
  9438. window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), rounding); // Color button are often in need of some sort of border
  9439.  
  9440. if (hovered && !(flags & ImGuiColorEditFlags_NoTooltip))
  9441. ColorTooltip(desc_id, &col.x, flags & (ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf));
  9442.  
  9443. return pressed;
  9444. }
  9445.  
  9446. bool ImGui::ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags)
  9447. {
  9448. return ColorEdit4(label, col, flags | ImGuiColorEditFlags_NoAlpha);
  9449. }
  9450.  
  9451. static void ColorEditOptionsPopup(ImGuiColorEditFlags flags)
  9452. {
  9453. bool allow_opt_inputs = !(flags & ImGuiColorEditFlags__InputsMask);
  9454. bool allow_opt_datatype = !(flags & ImGuiColorEditFlags__DataTypeMask);
  9455. if ((!allow_opt_inputs && !allow_opt_datatype) || !ImGui::BeginPopup("context"))
  9456. return;
  9457. ImGuiContext& g = *GImGui;
  9458. ImGuiColorEditFlags opts = g.ColorEditOptions;
  9459. if (allow_opt_inputs)
  9460. {
  9461. if (ImGui::RadioButton("RGB", (opts & ImGuiColorEditFlags_RGB) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__InputsMask) | ImGuiColorEditFlags_RGB;
  9462. if (ImGui::RadioButton("HSV", (opts & ImGuiColorEditFlags_HSV) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__InputsMask) | ImGuiColorEditFlags_HSV;
  9463. if (ImGui::RadioButton("HEX", (opts & ImGuiColorEditFlags_HEX) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__InputsMask) | ImGuiColorEditFlags_HEX;
  9464. }
  9465. if (allow_opt_datatype)
  9466. {
  9467. if (allow_opt_inputs) ImGui::Separator();
  9468. if (ImGui::RadioButton("0..255", (opts & ImGuiColorEditFlags_Uint8) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__DataTypeMask) | ImGuiColorEditFlags_Uint8;
  9469. if (ImGui::RadioButton("0.00..1.00", (opts & ImGuiColorEditFlags_Float) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__DataTypeMask) | ImGuiColorEditFlags_Float;
  9470. }
  9471. g.ColorEditOptions = opts;
  9472. ImGui::EndPopup();
  9473. }
  9474.  
  9475. static void ColorPickerOptionsPopup(ImGuiColorEditFlags flags, float* ref_col)
  9476. {
  9477. bool allow_opt_picker = !(flags & ImGuiColorEditFlags__PickerMask);
  9478. bool allow_opt_alpha_bar = !(flags & ImGuiColorEditFlags_NoAlpha) && !(flags & ImGuiColorEditFlags_AlphaBar);
  9479. if ((!allow_opt_picker && !allow_opt_alpha_bar) || !ImGui::BeginPopup("context"))
  9480. return;
  9481. ImGuiContext& g = *GImGui;
  9482. if (allow_opt_picker)
  9483. {
  9484. ImVec2 picker_size(g.FontSize * 8, ImMax(g.FontSize * 8 - (ColorSquareSize() + g.Style.ItemInnerSpacing.x), 1.0f)); // FIXME: Picker size copied from main picker function
  9485. ImGui::PushItemWidth(picker_size.x);
  9486. for (int picker_type = 0; picker_type < 2; picker_type++)
  9487. {
  9488. // Draw small/thumbnail version of each picker type (over an invisible button for selection)
  9489. if (picker_type > 0) ImGui::Separator();
  9490. ImGui::PushID(picker_type);
  9491. ImGuiColorEditFlags picker_flags = ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_NoSidePreview | (flags & ImGuiColorEditFlags_NoAlpha);
  9492. if (picker_type == 0) picker_flags |= ImGuiColorEditFlags_PickerHueBar;
  9493. if (picker_type == 1) picker_flags |= ImGuiColorEditFlags_PickerHueWheel;
  9494. ImVec2 backup_pos = ImGui::GetCursorScreenPos();
  9495. if (ImGui::Selectable("##selectable", false, 0, picker_size)) // By default, Selectable() is closing popup
  9496. g.ColorEditOptions = (g.ColorEditOptions & ~ImGuiColorEditFlags__PickerMask) | (picker_flags & ImGuiColorEditFlags__PickerMask);
  9497. ImGui::SetCursorScreenPos(backup_pos);
  9498. ImVec4 dummy_ref_col;
  9499. memcpy(&dummy_ref_col.x, ref_col, sizeof(float) * (picker_flags & ImGuiColorEditFlags_NoAlpha ? 3 : 4));
  9500. ImGui::ColorPicker4("##dummypicker", &dummy_ref_col.x, picker_flags);
  9501. ImGui::PopID();
  9502. }
  9503. ImGui::PopItemWidth();
  9504. }
  9505. if (allow_opt_alpha_bar)
  9506. {
  9507. if (allow_opt_picker) ImGui::Separator();
  9508. ImGui::CheckboxFlags("Alpha Bar", (unsigned int*)&g.ColorEditOptions, ImGuiColorEditFlags_AlphaBar);
  9509. }
  9510. ImGui::EndPopup();
  9511. }
  9512.  
  9513. // Edit colors components (each component in 0.0f..1.0f range).
  9514. // See enum ImGuiColorEditFlags_ for available options. e.g. Only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
  9515. // With typical options: Left-click on colored square to open color picker. Right-click to open option menu. CTRL-Click over input fields to edit them and TAB to go to next item.
  9516. bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags)
  9517. {
  9518. ImGuiWindow* window = GetCurrentWindow();
  9519. if (window->SkipItems)
  9520. return false;
  9521.  
  9522. ImGuiContext& g = *GImGui;
  9523. const ImGuiStyle& style = g.Style;
  9524. const float w_extra = (flags & ImGuiColorEditFlags_NoSmallPreview) ? 0.0f : (ColorSquareSize() + style.ItemInnerSpacing.x);
  9525. const float w_items_all = CalcItemWidth() - w_extra;
  9526. const char* label_display_end = FindRenderedTextEnd(label);
  9527.  
  9528. const bool alpha = (flags & ImGuiColorEditFlags_NoAlpha) == 0;
  9529. const bool hdr = (flags & ImGuiColorEditFlags_HDR) != 0;
  9530. const int components = alpha ? 4 : 3;
  9531. const ImGuiColorEditFlags flags_untouched = flags;
  9532.  
  9533. BeginGroup();
  9534. PushID(label);
  9535.  
  9536. // If we're not showing any slider there's no point in doing any HSV conversions
  9537. if (flags & ImGuiColorEditFlags_NoInputs)
  9538. flags = (flags & (~ImGuiColorEditFlags__InputsMask)) | ImGuiColorEditFlags_RGB | ImGuiColorEditFlags_NoOptions;
  9539.  
  9540. // Context menu: display and modify options (before defaults are applied)
  9541. if (!(flags & ImGuiColorEditFlags_NoOptions))
  9542. ColorEditOptionsPopup(flags);
  9543.  
  9544. // Read stored options
  9545. if (!(flags & ImGuiColorEditFlags__InputsMask))
  9546. flags |= (g.ColorEditOptions & ImGuiColorEditFlags__InputsMask);
  9547. if (!(flags & ImGuiColorEditFlags__DataTypeMask))
  9548. flags |= (g.ColorEditOptions & ImGuiColorEditFlags__DataTypeMask);
  9549. if (!(flags & ImGuiColorEditFlags__PickerMask))
  9550. flags |= (g.ColorEditOptions & ImGuiColorEditFlags__PickerMask);
  9551. flags |= (g.ColorEditOptions & ~(ImGuiColorEditFlags__InputsMask | ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask));
  9552.  
  9553. // Convert to the formats we need
  9554. float f[4] = { col[0], col[1], col[2], alpha ? col[3] : 1.0f };
  9555. if (flags & ImGuiColorEditFlags_HSV)
  9556. ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]);
  9557. int i[4] = { IM_F32_TO_INT8_UNBOUND(f[0]), IM_F32_TO_INT8_UNBOUND(f[1]), IM_F32_TO_INT8_UNBOUND(f[2]), IM_F32_TO_INT8_UNBOUND(f[3]) };
  9558.  
  9559. bool value_changed = false;
  9560. bool value_changed_as_float = false;
  9561.  
  9562. if ((flags & (ImGuiColorEditFlags_RGB | ImGuiColorEditFlags_HSV)) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0)
  9563. {
  9564. // RGB/HSV 0..255 Sliders
  9565. const float w_item_one = ImMax(1.0f, (float)(int)((w_items_all - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components));
  9566. const float w_item_last = ImMax(1.0f, (float)(int)(w_items_all - (w_item_one + style.ItemInnerSpacing.x) * (components - 1)));
  9567.  
  9568. const bool hide_prefix = (w_item_one <= CalcTextSize((flags & ImGuiColorEditFlags_Float) ? "M:0.000" : "M:000").x);
  9569. const char* ids[4] = { "##X", "##Y", "##Z", "##W" };
  9570. const char* fmt_table_int[3][4] =
  9571. {
  9572. { "%3.0f", "%3.0f", "%3.0f", "%3.0f" }, // Short display
  9573. { "R:%3.0f", "G:%3.0f", "B:%3.0f", "A:%3.0f" }, // Long display for RGBA
  9574. { "H:%3.0f", "S:%3.0f", "V:%3.0f", "A:%3.0f" } // Long display for HSVA
  9575. };
  9576. const char* fmt_table_float[3][4] =
  9577. {
  9578. { "%0.3f", "%0.3f", "%0.3f", "%0.3f" }, // Short display
  9579. { "R:%0.3f", "G:%0.3f", "B:%0.3f", "A:%0.3f" }, // Long display for RGBA
  9580. { "H:%0.3f", "S:%0.3f", "V:%0.3f", "A:%0.3f" } // Long display for HSVA
  9581. };
  9582. const int fmt_idx = hide_prefix ? 0 : (flags & ImGuiColorEditFlags_HSV) ? 2 : 1;
  9583.  
  9584. PushItemWidth(w_item_one);
  9585. PopItemWidth();
  9586. PopItemWidth();
  9587. }
  9588.  
  9589. bool picker_active = false;
  9590. if (!(flags & ImGuiColorEditFlags_NoSmallPreview))
  9591. {
  9592. if (!(flags & ImGuiColorEditFlags_NoInputs))
  9593. SameLine(0, style.ItemInnerSpacing.x);
  9594.  
  9595. const ImVec4 col_v4(col[0], col[1], col[2], alpha ? col[3] : 1.0f);
  9596. if (ColorButton("##ColorButton", col_v4, flags))
  9597. {
  9598. if (!(flags & ImGuiColorEditFlags_NoPicker))
  9599. {
  9600. // Store current color and open a picker
  9601. g.ColorPickerRef = col_v4;
  9602. OpenPopup("picker");
  9603. SetNextWindowPos(window->DC.LastItemRect.GetBL() + ImVec2(-1, style.ItemSpacing.y));
  9604. }
  9605. }
  9606. if (!(flags & ImGuiColorEditFlags_NoOptions) && IsItemHovered() && IsMouseClicked(1))
  9607. OpenPopup("context");
  9608.  
  9609. if (BeginPopup("picker"))
  9610. {
  9611. picker_active = true;
  9612. if (label != label_display_end)
  9613. {
  9614. TextUnformatted(label, label_display_end);
  9615. Separator();
  9616. }
  9617. float square_sz = ColorSquareSize();
  9618. ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar;
  9619. ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags__InputsMask | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf;
  9620. PushItemWidth(square_sz * 12.0f); // Use 256 + bar sizes?
  9621. value_changed |= ColorPicker4("##picker", col, picker_flags, &g.ColorPickerRef.x);
  9622. PopItemWidth();
  9623. EndPopup();
  9624. }
  9625. }
  9626.  
  9627. if (label != label_display_end && !(flags & ImGuiColorEditFlags_NoLabel))
  9628. {
  9629. SameLine(0, style.ItemInnerSpacing.x);
  9630. TextUnformatted(label, label_display_end);
  9631. }
  9632.  
  9633. // Convert back
  9634. if (!picker_active)
  9635. {
  9636. if (!value_changed_as_float)
  9637. for (int n = 0; n < 4; n++)
  9638. f[n] = i[n] / 255.0f;
  9639. if (flags & ImGuiColorEditFlags_HSV)
  9640. ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]);
  9641. if (value_changed)
  9642. {
  9643. col[0] = f[0];
  9644. col[1] = f[1];
  9645. col[2] = f[2];
  9646. if (alpha)
  9647. col[3] = f[3];
  9648. }
  9649. }
  9650.  
  9651. PopID();
  9652. EndGroup();
  9653.  
  9654. return value_changed;
  9655. }
  9656.  
  9657. bool ImGui::ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags)
  9658. {
  9659. float col4[4] = { col[0], col[1], col[2], 1.0f };
  9660. if (!ColorPicker4(label, col4, flags | ImGuiColorEditFlags_NoAlpha))
  9661. return false;
  9662. col[0] = col4[0]; col[1] = col4[1]; col[2] = col4[2];
  9663. return true;
  9664. }
  9665.  
  9666. // 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side.
  9667. static void RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col)
  9668. {
  9669. switch (direction)
  9670. {
  9671. case ImGuiDir_Left: draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), pos, col); return;
  9672. case ImGuiDir_Right: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), pos, col); return;
  9673. case ImGuiDir_Up: draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), pos, col); return;
  9674. case ImGuiDir_Down: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), pos, col); return;
  9675. default: return; // Fix warning for ImGuiDir_None
  9676. }
  9677. }
  9678.  
  9679. static void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, float bar_w)
  9680. {
  9681. RenderArrow(draw_list, ImVec2(pos.x + half_sz.x + 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Right, IM_COL32_BLACK);
  9682. RenderArrow(draw_list, ImVec2(pos.x + half_sz.x, pos.y), half_sz, ImGuiDir_Right, IM_COL32_WHITE);
  9683. RenderArrow(draw_list, ImVec2(pos.x + bar_w - half_sz.x - 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Left, IM_COL32_BLACK);
  9684. RenderArrow(draw_list, ImVec2(pos.x + bar_w - half_sz.x, pos.y), half_sz, ImGuiDir_Left, IM_COL32_WHITE);
  9685. }
  9686.  
  9687. static void PaintVertsLinearGradientKeepAlpha(ImDrawVert* vert_start, ImDrawVert* vert_end, ImVec2 gradient_p0, ImVec2 gradient_p1, ImU32 col0, ImU32 col1)
  9688. {
  9689. ImVec2 gradient_extent = gradient_p1 - gradient_p0;
  9690. float gradient_inv_length = ImInvLength(gradient_extent, 0.0f);
  9691. for (ImDrawVert* vert = vert_start; vert < vert_end; vert++)
  9692. {
  9693. float d = ImDot(vert->pos - gradient_p0, gradient_extent);
  9694. float t = ImMin(sqrtf(ImMax(d, 0.0f)) * gradient_inv_length, 1.0f);
  9695. int r = ImLerp((int)(col0 >> IM_COL32_R_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_R_SHIFT) & 0xFF, t);
  9696. int g = ImLerp((int)(col0 >> IM_COL32_G_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_G_SHIFT) & 0xFF, t);
  9697. int b = ImLerp((int)(col0 >> IM_COL32_B_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_B_SHIFT) & 0xFF, t);
  9698. vert->col = (r << IM_COL32_R_SHIFT) | (g << IM_COL32_G_SHIFT) | (b << IM_COL32_B_SHIFT) | (vert->col & IM_COL32_A_MASK);
  9699. }
  9700. }
  9701.  
  9702. // ColorPicker
  9703. // Note: only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
  9704. // FIXME: we adjust the big color square height based on item width, which may cause a flickering feedback loop (if automatic height makes a vertical scrollbar appears, affecting automatic width..)
  9705. bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags, const float* ref_col)
  9706. {
  9707. ImGuiContext& g = *GImGui;
  9708. ImGuiWindow* window = GetCurrentWindow();
  9709. ImDrawList* draw_list = window->DrawList;
  9710.  
  9711. ImGuiStyle& style = g.Style;
  9712. ImGuiIO& io = g.IO;
  9713.  
  9714. PushID(label);
  9715. BeginGroup();
  9716.  
  9717. if (!(flags & ImGuiColorEditFlags_NoSidePreview))
  9718. flags |= ImGuiColorEditFlags_NoSmallPreview;
  9719.  
  9720. // Context menu: display and store options.
  9721. if (!(flags & ImGuiColorEditFlags_NoOptions))
  9722. ColorPickerOptionsPopup(flags, col);
  9723.  
  9724. // Read stored options
  9725. if (!(flags & ImGuiColorEditFlags__PickerMask))
  9726. flags |= ((g.ColorEditOptions & ImGuiColorEditFlags__PickerMask) ? g.ColorEditOptions : ImGuiColorEditFlags__OptionsDefault) & ImGuiColorEditFlags__PickerMask;
  9727. IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__PickerMask))); // Check that only 1 is selected
  9728. if (!(flags & ImGuiColorEditFlags_NoOptions))
  9729. flags |= (g.ColorEditOptions & ImGuiColorEditFlags_AlphaBar);
  9730.  
  9731. // Setup
  9732. bool alpha_bar = (flags & ImGuiColorEditFlags_AlphaBar) && !(flags & ImGuiColorEditFlags_NoAlpha);
  9733. ImVec2 picker_pos = window->DC.CursorPos;
  9734. float bars_width = ColorSquareSize(); // Arbitrary smallish width of Hue/Alpha picking bars
  9735. float sv_picker_size = ImMax(bars_width * 1, CalcItemWidth() - (alpha_bar ? 2 : 1) * (bars_width + style.ItemInnerSpacing.x)); // Saturation/Value picking box
  9736. float bar0_pos_x = picker_pos.x + sv_picker_size + style.ItemInnerSpacing.x;
  9737. float bar1_pos_x = bar0_pos_x + bars_width + style.ItemInnerSpacing.x;
  9738. float bars_triangles_half_sz = (float)(int)(bars_width * 0.20f);
  9739.  
  9740. float wheel_thickness = sv_picker_size * 0.08f;
  9741. float wheel_r_outer = sv_picker_size * 0.50f;
  9742. float wheel_r_inner = wheel_r_outer - wheel_thickness;
  9743. ImVec2 wheel_center(picker_pos.x + (sv_picker_size + bars_width)*0.5f, picker_pos.y + sv_picker_size*0.5f);
  9744.  
  9745. // Note: the triangle is displayed rotated with triangle_pa pointing to Hue, but most coordinates stays unrotated for logic.
  9746. float triangle_r = wheel_r_inner - (int)(sv_picker_size * 0.027f);
  9747. ImVec2 triangle_pa = ImVec2(triangle_r, 0.0f); // Hue point.
  9748. ImVec2 triangle_pb = ImVec2(triangle_r * -0.5f, triangle_r * -0.866025f); // Black point.
  9749. ImVec2 triangle_pc = ImVec2(triangle_r * -0.5f, triangle_r * +0.866025f); // White point.
  9750.  
  9751. float H, S, V;
  9752. ColorConvertRGBtoHSV(col[0], col[1], col[2], H, S, V);
  9753.  
  9754. bool value_changed = false, value_changed_h = false, value_changed_sv = false;
  9755.  
  9756. if (flags & ImGuiColorEditFlags_PickerHueWheel)
  9757. {
  9758. // Hue wheel + SV triangle logic
  9759. InvisibleButton("hsv", ImVec2(sv_picker_size + style.ItemInnerSpacing.x + bars_width, sv_picker_size));
  9760. if (IsItemActive())
  9761. {
  9762. ImVec2 initial_off = g.IO.MouseClickedPos[0] - wheel_center;
  9763. ImVec2 current_off = g.IO.MousePos - wheel_center;
  9764. float initial_dist2 = ImLengthSqr(initial_off);
  9765. if (initial_dist2 >= (wheel_r_inner - 1)*(wheel_r_inner - 1) && initial_dist2 <= (wheel_r_outer + 1)*(wheel_r_outer + 1))
  9766. {
  9767. // Interactive with Hue wheel
  9768. H = atan2f(current_off.y, current_off.x) / IM_PI*0.5f;
  9769. if (H < 0.0f)
  9770. H += 1.0f;
  9771. value_changed = value_changed_h = true;
  9772. }
  9773. float cos_hue_angle = cosf(-H * 2.0f * IM_PI);
  9774. float sin_hue_angle = sinf(-H * 2.0f * IM_PI);
  9775. if (ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, ImRotate(initial_off, cos_hue_angle, sin_hue_angle)))
  9776. {
  9777. // Interacting with SV triangle
  9778. ImVec2 current_off_unrotated = ImRotate(current_off, cos_hue_angle, sin_hue_angle);
  9779. if (!ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated))
  9780. current_off_unrotated = ImTriangleClosestPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated);
  9781. float uu, vv, ww;
  9782. ImTriangleBarycentricCoords(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated, uu, vv, ww);
  9783. V = ImClamp(1.0f - vv, 0.0001f, 1.0f);
  9784. S = ImClamp(uu / V, 0.0001f, 1.0f);
  9785. value_changed = value_changed_sv = true;
  9786. }
  9787. }
  9788. if (!(flags & ImGuiColorEditFlags_NoOptions) && IsItemHovered() && IsMouseClicked(1))
  9789. OpenPopup("context");
  9790. }
  9791. else if (flags & ImGuiColorEditFlags_PickerHueBar)
  9792. {
  9793. // SV rectangle logic
  9794. InvisibleButton("sv", ImVec2(sv_picker_size, sv_picker_size));
  9795. if (IsItemActive())
  9796. {
  9797. S = ImSaturate((io.MousePos.x - picker_pos.x) / (sv_picker_size - 1));
  9798. V = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1));
  9799. value_changed = value_changed_sv = true;
  9800. }
  9801. if (!(flags & ImGuiColorEditFlags_NoOptions) && IsItemHovered() && IsMouseClicked(1))
  9802. OpenPopup("context");
  9803.  
  9804. // Hue bar logic
  9805. SetCursorScreenPos(ImVec2(bar0_pos_x, picker_pos.y));
  9806. InvisibleButton("hue", ImVec2(bars_width, sv_picker_size));
  9807. if (IsItemActive())
  9808. {
  9809. H = ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1));
  9810. value_changed = value_changed_h = true;
  9811. }
  9812. }
  9813.  
  9814. // Alpha bar logic
  9815. if (alpha_bar)
  9816. {
  9817. SetCursorScreenPos(ImVec2(bar1_pos_x, picker_pos.y));
  9818. InvisibleButton("alpha", ImVec2(bars_width, sv_picker_size));
  9819. if (IsItemActive())
  9820. {
  9821. col[3] = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1));
  9822. value_changed = true;
  9823. }
  9824. }
  9825.  
  9826. if (!(flags & ImGuiColorEditFlags_NoSidePreview))
  9827. {
  9828. SameLine(0, style.ItemInnerSpacing.x);
  9829. BeginGroup();
  9830. }
  9831.  
  9832. if (!(flags & ImGuiColorEditFlags_NoLabel))
  9833. {
  9834. const char* label_display_end = FindRenderedTextEnd(label);
  9835. if (label != label_display_end)
  9836. {
  9837. if ((flags & ImGuiColorEditFlags_NoSidePreview))
  9838. SameLine(0, style.ItemInnerSpacing.x);
  9839. TextUnformatted(label, label_display_end);
  9840. }
  9841. }
  9842.  
  9843. if (!(flags & ImGuiColorEditFlags_NoSidePreview))
  9844. {
  9845. ImVec4 col_v4(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
  9846. float square_sz = ColorSquareSize();
  9847. if ((flags & ImGuiColorEditFlags_NoLabel))
  9848. Text("Current");
  9849. ColorButton("##current", col_v4, (flags & (ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf | ImGuiColorEditFlags_NoTooltip)), ImVec2(square_sz * 3, square_sz * 2));
  9850. if (ref_col != NULL)
  9851. {
  9852. Text("Original");
  9853. ImVec4 ref_col_v4(ref_col[0], ref_col[1], ref_col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : ref_col[3]);
  9854. if (ColorButton("##original", ref_col_v4, (flags & (ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf | ImGuiColorEditFlags_NoTooltip)), ImVec2(square_sz * 3, square_sz * 2)))
  9855. {
  9856. memcpy(col, ref_col, ((flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4) * sizeof(float));
  9857. value_changed = true;
  9858. }
  9859. }
  9860. EndGroup();
  9861. }
  9862.  
  9863. // Convert back color to RGB
  9864. if (value_changed_h || value_changed_sv)
  9865. ColorConvertHSVtoRGB(H >= 1.0f ? H - 10 * 1e-6f : H, S > 0.0f ? S : 10 * 1e-6f, V > 0.0f ? V : 1e-6f, col[0], col[1], col[2]);
  9866.  
  9867. // R,G,B and H,S,V slider color editor
  9868. if ((flags & ImGuiColorEditFlags_NoInputs) == 0)
  9869. {
  9870. PushItemWidth((alpha_bar ? bar1_pos_x : bar0_pos_x) + bars_width - picker_pos.x);
  9871. ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoSmallPreview | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf;
  9872. ImGuiColorEditFlags sub_flags = (flags & sub_flags_to_forward) | ImGuiColorEditFlags_NoPicker;
  9873. if (flags & ImGuiColorEditFlags_RGB || (flags & ImGuiColorEditFlags__InputsMask) == 0)
  9874. value_changed |= ColorEdit4("##rgb", col, sub_flags | ImGuiColorEditFlags_RGB);
  9875. if (flags & ImGuiColorEditFlags_HSV || (flags & ImGuiColorEditFlags__InputsMask) == 0)
  9876. value_changed |= ColorEdit4("##hsv", col, sub_flags | ImGuiColorEditFlags_HSV);
  9877. if (flags & ImGuiColorEditFlags_HEX || (flags & ImGuiColorEditFlags__InputsMask) == 0)
  9878. value_changed |= ColorEdit4("##hex", col, sub_flags | ImGuiColorEditFlags_HEX);
  9879. PopItemWidth();
  9880. }
  9881.  
  9882. // Try to cancel hue wrap (after ColorEdit), if any
  9883. if (value_changed)
  9884. {
  9885. float new_H, new_S, new_V;
  9886. ColorConvertRGBtoHSV(col[0], col[1], col[2], new_H, new_S, new_V);
  9887. if (new_H <= 0 && H > 0)
  9888. {
  9889. if (new_V <= 0 && V != new_V)
  9890. ColorConvertHSVtoRGB(H, S, new_V <= 0 ? V * 0.5f : new_V, col[0], col[1], col[2]);
  9891. else if (new_S <= 0)
  9892. ColorConvertHSVtoRGB(H, new_S <= 0 ? S * 0.5f : new_S, new_V, col[0], col[1], col[2]);
  9893. }
  9894. }
  9895.  
  9896. ImVec4 hue_color_f(1, 1, 1, 1); ColorConvertHSVtoRGB(H, 1, 1, hue_color_f.x, hue_color_f.y, hue_color_f.z);
  9897. ImU32 hue_color32 = ColorConvertFloat4ToU32(hue_color_f);
  9898. ImU32 col32_no_alpha = ColorConvertFloat4ToU32(ImVec4(col[0], col[1], col[2], 1.0f));
  9899.  
  9900. const ImU32 hue_colors[6 + 1] = { IM_COL32(255,0,0,255), IM_COL32(255,255,0,255), IM_COL32(0,255,0,255), IM_COL32(0,255,255,255), IM_COL32(0,0,255,255), IM_COL32(255,0,255,255), IM_COL32(255,0,0,255) };
  9901. ImVec2 sv_cursor_pos;
  9902.  
  9903. if (flags & ImGuiColorEditFlags_PickerHueWheel)
  9904. {
  9905. // Render Hue Wheel
  9906. const float aeps = 1.5f / wheel_r_outer; // Half a pixel arc length in radians (2pi cancels out).
  9907. const int segment_per_arc = ImMax(4, (int)wheel_r_outer / 12);
  9908. for (int n = 0; n < 6; n++)
  9909. {
  9910. const float a0 = (n) / 6.0f * 2.0f * IM_PI - aeps;
  9911. const float a1 = (n + 1.0f) / 6.0f * 2.0f * IM_PI + aeps;
  9912. int vert_start_idx = draw_list->_VtxCurrentIdx;
  9913. draw_list->PathArcTo(wheel_center, (wheel_r_inner + wheel_r_outer)*0.5f, a0, a1, segment_per_arc);
  9914. draw_list->PathStroke(IM_COL32_WHITE, false, wheel_thickness);
  9915.  
  9916. // Paint colors over existing vertices
  9917. ImVec2 gradient_p0(wheel_center.x + cosf(a0) * wheel_r_inner, wheel_center.y + sinf(a0) * wheel_r_inner);
  9918. ImVec2 gradient_p1(wheel_center.x + cosf(a1) * wheel_r_inner, wheel_center.y + sinf(a1) * wheel_r_inner);
  9919. PaintVertsLinearGradientKeepAlpha(draw_list->_VtxWritePtr - (draw_list->_VtxCurrentIdx - vert_start_idx), draw_list->_VtxWritePtr, gradient_p0, gradient_p1, hue_colors[n], hue_colors[n + 1]);
  9920. }
  9921.  
  9922. // Render Cursor + preview on Hue Wheel
  9923. float cos_hue_angle = cosf(H * 2.0f * IM_PI);
  9924. float sin_hue_angle = sinf(H * 2.0f * IM_PI);
  9925. ImVec2 hue_cursor_pos(wheel_center.x + cos_hue_angle * (wheel_r_inner + wheel_r_outer)*0.5f, wheel_center.y + sin_hue_angle * (wheel_r_inner + wheel_r_outer)*0.5f);
  9926. float hue_cursor_rad = value_changed_h ? wheel_thickness * 0.65f : wheel_thickness * 0.55f;
  9927. int hue_cursor_segments = ImClamp((int)(hue_cursor_rad / 1.4f), 9, 32);
  9928. draw_list->AddCircleFilled(hue_cursor_pos, hue_cursor_rad, hue_color32, hue_cursor_segments);
  9929. draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad + 1, IM_COL32(128, 128, 128, 255), hue_cursor_segments);
  9930. draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad, IM_COL32_WHITE, hue_cursor_segments);
  9931.  
  9932. // Render SV triangle (rotated according to hue)
  9933. ImVec2 tra = wheel_center + ImRotate(triangle_pa, cos_hue_angle, sin_hue_angle);
  9934. ImVec2 trb = wheel_center + ImRotate(triangle_pb, cos_hue_angle, sin_hue_angle);
  9935. ImVec2 trc = wheel_center + ImRotate(triangle_pc, cos_hue_angle, sin_hue_angle);
  9936. ImVec2 uv_white = g.FontTexUvWhitePixel;
  9937. draw_list->PrimReserve(6, 6);
  9938. draw_list->PrimVtx(tra, uv_white, hue_color32);
  9939. draw_list->PrimVtx(trb, uv_white, hue_color32);
  9940. draw_list->PrimVtx(trc, uv_white, IM_COL32_WHITE);
  9941. draw_list->PrimVtx(tra, uv_white, IM_COL32_BLACK_TRANS);
  9942. draw_list->PrimVtx(trb, uv_white, IM_COL32_BLACK);
  9943. draw_list->PrimVtx(trc, uv_white, IM_COL32_BLACK_TRANS);
  9944. draw_list->AddTriangle(tra, trb, trc, IM_COL32(128, 128, 128, 255), 1.5f);
  9945. sv_cursor_pos = ImLerp(ImLerp(trc, tra, ImSaturate(S)), trb, ImSaturate(1 - V));
  9946. }
  9947. else if (flags & ImGuiColorEditFlags_PickerHueBar)
  9948. {
  9949. // Render SV Square
  9950. draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), IM_COL32_WHITE, hue_color32, hue_color32, IM_COL32_WHITE);
  9951. draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), IM_COL32_BLACK_TRANS, IM_COL32_BLACK_TRANS, IM_COL32_BLACK, IM_COL32_BLACK);
  9952. RenderFrameBorder(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), 0.0f);
  9953. sv_cursor_pos.x = ImClamp((float)(int)(picker_pos.x + ImSaturate(S) * sv_picker_size + 0.5f), picker_pos.x + 2, picker_pos.x + sv_picker_size - 2); // Sneakily prevent the circle to stick out too much
  9954. sv_cursor_pos.y = ImClamp((float)(int)(picker_pos.y + ImSaturate(1 - V) * sv_picker_size + 0.5f), picker_pos.y + 2, picker_pos.y + sv_picker_size - 2);
  9955.  
  9956. // Render Hue Bar
  9957. for (int i = 0; i < 6; ++i)
  9958. draw_list->AddRectFilledMultiColor(ImVec2(bar0_pos_x, picker_pos.y + i * (sv_picker_size / 6)), ImVec2(bar0_pos_x + bars_width, picker_pos.y + (i + 1) * (sv_picker_size / 6)), hue_colors[i], hue_colors[i], hue_colors[i + 1], hue_colors[i + 1]);
  9959. float bar0_line_y = (float)(int)(picker_pos.y + H * sv_picker_size + 0.5f);
  9960. RenderFrameBorder(ImVec2(bar0_pos_x, picker_pos.y), ImVec2(bar0_pos_x + bars_width, picker_pos.y + sv_picker_size), 0.0f);
  9961. RenderArrowsForVerticalBar(draw_list, ImVec2(bar0_pos_x - 1, bar0_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f);
  9962. }
  9963.  
  9964. // Render cursor/preview circle (clamp S/V within 0..1 range because floating points colors may lead HSV values to be out of range)
  9965. float sv_cursor_rad = value_changed_sv ? 10.0f : 6.0f;
  9966. draw_list->AddCircleFilled(sv_cursor_pos, sv_cursor_rad, col32_no_alpha, 12);
  9967. draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad + 1, IM_COL32(128, 128, 128, 255), 12);
  9968. draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad, IM_COL32_WHITE, 12);
  9969.  
  9970. // Render alpha bar
  9971. if (alpha_bar)
  9972. {
  9973. float alpha = ImSaturate(col[3]);
  9974. ImRect bar1_bb(bar1_pos_x, picker_pos.y, bar1_pos_x + bars_width, picker_pos.y + sv_picker_size);
  9975. RenderColorRectWithAlphaCheckerboard(bar1_bb.Min, bar1_bb.Max, IM_COL32(0, 0, 0, 0), bar1_bb.GetWidth() / 2.0f, ImVec2(0.0f, 0.0f));
  9976. draw_list->AddRectFilledMultiColor(bar1_bb.Min, bar1_bb.Max, col32_no_alpha, col32_no_alpha, col32_no_alpha & ~IM_COL32_A_MASK, col32_no_alpha & ~IM_COL32_A_MASK);
  9977. float bar1_line_y = (float)(int)(picker_pos.y + (1.0f - alpha) * sv_picker_size + 0.5f);
  9978. RenderFrameBorder(bar1_bb.Min, bar1_bb.Max, 0.0f);
  9979. RenderArrowsForVerticalBar(draw_list, ImVec2(bar1_pos_x - 1, bar1_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f);
  9980. }
  9981.  
  9982. EndGroup();
  9983. PopID();
  9984.  
  9985. return value_changed;
  9986. }
  9987.  
  9988. // Horizontal separating line.
  9989. void ImGui::Separator()
  9990. {
  9991. ImGuiWindow* window = GetCurrentWindow();
  9992. if (window->SkipItems)
  9993. return;
  9994.  
  9995. if (window->DC.ColumnsCount > 1)
  9996. PopClipRect();
  9997.  
  9998. float x1 = window->Pos.x;
  9999. float x2 = window->Pos.x + window->Size.x;
  10000. if (!window->DC.GroupStack.empty())
  10001. x1 += window->DC.IndentX;
  10002.  
  10003. const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y + 1.0f));
  10004. ItemSize(ImVec2(0.0f, 0.0f)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit, we don't provide height to not alter layout.
  10005. if (!ItemAdd(bb, NULL))
  10006. {
  10007. if (window->DC.ColumnsCount > 1)
  10008. PushColumnClipRect();
  10009. return;
  10010. }
  10011.  
  10012. window->DrawList->AddLine(bb.Min, ImVec2(bb.Max.x, bb.Min.y), GetColorU32(ImGuiCol_Separator));
  10013.  
  10014. ImGuiContext& g = *GImGui;
  10015. if (g.LogEnabled)
  10016. LogText(IM_NEWLINE "--------------------------------");
  10017.  
  10018. if (window->DC.ColumnsCount > 1)
  10019. {
  10020. PushColumnClipRect();
  10021. window->DC.ColumnsCellMinY = window->DC.CursorPos.y;
  10022. }
  10023. }
  10024.  
  10025. void ImGui::Spacing()
  10026. {
  10027. ImGuiWindow* window = GetCurrentWindow();
  10028. if (window->SkipItems)
  10029. return;
  10030. ItemSize(ImVec2(0, 0));
  10031. }
  10032.  
  10033. void ImGui::Dummy(const ImVec2& size)
  10034. {
  10035. ImGuiWindow* window = GetCurrentWindow();
  10036. if (window->SkipItems)
  10037. return;
  10038.  
  10039. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
  10040. ItemSize(bb);
  10041. ItemAdd(bb, NULL);
  10042. }
  10043.  
  10044. bool ImGui::IsRectVisible(const ImVec2& size)
  10045. {
  10046. ImGuiWindow* window = GetCurrentWindowRead();
  10047. return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
  10048. }
  10049.  
  10050. bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
  10051. {
  10052. ImGuiWindow* window = GetCurrentWindowRead();
  10053. return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
  10054. }
  10055.  
  10056. // Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
  10057. void ImGui::BeginGroup()
  10058. {
  10059. ImGuiWindow* window = GetCurrentWindow();
  10060.  
  10061. window->DC.GroupStack.resize(window->DC.GroupStack.Size + 1);
  10062. ImGuiGroupData& group_data = window->DC.GroupStack.back();
  10063. group_data.BackupCursorPos = window->DC.CursorPos;
  10064. group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
  10065. group_data.BackupIndentX = window->DC.IndentX;
  10066. group_data.BackupGroupOffsetX = window->DC.GroupOffsetX;
  10067. group_data.BackupCurrentLineHeight = window->DC.CurrentLineHeight;
  10068. group_data.BackupCurrentLineTextBaseOffset = window->DC.CurrentLineTextBaseOffset;
  10069. group_data.BackupLogLinePosY = window->DC.LogLinePosY;
  10070. group_data.BackupActiveIdIsAlive = GImGui->ActiveIdIsAlive;
  10071. group_data.AdvanceCursor = true;
  10072.  
  10073. window->DC.GroupOffsetX = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffsetX;
  10074. window->DC.IndentX = window->DC.GroupOffsetX;
  10075. window->DC.CursorMaxPos = window->DC.CursorPos;
  10076. window->DC.CurrentLineHeight = 0.0f;
  10077. window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
  10078. }
  10079.  
  10080. void ImGui::EndGroup()
  10081. {
  10082. ImGuiContext& g = *GImGui;
  10083. ImGuiWindow* window = GetCurrentWindow();
  10084.  
  10085. IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls
  10086.  
  10087. ImGuiGroupData& group_data = window->DC.GroupStack.back();
  10088.  
  10089. ImRect group_bb(group_data.BackupCursorPos, window->DC.CursorMaxPos);
  10090. group_bb.Max.y -= g.Style.ItemSpacing.y; // Cancel out last vertical spacing because we are adding one ourselves.
  10091. group_bb.Max = ImMax(group_bb.Min, group_bb.Max);
  10092.  
  10093. window->DC.CursorPos = group_data.BackupCursorPos;
  10094. window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
  10095. window->DC.CurrentLineHeight = group_data.BackupCurrentLineHeight;
  10096. window->DC.CurrentLineTextBaseOffset = group_data.BackupCurrentLineTextBaseOffset;
  10097. window->DC.IndentX = group_data.BackupIndentX;
  10098. window->DC.GroupOffsetX = group_data.BackupGroupOffsetX;
  10099. window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
  10100.  
  10101. if (group_data.AdvanceCursor)
  10102. {
  10103. window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrentLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
  10104. ItemSize(group_bb.GetSize(), group_data.BackupCurrentLineTextBaseOffset);
  10105. ItemAdd(group_bb, NULL);
  10106. }
  10107.  
  10108. // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive() will function on the entire group.
  10109. // It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but if you search for LastItemId you'll notice it is only used in that context.
  10110. const bool active_id_within_group = (!group_data.BackupActiveIdIsAlive && g.ActiveIdIsAlive && g.ActiveId && g.ActiveIdWindow->RootWindow == window->RootWindow);
  10111. if (active_id_within_group)
  10112. window->DC.LastItemId = g.ActiveId;
  10113. if (active_id_within_group && g.HoveredId == g.ActiveId)
  10114. window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = true;
  10115.  
  10116. window->DC.GroupStack.pop_back();
  10117.  
  10118. //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
  10119. }
  10120.  
  10121. // Gets back to previous line and continue with horizontal layout
  10122. // pos_x == 0 : follow right after previous item
  10123. // pos_x != 0 : align to specified x position (relative to window/group left)
  10124. // spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0
  10125. // spacing_w >= 0 : enforce spacing amount
  10126. void ImGui::SameLine(float pos_x, float spacing_w)
  10127. {
  10128. ImGuiWindow* window = GetCurrentWindow();
  10129. if (window->SkipItems)
  10130. return;
  10131.  
  10132. ImGuiContext& g = *GImGui;
  10133. if (pos_x != 0.0f)
  10134. {
  10135. if (spacing_w < 0.0f) spacing_w = 0.0f;
  10136. window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + pos_x + spacing_w + window->DC.GroupOffsetX + window->DC.ColumnsOffsetX;
  10137. window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
  10138. }
  10139. else
  10140. {
  10141. if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x;
  10142. window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
  10143. window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
  10144. }
  10145. window->DC.CurrentLineHeight = window->DC.PrevLineHeight;
  10146. window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
  10147. }
  10148.  
  10149. void ImGui::NewLine()
  10150. {
  10151. ImGuiWindow* window = GetCurrentWindow();
  10152. if (window->SkipItems)
  10153. return;
  10154. if (window->DC.CurrentLineHeight > 0.0f) // In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height.
  10155. ItemSize(ImVec2(0, 0));
  10156. else
  10157. ItemSize(ImVec2(0.0f, GImGui->FontSize));
  10158. }
  10159.  
  10160. void ImGui::NextColumn()
  10161. {
  10162. ImGuiWindow* window = GetCurrentWindow();
  10163. if (window->SkipItems || window->DC.ColumnsCount <= 1)
  10164. return;
  10165.  
  10166. ImGuiContext& g = *GImGui;
  10167. PopItemWidth();
  10168. PopClipRect();
  10169.  
  10170. window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y);
  10171. if (++window->DC.ColumnsCurrent < window->DC.ColumnsCount)
  10172. {
  10173. // Columns 1+ cancel out IndentX
  10174. window->DC.ColumnsOffsetX = GetColumnOffset(window->DC.ColumnsCurrent) - window->DC.IndentX + g.Style.ItemSpacing.x;
  10175. window->DrawList->ChannelsSetCurrent(window->DC.ColumnsCurrent);
  10176. }
  10177. else
  10178. {
  10179. window->DC.ColumnsCurrent = 0;
  10180. window->DC.ColumnsOffsetX = 0.0f;
  10181. window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY;
  10182. window->DrawList->ChannelsSetCurrent(0);
  10183. }
  10184. window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX);
  10185. window->DC.CursorPos.y = window->DC.ColumnsCellMinY;
  10186. window->DC.CurrentLineHeight = 0.0f;
  10187. window->DC.CurrentLineTextBaseOffset = 0.0f;
  10188.  
  10189. PushColumnClipRect();
  10190. PushItemWidth(GetColumnWidth() * 0.65f); // FIXME: Move on columns setup
  10191. }
  10192.  
  10193. int ImGui::GetColumnIndex()
  10194. {
  10195. ImGuiWindow* window = GetCurrentWindowRead();
  10196. return window->DC.ColumnsCurrent;
  10197. }
  10198.  
  10199. int ImGui::GetColumnsCount()
  10200. {
  10201. ImGuiWindow* window = GetCurrentWindowRead();
  10202. return window->DC.ColumnsCount;
  10203. }
  10204.  
  10205. static float OffsetNormToPixels(ImGuiWindow* window, float offset_norm)
  10206. {
  10207. return offset_norm * (window->DC.ColumnsMaxX - window->DC.ColumnsMinX);
  10208. }
  10209.  
  10210. static float PixelsToOffsetNorm(ImGuiWindow* window, float offset)
  10211. {
  10212. return (offset - window->DC.ColumnsMinX) / (window->DC.ColumnsMaxX - window->DC.ColumnsMinX);
  10213. }
  10214.  
  10215. static float GetDraggedColumnOffset(int column_index)
  10216. {
  10217. // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing
  10218. // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning.
  10219. ImGuiContext& g = *GImGui;
  10220. ImGuiWindow* window = ImGui::GetCurrentWindowRead();
  10221. IM_ASSERT(column_index > 0); // We cannot drag column 0. If you get this assert you may have a conflict between the ID of your columns and another widgets.
  10222. IM_ASSERT(g.ActiveId == window->DC.ColumnsSetId + ImGuiID(column_index));
  10223.  
  10224. float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x - window->Pos.x;
  10225. x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing);
  10226. if ((window->DC.ColumnsFlags & ImGuiColumnsFlags_NoPreserveWidths))
  10227. x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing);
  10228.  
  10229. return x;
  10230. }
  10231.  
  10232. float ImGui::GetColumnOffset(int column_index)
  10233. {
  10234. ImGuiWindow* window = GetCurrentWindowRead();
  10235. if (column_index < 0)
  10236. column_index = window->DC.ColumnsCurrent;
  10237.  
  10238. /*
  10239. if (g.ActiveId)
  10240. {
  10241. ImGuiContext& g = *GImGui;
  10242. const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index);
  10243. if (g.ActiveId == column_id)
  10244. return GetDraggedColumnOffset(column_index);
  10245. }
  10246. */
  10247.  
  10248. IM_ASSERT(column_index < window->DC.ColumnsData.Size);
  10249. const float t = window->DC.ColumnsData[column_index].OffsetNorm;
  10250. const float x_offset = ImLerp(window->DC.ColumnsMinX, window->DC.ColumnsMaxX, t);
  10251. return x_offset;
  10252. }
  10253.  
  10254. void ImGui::SetColumnOffset(int column_index, float offset)
  10255. {
  10256. ImGuiContext& g = *GImGui;
  10257. ImGuiWindow* window = GetCurrentWindow();
  10258. if (column_index < 0)
  10259. column_index = window->DC.ColumnsCurrent;
  10260.  
  10261. IM_ASSERT(column_index < window->DC.ColumnsData.Size);
  10262.  
  10263. const bool preserve_width = !(window->DC.ColumnsFlags & ImGuiColumnsFlags_NoPreserveWidths) && (column_index < window->DC.ColumnsCount - 1);
  10264. const float width = preserve_width ? GetColumnWidth(column_index) : 0.0f;
  10265.  
  10266. if (!(window->DC.ColumnsFlags & ImGuiColumnsFlags_NoForceWithinWindow))
  10267. offset = ImMin(offset, window->DC.ColumnsMaxX - g.Style.ColumnsMinSpacing * (window->DC.ColumnsCount - column_index));
  10268. const float offset_norm = PixelsToOffsetNorm(window, offset);
  10269.  
  10270. const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index);
  10271. window->DC.StateStorage->SetFloat(column_id, offset_norm);
  10272. window->DC.ColumnsData[column_index].OffsetNorm = offset_norm;
  10273.  
  10274. if (preserve_width)
  10275. SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width));
  10276. }
  10277.  
  10278. float ImGui::GetColumnWidth(int column_index)
  10279. {
  10280. ImGuiWindow* window = GetCurrentWindowRead();
  10281. if (column_index < 0)
  10282. column_index = window->DC.ColumnsCurrent;
  10283.  
  10284. return OffsetNormToPixels(window, window->DC.ColumnsData[column_index + 1].OffsetNorm - window->DC.ColumnsData[column_index].OffsetNorm);
  10285. }
  10286.  
  10287. void ImGui::SetColumnWidth(int column_index, float width)
  10288. {
  10289. ImGuiWindow* window = GetCurrentWindowRead();
  10290. if (column_index < 0)
  10291. column_index = window->DC.ColumnsCurrent;
  10292.  
  10293. SetColumnOffset(column_index + 1, GetColumnOffset(column_index) + width);
  10294. }
  10295.  
  10296. void ImGui::PushColumnClipRect(int column_index)
  10297. {
  10298. ImGuiWindow* window = GetCurrentWindowRead();
  10299. if (column_index < 0)
  10300. column_index = window->DC.ColumnsCurrent;
  10301.  
  10302. PushClipRect(window->DC.ColumnsData[column_index].ClipRect.Min, window->DC.ColumnsData[column_index].ClipRect.Max, false);
  10303. }
  10304.  
  10305. void ImGui::BeginColumns(const char* id, int columns_count, ImGuiColumnsFlags flags)
  10306. {
  10307. ImGuiContext& g = *GImGui;
  10308. ImGuiWindow* window = GetCurrentWindow();
  10309.  
  10310. IM_ASSERT(columns_count > 1);
  10311. IM_ASSERT(window->DC.ColumnsCount == 1); // Nested columns are currently not supported
  10312.  
  10313. // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget.
  10314. // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer.
  10315. PushID(0x11223347 + (id ? 0 : columns_count));
  10316. window->DC.ColumnsSetId = window->GetID(id ? id : "columns");
  10317. PopID();
  10318.  
  10319. // Set state for first column
  10320. window->DC.ColumnsCurrent = 0;
  10321. window->DC.ColumnsCount = columns_count;
  10322. window->DC.ColumnsFlags = flags;
  10323.  
  10324. const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? (window->SizeContentsExplicit.x) : (window->Size.x - window->ScrollbarSizes.x);
  10325. window->DC.ColumnsMinX = window->DC.IndentX - g.Style.ItemSpacing.x; // Lock our horizontal range
  10326. //window->DC.ColumnsMaxX = content_region_width - window->Scroll.x -((window->Flags & ImGuiWindowFlags_NoScrollbar) ? 0 : g.Style.ScrollbarSize);// - window->WindowPadding().x;
  10327. window->DC.ColumnsMaxX = content_region_width - window->Scroll.x;
  10328. window->DC.ColumnsStartPosY = window->DC.CursorPos.y;
  10329. window->DC.ColumnsStartMaxPosX = window->DC.CursorMaxPos.x;
  10330. window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.CursorPos.y;
  10331. window->DC.ColumnsOffsetX = 0.0f;
  10332. window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX);
  10333.  
  10334. // Cache column offsets
  10335. window->DC.ColumnsData.resize(columns_count + 1);
  10336. for (int column_index = 0; column_index < columns_count + 1; column_index++)
  10337. {
  10338. const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index);
  10339. KeepAliveID(column_id);
  10340. const float default_t = column_index / (float)window->DC.ColumnsCount;
  10341. float t = window->DC.StateStorage->GetFloat(column_id, default_t);
  10342. if (!(window->DC.ColumnsFlags & ImGuiColumnsFlags_NoForceWithinWindow))
  10343. t = ImMin(t, PixelsToOffsetNorm(window, window->DC.ColumnsMaxX - g.Style.ColumnsMinSpacing * (window->DC.ColumnsCount - column_index)));
  10344. window->DC.ColumnsData[column_index].OffsetNorm = t;
  10345. }
  10346.  
  10347. // Cache clipping rectangles
  10348. for (int column_index = 0; column_index < columns_count; column_index++)
  10349. {
  10350. float clip_x1 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(column_index) - 1.0f);
  10351. float clip_x2 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(column_index + 1) - 1.0f);
  10352. window->DC.ColumnsData[column_index].ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX);
  10353. window->DC.ColumnsData[column_index].ClipRect.ClipWith(window->ClipRect);
  10354. }
  10355.  
  10356. window->DrawList->ChannelsSplit(window->DC.ColumnsCount);
  10357. PushColumnClipRect();
  10358. PushItemWidth(GetColumnWidth() * 0.65f);
  10359. }
  10360.  
  10361. void ImGui::EndColumns()
  10362. {
  10363. ImGuiContext& g = *GImGui;
  10364. ImGuiWindow* window = GetCurrentWindow();
  10365. IM_ASSERT(window->DC.ColumnsCount > 1);
  10366.  
  10367. PopItemWidth();
  10368. PopClipRect();
  10369. window->DrawList->ChannelsMerge();
  10370.  
  10371. window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y);
  10372. window->DC.CursorPos.y = window->DC.ColumnsCellMaxY;
  10373. window->DC.CursorMaxPos.x = ImMax(window->DC.ColumnsStartMaxPosX, window->DC.ColumnsMaxX); // Columns don't grow parent
  10374.  
  10375. // Draw columns borders and handle resize
  10376. if (!(window->DC.ColumnsFlags & ImGuiColumnsFlags_NoBorder) && !window->SkipItems)
  10377. {
  10378. const float y1 = window->DC.ColumnsStartPosY;
  10379. const float y2 = window->DC.CursorPos.y;
  10380. int dragging_column = -1;
  10381. for (int i = 1; i < window->DC.ColumnsCount; i++)
  10382. {
  10383. float x = window->Pos.x + GetColumnOffset(i);
  10384. const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(i);
  10385. const float column_w = 4.0f; // Width for interaction
  10386. const ImRect column_rect(ImVec2(x - column_w, y1), ImVec2(x + column_w, y2));
  10387. if (IsClippedEx(column_rect, &column_id, false))
  10388. continue;
  10389.  
  10390. bool hovered = false, held = false;
  10391. if (!(window->DC.ColumnsFlags & ImGuiColumnsFlags_NoResize))
  10392. {
  10393. ButtonBehavior(column_rect, column_id, &hovered, &held);
  10394. if (hovered || held)
  10395. g.MouseCursor = ImGuiMouseCursor_ResizeEW;
  10396. if (held && g.ActiveIdIsJustActivated)
  10397. g.ActiveIdClickOffset.x -= column_w; // Store from center of column line (we used a 8 wide rect for columns clicking). This is used by GetDraggedColumnOffset().
  10398. if (held)
  10399. dragging_column = i;
  10400. }
  10401.  
  10402. // Draw column
  10403. const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
  10404. const float xi = (float)(int)x;
  10405. window->DrawList->AddLine(ImVec2(xi, y1 + 1.0f), ImVec2(xi, y2), col);
  10406. }
  10407.  
  10408. // Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame.
  10409. if (dragging_column != -1)
  10410. {
  10411. float x = GetDraggedColumnOffset(dragging_column);
  10412. SetColumnOffset(dragging_column, x);
  10413. }
  10414. }
  10415.  
  10416. window->DC.ColumnsSetId = 0;
  10417. window->DC.ColumnsCurrent = 0;
  10418. window->DC.ColumnsCount = 1;
  10419. window->DC.ColumnsFlags = 0;
  10420. window->DC.ColumnsData.resize(0);
  10421. window->DC.ColumnsOffsetX = 0.0f;
  10422. window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX);
  10423. }
  10424.  
  10425. // [2017/08: This is currently the only public API, while we are working on making BeginColumns/EndColumns user-facing]
  10426. void ImGui::Columns(int columns_count, const char* id, bool border)
  10427. {
  10428. ImGuiWindow* window = GetCurrentWindow();
  10429. IM_ASSERT(columns_count >= 1);
  10430.  
  10431. if (window->DC.ColumnsCount != columns_count && window->DC.ColumnsCount != 1)
  10432. EndColumns();
  10433.  
  10434. ImGuiColumnsFlags flags = (border ? 0 : ImGuiColumnsFlags_NoBorder);
  10435. //flags |= ImGuiColumnsFlags_NoPreserveWidths; // NB: Legacy behavior
  10436. if (columns_count != 1)
  10437. BeginColumns(id, columns_count, flags);
  10438. }
  10439.  
  10440. void ImGui::Indent(float indent_w)
  10441. {
  10442. ImGuiContext& g = *GImGui;
  10443. ImGuiWindow* window = GetCurrentWindow();
  10444. window->DC.IndentX += (indent_w > 0.0f) ? indent_w : g.Style.IndentSpacing;
  10445. window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX;
  10446. }
  10447.  
  10448. void ImGui::Unindent(float indent_w)
  10449. {
  10450. ImGuiContext& g = *GImGui;
  10451. ImGuiWindow* window = GetCurrentWindow();
  10452. window->DC.IndentX -= (indent_w > 0.0f) ? indent_w : g.Style.IndentSpacing;
  10453. window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX;
  10454. }
  10455.  
  10456. void ImGui::TreePush(const char* str_id)
  10457. {
  10458. ImGuiWindow* window = GetCurrentWindow();
  10459. Indent();
  10460. window->DC.TreeDepth++;
  10461. PushID(str_id ? str_id : "#TreePush");
  10462. }
  10463.  
  10464. void ImGui::TreePush(const void* ptr_id)
  10465. {
  10466. ImGuiWindow* window = GetCurrentWindow();
  10467. Indent();
  10468. window->DC.TreeDepth++;
  10469. PushID(ptr_id ? ptr_id : (const void*)"#TreePush");
  10470. }
  10471.  
  10472. void ImGui::TreePushRawID(ImGuiID id)
  10473. {
  10474. ImGuiWindow* window = GetCurrentWindow();
  10475. Indent();
  10476. window->DC.TreeDepth++;
  10477. window->IDStack.push_back(id);
  10478. }
  10479.  
  10480. void ImGui::TreePop()
  10481. {
  10482. ImGuiWindow* window = GetCurrentWindow();
  10483. Unindent();
  10484. window->DC.TreeDepth--;
  10485. PopID();
  10486. }
  10487.  
  10488. void ImGui::Value(const char* prefix, bool b)
  10489. {
  10490. Text("%s: %s", prefix, (b ? "true" : "false"));
  10491. }
  10492.  
  10493. void ImGui::Value(const char* prefix, int v)
  10494. {
  10495. Text("%s: %d", prefix, v);
  10496. }
  10497.  
  10498. void ImGui::Value(const char* prefix, unsigned int v)
  10499. {
  10500. Text("%s: %d", prefix, v);
  10501. }
  10502.  
  10503. void ImGui::Value(const char* prefix, float v, const char* float_format)
  10504. {
  10505. if (float_format)
  10506. {
  10507. char fmt[64];
  10508. ImFormatString(fmt, IM_ARRAYSIZE(fmt), "%%s: %s", float_format);
  10509. Text(fmt, prefix, v);
  10510. }
  10511. else
  10512. {
  10513. Text("%s: %.3f", prefix, v);
  10514. }
  10515. }
  10516.  
  10517. //-----------------------------------------------------------------------------
  10518. // PLATFORM DEPENDENT HELPERS
  10519. //-----------------------------------------------------------------------------
  10520.  
  10521. #if defined(_WIN32) && !defined(_WINDOWS_) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS))
  10522. #undef WIN32_LEAN_AND_MEAN
  10523. #define WIN32_LEAN_AND_MEAN
  10524. #include <windows.h>
  10525. #endif
  10526.  
  10527. // Win32 API clipboard implementation
  10528. #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS)
  10529.  
  10530. #ifdef _MSC_VER
  10531. #pragma comment(lib, "user32")
  10532. #endif
  10533.  
  10534. static const char* GetClipboardTextFn_DefaultImpl(void*)
  10535. {
  10536. static ImVector<char> buf_local;
  10537. buf_local.clear();
  10538. if (!OpenClipboard(NULL))
  10539. return NULL;
  10540. HANDLE wbuf_handle = GetClipboardData(CF_UNICODETEXT);
  10541. if (wbuf_handle == NULL)
  10542. {
  10543. CloseClipboard();
  10544. return NULL;
  10545. }
  10546. if (ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle))
  10547. {
  10548. int buf_len = ImTextCountUtf8BytesFromStr(wbuf_global, NULL) + 1;
  10549. buf_local.resize(buf_len);
  10550. ImTextStrToUtf8(buf_local.Data, buf_len, wbuf_global, NULL);
  10551. }
  10552. GlobalUnlock(wbuf_handle);
  10553. CloseClipboard();
  10554. return buf_local.Data;
  10555. }
  10556.  
  10557. static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
  10558. {
  10559. if (!OpenClipboard(NULL))
  10560. return;
  10561. const int wbuf_length = ImTextCountCharsFromUtf8(text, NULL) + 1;
  10562. HGLOBAL wbuf_handle = GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar));
  10563. if (wbuf_handle == NULL)
  10564. return;
  10565. ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle);
  10566. ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL);
  10567. GlobalUnlock(wbuf_handle);
  10568. EmptyClipboard();
  10569. SetClipboardData(CF_UNICODETEXT, wbuf_handle);
  10570. CloseClipboard();
  10571. }
  10572.  
  10573. #else
  10574.  
  10575. // Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers
  10576. static const char* GetClipboardTextFn_DefaultImpl(void*)
  10577. {
  10578. ImGuiContext& g = *GImGui;
  10579. return g.PrivateClipboard.empty() ? NULL : g.PrivateClipboard.begin();
  10580. }
  10581.  
  10582. // Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers
  10583. static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
  10584. {
  10585. ImGuiContext& g = *GImGui;
  10586. g.PrivateClipboard.clear();
  10587. const char* text_end = text + strlen(text);
  10588. g.PrivateClipboard.resize((size_t)(text_end - text) + 1);
  10589. memcpy(&g.PrivateClipboard[0], text, (size_t)(text_end - text));
  10590. g.PrivateClipboard[(int)(text_end - text)] = 0;
  10591. }
  10592.  
  10593. #endif
  10594.  
  10595. // Win32 API IME support (for Asian languages, etc.)
  10596. #if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS)
  10597.  
  10598. #include <imm.h>
  10599. #ifdef _MSC_VER
  10600. #pragma comment(lib, "imm32")
  10601. #endif
  10602.  
  10603. static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y)
  10604. {
  10605. // Notify OS Input Method Editor of text input position
  10606. if (HWND hwnd = (HWND)GImGui->IO.ImeWindowHandle)
  10607. if (HIMC himc = ImmGetContext(hwnd))
  10608. {
  10609. COMPOSITIONFORM cf;
  10610. cf.ptCurrentPos.x = x;
  10611. cf.ptCurrentPos.y = y;
  10612. cf.dwStyle = CFS_FORCE_POSITION;
  10613. ImmSetCompositionWindow(himc, &cf);
  10614. }
  10615. }
  10616.  
  10617. #else
  10618.  
  10619. static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {}
  10620.  
  10621. #endif
  10622.  
  10623. //-----------------------------------------------------------------------------
  10624. // HELP
  10625. //-----------------------------------------------------------------------------
  10626.  
  10627. void ImGui::ShowMetricsWindow(bool* p_open)
  10628. {
  10629. if (ImGui::Begin("ImGui Metrics", p_open))
  10630. {
  10631. ImGui::Text("ImGui %s", ImGui::GetVersion());
  10632. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
  10633. ImGui::Text("%d vertices, %d indices (%d triangles)", ImGui::GetIO().MetricsRenderVertices, ImGui::GetIO().MetricsRenderIndices, ImGui::GetIO().MetricsRenderIndices / 3);
  10634. ImGui::Text("%d allocations", ImGui::GetIO().MetricsAllocs);
  10635. static bool show_clip_rects = true;
  10636. ImGui::Checkbox("Show clipping rectangles when hovering an ImDrawCmd", &show_clip_rects);
  10637. ImGui::Separator();
  10638.  
  10639. struct Funcs
  10640. {
  10641. static void NodeDrawList(ImDrawList* draw_list, const char* label)
  10642. {
  10643. bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size);
  10644. if (draw_list == ImGui::GetWindowDrawList())
  10645. {
  10646. ImGui::SameLine();
  10647. ImGui::TextColored(ImColor(255, 100, 100), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
  10648. if (node_open) ImGui::TreePop();
  10649. return;
  10650. }
  10651. if (!node_open)
  10652. return;
  10653.  
  10654. ImDrawList* overlay_draw_list = &GImGui->OverlayDrawList; // Render additional visuals into the top-most draw list
  10655. overlay_draw_list->PushClipRectFullScreen();
  10656. int elem_offset = 0;
  10657. for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++)
  10658. {
  10659. if (pcmd->UserCallback)
  10660. {
  10661. ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
  10662. continue;
  10663. }
  10664. ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
  10665. bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "Draw %-4d %s vtx, tex = %p, clip_rect = (%.0f,%.0f)..(%.0f,%.0f)", pcmd->ElemCount, draw_list->IdxBuffer.Size > 0 ? "indexed" : "non-indexed", pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
  10666. if (show_clip_rects && ImGui::IsItemHovered())
  10667. {
  10668. ImRect clip_rect = pcmd->ClipRect;
  10669. ImRect vtxs_rect;
  10670. for (int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++)
  10671. vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos);
  10672. clip_rect.Floor(); overlay_draw_list->AddRect(clip_rect.Min, clip_rect.Max, IM_COL32(255, 255, 0, 255));
  10673. vtxs_rect.Floor(); overlay_draw_list->AddRect(vtxs_rect.Min, vtxs_rect.Max, IM_COL32(255, 0, 255, 255));
  10674. }
  10675. if (!pcmd_node_open)
  10676. continue;
  10677. ImGuiListClipper clipper(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
  10678. while (clipper.Step())
  10679. for (int prim = clipper.DisplayStart, vtx_i = elem_offset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
  10680. {
  10681. char buf[300], *buf_p = buf;
  10682. ImVec2 triangles_pos[3];
  10683. for (int n = 0; n < 3; n++, vtx_i++)
  10684. {
  10685. ImDrawVert& v = draw_list->VtxBuffer[idx_buffer ? idx_buffer[vtx_i] : vtx_i];
  10686. triangles_pos[n] = v.pos;
  10687. buf_p += sprintf(buf_p, "%s %04d { pos = (%8.2f,%8.2f), uv = (%.6f,%.6f), col = %08X }\n", (n == 0) ? "vtx" : " ", vtx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
  10688. }
  10689. ImGui::Selectable(buf, false);
  10690. if (ImGui::IsItemHovered())
  10691. overlay_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255, 255, 0, 255), true, 1.0f, false); // Add triangle without AA, more readable for large-thin triangle
  10692. }
  10693. ImGui::TreePop();
  10694. }
  10695. overlay_draw_list->PopClipRect();
  10696. ImGui::TreePop();
  10697. }
  10698.  
  10699. static void NodeWindows(ImVector<ImGuiWindow*>& windows, const char* label)
  10700. {
  10701. if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size))
  10702. return;
  10703. for (int i = 0; i < windows.Size; i++)
  10704. Funcs::NodeWindow(windows[i], "Window");
  10705. ImGui::TreePop();
  10706. }
  10707.  
  10708. static void NodeWindow(ImGuiWindow* window, const char* label)
  10709. {
  10710. if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Active || window->WasActive, window))
  10711. return;
  10712. NodeDrawList(window->DrawList, "DrawList");
  10713. ImGui::BulletText("Pos: (%.1f,%.1f)", window->Pos.x, window->Pos.y);
  10714. ImGui::BulletText("Size: (%.1f,%.1f), SizeContents (%.1f,%.1f)", window->Size.x, window->Size.y, window->SizeContents.x, window->SizeContents.y);
  10715. ImGui::BulletText("Scroll: (%.2f,%.2f)", window->Scroll.x, window->Scroll.y);
  10716. ImGui::BulletText("Active: %d, Accessed: %d", window->Active, window->Accessed);
  10717. if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow");
  10718. if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows");
  10719. ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.Size * (int)sizeof(ImGuiStorage::Pair));
  10720. ImGui::TreePop();
  10721. }
  10722. };
  10723.  
  10724. ImGuiContext& g = *GImGui; // Access private state
  10725. Funcs::NodeWindows(g.Windows, "Windows");
  10726. if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", g.RenderDrawLists[0].Size))
  10727. {
  10728. for (int i = 0; i < g.RenderDrawLists[0].Size; i++)
  10729. Funcs::NodeDrawList(g.RenderDrawLists[0][i], "DrawList");
  10730. ImGui::TreePop();
  10731. }
  10732. if (ImGui::TreeNode("Popups", "Open Popups Stack (%d)", g.OpenPopupStack.Size))
  10733. {
  10734. for (int i = 0; i < g.OpenPopupStack.Size; i++)
  10735. {
  10736. ImGuiWindow* window = g.OpenPopupStack[i].Window;
  10737. ImGui::BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : "");
  10738. }
  10739. ImGui::TreePop();
  10740. }
  10741. if (ImGui::TreeNode("Basic state"))
  10742. {
  10743. ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
  10744. ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL");
  10745. ImGui::Text("HoveredId: 0x%08X/0x%08X", g.HoveredId, g.HoveredIdPreviousFrame); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not
  10746. ImGui::Text("ActiveId: 0x%08X/0x%08X", g.ActiveId, g.ActiveIdPreviousFrame);
  10747. ImGui::Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
  10748. ImGui::Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
  10749. ImGui::TreePop();
  10750. }
  10751. }
  10752. ImGui::End();
  10753. }
  10754.  
  10755. //-----------------------------------------------------------------------------
  10756.  
  10757. // Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
  10758. // Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
  10759. #ifdef IMGUI_INCLUDE_IMGUI_USER_INL
  10760. #include "imgui_user.inl"
  10761. #endif
  10762.  
  10763. //-----------------------------------------------------------------------------
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement