Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 440.05 KB | None | 0 0
  1. // dear imgui, v1.50 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/772
  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. - API BREAKING CHANGES (read me when you update!)
  20. - FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
  21. - How can I help?
  22. - How do I update to a newer version of ImGui?
  23. - What is ImTextureID and how do I display an image?
  24. - I integrated ImGui in my engine and the text or lines are blurry..
  25. - I integrated ImGui in my engine and some elements are clipping or disappearing when I move windows around..
  26. - How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on the purpose of labels/IDs.
  27. - How can I tell when ImGui wants my mouse/keyboard inputs and when I can pass them to my application?
  28. - How can I load a different font than the default?
  29. - How can I easily use icons in my application?
  30. - How can I load multiple fonts?
  31. - How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic?
  32. - How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
  33. - ISSUES & TODO-LIST
  34. - CODE
  35.  
  36.  
  37. MISSION STATEMENT
  38. =================
  39.  
  40. - easy to use to create code-driven and data-driven tools
  41. - easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools
  42. - easy to hack and improve
  43. - minimize screen real-estate usage
  44. - minimize setup and maintenance
  45. - minimize state storage on user side
  46. - portable, minimize dependencies, run on target (consoles, phones, etc.)
  47. - efficient runtime (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)
  48. - read about immediate-mode gui principles @ http://mollyrocket.com/861, http://mollyrocket.com/forums/index.html
  49.  
  50. Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes:
  51. - doesn't look fancy, doesn't animate
  52. - limited layout features, intricate layouts are typically crafted in code
  53. - occasionally uses statically sized buffers for string manipulations - won't crash, but some very long pieces of text may be clipped. functions like ImGui::TextUnformatted() don't have such restriction.
  54.  
  55.  
  56. END-USER GUIDE
  57. ==============
  58.  
  59. - double-click title bar to collapse window
  60. - click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin()
  61. - click and drag on lower right corner to resize window
  62. - click and drag on any empty space to move window
  63. - double-click/double-tap on lower right corner grip to auto-fit to content
  64. - TAB/SHIFT+TAB to cycle through keyboard editable fields
  65. - use mouse wheel to scroll
  66. - use CTRL+mouse wheel to zoom window contents (if IO.FontAllowScaling is true)
  67. - CTRL+Click on a slider or drag box to input value as text
  68. - text editor:
  69. - Hold SHIFT or use mouse to select text.
  70. - CTRL+Left/Right to word jump
  71. - CTRL+Shift+Left/Right to select words
  72. - CTRL+A our Double-Click to select all
  73. - CTRL+X,CTRL+C,CTRL+V to use OS clipboard
  74. - CTRL+Z,CTRL+Y to undo/redo
  75. - ESCAPE to revert text to its original value
  76. - You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!)
  77.  
  78.  
  79. PROGRAMMER GUIDE
  80. ================
  81.  
  82. - read the FAQ below this section!
  83. - 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.
  84. - call and read ImGui::ShowTestWindow() for demo code demonstrating most features.
  85. - see examples/ folder for standalone sample applications. Prefer reading examples/opengl2_example/ first as it is the simplest.
  86. you may be able to grab and copy a ready made imgui_impl_*** file from the examples/.
  87. - customization: PushStyleColor()/PushStyleVar() or the style editor to tweak the look of the interface (e.g. if you want a more compact UI or a different color scheme).
  88.  
  89. - getting started:
  90. - init: call ImGui::GetIO() to retrieve the ImGuiIO structure and fill the fields marked 'Settings'.
  91. - init: call io.Fonts->GetTexDataAsRGBA32(...) and load the font texture pixels into graphics memory.
  92. - every frame:
  93. 1/ in your mainloop or right after you got your keyboard/mouse info, call ImGui::GetIO() and fill the fields marked 'Input'
  94. 2/ call ImGui::NewFrame() as early as you can!
  95. 3/ use any ImGui function you want between NewFrame() and Render()
  96. 4/ call ImGui::Render() as late as you can to end the frame and finalize render data. it will call your RenderDrawListFn handler that you set in the IO structure.
  97. (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.)
  98. - all rendering information are stored into command-lists until ImGui::Render() is called.
  99. - ImGui never touches or know about your GPU state. the only function that knows about GPU is the RenderDrawListFn handler that you provide.
  100. - 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.
  101. - refer to the examples applications in the examples/ folder for instruction on how to setup your code.
  102. - a typical application skeleton may be:
  103.  
  104. // Application init
  105. ImGuiIO& io = ImGui::GetIO();
  106. io.DisplaySize.x = 1920.0f;
  107. io.DisplaySize.y = 1280.0f;
  108. io.IniFilename = "imgui.ini";
  109. io.RenderDrawListsFn = my_render_function; // Setup a render function, or set to NULL and call GetDrawData() after Render() to access the render data.
  110. // TODO: Fill others settings of the io structure
  111.  
  112. // Load texture atlas
  113. // There is a default font so you don't need to care about choosing a font yet
  114. unsigned char* pixels;
  115. int width, height;
  116. io.Fonts->GetTexDataAsRGBA32(pixels, &width, &height);
  117. // TODO: At this points you've got a texture pointed to by 'pixels' and you need to upload that your your graphic system
  118. // TODO: Store your texture pointer/identifier (whatever your engine uses) in 'io.Fonts->TexID'
  119.  
  120. // Application main loop
  121. while (true)
  122. {
  123. // 1) get low-level inputs (e.g. on Win32, GetKeyboardState(), or poll your events, etc.)
  124. // TODO: fill all fields of IO structure and call NewFrame
  125. ImGuiIO& io = ImGui::GetIO();
  126. io.DeltaTime = 1.0f/60.0f;
  127. io.MousePos = mouse_pos;
  128. io.MouseDown[0] = mouse_button_0;
  129. io.MouseDown[1] = mouse_button_1;
  130. io.KeysDown[i] = ...
  131.  
  132. // 2) call NewFrame(), after this point you can use ImGui::* functions anytime
  133. ImGui::NewFrame();
  134.  
  135. // 3) most of your application code here
  136. MyGameUpdate(); // may use any ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
  137. MyGameRender(); // may use any ImGui functions
  138.  
  139. // 4) render & swap video buffers
  140. ImGui::Render();
  141. SwapBuffers();
  142. }
  143.  
  144. - You can read back 'io.WantCaptureMouse', 'io.WantCaptureKeybord' etc. flags from the IO structure to tell how ImGui intends to use your
  145. inputs and to know if you should share them or hide them from the rest of your application. Read the FAQ below for more information.
  146.  
  147.  
  148. API BREAKING CHANGES
  149. ====================
  150.  
  151. Occasionally introducing changes that are breaking the API. The breakage are generally minor and easy to fix.
  152. 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.
  153. Also read releases logs https://github.com/ocornut/imgui/releases for more details.
  154.  
  155. - 2017/05/01 (1.50) - Renamed ImDrawList::PathFill() to ImDrawList::PathFillConvex() for clarity.
  156. - 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().
  157. - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
  158. - 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.
  159. - 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.
  160. - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
  161. If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you.
  162. 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.
  163. 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.
  164. ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col)
  165. {
  166. float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a;
  167. 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);
  168. }
  169. 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.
  170. - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
  171. - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
  172. - 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).
  173. - 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.
  174. - 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).
  175. - 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)
  176. - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
  177. - 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.
  178. - 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.
  179. - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
  180. - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
  181. - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
  182. 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.
  183. 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!
  184. - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
  185. - 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.
  186. - 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
  187. - 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.
  188. you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
  189. - 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.
  190. this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
  191. - 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.
  192. - the signature of the io.RenderDrawListsFn handler has changed!
  193. ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
  194. became:
  195. ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
  196. argument 'cmd_lists' -> 'draw_data->CmdLists'
  197. argument 'cmd_lists_count' -> 'draw_data->CmdListsCount'
  198. ImDrawList 'commands' -> 'CmdBuffer'
  199. ImDrawList 'vtx_buffer' -> 'VtxBuffer'
  200. ImDrawList n/a -> 'IdxBuffer' (new)
  201. ImDrawCmd 'vtx_count' -> 'ElemCount'
  202. ImDrawCmd 'clip_rect' -> 'ClipRect'
  203. ImDrawCmd 'user_callback' -> 'UserCallback'
  204. ImDrawCmd 'texture_id' -> 'TextureId'
  205. - 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.
  206. - 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!
  207. - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
  208. - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
  209. - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
  210. - 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.
  211. - 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
  212. - 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!
  213. - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
  214. - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
  215. - 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.
  216. - 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.
  217. - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
  218. - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
  219. - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
  220. - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
  221. - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
  222. - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
  223. - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
  224. - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
  225. - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
  226. - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
  227. - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
  228. - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
  229. - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
  230. - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
  231. - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
  232. - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
  233. - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
  234. (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
  235. this sequence:
  236. const void* png_data;
  237. unsigned int png_size;
  238. ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size);
  239. // <Copy to GPU>
  240. became:
  241. unsigned char* pixels;
  242. int width, height;
  243. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  244. // <Copy to GPU>
  245. io.Fonts->TexID = (your_texture_identifier);
  246. you now have much more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs.
  247. it is now recommended that you sample the font texture with bilinear interpolation.
  248. (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID.
  249. (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
  250. (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
  251. - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
  252. - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
  253. - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
  254. - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
  255. - 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)
  256. - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
  257. - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
  258. - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
  259. - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
  260. - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
  261. - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
  262.  
  263.  
  264. FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
  265. ======================================
  266.  
  267. Q: How can I help?
  268. A: - If you are experienced enough with ImGui and with C/C++, look at the todo list and see how you want/can help!
  269. - Become a Patron/donate. Convince your company to become a Patron or provide serious funding for development time.
  270.  
  271. Q: How do I update to a newer version of ImGui?
  272. A: Overwrite the following files:
  273. imgui.cpp
  274. imgui.h
  275. imgui_demo.cpp
  276. imgui_draw.cpp
  277. imgui_internal.h
  278. stb_rect_pack.h
  279. stb_textedit.h
  280. stb_truetype.h
  281. Don't overwrite imconfig.h if you have made modification to your copy.
  282. Check the "API BREAKING CHANGES" sections for a list of occasional API breaking changes. If you have a problem with a function, search for its name
  283. in the code, there will likely be a comment about it. Please report any issue to the GitHub page!
  284.  
  285. Q: What is ImTextureID and how do I display an image?
  286. A: ImTextureID is a void* used to pass renderer-agnostic texture references around until it hits your render function.
  287. 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!
  288. 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.
  289. 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.
  290. Refer to examples applications, where each renderer (in a imgui_impl_xxxx.cpp file) is treating ImTextureID as a different thing.
  291. (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!)
  292. To display a custom image/texture within an ImGui window, you may use ImGui::Image(), ImGui::ImageButton(), ImDrawList::AddImage() functions.
  293. ImGui will generate the geometry and draw calls using the ImTextureID that you passed and which your renderer can use.
  294. It is your responsibility to get textures uploaded to your GPU.
  295.  
  296. Q: I integrated ImGui in my engine and the text or lines are blurry..
  297. A: In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f).
  298. Also make sure your orthographic projection matrix and io.DisplaySize matches your actual framebuffer dimension.
  299.  
  300. Q: I integrated ImGui in my engine and some elements are clipping or disappearing when I move windows around..
  301. 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).
  302.  
  303. Q: Can I have multiple widgets with the same label? Can I have widget without a label? (Yes)
  304. A: Yes. A primer on the use of labels/IDs in ImGui..
  305.  
  306. - Elements that are not clickable, such as Text() items don't need an ID.
  307.  
  308. - Interactive widgets require state to be carried over multiple frames (most typically ImGui often needs to remember what is the "active" widget).
  309. to do so they need a unique ID. unique ID are typically derived from a string label, an integer index or a pointer.
  310.  
  311. Button("OK"); // Label = "OK", ID = hash of "OK"
  312. Button("Cancel"); // Label = "Cancel", ID = hash of "Cancel"
  313.  
  314. - 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
  315. or in two different locations of a tree.
  316.  
  317. - If you have a same ID twice in the same location, you'll have a conflict:
  318.  
  319. Button("OK");
  320. Button("OK"); // ID collision! Both buttons will be treated as the same.
  321.  
  322. Fear not! this is easy to solve and there are many ways to solve it!
  323.  
  324. - When passing a label you can optionally specify extra unique ID information within string itself. This helps solving the simpler collision cases.
  325. use "##" to pass a complement to the ID that won't be visible to the end-user:
  326.  
  327. Button("Play"); // Label = "Play", ID = hash of "Play"
  328. Button("Play##foo1"); // Label = "Play", ID = hash of "Play##foo1" (different from above)
  329. Button("Play##foo2"); // Label = "Play", ID = hash of "Play##foo2" (different from above)
  330.  
  331. - If you want to completely hide the label, but still need an ID:
  332.  
  333. Checkbox("##On", &b); // Label = "", ID = hash of "##On" (no label!)
  334.  
  335. - Occasionally/rarely you might want change a label while preserving a constant ID. This allows you to animate labels.
  336. For example you may want to include varying information in a window title bar (and windows are uniquely identified by their ID.. obviously)
  337. Use "###" to pass a label that isn't part of ID:
  338.  
  339. Button("Hello###ID"; // Label = "Hello", ID = hash of "ID"
  340. Button("World###ID"; // Label = "World", ID = hash of "ID" (same as above)
  341.  
  342. sprintf(buf, "My game (%f FPS)###MyGame");
  343. Begin(buf); // Variable label, ID = hash of "MyGame"
  344.  
  345. - Use PushID() / PopID() to create scopes and avoid ID conflicts within the same Window.
  346. This is the most convenient way of distinguishing ID if you are iterating and creating many UI elements.
  347. 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!
  348.  
  349. for (int i = 0; i < 100; i++)
  350. {
  351. PushID(i);
  352. Button("Click"); // Label = "Click", ID = hash of integer + "label" (unique)
  353. PopID();
  354. }
  355.  
  356. for (int i = 0; i < 100; i++)
  357. {
  358. MyObject* obj = Objects[i];
  359. PushID(obj);
  360. Button("Click"); // Label = "Click", ID = hash of pointer + "label" (unique)
  361. PopID();
  362. }
  363.  
  364. for (int i = 0; i < 100; i++)
  365. {
  366. MyObject* obj = Objects[i];
  367. PushID(obj->Name);
  368. Button("Click"); // Label = "Click", ID = hash of string + "label" (unique)
  369. PopID();
  370. }
  371.  
  372. - More example showing that you can stack multiple prefixes into the ID stack:
  373.  
  374. Button("Click"); // Label = "Click", ID = hash of "Click"
  375. PushID("node");
  376. Button("Click"); // Label = "Click", ID = hash of "node" + "Click"
  377. PushID(my_ptr);
  378. Button("Click"); // Label = "Click", ID = hash of "node" + ptr + "Click"
  379. PopID();
  380. PopID();
  381.  
  382. - Tree nodes implicitly creates a scope for you by calling PushID().
  383.  
  384. Button("Click"); // Label = "Click", ID = hash of "Click"
  385. if (TreeNode("node"))
  386. {
  387. Button("Click"); // Label = "Click", ID = hash of "node" + "Click"
  388. TreePop();
  389. }
  390.  
  391. - When working with trees, ID are used to preserve the open/close state of each tree node.
  392. Depending on your use cases you may want to use strings, indices or pointers as ID.
  393. 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.
  394. 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!
  395.  
  396. Q: How can I tell when ImGui wants my mouse/keyboard inputs and when I can pass them to my application?
  397. A: You can read the 'io.WantCaptureXXX' flags in the ImGuiIO structure. Preferably read them after calling ImGui::NewFrame() to avoid those flags lagging by one frame, but either should be fine.
  398. When 'io.WantCaptureMouse' or 'io.WantCaptureKeyboard' flags are set you may want to discard/hide the inputs from the rest of your application.
  399. When 'io.WantInputsCharacters' is set to may want to notify your OS to popup an on-screen keyboard, if available.
  400. ImGui is tracking dragging and widget activity that may occur outside the boundary of a window, so 'io.WantCaptureMouse' is a more accurate and complete than testing for ImGui::IsMouseHoveringAnyWindow().
  401. (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'.
  402. 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.)
  403.  
  404. Q: How can I load a different font than the default? (default is an embedded version of ProggyClean.ttf, rendered at size 13)
  405. A: Use the font atlas to load the TTF file you want:
  406.  
  407. ImGuiIO& io = ImGui::GetIO();
  408. io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
  409. io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
  410.  
  411. Q: How can I easily use icons in my application?
  412. 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.
  413. Read 'How can I load multiple fonts?' and the file 'extra_fonts/README.txt' for instructions.
  414.  
  415. Q: How can I load multiple fonts?
  416. A: Use the font atlas to pack them into a single texture:
  417. (Read extra_fonts/README.txt and the code in ImFontAtlas for more details.)
  418.  
  419. ImGuiIO& io = ImGui::GetIO();
  420. ImFont* font0 = io.Fonts->AddFontDefault();
  421. ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
  422. ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels);
  423. io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
  424. // the first loaded font gets used by default
  425. // use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime
  426.  
  427. // Options
  428. ImFontConfig config;
  429. config.OversampleH = 3;
  430. config.OversampleV = 1;
  431. config.GlyphExtraSpacing.x = 1.0f;
  432. io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, &config);
  433.  
  434. // Combine multiple fonts into one (e.g. for icon fonts)
  435. ImWchar ranges[] = { 0xf000, 0xf3ff, 0 };
  436. ImFontConfig config;
  437. config.MergeMode = true;
  438. io.Fonts->AddFontDefault();
  439. io.Fonts->LoadFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges); // Merge icon font
  440. io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, NULL, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge japanese glyphs
  441.  
  442. Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
  443. A: When loading a font, pass custom Unicode ranges to specify the glyphs to load.
  444. All your strings needs to use UTF-8 encoding. 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.
  445. In C++11 you can encode a string literal in UTF-8 by using the u8"hello" syntax. Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8.
  446. You can also try to remap your local codepage characters to their Unicode codepoint using font->AddRemapChar(), but international users may have problems reading/editing your source code.
  447.  
  448. io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese()); // Load Japanese characters
  449. io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
  450. io.ImeWindowHandle = MY_HWND; // To input using Microsoft IME, give ImGui the hwnd of your application
  451.  
  452. As for text input, depends on you passing the right character code to io.AddInputCharacter(). The example applications do that.
  453.  
  454. Q: How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
  455. A: The easiest way is to create a dummy window. Call Begin() with NoTitleBar|NoResize|NoMove|NoScrollbar|NoSavedSettings|NoInputs flag, zero background alpha,
  456. then retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like.
  457.  
  458. - 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.
  459. - tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug"
  460. - 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)
  461. - tip: you can call Render() multiple times (e.g for VR renders).
  462. - tip: call and read the ShowTestWindow() code in imgui_demo.cpp for more example of how to use ImGui!
  463.  
  464.  
  465. ISSUES & TODO-LIST
  466. ==================
  467. Issue numbers (#) refer to github issues listed at https://github.com/ocornut/imgui/issues
  468. The list below consist mostly of ideas noted down before they are requested/discussed by users (at which point it usually moves to the github)
  469.  
  470. - doc: add a proper documentation+regression testing system (#435)
  471. - window: add a way for very transient windows (non-saved, temporary overlay over hundreds of objects) to "clean" up from the global window list. perhaps a lightweight explicit cleanup pass.
  472. - window: calling SetNextWindowSize() every frame with <= 0 doesn't do anything, may be useful to allow (particularly when used for a single axis) (#690)
  473. - window: auto-fit feedback loop when user relies on any dynamic layout (window width multiplier, column) appears weird to end-user. clarify.
  474. - window: allow resizing of child windows (possibly given min/max for each axis?)
  475. - window: background options for child windows, border option (disable rounding)
  476. - window: add a way to clear an existing window instead of appending (e.g. for tooltip override using a consistent api rather than the deferred tooltip)
  477. - window: resizing from any sides? + mouse cursor directives for app.
  478. !- window: begin with *p_open == false should return false.
  479. - window: get size/pos helpers given names (see discussion in #249)
  480. - window: a collapsed window can be stuck behind the main menu bar?
  481. - window: when window is small, prioritize resize button over close button.
  482. - window: detect extra End() call that pop the "Debug" window out and assert at call site instead of later.
  483. - window/tooltip: allow to set the width of a tooltip to allow TextWrapped() etc. while keeping the height automatic.
  484. - window: increase minimum size of a window with menus or fix the menu rendering so that it doesn't look odd.
  485. - draw-list: maintaining bounding box per command would allow to merge draw command when clipping isn't relied on (typical non-scrolling window or non-overflowing column would merge with previous command).
  486. !- scrolling: allow immediately effective change of scroll if we haven't appended items yet
  487. - splitter/separator: formalize the splitter idiom into an official api (we want to handle n-way split) (#319)
  488. - widgets: display mode: widget-label, label-widget (aligned on column or using fixed size), label-newline-tab-widget etc.
  489. - widgets: clean up widgets internal toward exposing everything.
  490. - widgets: add disabled and read-only modes (#211)
  491. - main: considering adding an Init() function? some constructs are awkward in the implementation because of the lack of them.
  492. !- main: make it so that a frame with no window registered won't refocus every window on subsequent frames (~bump LastFrameActive of all windows).
  493. - main: IsItemHovered() make it more consistent for various type of widgets, widgets with multiple components, etc. also effectively IsHovered() region sometimes differs from hot region, e.g tree nodes
  494. - main: IsItemHovered() info stored in a stack? so that 'if TreeNode() { Text; TreePop; } if IsHovered' return the hover state of the TreeNode?
  495. - input text: clean up the mess caused by converting UTF-8 <> wchar. the code is rather inefficient right now and super fragile.
  496. - input text: reorganize event handling, allow CharFilter to modify buffers, allow multiple events? (#541)
  497. - input text: expose CursorPos in char filter event (#816)
  498. - input text: flag to disable live update of the user buffer (also applies to float/int text input)
  499. - input text: resize behavior - field could stretch when being edited? hover tooltip shows more text?
  500. - input text: add ImGuiInputTextFlags_EnterToApply? (off #218)
  501. - input text: add discard flag (e.g. ImGuiInputTextFlags_DiscardActiveBuffer) or make it easier to clear active focus for text replacement during edition (#725)
  502. - input text multi-line: don't directly call AddText() which does an unnecessary vertex reserve for character count prior to clipping. and/or more line-based clipping to AddText(). and/or reorganize TextUnformatted/RenderText for more efficiency for large text (e.g TextUnformatted could clip and log separately, etc).
  503. - input text multi-line: way to dynamically grow the buffer without forcing the user to initially allocate for worse case (follow up on #200)
  504. - input text multi-line: line numbers? status bar? (follow up on #200)
  505. - input text multi-line: behave better when user changes input buffer while editing is active (even though it is illegal behavior). namely, the change of buffer can create a scrollbar glitch (#725)
  506. - input text: allow centering/positioning text so that ctrl+clicking Drag or Slider keeps the textual value at the same pixel position.
  507. - input number: optional range min/max for Input*() functions
  508. - input number: holding [-]/[+] buttons could increase the step speed non-linearly (or user-controlled)
  509. - input number: use mouse wheel to step up/down
  510. - input number: applying arithmetics ops (+,-,*,/) messes up with text edit undo stack.
  511. - button: provide a button that looks framed.
  512. - text: proper alignment options
  513. - image/image button: misalignment on padded/bordered button?
  514. - image/image button: parameters are confusing, image() has tint_col,border_col whereas imagebutton() has bg_col/tint_col. Even thou they are different parameters ordering could be more consistent. can we fix that?
  515. - layout: horizontal layout helper (#97)
  516. - layout: horizontal flow until no space left (#404)
  517. - layout: more generic alignment state (left/right/centered) for single items?
  518. - layout: clean up the InputFloatN/SliderFloatN/ColorEdit4 layout code. item width should include frame padding.
  519. - layout: BeginGroup() needs a border option.
  520. - columns: declare column set (each column: fixed size, %, fill, distribute default size among fills) (#513, #125)
  521. - columns: add a conditional parameter to SetColumnOffset() (#513, #125)
  522. - columns: separator function or parameter that works within the column (currently Separator() bypass all columns) (#125)
  523. - columns: columns header to act as button (~sort op) and allow resize/reorder (#513, #125)
  524. - columns: user specify columns size (#513, #125)
  525. - columns: flag to add horizontal separator above/below?
  526. - columns/layout: setup minimum line height (equivalent of automatically calling AlignFirstTextHeightToWidgets)
  527. - combo: sparse combo boxes (via function call?) / iterators
  528. - combo: contents should extends to fit label if combo widget is small
  529. - combo/listbox: keyboard control. need InputText-like non-active focus + key handling. considering keyboard for custom listbox (pr #203)
  530. - listbox: multiple selection
  531. - listbox: user may want to initial scroll to focus on the one selected value?
  532. - listbox: keyboard navigation.
  533. - listbox: scrolling should track modified selection.
  534. !- popups/menus: clarify usage of popups id, how MenuItem/Selectable closing parent popups affects the ID, etc. this is quite fishy needs improvement! (#331, #402)
  535. - popups: add variant using global identifier similar to Begin/End (#402)
  536. - popups: border options. richer api like BeginChild() perhaps? (#197)
  537. - tooltip: tooltip that doesn't fit in entire screen seems to lose their "last preferred button" and may teleport when moving mouse
  538. - menus: local shortcuts, global shortcuts (#456, #126)
  539. - menus: icons
  540. - menus: menubars: some sort of priority / effect of main menu-bar on desktop size?
  541. - menus: calling BeginMenu() twice with a same name doesn't seem to append nicely
  542. - statusbar: add a per-window status bar helper similar to what menubar does.
  543. - tabs (#261, #351)
  544. - separator: separator on the initial position of a window is not visible (cursorpos.y <= clippos.y)
  545. !- color: the color helpers/typing is a mess and needs sorting out.
  546. - color: add a better color picker (#346)
  547. - node/graph editor (#306)
  548. - pie menus patterns (#434)
  549. - drag'n drop, dragging helpers (carry dragging info, visualize drag source before clicking, drop target, etc.) (#143, #479)
  550. - plot: PlotLines() should use the polygon-stroke facilities (currently issues with averaging normals)
  551. - plot: make it easier for user to draw extra stuff into the graph (e.g: draw basis, highlight certain points, 2d plots, multiple plots)
  552. - plot: "smooth" automatic scale over time, user give an input 0.0(full user scale) 1.0(full derived from value)
  553. - plot: add a helper e.g. Plot(char* label, float value, float time_span=2.0f) that stores values and Plot them for you - probably another function name. and/or automatically allow to plot ANY displayed value (more reliance on stable ID)
  554. - slider: allow using the [-]/[+] buttons used by InputFloat()/InputInt()
  555. - slider: initial absolute click is imprecise. change to relative movement slider (same as scrollbar).
  556. - slider: add dragging-based widgets to edit values with mouse (on 2 axises), saving screen real-estate.
  557. - slider: tint background based on value (e.g. v_min -> v_max, or use 0.0f either side of the sign)
  558. - slider & drag: int data passing through a float
  559. - drag float: up/down axis
  560. - drag float: added leeway on edge (e.g. a few invisible steps past the clamp limits)
  561. - tree node / optimization: avoid formatting when clipped.
  562. - tree node: tree-node/header right-most side doesn't take account of horizontal scrolling.
  563. - tree node: add treenode/treepush int variants? not there because (void*) cast from int warns on some platforms/settings?
  564. - tree node: try to apply scrolling at time of TreePop() if node was just opened and end of node is past scrolling limits?
  565. - tree node / selectable render mismatch which is visible if you use them both next to each other (e.g. cf. property viewer)
  566. - tree node: tweak color scheme to distinguish headers from selected tree node (#581)
  567. - textwrapped: figure out better way to use TextWrapped() in an always auto-resize context (tooltip, etc.) (#249)
  568. - settings: write more decent code to allow saving/loading new fields
  569. - settings: api for per-tool simple persistent data (bool,int,float,columns sizes,etc.) in .ini file
  570. - style: add window shadows.
  571. - style/optimization: store rounded corners in texture to use 1 quad per corner (filled and wireframe) to lower the cost of rounding.
  572. - style: color-box not always square?
  573. - style: a concept of "compact style" that the end-user can easily rely on (e.g. PushStyleCompact()?) that maps to other settings? avoid implementing duplicate helpers such as SmallCheckbox(), etc.
  574. - style: try to make PushStyleVar() more robust to incorrect parameters (to be more friendly to edit & continues situation).
  575. - style: global scale setting.
  576. - style: WindowPadding needs to be EVEN needs the 0.5 multiplier probably have a subtle effect on clip rectangle
  577. - text: simple markup language for color change?
  578. - font: dynamic font atlas to avoid baking huge ranges into bitmap and make scaling easier.
  579. - font: small opt: for monospace font (like the defalt one) we can trim IndexXAdvance as long as trailing value is == FallbackXAdvance
  580. - font: add support for kerning, probably optional. perhaps default to (32..128)^2 matrix ~ 36KB then hash fallback.
  581. - font: add a simpler CalcTextSizeA() api? current one ok but not welcome if user needs to call it directly (without going through ImGui::CalcTextSize)
  582. - font: fix AddRemapChar() to work before font has been built.
  583. - log: LogButtons() options for specifying depth and/or hiding depth slider
  584. - log: have more control over the log scope (e.g. stop logging when leaving current tree node scope)
  585. - log: be able to log anything (e.g. right-click on a window/tree-node, shows context menu? log into tty/file/clipboard)
  586. - log: let user copy any window content to clipboard easily (CTRL+C on windows? while moving it? context menu?). code is commented because it fails with multiple Begin/End pairs.
  587. - filters: set a current filter that tree node can automatically query to hide themselves
  588. - filters: handle wildcards (with implicit leading/trailing *), regexps
  589. - shortcuts: add a shortcut api, e.g. parse "&Save" and/or "Save (CTRL+S)", pass in to widgets or provide simple ways to use (button=activate, input=focus)
  590. !- keyboard: tooltip & combo boxes are messing up / not honoring keyboard tabbing
  591. - keyboard: full keyboard navigation and focus. (#323)
  592. - focus: preserve ActiveId/focus stack state, e.g. when opening a menu and close it, previously selected InputText() focus gets restored (#622)
  593. - focus: SetKeyboardFocusHere() on with >= 0 offset could be done on same frame (else latch and modulate on beginning of next frame)
  594. - input: rework IO system to be able to pass actual ordered/timestamped events. (~#335, #71)
  595. - input: allow to decide and pass explicit double-clicks (e.g. for windows by the CS_DBLCLKS style).
  596. - input: support track pad style scrolling & slider edit.
  597. - misc: provide a way to compile out the entire implementation while providing a dummy API (e.g. #define IMGUI_DUMMY_IMPL)
  598. - misc: double-clicking on title bar to minimize isn't consistent, perhaps move to single-click on left-most collapse icon?
  599. - misc: provide HoveredTime and ActivatedTime to ease the creation of animations.
  600. - style editor: have a more global HSV setter (e.g. alter hue on all elements). consider replacing active/hovered by offset in HSV space? (#438)
  601. - style editor: color child window height expressed in multiple of line height.
  602. - remote: make a system like RemoteImGui first-class citizen/project (#75)
  603. - drawlist: move Font, FontSize, FontTexUvWhitePixel inside ImDrawList and make it self-contained (apart from drawing settings?)
  604. - drawlist: end-user probably can't call Clear() directly because we expect a texture to be pushed in the stack.
  605. - examples: directx9: save/restore device state more thoroughly.
  606. - examples: window minimize, maximize (#583)
  607. - optimization: add a flag to disable most of rendering, for the case where the user expect to skip it (#335)
  608. - optimization: use another hash function than crc32, e.g. FNV1a
  609. - optimization/render: merge command-lists with same clip-rect into one even if they aren't sequential? (as long as in-between clip rectangle don't overlap)?
  610. - optimization: turn some the various stack vectors into statically-sized arrays
  611. - optimization: better clipping for multi-component widgets
  612. */
  613.  
  614. #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
  615. #define _CRT_SECURE_NO_WARNINGS
  616. #endif
  617.  
  618. #include "imgui.h"
  619. #define IMGUI_DEFINE_MATH_OPERATORS
  620. #define IMGUI_DEFINE_PLACEMENT_NEW
  621. #include "imgui_internal.h"
  622.  
  623. #include <ctype.h> // toupper, isprint
  624. #include <stdlib.h> // NULL, malloc, free, qsort, atoi
  625. #include <stdio.h> // vsnprintf, sscanf, printf
  626. #include <limits.h> // INT_MIN, INT_MAX
  627. #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
  628. #include <stddef.h> // intptr_t
  629. #else
  630. #include <stdint.h> // intptr_t
  631. #endif
  632.  
  633. #ifdef _MSC_VER
  634. #pragma warning (disable: 4127) // condition expression is constant
  635. #pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff)
  636. #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
  637. #endif
  638.  
  639. // Clang warnings with -Weverything
  640. #ifdef __clang__
  641. #pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse.
  642. #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.
  643. #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.
  644. #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.
  645. #pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it.
  646. #pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness //
  647. #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.
  648. #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int' //
  649. #elif defined(__GNUC__)
  650. #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
  651. #pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
  652. #pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
  653. #pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
  654. #pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
  655. #pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'xxxx' to type 'xxxx' casts away qualifiers
  656. #endif
  657.  
  658. //-------------------------------------------------------------------------
  659. // Forward Declarations
  660. //-------------------------------------------------------------------------
  661.  
  662. static void LogRenderedText(const ImVec2& ref_pos, const char* text, const char* text_end = NULL);
  663.  
  664. static void PushMultiItemsWidths(int components, float w_full = 0.0f);
  665. static float GetDraggedColumnOffset(int column_index);
  666.  
  667. static bool IsKeyPressedMap(ImGuiKey key, bool repeat = true);
  668.  
  669. static ImFont* GetDefaultFont();
  670. static void SetCurrentFont(ImFont* font);
  671. static void SetCurrentWindow(ImGuiWindow* window);
  672. static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y);
  673. static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiSetCond cond);
  674. static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiSetCond cond);
  675. static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiSetCond cond);
  676. static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs);
  677. static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags);
  678. static inline bool IsWindowContentHoverable(ImGuiWindow* window);
  679. static void ClearSetNextWindowData();
  680. static void CheckStacksSize(ImGuiWindow* window, bool write);
  681. static void Scrollbar(ImGuiWindow* window, bool horizontal);
  682.  
  683. static void AddDrawListToRenderList(ImVector<ImDrawList*>& out_render_list, ImDrawList* draw_list);
  684. static void AddWindowToRenderList(ImVector<ImDrawList*>& out_render_list, ImGuiWindow* window);
  685. static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>& out_sorted_windows, ImGuiWindow* window);
  686.  
  687. static ImGuiIniData* FindWindowSettings(const char* name);
  688. static ImGuiIniData* AddWindowSettings(const char* name);
  689. static void LoadIniSettingsFromDisk(const char* ini_filename);
  690. static void SaveIniSettingsToDisk(const char* ini_filename);
  691. static void MarkIniSettingsDirty();
  692.  
  693. static void PushColumnClipRect(int column_index = -1);
  694. static ImRect GetVisibleRect();
  695.  
  696. static bool BeginPopupEx(const char* str_id, ImGuiWindowFlags extra_flags);
  697. static void CloseInactivePopups();
  698. static void ClosePopupToLevel(int remaining);
  699. static void ClosePopup(ImGuiID id);
  700. static bool IsPopupOpen(ImGuiID id);
  701. static ImGuiWindow* GetFrontMostModalRootWindow();
  702. static ImVec2 FindBestPopupWindowPos(const ImVec2& base_pos, const ImVec2& size, int* last_dir, const ImRect& rect_to_avoid);
  703.  
  704. static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data);
  705. static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end);
  706. 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);
  707.  
  708. static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size);
  709. static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size);
  710. static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2);
  711. static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format);
  712.  
  713. //-----------------------------------------------------------------------------
  714. // Platform dependent default implementations
  715. //-----------------------------------------------------------------------------
  716.  
  717. static const char* GetClipboardTextFn_DefaultImpl(void* user_data);
  718. static void SetClipboardTextFn_DefaultImpl(void* user_data, const char* text);
  719. static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y);
  720.  
  721. //-----------------------------------------------------------------------------
  722. // Context
  723. //-----------------------------------------------------------------------------
  724.  
  725. // Default font atlas storage .
  726. // New contexts always point by default to this font atlas. It can be changed by reassigning the GetIO().Fonts variable.
  727. static ImFontAtlas GImDefaultFontAtlas;
  728.  
  729. // Default context storage + current context pointer.
  730. // Implicitely used by all ImGui functions. Always assumed to be != NULL. Change to a different context by calling ImGui::SetCurrentContext()
  731. // 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:
  732. // - Having multiple instances of the ImGui code compiled inside different namespace (easiest/safest, if you have a finite number of contexts)
  733. // - 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
  734. #ifndef GImGui
  735. static ImGuiContext GImDefaultContext;
  736. ImGuiContext* GImGui = &GImDefaultContext;
  737. #endif
  738.  
  739. //-----------------------------------------------------------------------------
  740. // User facing structures
  741. //-----------------------------------------------------------------------------
  742.  
  743. ImGuiStyle::ImGuiStyle()
  744. {
  745. Alpha = 1.0f; // Global alpha applies to everything in ImGui
  746. WindowPadding = ImVec2(8,8); // Padding within a window
  747. WindowMinSize = ImVec2(32,32); // Minimum window size
  748. WindowRounding = 9.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows
  749. WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
  750. ChildWindowRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
  751. FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
  752. FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
  753. ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
  754. ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
  755. 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!
  756. IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
  757. ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns
  758. ScrollbarSize = 16.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
  759. ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
  760. GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar
  761. GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
  762. ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
  763. DisplayWindowPadding = ImVec2(22,22); // Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows.
  764. 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.
  765. AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU.
  766. AntiAliasedShapes = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
  767. CurveTessellationTol = 1.25f; // Tessellation tolerance. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
  768.  
  769. Colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);
  770. Colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f);
  771. Colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.70f);
  772. Colors[ImGuiCol_ChildWindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
  773. Colors[ImGuiCol_PopupBg] = ImVec4(0.05f, 0.05f, 0.10f, 0.90f);
  774. Colors[ImGuiCol_Border] = ImVec4(0.70f, 0.70f, 0.70f, 0.65f);
  775. Colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
  776. Colors[ImGuiCol_FrameBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.30f); // Background of checkbox, radio button, plot, slider, text input
  777. Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.90f, 0.80f, 0.80f, 0.40f);
  778. Colors[ImGuiCol_FrameBgActive] = ImVec4(0.90f, 0.65f, 0.65f, 0.45f);
  779. Colors[ImGuiCol_TitleBg] = ImVec4(0.27f, 0.27f, 0.54f, 0.83f);
  780. Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.40f, 0.80f, 0.20f);
  781. Colors[ImGuiCol_TitleBgActive] = ImVec4(0.32f, 0.32f, 0.63f, 0.87f);
  782. Colors[ImGuiCol_MenuBarBg] = ImVec4(0.40f, 0.40f, 0.55f, 0.80f);
  783. Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.20f, 0.25f, 0.30f, 0.60f);
  784. Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.40f, 0.40f, 0.80f, 0.30f);
  785. Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.40f, 0.40f, 0.80f, 0.40f);
  786. Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 0.40f);
  787. Colors[ImGuiCol_ComboBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.99f);
  788. Colors[ImGuiCol_CheckMark] = ImVec4(0.90f, 0.90f, 0.90f, 0.50f);
  789. Colors[ImGuiCol_SliderGrab] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f);
  790. Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f);
  791. Colors[ImGuiCol_Button] = ImVec4(0.67f, 0.40f, 0.40f, 0.60f);
  792. Colors[ImGuiCol_ButtonHovered] = ImVec4(0.67f, 0.40f, 0.40f, 1.00f);
  793. Colors[ImGuiCol_ButtonActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f);
  794. Colors[ImGuiCol_Header] = ImVec4(0.40f, 0.40f, 0.90f, 0.45f);
  795. Colors[ImGuiCol_HeaderHovered] = ImVec4(0.45f, 0.45f, 0.90f, 0.80f);
  796. Colors[ImGuiCol_HeaderActive] = ImVec4(0.53f, 0.53f, 0.87f, 0.80f);
  797. Colors[ImGuiCol_Column] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);
  798. Colors[ImGuiCol_ColumnHovered] = ImVec4(0.70f, 0.60f, 0.60f, 1.00f);
  799. Colors[ImGuiCol_ColumnActive] = ImVec4(0.90f, 0.70f, 0.70f, 1.00f);
  800. Colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f);
  801. Colors[ImGuiCol_ResizeGripHovered] = ImVec4(1.00f, 1.00f, 1.00f, 0.60f);
  802. Colors[ImGuiCol_ResizeGripActive] = ImVec4(1.00f, 1.00f, 1.00f, 0.90f);
  803. Colors[ImGuiCol_CloseButton] = ImVec4(0.50f, 0.50f, 0.90f, 0.50f);
  804. Colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.70f, 0.70f, 0.90f, 0.60f);
  805. Colors[ImGuiCol_CloseButtonActive] = ImVec4(0.70f, 0.70f, 0.70f, 1.00f);
  806. Colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
  807. Colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
  808. Colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
  809. Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f);
  810. Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f);
  811. Colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f);
  812. }
  813.  
  814. ImGuiIO::ImGuiIO()
  815. {
  816. // Most fields are initialized with zero
  817. memset(this, 0, sizeof(*this));
  818.  
  819. DisplaySize = ImVec2(-1.0f, -1.0f);
  820. DeltaTime = 1.0f/60.0f;
  821. IniSavingRate = 5.0f;
  822. IniFilename = "imgui.ini";
  823. LogFilename = "imgui_log.txt";
  824. Fonts = &GImDefaultFontAtlas;
  825. FontGlobalScale = 1.0f;
  826. FontDefault = NULL;
  827. DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
  828. MousePos = ImVec2(-1,-1);
  829. MousePosPrev = ImVec2(-1,-1);
  830. MouseDoubleClickTime = 0.30f;
  831. MouseDoubleClickMaxDist = 6.0f;
  832. MouseDragThreshold = 6.0f;
  833. for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++)
  834. MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
  835. for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++)
  836. KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f;
  837. for (int i = 0; i < ImGuiKey_COUNT; i++)
  838. KeyMap[i] = -1;
  839. KeyRepeatDelay = 0.250f;
  840. KeyRepeatRate = 0.050f;
  841. UserData = NULL;
  842.  
  843. // User functions
  844. RenderDrawListsFn = NULL;
  845. MemAllocFn = malloc;
  846. MemFreeFn = free;
  847. GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
  848. SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
  849. ClipboardUserData = NULL;
  850. ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl;
  851.  
  852. // Set OS X style defaults based on __APPLE__ compile time flag
  853. #ifdef __APPLE__
  854. OSXBehaviors = true;
  855. #endif
  856. }
  857.  
  858. // Pass in translated ASCII characters for text input.
  859. // - with glfw you can get those from the callback set in glfwSetCharCallback()
  860. // - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
  861. void ImGuiIO::AddInputCharacter(ImWchar c)
  862. {
  863. const int n = ImStrlenW(InputCharacters);
  864. if (n + 1 < IM_ARRAYSIZE(InputCharacters))
  865. {
  866. InputCharacters[n] = c;
  867. InputCharacters[n+1] = '\0';
  868. }
  869. }
  870.  
  871. void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
  872. {
  873. // We can't pass more wchars than ImGuiIO::InputCharacters[] can hold so don't convert more
  874. const int wchars_buf_len = sizeof(ImGuiIO::InputCharacters) / sizeof(ImWchar);
  875. ImWchar wchars[wchars_buf_len];
  876. ImTextStrFromUtf8(wchars, wchars_buf_len, utf8_chars, NULL);
  877. for (int i = 0; i < wchars_buf_len && wchars[i] != 0; i++)
  878. AddInputCharacter(wchars[i]);
  879. }
  880.  
  881. //-----------------------------------------------------------------------------
  882. // HELPERS
  883. //-----------------------------------------------------------------------------
  884.  
  885. #define IM_F32_TO_INT8_UNBOUND(_VAL) ((int)((_VAL) * 255.0f + ((_VAL)>=0 ? 0.5f : -0.5f))) // Unsaturated, for display purpose
  886. #define IM_F32_TO_INT8_SAT(_VAL) ((int)(ImSaturate(_VAL) * 255.0f + 0.5f)) // Saturated, always output 0..255
  887.  
  888. // Play it nice with Windows users. Notepad in 2015 still doesn't display text data with Unix-style \n.
  889. #ifdef _WIN32
  890. #define IM_NEWLINE "\r\n"
  891. #else
  892. #define IM_NEWLINE "\n"
  893. #endif
  894.  
  895. bool ImIsPointInTriangle(const ImVec2& p, const ImVec2& a, const ImVec2& b, const ImVec2& c)
  896. {
  897. bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
  898. bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
  899. bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
  900. return ((b1 == b2) && (b2 == b3));
  901. }
  902.  
  903. int ImStricmp(const char* str1, const char* str2)
  904. {
  905. int d;
  906. while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; }
  907. return d;
  908. }
  909.  
  910. int ImStrnicmp(const char* str1, const char* str2, int count)
  911. {
  912. int d = 0;
  913. while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
  914. return d;
  915. }
  916.  
  917. void ImStrncpy(char* dst, const char* src, int count)
  918. {
  919. if (count < 1) return;
  920. strncpy(dst, src, (size_t)count);
  921. dst[count-1] = 0;
  922. }
  923.  
  924. char* ImStrdup(const char *str)
  925. {
  926. size_t len = strlen(str) + 1;
  927. void* buff = ImGui::MemAlloc(len);
  928. return (char*)memcpy(buff, (const void*)str, len);
  929. }
  930.  
  931. int ImStrlenW(const ImWchar* str)
  932. {
  933. int n = 0;
  934. while (*str++) n++;
  935. return n;
  936. }
  937.  
  938. const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
  939. {
  940. while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
  941. buf_mid_line--;
  942. return buf_mid_line;
  943. }
  944.  
  945. const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
  946. {
  947. if (!needle_end)
  948. needle_end = needle + strlen(needle);
  949.  
  950. const char un0 = (char)toupper(*needle);
  951. while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
  952. {
  953. if (toupper(*haystack) == un0)
  954. {
  955. const char* b = needle + 1;
  956. for (const char* a = haystack + 1; b < needle_end; a++, b++)
  957. if (toupper(*a) != toupper(*b))
  958. break;
  959. if (b == needle_end)
  960. return haystack;
  961. }
  962. haystack++;
  963. }
  964. return NULL;
  965. }
  966.  
  967.  
  968. // MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
  969. // 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.
  970. int ImFormatString(char* buf, int buf_size, const char* fmt, ...)
  971. {
  972. IM_ASSERT(buf_size > 0);
  973. va_list args;
  974. va_start(args, fmt);
  975. int w = vsnprintf(buf, buf_size, fmt, args);
  976. va_end(args);
  977. if (w == -1 || w >= buf_size)
  978. w = buf_size - 1;
  979. buf[w] = 0;
  980. return w;
  981. }
  982.  
  983. int ImFormatStringV(char* buf, int buf_size, const char* fmt, va_list args)
  984. {
  985. IM_ASSERT(buf_size > 0);
  986. int w = vsnprintf(buf, buf_size, fmt, args);
  987. if (w == -1 || w >= buf_size)
  988. w = buf_size - 1;
  989. buf[w] = 0;
  990. return w;
  991. }
  992.  
  993. // Pass data_size==0 for zero-terminated strings
  994. // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
  995. ImU32 ImHash(const void* data, int data_size, ImU32 seed)
  996. {
  997. static ImU32 crc32_lut[256] = { 0 };
  998. if (!crc32_lut[1])
  999. {
  1000. const ImU32 polynomial = 0xEDB88320;
  1001. for (ImU32 i = 0; i < 256; i++)
  1002. {
  1003. ImU32 crc = i;
  1004. for (ImU32 j = 0; j < 8; j++)
  1005. crc = (crc >> 1) ^ (ImU32(-int(crc & 1)) & polynomial);
  1006. crc32_lut[i] = crc;
  1007. }
  1008. }
  1009.  
  1010. seed = ~seed;
  1011. ImU32 crc = seed;
  1012. const unsigned char* current = (const unsigned char*)data;
  1013.  
  1014. if (data_size > 0)
  1015. {
  1016. // Known size
  1017. while (data_size--)
  1018. crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *current++];
  1019. }
  1020. else
  1021. {
  1022. // Zero-terminated string
  1023. while (unsigned char c = *current++)
  1024. {
  1025. // We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
  1026. // Because this syntax is rarely used we are optimizing for the common case.
  1027. // - If we reach ### in the string we discard the hash so far and reset to the seed.
  1028. // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller.
  1029. if (c == '#' && current[0] == '#' && current[1] == '#')
  1030. crc = seed;
  1031. crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
  1032. }
  1033. }
  1034. return ~crc;
  1035. }
  1036.  
  1037. //-----------------------------------------------------------------------------
  1038. // ImText* helpers
  1039. //-----------------------------------------------------------------------------
  1040.  
  1041. // Convert UTF-8 to 32-bits character, process single character input.
  1042. // Based on stb_from_utf8() from github.com/nothings/stb/
  1043. // We handle UTF-8 decoding error by skipping forward.
  1044. int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
  1045. {
  1046. unsigned int c = (unsigned int)-1;
  1047. const unsigned char* str = (const unsigned char*)in_text;
  1048. if (!(*str & 0x80))
  1049. {
  1050. c = (unsigned int)(*str++);
  1051. *out_char = c;
  1052. return 1;
  1053. }
  1054. if ((*str & 0xe0) == 0xc0)
  1055. {
  1056. *out_char = 0xFFFD; // will be invalid but not end of string
  1057. if (in_text_end && in_text_end - (const char*)str < 2) return 1;
  1058. if (*str < 0xc2) return 2;
  1059. c = (unsigned int)((*str++ & 0x1f) << 6);
  1060. if ((*str & 0xc0) != 0x80) return 2;
  1061. c += (*str++ & 0x3f);
  1062. *out_char = c;
  1063. return 2;
  1064. }
  1065. if ((*str & 0xf0) == 0xe0)
  1066. {
  1067. *out_char = 0xFFFD; // will be invalid but not end of string
  1068. if (in_text_end && in_text_end - (const char*)str < 3) return 1;
  1069. if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3;
  1070. if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below
  1071. c = (unsigned int)((*str++ & 0x0f) << 12);
  1072. if ((*str & 0xc0) != 0x80) return 3;
  1073. c += (unsigned int)((*str++ & 0x3f) << 6);
  1074. if ((*str & 0xc0) != 0x80) return 3;
  1075. c += (*str++ & 0x3f);
  1076. *out_char = c;
  1077. return 3;
  1078. }
  1079. if ((*str & 0xf8) == 0xf0)
  1080. {
  1081. *out_char = 0xFFFD; // will be invalid but not end of string
  1082. if (in_text_end && in_text_end - (const char*)str < 4) return 1;
  1083. if (*str > 0xf4) return 4;
  1084. if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4;
  1085. if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below
  1086. c = (unsigned int)((*str++ & 0x07) << 18);
  1087. if ((*str & 0xc0) != 0x80) return 4;
  1088. c += (unsigned int)((*str++ & 0x3f) << 12);
  1089. if ((*str & 0xc0) != 0x80) return 4;
  1090. c += (unsigned int)((*str++ & 0x3f) << 6);
  1091. if ((*str & 0xc0) != 0x80) return 4;
  1092. c += (*str++ & 0x3f);
  1093. // utf-8 encodings of values used in surrogate pairs are invalid
  1094. if ((c & 0xFFFFF800) == 0xD800) return 4;
  1095. *out_char = c;
  1096. return 4;
  1097. }
  1098. *out_char = 0;
  1099. return 0;
  1100. }
  1101.  
  1102. int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
  1103. {
  1104. ImWchar* buf_out = buf;
  1105. ImWchar* buf_end = buf + buf_size;
  1106. while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
  1107. {
  1108. unsigned int c;
  1109. in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
  1110. if (c == 0)
  1111. break;
  1112. if (c < 0x10000) // FIXME: Losing characters that don't fit in 2 bytes
  1113. *buf_out++ = (ImWchar)c;
  1114. }
  1115. *buf_out = 0;
  1116. if (in_text_remaining)
  1117. *in_text_remaining = in_text;
  1118. return (int)(buf_out - buf);
  1119. }
  1120.  
  1121. int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
  1122. {
  1123. int char_count = 0;
  1124. while ((!in_text_end || in_text < in_text_end) && *in_text)
  1125. {
  1126. unsigned int c;
  1127. in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
  1128. if (c == 0)
  1129. break;
  1130. if (c < 0x10000)
  1131. char_count++;
  1132. }
  1133. return char_count;
  1134. }
  1135.  
  1136. // Based on stb_to_utf8() from github.com/nothings/stb/
  1137. static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c)
  1138. {
  1139. if (c < 0x80)
  1140. {
  1141. buf[0] = (char)c;
  1142. return 1;
  1143. }
  1144. if (c < 0x800)
  1145. {
  1146. if (buf_size < 2) return 0;
  1147. buf[0] = (char)(0xc0 + (c >> 6));
  1148. buf[1] = (char)(0x80 + (c & 0x3f));
  1149. return 2;
  1150. }
  1151. if (c >= 0xdc00 && c < 0xe000)
  1152. {
  1153. return 0;
  1154. }
  1155. if (c >= 0xd800 && c < 0xdc00)
  1156. {
  1157. if (buf_size < 4) return 0;
  1158. buf[0] = (char)(0xf0 + (c >> 18));
  1159. buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
  1160. buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
  1161. buf[3] = (char)(0x80 + ((c ) & 0x3f));
  1162. return 4;
  1163. }
  1164. //else if (c < 0x10000)
  1165. {
  1166. if (buf_size < 3) return 0;
  1167. buf[0] = (char)(0xe0 + (c >> 12));
  1168. buf[1] = (char)(0x80 + ((c>> 6) & 0x3f));
  1169. buf[2] = (char)(0x80 + ((c ) & 0x3f));
  1170. return 3;
  1171. }
  1172. }
  1173.  
  1174. static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
  1175. {
  1176. if (c < 0x80) return 1;
  1177. if (c < 0x800) return 2;
  1178. if (c >= 0xdc00 && c < 0xe000) return 0;
  1179. if (c >= 0xd800 && c < 0xdc00) return 4;
  1180. return 3;
  1181. }
  1182.  
  1183. int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
  1184. {
  1185. char* buf_out = buf;
  1186. const char* buf_end = buf + buf_size;
  1187. while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
  1188. {
  1189. unsigned int c = (unsigned int)(*in_text++);
  1190. if (c < 0x80)
  1191. *buf_out++ = (char)c;
  1192. else
  1193. buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end-buf_out-1), c);
  1194. }
  1195. *buf_out = 0;
  1196. return (int)(buf_out - buf);
  1197. }
  1198.  
  1199. int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
  1200. {
  1201. int bytes_count = 0;
  1202. while ((!in_text_end || in_text < in_text_end) && *in_text)
  1203. {
  1204. unsigned int c = (unsigned int)(*in_text++);
  1205. if (c < 0x80)
  1206. bytes_count++;
  1207. else
  1208. bytes_count += ImTextCountUtf8BytesFromChar(c);
  1209. }
  1210. return bytes_count;
  1211. }
  1212.  
  1213. ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
  1214. {
  1215. float s = 1.0f/255.0f;
  1216. return ImVec4(
  1217. ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
  1218. ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
  1219. ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
  1220. ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
  1221. }
  1222.  
  1223. ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
  1224. {
  1225. ImU32 out;
  1226. out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
  1227. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
  1228. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
  1229. out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
  1230. return out;
  1231. }
  1232.  
  1233. ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
  1234. {
  1235. ImVec4 c = GImGui->Style.Colors[idx];
  1236. c.w *= GImGui->Style.Alpha * alpha_mul;
  1237. return ColorConvertFloat4ToU32(c);
  1238. }
  1239.  
  1240. ImU32 ImGui::GetColorU32(const ImVec4& col)
  1241. {
  1242. ImVec4 c = col;
  1243. c.w *= GImGui->Style.Alpha;
  1244. return ColorConvertFloat4ToU32(c);
  1245. }
  1246.  
  1247. // Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
  1248. // Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
  1249. void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
  1250. {
  1251. float K = 0.f;
  1252. if (g < b)
  1253. {
  1254. const float tmp = g; g = b; b = tmp;
  1255. K = -1.f;
  1256. }
  1257. if (r < g)
  1258. {
  1259. const float tmp = r; r = g; g = tmp;
  1260. K = -2.f / 6.f - K;
  1261. }
  1262.  
  1263. const float chroma = r - (g < b ? g : b);
  1264. out_h = fabsf(K + (g - b) / (6.f * chroma + 1e-20f));
  1265. out_s = chroma / (r + 1e-20f);
  1266. out_v = r;
  1267. }
  1268.  
  1269. // Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
  1270. // also http://en.wikipedia.org/wiki/HSL_and_HSV
  1271. void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
  1272. {
  1273. if (s == 0.0f)
  1274. {
  1275. // gray
  1276. out_r = out_g = out_b = v;
  1277. return;
  1278. }
  1279.  
  1280. h = fmodf(h, 1.0f) / (60.0f/360.0f);
  1281. int i = (int)h;
  1282. float f = h - (float)i;
  1283. float p = v * (1.0f - s);
  1284. float q = v * (1.0f - s * f);
  1285. float t = v * (1.0f - s * (1.0f - f));
  1286.  
  1287. switch (i)
  1288. {
  1289. case 0: out_r = v; out_g = t; out_b = p; break;
  1290. case 1: out_r = q; out_g = v; out_b = p; break;
  1291. case 2: out_r = p; out_g = v; out_b = t; break;
  1292. case 3: out_r = p; out_g = q; out_b = v; break;
  1293. case 4: out_r = t; out_g = p; out_b = v; break;
  1294. case 5: default: out_r = v; out_g = p; out_b = q; break;
  1295. }
  1296. }
  1297.  
  1298. FILE* ImFileOpen(const char* filename, const char* mode)
  1299. {
  1300. #if defined(_WIN32) && !defined(__CYGWIN__)
  1301. // 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)
  1302. const int filename_wsize = ImTextCountCharsFromUtf8(filename, NULL) + 1;
  1303. const int mode_wsize = ImTextCountCharsFromUtf8(mode, NULL) + 1;
  1304. ImVector<ImWchar> buf;
  1305. buf.resize(filename_wsize + mode_wsize);
  1306. ImTextStrFromUtf8(&buf[0], filename_wsize, filename, NULL);
  1307. ImTextStrFromUtf8(&buf[filename_wsize], mode_wsize, mode, NULL);
  1308. return _wfopen((wchar_t*)&buf[0], (wchar_t*)&buf[filename_wsize]);
  1309. #else
  1310. return fopen(filename, mode);
  1311. #endif
  1312. }
  1313.  
  1314. // Load file content into memory
  1315. // Memory allocated with ImGui::MemAlloc(), must be freed by user using ImGui::MemFree()
  1316. void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, int* out_file_size, int padding_bytes)
  1317. {
  1318. IM_ASSERT(filename && file_open_mode);
  1319. if (out_file_size)
  1320. *out_file_size = 0;
  1321.  
  1322. FILE* f;
  1323. if ((f = ImFileOpen(filename, file_open_mode)) == NULL)
  1324. return NULL;
  1325.  
  1326. long file_size_signed;
  1327. if (fseek(f, 0, SEEK_END) || (file_size_signed = ftell(f)) == -1 || fseek(f, 0, SEEK_SET))
  1328. {
  1329. fclose(f);
  1330. return NULL;
  1331. }
  1332.  
  1333. int file_size = (int)file_size_signed;
  1334. void* file_data = ImGui::MemAlloc(file_size + padding_bytes);
  1335. if (file_data == NULL)
  1336. {
  1337. fclose(f);
  1338. return NULL;
  1339. }
  1340. if (fread(file_data, 1, (size_t)file_size, f) != (size_t)file_size)
  1341. {
  1342. fclose(f);
  1343. ImGui::MemFree(file_data);
  1344. return NULL;
  1345. }
  1346. if (padding_bytes > 0)
  1347. memset((void *)(((char*)file_data) + file_size), 0, padding_bytes);
  1348.  
  1349. fclose(f);
  1350. if (out_file_size)
  1351. *out_file_size = file_size;
  1352.  
  1353. return file_data;
  1354. }
  1355.  
  1356. //-----------------------------------------------------------------------------
  1357. // ImGuiStorage
  1358. //-----------------------------------------------------------------------------
  1359.  
  1360. // Helper: Key->value storage
  1361. void ImGuiStorage::Clear()
  1362. {
  1363. Data.clear();
  1364. }
  1365.  
  1366. // std::lower_bound but without the bullshit
  1367. static ImVector<ImGuiStorage::Pair>::iterator LowerBound(ImVector<ImGuiStorage::Pair>& data, ImGuiID key)
  1368. {
  1369. ImVector<ImGuiStorage::Pair>::iterator first = data.begin();
  1370. ImVector<ImGuiStorage::Pair>::iterator last = data.end();
  1371. int count = (int)(last - first);
  1372. while (count > 0)
  1373. {
  1374. int count2 = count / 2;
  1375. ImVector<ImGuiStorage::Pair>::iterator mid = first + count2;
  1376. if (mid->key < key)
  1377. {
  1378. first = ++mid;
  1379. count -= count2 + 1;
  1380. }
  1381. else
  1382. {
  1383. count = count2;
  1384. }
  1385. }
  1386. return first;
  1387. }
  1388.  
  1389. int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
  1390. {
  1391. ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
  1392. if (it == Data.end() || it->key != key)
  1393. return default_val;
  1394. return it->val_i;
  1395. }
  1396.  
  1397. bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
  1398. {
  1399. return GetInt(key, default_val ? 1 : 0) != 0;
  1400. }
  1401.  
  1402. float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
  1403. {
  1404. ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
  1405. if (it == Data.end() || it->key != key)
  1406. return default_val;
  1407. return it->val_f;
  1408. }
  1409.  
  1410. void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
  1411. {
  1412. ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
  1413. if (it == Data.end() || it->key != key)
  1414. return NULL;
  1415. return it->val_p;
  1416. }
  1417.  
  1418. // 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.
  1419. int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
  1420. {
  1421. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1422. if (it == Data.end() || it->key != key)
  1423. it = Data.insert(it, Pair(key, default_val));
  1424. return &it->val_i;
  1425. }
  1426.  
  1427. bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
  1428. {
  1429. return (bool*)GetIntRef(key, default_val ? 1 : 0);
  1430. }
  1431.  
  1432. float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
  1433. {
  1434. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1435. if (it == Data.end() || it->key != key)
  1436. it = Data.insert(it, Pair(key, default_val));
  1437. return &it->val_f;
  1438. }
  1439.  
  1440. void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
  1441. {
  1442. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1443. if (it == Data.end() || it->key != key)
  1444. it = Data.insert(it, Pair(key, default_val));
  1445. return &it->val_p;
  1446. }
  1447.  
  1448. // 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)
  1449. void ImGuiStorage::SetInt(ImGuiID key, int val)
  1450. {
  1451. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1452. if (it == Data.end() || it->key != key)
  1453. {
  1454. Data.insert(it, Pair(key, val));
  1455. return;
  1456. }
  1457. it->val_i = val;
  1458. }
  1459.  
  1460. void ImGuiStorage::SetBool(ImGuiID key, bool val)
  1461. {
  1462. SetInt(key, val ? 1 : 0);
  1463. }
  1464.  
  1465. void ImGuiStorage::SetFloat(ImGuiID key, float val)
  1466. {
  1467. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1468. if (it == Data.end() || it->key != key)
  1469. {
  1470. Data.insert(it, Pair(key, val));
  1471. return;
  1472. }
  1473. it->val_f = val;
  1474. }
  1475.  
  1476. void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
  1477. {
  1478. ImVector<Pair>::iterator it = LowerBound(Data, key);
  1479. if (it == Data.end() || it->key != key)
  1480. {
  1481. Data.insert(it, Pair(key, val));
  1482. return;
  1483. }
  1484. it->val_p = val;
  1485. }
  1486.  
  1487. void ImGuiStorage::SetAllInt(int v)
  1488. {
  1489. for (int i = 0; i < Data.Size; i++)
  1490. Data[i].val_i = v;
  1491. }
  1492.  
  1493. //-----------------------------------------------------------------------------
  1494. // ImGuiTextFilter
  1495. //-----------------------------------------------------------------------------
  1496.  
  1497. // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
  1498. ImGuiTextFilter::ImGuiTextFilter(const char* default_filter)
  1499. {
  1500. if (default_filter)
  1501. {
  1502. ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
  1503. Build();
  1504. }
  1505. else
  1506. {
  1507. InputBuf[0] = 0;
  1508. CountGrep = 0;
  1509. }
  1510. }
  1511.  
  1512. bool ImGuiTextFilter::Draw(const char* label, float width)
  1513. {
  1514. if (width != 0.0f)
  1515. ImGui::PushItemWidth(width);
  1516. bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
  1517. if (width != 0.0f)
  1518. ImGui::PopItemWidth();
  1519. if (value_changed)
  1520. Build();
  1521. return value_changed;
  1522. }
  1523.  
  1524. void ImGuiTextFilter::TextRange::split(char separator, ImVector<TextRange>& out)
  1525. {
  1526. out.resize(0);
  1527. const char* wb = b;
  1528. const char* we = wb;
  1529. while (we < e)
  1530. {
  1531. if (*we == separator)
  1532. {
  1533. out.push_back(TextRange(wb, we));
  1534. wb = we + 1;
  1535. }
  1536. we++;
  1537. }
  1538. if (wb != we)
  1539. out.push_back(TextRange(wb, we));
  1540. }
  1541.  
  1542. void ImGuiTextFilter::Build()
  1543. {
  1544. Filters.resize(0);
  1545. TextRange input_range(InputBuf, InputBuf+strlen(InputBuf));
  1546. input_range.split(',', Filters);
  1547.  
  1548. CountGrep = 0;
  1549. for (int i = 0; i != Filters.Size; i++)
  1550. {
  1551. Filters[i].trim_blanks();
  1552. if (Filters[i].empty())
  1553. continue;
  1554. if (Filters[i].front() != '-')
  1555. CountGrep += 1;
  1556. }
  1557. }
  1558.  
  1559. bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
  1560. {
  1561. if (Filters.empty())
  1562. return true;
  1563.  
  1564. if (text == NULL)
  1565. text = "";
  1566.  
  1567. for (int i = 0; i != Filters.Size; i++)
  1568. {
  1569. const TextRange& f = Filters[i];
  1570. if (f.empty())
  1571. continue;
  1572. if (f.front() == '-')
  1573. {
  1574. // Subtract
  1575. if (ImStristr(text, text_end, f.begin()+1, f.end()) != NULL)
  1576. return false;
  1577. }
  1578. else
  1579. {
  1580. // Grep
  1581. if (ImStristr(text, text_end, f.begin(), f.end()) != NULL)
  1582. return true;
  1583. }
  1584. }
  1585.  
  1586. // Implicit * grep
  1587. if (CountGrep == 0)
  1588. return true;
  1589.  
  1590. return false;
  1591. }
  1592.  
  1593. //-----------------------------------------------------------------------------
  1594. // ImGuiTextBuffer
  1595. //-----------------------------------------------------------------------------
  1596.  
  1597. // On some platform vsnprintf() takes va_list by reference and modifies it.
  1598. // va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
  1599. #ifndef va_copy
  1600. #define va_copy(dest, src) (dest = src)
  1601. #endif
  1602.  
  1603. // Helper: Text buffer for logging/accumulating text
  1604. void ImGuiTextBuffer::appendv(const char* fmt, va_list args)
  1605. {
  1606. va_list args_copy;
  1607. va_copy(args_copy, args);
  1608.  
  1609. int len = vsnprintf(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
  1610. if (len <= 0)
  1611. return;
  1612.  
  1613. const int write_off = Buf.Size;
  1614. const int needed_sz = write_off + len;
  1615. if (write_off + len >= Buf.Capacity)
  1616. {
  1617. int double_capacity = Buf.Capacity * 2;
  1618. Buf.reserve(needed_sz > double_capacity ? needed_sz : double_capacity);
  1619. }
  1620.  
  1621. Buf.resize(needed_sz);
  1622. ImFormatStringV(&Buf[write_off] - 1, len+1, fmt, args_copy);
  1623. }
  1624.  
  1625. void ImGuiTextBuffer::append(const char* fmt, ...)
  1626. {
  1627. va_list args;
  1628. va_start(args, fmt);
  1629. appendv(fmt, args);
  1630. va_end(args);
  1631. }
  1632.  
  1633. //-----------------------------------------------------------------------------
  1634. // ImGuiSimpleColumns
  1635. //-----------------------------------------------------------------------------
  1636.  
  1637. ImGuiSimpleColumns::ImGuiSimpleColumns()
  1638. {
  1639. Count = 0;
  1640. Spacing = Width = NextWidth = 0.0f;
  1641. memset(Pos, 0, sizeof(Pos));
  1642. memset(NextWidths, 0, sizeof(NextWidths));
  1643. }
  1644.  
  1645. void ImGuiSimpleColumns::Update(int count, float spacing, bool clear)
  1646. {
  1647. IM_ASSERT(Count <= IM_ARRAYSIZE(Pos));
  1648. Count = count;
  1649. Width = NextWidth = 0.0f;
  1650. Spacing = spacing;
  1651. if (clear) memset(NextWidths, 0, sizeof(NextWidths));
  1652. for (int i = 0; i < Count; i++)
  1653. {
  1654. if (i > 0 && NextWidths[i] > 0.0f)
  1655. Width += Spacing;
  1656. Pos[i] = (float)(int)Width;
  1657. Width += NextWidths[i];
  1658. NextWidths[i] = 0.0f;
  1659. }
  1660. }
  1661.  
  1662. float ImGuiSimpleColumns::DeclColumns(float w0, float w1, float w2) // not using va_arg because they promote float to double
  1663. {
  1664. NextWidth = 0.0f;
  1665. NextWidths[0] = ImMax(NextWidths[0], w0);
  1666. NextWidths[1] = ImMax(NextWidths[1], w1);
  1667. NextWidths[2] = ImMax(NextWidths[2], w2);
  1668. for (int i = 0; i < 3; i++)
  1669. NextWidth += NextWidths[i] + ((i > 0 && NextWidths[i] > 0.0f) ? Spacing : 0.0f);
  1670. return ImMax(Width, NextWidth);
  1671. }
  1672.  
  1673. float ImGuiSimpleColumns::CalcExtraSpace(float avail_w)
  1674. {
  1675. return ImMax(0.0f, avail_w - Width);
  1676. }
  1677.  
  1678. //-----------------------------------------------------------------------------
  1679. // ImGuiListClipper
  1680. //-----------------------------------------------------------------------------
  1681.  
  1682. static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height)
  1683. {
  1684. // Set cursor position and a few other things so that SetScrollHere() and Columns() can work when seeking cursor.
  1685. // 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?
  1686. ImGui::SetCursorPosY(pos_y);
  1687. ImGuiWindow* window = ImGui::GetCurrentWindow();
  1688. 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.
  1689. 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.
  1690. if (window->DC.ColumnsCount > 1)
  1691. window->DC.ColumnsCellMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
  1692. }
  1693.  
  1694. // Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1
  1695. // Use case B: Begin() called from constructor with items_height>0
  1696. // 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.
  1697. void ImGuiListClipper::Begin(int count, float items_height)
  1698. {
  1699. StartPosY = ImGui::GetCursorPosY();
  1700. ItemsHeight = items_height;
  1701. ItemsCount = count;
  1702. StepNo = 0;
  1703. DisplayEnd = DisplayStart = -1;
  1704. if (ItemsHeight > 0.0f)
  1705. {
  1706. ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display
  1707. if (DisplayStart > 0)
  1708. SetCursorPosYAndSetupDummyPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor
  1709. StepNo = 2;
  1710. }
  1711. }
  1712.  
  1713. void ImGuiListClipper::End()
  1714. {
  1715. if (ItemsCount < 0)
  1716. return;
  1717. // 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.
  1718. if (ItemsCount < INT_MAX)
  1719. SetCursorPosYAndSetupDummyPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor
  1720. ItemsCount = -1;
  1721. StepNo = 3;
  1722. }
  1723.  
  1724. bool ImGuiListClipper::Step()
  1725. {
  1726. if (ItemsCount == 0 || ImGui::GetCurrentWindowRead()->SkipItems)
  1727. {
  1728. ItemsCount = -1;
  1729. return false;
  1730. }
  1731. 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.
  1732. {
  1733. DisplayStart = 0;
  1734. DisplayEnd = 1;
  1735. StartPosY = ImGui::GetCursorPosY();
  1736. StepNo = 1;
  1737. return true;
  1738. }
  1739. 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.
  1740. {
  1741. if (ItemsCount == 1) { ItemsCount = -1; return false; }
  1742. float items_height = ImGui::GetCursorPosY() - StartPosY;
  1743. IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically
  1744. Begin(ItemsCount-1, items_height);
  1745. DisplayStart++;
  1746. DisplayEnd++;
  1747. StepNo = 3;
  1748. return true;
  1749. }
  1750. 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.
  1751. {
  1752. IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0);
  1753. StepNo = 3;
  1754. return true;
  1755. }
  1756. 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.
  1757. End();
  1758. return false;
  1759. }
  1760.  
  1761. //-----------------------------------------------------------------------------
  1762. // ImGuiWindow
  1763. //-----------------------------------------------------------------------------
  1764.  
  1765. ImGuiWindow::ImGuiWindow(const char* name)
  1766. {
  1767. Name = ImStrdup(name);
  1768. ID = ImHash(name, 0);
  1769. IDStack.push_back(ID);
  1770. MoveId = GetID("#MOVE");
  1771.  
  1772. Flags = 0;
  1773. IndexWithinParent = 0;
  1774. PosFloat = Pos = ImVec2(0.0f, 0.0f);
  1775. Size = SizeFull = ImVec2(0.0f, 0.0f);
  1776. SizeContents = SizeContentsExplicit = ImVec2(0.0f, 0.0f);
  1777. WindowPadding = ImVec2(0.0f, 0.0f);
  1778. Scroll = ImVec2(0.0f, 0.0f);
  1779. ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
  1780. ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
  1781. ScrollbarX = ScrollbarY = false;
  1782. ScrollbarSizes = ImVec2(0.0f, 0.0f);
  1783. BorderSize = 0.0f;
  1784. Active = WasActive = false;
  1785. Accessed = false;
  1786. Collapsed = false;
  1787. SkipItems = false;
  1788. BeginCount = 0;
  1789. PopupId = 0;
  1790. AutoFitFramesX = AutoFitFramesY = -1;
  1791. AutoFitOnlyGrows = false;
  1792. AutoPosLastDirection = -1;
  1793. HiddenFrames = 0;
  1794. SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiSetCond_Always | ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing;
  1795. SetWindowPosCenterWanted = false;
  1796.  
  1797. LastFrameActive = -1;
  1798. ItemWidthDefault = 0.0f;
  1799. FontWindowScale = 1.0f;
  1800.  
  1801. DrawList = (ImDrawList*)ImGui::MemAlloc(sizeof(ImDrawList));
  1802. IM_PLACEMENT_NEW(DrawList) ImDrawList();
  1803. DrawList->_OwnerName = Name;
  1804. RootWindow = NULL;
  1805. RootNonPopupWindow = NULL;
  1806. ParentWindow = NULL;
  1807.  
  1808. FocusIdxAllCounter = FocusIdxTabCounter = -1;
  1809. FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = INT_MAX;
  1810. FocusIdxAllRequestNext = FocusIdxTabRequestNext = INT_MAX;
  1811. }
  1812.  
  1813. ImGuiWindow::~ImGuiWindow()
  1814. {
  1815. DrawList->~ImDrawList();
  1816. ImGui::MemFree(DrawList);
  1817. DrawList = NULL;
  1818. ImGui::MemFree(Name);
  1819. Name = NULL;
  1820. }
  1821.  
  1822. ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
  1823. {
  1824. ImGuiID seed = IDStack.back();
  1825. ImGuiID id = ImHash(str, str_end ? (int)(str_end - str) : 0, seed);
  1826. ImGui::KeepAliveID(id);
  1827. return id;
  1828. }
  1829.  
  1830. ImGuiID ImGuiWindow::GetID(const void* ptr)
  1831. {
  1832. ImGuiID seed = IDStack.back();
  1833. ImGuiID id = ImHash(&ptr, sizeof(void*), seed);
  1834. ImGui::KeepAliveID(id);
  1835. return id;
  1836. }
  1837.  
  1838. ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end)
  1839. {
  1840. ImGuiID seed = IDStack.back();
  1841. return ImHash(str, str_end ? (int)(str_end - str) : 0, seed);
  1842. }
  1843.  
  1844. //-----------------------------------------------------------------------------
  1845. // Internal API exposed in imgui_internal.h
  1846. //-----------------------------------------------------------------------------
  1847.  
  1848. static void SetCurrentWindow(ImGuiWindow* window)
  1849. {
  1850. ImGuiContext& g = *GImGui;
  1851. g.CurrentWindow = window;
  1852. if (window)
  1853. g.FontSize = window->CalcFontSize();
  1854. }
  1855.  
  1856. ImGuiWindow* ImGui::GetParentWindow()
  1857. {
  1858. ImGuiContext& g = *GImGui;
  1859. IM_ASSERT(g.CurrentWindowStack.Size >= 2);
  1860. return g.CurrentWindowStack[(unsigned int)g.CurrentWindowStack.Size - 2];
  1861. }
  1862.  
  1863. void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
  1864. {
  1865. ImGuiContext& g = *GImGui;
  1866. g.ActiveId = id;
  1867. g.ActiveIdAllowOverlap = false;
  1868. g.ActiveIdIsJustActivated = true;
  1869. if (id)
  1870. g.ActiveIdIsAlive = true;
  1871. g.ActiveIdWindow = window;
  1872. }
  1873.  
  1874. void ImGui::ClearActiveID()
  1875. {
  1876. SetActiveID(0, NULL);
  1877. }
  1878.  
  1879. void ImGui::SetHoveredID(ImGuiID id)
  1880. {
  1881. ImGuiContext& g = *GImGui;
  1882. g.HoveredId = id;
  1883. g.HoveredIdAllowOverlap = false;
  1884. }
  1885.  
  1886. void ImGui::KeepAliveID(ImGuiID id)
  1887. {
  1888. ImGuiContext& g = *GImGui;
  1889. if (g.ActiveId == id)
  1890. g.ActiveIdIsAlive = true;
  1891. }
  1892.  
  1893. // Advance cursor given item size for layout.
  1894. void ImGui::ItemSize(const ImVec2& size, float text_offset_y)
  1895. {
  1896. ImGuiWindow* window = GetCurrentWindow();
  1897. if (window->SkipItems)
  1898. return;
  1899.  
  1900. // Always align ourselves on pixel boundaries
  1901. ImGuiContext& g = *GImGui;
  1902. const float line_height = ImMax(window->DC.CurrentLineHeight, size.y);
  1903. const float text_base_offset = ImMax(window->DC.CurrentLineTextBaseOffset, text_offset_y);
  1904. window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x + size.x, window->DC.CursorPos.y);
  1905. 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));
  1906. window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
  1907. window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
  1908.  
  1909. //window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // Debug
  1910.  
  1911. window->DC.PrevLineHeight = line_height;
  1912. window->DC.PrevLineTextBaseOffset = text_base_offset;
  1913. window->DC.CurrentLineHeight = window->DC.CurrentLineTextBaseOffset = 0.0f;
  1914. }
  1915.  
  1916. void ImGui::ItemSize(const ImRect& bb, float text_offset_y)
  1917. {
  1918. ItemSize(bb.GetSize(), text_offset_y);
  1919. }
  1920.  
  1921. // Declare item bounding box for clipping and interaction.
  1922. // Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
  1923. // declares their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd().
  1924. bool ImGui::ItemAdd(const ImRect& bb, const ImGuiID* id)
  1925. {
  1926. ImGuiWindow* window = GetCurrentWindow();
  1927. window->DC.LastItemId = id ? *id : 0;
  1928. window->DC.LastItemRect = bb;
  1929. window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = false;
  1930. if (IsClippedEx(bb, id, false))
  1931. return false;
  1932.  
  1933. // This is a sensible default, but widgets are free to override it after calling ItemAdd()
  1934. ImGuiContext& g = *GImGui;
  1935. if (IsMouseHoveringRect(bb.Min, bb.Max))
  1936. {
  1937. // Matching the behavior of IsHovered() but allow if ActiveId==window->MoveID (we clicked on the window background)
  1938. // So that clicking on items with no active id such as Text() still returns true with IsItemHovered()
  1939. window->DC.LastItemHoveredRect = true;
  1940. if (g.HoveredRootWindow == window->RootWindow)
  1941. if (g.ActiveId == 0 || (id && g.ActiveId == *id) || g.ActiveIdAllowOverlap || (g.ActiveId == window->MoveId))
  1942. if (IsWindowContentHoverable(window))
  1943. window->DC.LastItemHoveredAndUsable = true;
  1944. }
  1945.  
  1946. return true;
  1947. }
  1948.  
  1949. bool ImGui::IsClippedEx(const ImRect& bb, const ImGuiID* id, bool clip_even_when_logged)
  1950. {
  1951. ImGuiContext& g = *GImGui;
  1952. ImGuiWindow* window = GetCurrentWindowRead();
  1953.  
  1954. if (!bb.Overlaps(window->ClipRect))
  1955. if (!id || *id != GImGui->ActiveId)
  1956. if (clip_even_when_logged || !g.LogEnabled)
  1957. return true;
  1958. return false;
  1959. }
  1960.  
  1961. // NB: This is an internal helper. The user-facing IsItemHovered() is using data emitted from ItemAdd(), with a slightly different logic.
  1962. bool ImGui::IsHovered(const ImRect& bb, ImGuiID id, bool flatten_childs)
  1963. {
  1964. ImGuiContext& g = *GImGui;
  1965. if (g.HoveredId == 0 || g.HoveredId == id || g.HoveredIdAllowOverlap)
  1966. {
  1967. ImGuiWindow* window = GetCurrentWindowRead();
  1968. if (g.HoveredWindow == window || (flatten_childs && g.HoveredRootWindow == window->RootWindow))
  1969. if ((g.ActiveId == 0 || g.ActiveId == id || g.ActiveIdAllowOverlap) && IsMouseHoveringRect(bb.Min, bb.Max))
  1970. if (IsWindowContentHoverable(g.HoveredRootWindow))
  1971. return true;
  1972. }
  1973. return false;
  1974. }
  1975.  
  1976. bool ImGui::FocusableItemRegister(ImGuiWindow* window, bool is_active, bool tab_stop)
  1977. {
  1978. ImGuiContext& g = *GImGui;
  1979.  
  1980. const bool allow_keyboard_focus = window->DC.AllowKeyboardFocus;
  1981. window->FocusIdxAllCounter++;
  1982. if (allow_keyboard_focus)
  1983. window->FocusIdxTabCounter++;
  1984.  
  1985. // Process keyboard input at this point: TAB, Shift-TAB switch focus
  1986. // We can always TAB out of a widget that doesn't allow tabbing in.
  1987. if (tab_stop && window->FocusIdxAllRequestNext == INT_MAX && window->FocusIdxTabRequestNext == INT_MAX && is_active && IsKeyPressedMap(ImGuiKey_Tab))
  1988. {
  1989. // Modulo on index will be applied at the end of frame once we've got the total counter of items.
  1990. window->FocusIdxTabRequestNext = window->FocusIdxTabCounter + (g.IO.KeyShift ? (allow_keyboard_focus ? -1 : 0) : +1);
  1991. }
  1992.  
  1993. if (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent)
  1994. return true;
  1995.  
  1996. if (allow_keyboard_focus)
  1997. if (window->FocusIdxTabCounter == window->FocusIdxTabRequestCurrent)
  1998. return true;
  1999.  
  2000. return false;
  2001. }
  2002.  
  2003. void ImGui::FocusableItemUnregister(ImGuiWindow* window)
  2004. {
  2005. window->FocusIdxAllCounter--;
  2006. window->FocusIdxTabCounter--;
  2007. }
  2008.  
  2009. ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_x, float default_y)
  2010. {
  2011. ImGuiContext& g = *GImGui;
  2012. ImVec2 content_max;
  2013. if (size.x < 0.0f || size.y < 0.0f)
  2014. content_max = g.CurrentWindow->Pos + GetContentRegionMax();
  2015. if (size.x <= 0.0f)
  2016. size.x = (size.x == 0.0f) ? default_x : ImMax(content_max.x - g.CurrentWindow->DC.CursorPos.x, 4.0f) + size.x;
  2017. if (size.y <= 0.0f)
  2018. size.y = (size.y == 0.0f) ? default_y : ImMax(content_max.y - g.CurrentWindow->DC.CursorPos.y, 4.0f) + size.y;
  2019. return size;
  2020. }
  2021.  
  2022. float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
  2023. {
  2024. if (wrap_pos_x < 0.0f)
  2025. return 0.0f;
  2026.  
  2027. ImGuiWindow* window = GetCurrentWindowRead();
  2028. if (wrap_pos_x == 0.0f)
  2029. wrap_pos_x = GetContentRegionMax().x + window->Pos.x;
  2030. else if (wrap_pos_x > 0.0f)
  2031. wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
  2032.  
  2033. return ImMax(wrap_pos_x - pos.x, 1.0f);
  2034. }
  2035.  
  2036. //-----------------------------------------------------------------------------
  2037.  
  2038. void* ImGui::MemAlloc(size_t sz)
  2039. {
  2040. GImGui->IO.MetricsAllocs++;
  2041. return GImGui->IO.MemAllocFn(sz);
  2042. }
  2043.  
  2044. void ImGui::MemFree(void* ptr)
  2045. {
  2046. if (ptr) GImGui->IO.MetricsAllocs--;
  2047. return GImGui->IO.MemFreeFn(ptr);
  2048. }
  2049.  
  2050. const char* ImGui::GetClipboardText()
  2051. {
  2052. return GImGui->IO.GetClipboardTextFn ? GImGui->IO.GetClipboardTextFn(GImGui->IO.ClipboardUserData) : "";
  2053. }
  2054.  
  2055. void ImGui::SetClipboardText(const char* text)
  2056. {
  2057. if (GImGui->IO.SetClipboardTextFn)
  2058. GImGui->IO.SetClipboardTextFn(GImGui->IO.ClipboardUserData, text);
  2059. }
  2060.  
  2061. const char* ImGui::GetVersion()
  2062. {
  2063. return IMGUI_VERSION;
  2064. }
  2065.  
  2066. // Internal state access - if you want to share ImGui state between modules (e.g. DLL) or allocate it yourself
  2067. // 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
  2068. ImGuiContext* ImGui::GetCurrentContext()
  2069. {
  2070. return GImGui;
  2071. }
  2072.  
  2073. void ImGui::SetCurrentContext(ImGuiContext* ctx)
  2074. {
  2075. #ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
  2076. IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
  2077. #else
  2078. GImGui = ctx;
  2079. #endif
  2080. }
  2081.  
  2082. ImGuiContext* ImGui::CreateContext(void* (*malloc_fn)(size_t), void (*free_fn)(void*))
  2083. {
  2084. if (!malloc_fn) malloc_fn = malloc;
  2085. ImGuiContext* ctx = (ImGuiContext*)malloc_fn(sizeof(ImGuiContext));
  2086. IM_PLACEMENT_NEW(ctx) ImGuiContext();
  2087. ctx->IO.MemAllocFn = malloc_fn;
  2088. ctx->IO.MemFreeFn = free_fn ? free_fn : free;
  2089. return ctx;
  2090. }
  2091.  
  2092. void ImGui::DestroyContext(ImGuiContext* ctx)
  2093. {
  2094. void (*free_fn)(void*) = ctx->IO.MemFreeFn;
  2095. ctx->~ImGuiContext();
  2096. free_fn(ctx);
  2097. if (GImGui == ctx)
  2098. SetCurrentContext(NULL);
  2099. }
  2100.  
  2101. ImGuiIO& ImGui::GetIO()
  2102. {
  2103. return GImGui->IO;
  2104. }
  2105.  
  2106. ImGuiStyle& ImGui::GetStyle()
  2107. {
  2108. return GImGui->Style;
  2109. }
  2110.  
  2111. // Same value as passed to your RenderDrawListsFn() function. valid after Render() and until the next call to NewFrame()
  2112. ImDrawData* ImGui::GetDrawData()
  2113. {
  2114. return GImGui->RenderDrawData.Valid ? &GImGui->RenderDrawData : NULL;
  2115. }
  2116.  
  2117. float ImGui::GetTime()
  2118. {
  2119. return GImGui->Time;
  2120. }
  2121.  
  2122. int ImGui::GetFrameCount()
  2123. {
  2124. return GImGui->FrameCount;
  2125. }
  2126.  
  2127. void ImGui::NewFrame()
  2128. {
  2129. ImGuiContext& g = *GImGui;
  2130.  
  2131. // Check user data
  2132. IM_ASSERT(g.IO.DeltaTime >= 0.0f); // Need a positive DeltaTime (zero is tolerated but will cause some timing issues)
  2133. IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f);
  2134. IM_ASSERT(g.IO.Fonts->Fonts.Size > 0); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
  2135. IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
  2136. IM_ASSERT(g.Style.CurveTessellationTol > 0.0f); // Invalid style setting
  2137.  
  2138. if (!g.Initialized)
  2139. {
  2140. // Initialize on first frame
  2141. g.LogClipboard = (ImGuiTextBuffer*)ImGui::MemAlloc(sizeof(ImGuiTextBuffer));
  2142. IM_PLACEMENT_NEW(g.LogClipboard) ImGuiTextBuffer();
  2143.  
  2144. IM_ASSERT(g.Settings.empty());
  2145. LoadIniSettingsFromDisk(g.IO.IniFilename);
  2146. g.Initialized = true;
  2147. }
  2148.  
  2149. SetCurrentFont(GetDefaultFont());
  2150. IM_ASSERT(g.Font->IsLoaded());
  2151.  
  2152. g.Time += g.IO.DeltaTime;
  2153. g.FrameCount += 1;
  2154. g.Tooltip[0] = '\0';
  2155. g.OverlayDrawList.Clear();
  2156. g.OverlayDrawList.PushTextureID(g.IO.Fonts->TexID);
  2157. g.OverlayDrawList.PushClipRectFullScreen();
  2158.  
  2159. // Mark rendering data as invalid to prevent user who may have a handle on it to use it
  2160. g.RenderDrawData.Valid = false;
  2161. g.RenderDrawData.CmdLists = NULL;
  2162. g.RenderDrawData.CmdListsCount = g.RenderDrawData.TotalVtxCount = g.RenderDrawData.TotalIdxCount = 0;
  2163.  
  2164. // Update inputs state
  2165. if (g.IO.MousePos.x < 0 && g.IO.MousePos.y < 0)
  2166. g.IO.MousePos = ImVec2(-9999.0f, -9999.0f);
  2167. if ((g.IO.MousePos.x < 0 && g.IO.MousePos.y < 0) || (g.IO.MousePosPrev.x < 0 && g.IO.MousePosPrev.y < 0)) // if mouse just appeared or disappeared (negative coordinate) we cancel out movement in MouseDelta
  2168. g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
  2169. else
  2170. g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev;
  2171. g.IO.MousePosPrev = g.IO.MousePos;
  2172. for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
  2173. {
  2174. g.IO.MouseClicked[i] = g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] < 0.0f;
  2175. g.IO.MouseReleased[i] = !g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] >= 0.0f;
  2176. g.IO.MouseDownDurationPrev[i] = g.IO.MouseDownDuration[i];
  2177. 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;
  2178. g.IO.MouseDoubleClicked[i] = false;
  2179. if (g.IO.MouseClicked[i])
  2180. {
  2181. if (g.Time - g.IO.MouseClickedTime[i] < g.IO.MouseDoubleClickTime)
  2182. {
  2183. if (ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i]) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist)
  2184. g.IO.MouseDoubleClicked[i] = true;
  2185. g.IO.MouseClickedTime[i] = -FLT_MAX; // so the third click isn't turned into a double-click
  2186. }
  2187. else
  2188. {
  2189. g.IO.MouseClickedTime[i] = g.Time;
  2190. }
  2191. g.IO.MouseClickedPos[i] = g.IO.MousePos;
  2192. g.IO.MouseDragMaxDistanceSqr[i] = 0.0f;
  2193. }
  2194. else if (g.IO.MouseDown[i])
  2195. {
  2196. g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i]));
  2197. }
  2198. }
  2199. memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration));
  2200. for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++)
  2201. 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;
  2202.  
  2203. // Calculate frame-rate for the user, as a purely luxurious feature
  2204. g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
  2205. g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
  2206. g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
  2207. g.IO.Framerate = 1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame));
  2208.  
  2209. // Clear reference to active widget if the widget isn't alive anymore
  2210. g.HoveredIdPreviousFrame = g.HoveredId;
  2211. g.HoveredId = 0;
  2212. g.HoveredIdAllowOverlap = false;
  2213. if (!g.ActiveIdIsAlive && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0)
  2214. ClearActiveID();
  2215. g.ActiveIdPreviousFrame = g.ActiveId;
  2216. g.ActiveIdIsAlive = false;
  2217. g.ActiveIdIsJustActivated = false;
  2218.  
  2219. // Handle user moving window (at the beginning of the frame to avoid input lag or sheering). Only valid for root windows.
  2220. if (g.MovedWindowMoveId && g.MovedWindowMoveId == g.ActiveId)
  2221. {
  2222. KeepAliveID(g.MovedWindowMoveId);
  2223. IM_ASSERT(g.MovedWindow && g.MovedWindow->RootWindow);
  2224. IM_ASSERT(g.MovedWindow->RootWindow->MoveId == g.MovedWindowMoveId);
  2225. if (g.IO.MouseDown[0])
  2226. {
  2227. if (!(g.MovedWindow->Flags & ImGuiWindowFlags_NoMove))
  2228. {
  2229. g.MovedWindow->PosFloat += g.IO.MouseDelta;
  2230. if (!(g.MovedWindow->Flags & ImGuiWindowFlags_NoSavedSettings) && (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f))
  2231. MarkIniSettingsDirty();
  2232. }
  2233. FocusWindow(g.MovedWindow);
  2234. }
  2235. else
  2236. {
  2237. ClearActiveID();
  2238. g.MovedWindow = NULL;
  2239. g.MovedWindowMoveId = 0;
  2240. }
  2241. }
  2242. else
  2243. {
  2244. g.MovedWindow = NULL;
  2245. g.MovedWindowMoveId = 0;
  2246. }
  2247.  
  2248. // Delay saving settings so we don't spam disk too much
  2249. if (g.SettingsDirtyTimer > 0.0f)
  2250. {
  2251. g.SettingsDirtyTimer -= g.IO.DeltaTime;
  2252. if (g.SettingsDirtyTimer <= 0.0f)
  2253. SaveIniSettingsToDisk(g.IO.IniFilename);
  2254. }
  2255.  
  2256. // Find the window we are hovering. Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow
  2257. g.HoveredWindow = g.MovedWindow ? g.MovedWindow : FindHoveredWindow(g.IO.MousePos, false);
  2258. if (g.HoveredWindow && (g.HoveredWindow->Flags & ImGuiWindowFlags_ChildWindow))
  2259. g.HoveredRootWindow = g.HoveredWindow->RootWindow;
  2260. else
  2261. g.HoveredRootWindow = g.MovedWindow ? g.MovedWindow->RootWindow : FindHoveredWindow(g.IO.MousePos, true);
  2262.  
  2263. if (ImGuiWindow* modal_window = GetFrontMostModalRootWindow())
  2264. {
  2265. g.ModalWindowDarkeningRatio = ImMin(g.ModalWindowDarkeningRatio + g.IO.DeltaTime * 6.0f, 1.0f);
  2266. ImGuiWindow* window = g.HoveredRootWindow;
  2267. while (window && window != modal_window)
  2268. window = window->ParentWindow;
  2269. if (!window)
  2270. g.HoveredRootWindow = g.HoveredWindow = NULL;
  2271. }
  2272. else
  2273. {
  2274. g.ModalWindowDarkeningRatio = 0.0f;
  2275. }
  2276.  
  2277. // Are we using inputs? Tell user so they can capture/discard the inputs away from the rest of their application.
  2278. // 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.
  2279. int mouse_earliest_button_down = -1;
  2280. bool mouse_any_down = false;
  2281. for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
  2282. {
  2283. if (g.IO.MouseClicked[i])
  2284. g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (!g.OpenPopupStack.empty());
  2285. mouse_any_down |= g.IO.MouseDown[i];
  2286. if (g.IO.MouseDown[i])
  2287. if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[mouse_earliest_button_down] > g.IO.MouseClickedTime[i])
  2288. mouse_earliest_button_down = i;
  2289. }
  2290. bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down];
  2291. if (g.CaptureMouseNextFrame != -1)
  2292. g.IO.WantCaptureMouse = (g.CaptureMouseNextFrame != 0);
  2293. else
  2294. g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (g.ActiveId != 0) || (!g.OpenPopupStack.empty());
  2295. g.IO.WantCaptureKeyboard = (g.CaptureKeyboardNextFrame != -1) ? (g.CaptureKeyboardNextFrame != 0) : (g.ActiveId != 0);
  2296. g.IO.WantTextInput = (g.ActiveId != 0 && g.InputTextState.Id == g.ActiveId);
  2297. g.MouseCursor = ImGuiMouseCursor_Arrow;
  2298. g.CaptureMouseNextFrame = g.CaptureKeyboardNextFrame = -1;
  2299. g.OsImePosRequest = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default
  2300.  
  2301. // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
  2302. if (!mouse_avail_to_imgui)
  2303. g.HoveredWindow = g.HoveredRootWindow = NULL;
  2304.  
  2305. // Scale & Scrolling
  2306. if (g.HoveredWindow && g.IO.MouseWheel != 0.0f && !g.HoveredWindow->Collapsed)
  2307. {
  2308. ImGuiWindow* window = g.HoveredWindow;
  2309. if (g.IO.KeyCtrl)
  2310. {
  2311. if (g.IO.FontAllowUserScaling)
  2312. {
  2313. // Zoom / Scale window
  2314. float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
  2315. float scale = new_font_scale / window->FontWindowScale;
  2316. window->FontWindowScale = new_font_scale;
  2317.  
  2318. const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
  2319. window->Pos += offset;
  2320. window->PosFloat += offset;
  2321. window->Size *= scale;
  2322. window->SizeFull *= scale;
  2323. }
  2324. }
  2325. else if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse))
  2326. {
  2327. // Scroll
  2328. const int scroll_lines = (window->Flags & ImGuiWindowFlags_ComboBox) ? 3 : 5;
  2329. SetWindowScrollY(window, window->Scroll.y - g.IO.MouseWheel * window->CalcFontSize() * scroll_lines);
  2330. }
  2331. }
  2332.  
  2333. // Pressing TAB activate widget focus
  2334. // 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.
  2335. if (g.ActiveId == 0 && g.FocusedWindow != NULL && g.FocusedWindow->Active && IsKeyPressedMap(ImGuiKey_Tab, false))
  2336. g.FocusedWindow->FocusIdxTabRequestNext = 0;
  2337.  
  2338. // Mark all windows as not visible
  2339. for (int i = 0; i != g.Windows.Size; i++)
  2340. {
  2341. ImGuiWindow* window = g.Windows[i];
  2342. window->WasActive = window->Active;
  2343. window->Active = false;
  2344. window->Accessed = false;
  2345. }
  2346.  
  2347. // Closing the focused window restore focus to the first active root window in descending z-order
  2348. if (g.FocusedWindow && !g.FocusedWindow->WasActive)
  2349. for (int i = g.Windows.Size-1; i >= 0; i--)
  2350. if (g.Windows[i]->WasActive && !(g.Windows[i]->Flags & ImGuiWindowFlags_ChildWindow))
  2351. {
  2352. FocusWindow(g.Windows[i]);
  2353. break;
  2354. }
  2355.  
  2356. // No window should be open at the beginning of the frame.
  2357. // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
  2358. g.CurrentWindowStack.resize(0);
  2359. g.CurrentPopupStack.resize(0);
  2360. CloseInactivePopups();
  2361.  
  2362. // Create implicit window - we will only render it if the user has added something to it.
  2363. ImGui::SetNextWindowSize(ImVec2(400,400), ImGuiSetCond_FirstUseEver);
  2364. ImGui::Begin("Debug");
  2365. }
  2366.  
  2367. // NB: behavior of ImGui after Shutdown() is not tested/guaranteed at the moment. This function is merely here to free heap allocations.
  2368. void ImGui::Shutdown()
  2369. {
  2370. ImGuiContext& g = *GImGui;
  2371.  
  2372. // 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)
  2373. if (g.IO.Fonts) // Testing for NULL to allow user to NULLify in case of running Shutdown() on multiple contexts. Bit hacky.
  2374. g.IO.Fonts->Clear();
  2375.  
  2376. // Cleanup of other data are conditional on actually having used ImGui.
  2377. if (!g.Initialized)
  2378. return;
  2379.  
  2380. SaveIniSettingsToDisk(g.IO.IniFilename);
  2381.  
  2382. for (int i = 0; i < g.Windows.Size; i++)
  2383. {
  2384. g.Windows[i]->~ImGuiWindow();
  2385. ImGui::MemFree(g.Windows[i]);
  2386. }
  2387. g.Windows.clear();
  2388. g.WindowsSortBuffer.clear();
  2389. g.CurrentWindow = NULL;
  2390. g.CurrentWindowStack.clear();
  2391. g.FocusedWindow = NULL;
  2392. g.HoveredWindow = NULL;
  2393. g.HoveredRootWindow = NULL;
  2394. g.ActiveIdWindow = NULL;
  2395. g.MovedWindow = NULL;
  2396. for (int i = 0; i < g.Settings.Size; i++)
  2397. ImGui::MemFree(g.Settings[i].Name);
  2398. g.Settings.clear();
  2399. g.ColorModifiers.clear();
  2400. g.StyleModifiers.clear();
  2401. g.FontStack.clear();
  2402. g.OpenPopupStack.clear();
  2403. g.CurrentPopupStack.clear();
  2404. g.SetNextWindowSizeConstraintCallback = NULL;
  2405. g.SetNextWindowSizeConstraintCallbackUserData = NULL;
  2406. for (int i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
  2407. g.RenderDrawLists[i].clear();
  2408. g.OverlayDrawList.ClearFreeMemory();
  2409. g.ColorEditModeStorage.Clear();
  2410. if (g.PrivateClipboard)
  2411. {
  2412. ImGui::MemFree(g.PrivateClipboard);
  2413. g.PrivateClipboard = NULL;
  2414. }
  2415. g.InputTextState.Text.clear();
  2416. g.InputTextState.InitialText.clear();
  2417. g.InputTextState.TempTextBuffer.clear();
  2418.  
  2419. if (g.LogFile && g.LogFile != stdout)
  2420. {
  2421. fclose(g.LogFile);
  2422. g.LogFile = NULL;
  2423. }
  2424. if (g.LogClipboard)
  2425. {
  2426. g.LogClipboard->~ImGuiTextBuffer();
  2427. ImGui::MemFree(g.LogClipboard);
  2428. }
  2429.  
  2430. g.Initialized = false;
  2431. }
  2432.  
  2433. static ImGuiIniData* FindWindowSettings(const char* name)
  2434. {
  2435. ImGuiContext& g = *GImGui;
  2436. ImGuiID id = ImHash(name, 0);
  2437. for (int i = 0; i != g.Settings.Size; i++)
  2438. {
  2439. ImGuiIniData* ini = &g.Settings[i];
  2440. if (ini->Id == id)
  2441. return ini;
  2442. }
  2443. return NULL;
  2444. }
  2445.  
  2446. static ImGuiIniData* AddWindowSettings(const char* name)
  2447. {
  2448. GImGui->Settings.resize(GImGui->Settings.Size + 1);
  2449. ImGuiIniData* ini = &GImGui->Settings.back();
  2450. ini->Name = ImStrdup(name);
  2451. ini->Id = ImHash(name, 0);
  2452. ini->Collapsed = false;
  2453. ini->Pos = ImVec2(FLT_MAX,FLT_MAX);
  2454. ini->Size = ImVec2(0,0);
  2455. return ini;
  2456. }
  2457.  
  2458. // Zero-tolerance, poor-man .ini parsing
  2459. // FIXME: Write something less rubbish
  2460. static void LoadIniSettingsFromDisk(const char* ini_filename)
  2461. {
  2462. ImGuiContext& g = *GImGui;
  2463. if (!ini_filename)
  2464. return;
  2465.  
  2466. int file_size;
  2467. char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_size, 1);
  2468. if (!file_data)
  2469. return;
  2470.  
  2471. ImGuiIniData* settings = NULL;
  2472. const char* buf_end = file_data + file_size;
  2473. for (const char* line_start = file_data; line_start < buf_end; )
  2474. {
  2475. const char* line_end = line_start;
  2476. while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
  2477. line_end++;
  2478.  
  2479. if (line_start[0] == '[' && line_end > line_start && line_end[-1] == ']')
  2480. {
  2481. char name[64];
  2482. ImFormatString(name, IM_ARRAYSIZE(name), "%.*s", (int)(line_end-line_start-2), line_start+1);
  2483. settings = FindWindowSettings(name);
  2484. if (!settings)
  2485. settings = AddWindowSettings(name);
  2486. }
  2487. else if (settings)
  2488. {
  2489. float x, y;
  2490. int i;
  2491. if (sscanf(line_start, "Pos=%f,%f", &x, &y) == 2)
  2492. settings->Pos = ImVec2(x, y);
  2493. else if (sscanf(line_start, "Size=%f,%f", &x, &y) == 2)
  2494. settings->Size = ImMax(ImVec2(x, y), g.Style.WindowMinSize);
  2495. else if (sscanf(line_start, "Collapsed=%d", &i) == 1)
  2496. settings->Collapsed = (i != 0);
  2497. }
  2498.  
  2499. line_start = line_end+1;
  2500. }
  2501.  
  2502. ImGui::MemFree(file_data);
  2503. }
  2504.  
  2505. static void SaveIniSettingsToDisk(const char* ini_filename)
  2506. {
  2507. ImGuiContext& g = *GImGui;
  2508. g.SettingsDirtyTimer = 0.0f;
  2509. if (!ini_filename)
  2510. return;
  2511.  
  2512. // Gather data from windows that were active during this session
  2513. for (int i = 0; i != g.Windows.Size; i++)
  2514. {
  2515. ImGuiWindow* window = g.Windows[i];
  2516. if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
  2517. continue;
  2518. ImGuiIniData* settings = FindWindowSettings(window->Name);
  2519. settings->Pos = window->Pos;
  2520. settings->Size = window->SizeFull;
  2521. settings->Collapsed = window->Collapsed;
  2522. }
  2523.  
  2524. // Write .ini file
  2525. // If a window wasn't opened in this session we preserve its settings
  2526. FILE* f = ImFileOpen(ini_filename, "wt");
  2527. if (!f)
  2528. return;
  2529. for (int i = 0; i != g.Settings.Size; i++)
  2530. {
  2531. const ImGuiIniData* settings = &g.Settings[i];
  2532. if (settings->Pos.x == FLT_MAX)
  2533. continue;
  2534. const char* name = settings->Name;
  2535. if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
  2536. name = p;
  2537. fprintf(f, "[%s]\n", name);
  2538. fprintf(f, "Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y);
  2539. fprintf(f, "Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y);
  2540. fprintf(f, "Collapsed=%d\n", settings->Collapsed);
  2541. fprintf(f, "\n");
  2542. }
  2543.  
  2544. fclose(f);
  2545. }
  2546.  
  2547. static void MarkIniSettingsDirty()
  2548. {
  2549. ImGuiContext& g = *GImGui;
  2550. if (g.SettingsDirtyTimer <= 0.0f)
  2551. g.SettingsDirtyTimer = g.IO.IniSavingRate;
  2552. }
  2553.  
  2554. // FIXME: Add a more explicit sort order in the window structure.
  2555. static int ChildWindowComparer(const void* lhs, const void* rhs)
  2556. {
  2557. const ImGuiWindow* a = *(const ImGuiWindow**)lhs;
  2558. const ImGuiWindow* b = *(const ImGuiWindow**)rhs;
  2559. if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
  2560. return d;
  2561. if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
  2562. return d;
  2563. if (int d = (a->Flags & ImGuiWindowFlags_ComboBox) - (b->Flags & ImGuiWindowFlags_ComboBox))
  2564. return d;
  2565. return (a->IndexWithinParent - b->IndexWithinParent);
  2566. }
  2567.  
  2568. static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>& out_sorted_windows, ImGuiWindow* window)
  2569. {
  2570. out_sorted_windows.push_back(window);
  2571. if (window->Active)
  2572. {
  2573. int count = window->DC.ChildWindows.Size;
  2574. if (count > 1)
  2575. qsort(window->DC.ChildWindows.begin(), (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
  2576. for (int i = 0; i < count; i++)
  2577. {
  2578. ImGuiWindow* child = window->DC.ChildWindows[i];
  2579. if (child->Active)
  2580. AddWindowToSortedBuffer(out_sorted_windows, child);
  2581. }
  2582. }
  2583. }
  2584.  
  2585. static void AddDrawListToRenderList(ImVector<ImDrawList*>& out_render_list, ImDrawList* draw_list)
  2586. {
  2587. if (draw_list->CmdBuffer.empty())
  2588. return;
  2589.  
  2590. // Remove trailing command if unused
  2591. ImDrawCmd& last_cmd = draw_list->CmdBuffer.back();
  2592. if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL)
  2593. {
  2594. draw_list->CmdBuffer.pop_back();
  2595. if (draw_list->CmdBuffer.empty())
  2596. return;
  2597. }
  2598.  
  2599. // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc.
  2600. IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
  2601. IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
  2602. IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
  2603.  
  2604. // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = 2 bytes = 64K vertices)
  2605. // If this assert triggers because you are drawing lots of stuff manually, A) workaround by calling BeginChild()/EndChild() to put your draw commands in multiple draw lists, B) #define ImDrawIdx to a 'unsigned int' in imconfig.h and render accordingly.
  2606. IM_ASSERT((int64_t)draw_list->_VtxCurrentIdx <= ((int64_t)1L << (sizeof(ImDrawIdx)*8))); // Too many vertices in same ImDrawList. See comment above.
  2607.  
  2608. out_render_list.push_back(draw_list);
  2609. GImGui->IO.MetricsRenderVertices += draw_list->VtxBuffer.Size;
  2610. GImGui->IO.MetricsRenderIndices += draw_list->IdxBuffer.Size;
  2611. }
  2612.  
  2613. static void AddWindowToRenderList(ImVector<ImDrawList*>& out_render_list, ImGuiWindow* window)
  2614. {
  2615. AddDrawListToRenderList(out_render_list, window->DrawList);
  2616. for (int i = 0; i < window->DC.ChildWindows.Size; i++)
  2617. {
  2618. ImGuiWindow* child = window->DC.ChildWindows[i];
  2619. if (!child->Active) // clipped children may have been marked not active
  2620. continue;
  2621. if ((child->Flags & ImGuiWindowFlags_Popup) && child->HiddenFrames > 0)
  2622. continue;
  2623. AddWindowToRenderList(out_render_list, child);
  2624. }
  2625. }
  2626.  
  2627. // 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.
  2628. void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
  2629. {
  2630. ImGuiWindow* window = GetCurrentWindow();
  2631. window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
  2632. window->ClipRect = window->DrawList->_ClipRectStack.back();
  2633. }
  2634.  
  2635. void ImGui::PopClipRect()
  2636. {
  2637. ImGuiWindow* window = GetCurrentWindow();
  2638. window->DrawList->PopClipRect();
  2639. window->ClipRect = window->DrawList->_ClipRectStack.back();
  2640. }
  2641.  
  2642. // 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.
  2643. void ImGui::EndFrame()
  2644. {
  2645. ImGuiContext& g = *GImGui;
  2646. IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame()
  2647. IM_ASSERT(g.FrameCountEnded != g.FrameCount); // ImGui::EndFrame() called multiple times, or forgot to call ImGui::NewFrame() again
  2648.  
  2649. // Render tooltip
  2650. if (g.Tooltip[0])
  2651. {
  2652. ImGui::BeginTooltip();
  2653. ImGui::TextUnformatted(g.Tooltip);
  2654. ImGui::EndTooltip();
  2655. }
  2656.  
  2657. // Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
  2658. if (g.IO.ImeSetInputScreenPosFn && ImLengthSqr(g.OsImePosRequest - g.OsImePosSet) > 0.0001f)
  2659. {
  2660. g.IO.ImeSetInputScreenPosFn((int)g.OsImePosRequest.x, (int)g.OsImePosRequest.y);
  2661. g.OsImePosSet = g.OsImePosRequest;
  2662. }
  2663.  
  2664. // Hide implicit "Debug" window if it hasn't been used
  2665. IM_ASSERT(g.CurrentWindowStack.Size == 1); // Mismatched Begin()/End() calls
  2666. if (g.CurrentWindow && !g.CurrentWindow->Accessed)
  2667. g.CurrentWindow->Active = false;
  2668. ImGui::End();
  2669.  
  2670. // Click to focus window and start moving (after we're done with all our widgets)
  2671. if (g.ActiveId == 0 && g.HoveredId == 0 && g.IO.MouseClicked[0])
  2672. {
  2673. if (!(g.FocusedWindow && !g.FocusedWindow->WasActive && g.FocusedWindow->Active)) // Unless we just made a popup appear
  2674. {
  2675. if (g.HoveredRootWindow != NULL)
  2676. {
  2677. FocusWindow(g.HoveredWindow);
  2678. if (!(g.HoveredWindow->Flags & ImGuiWindowFlags_NoMove))
  2679. {
  2680. g.MovedWindow = g.HoveredWindow;
  2681. g.MovedWindowMoveId = g.HoveredRootWindow->MoveId;
  2682. SetActiveID(g.MovedWindowMoveId, g.HoveredRootWindow);
  2683. }
  2684. }
  2685. else if (g.FocusedWindow != NULL && GetFrontMostModalRootWindow() == NULL)
  2686. {
  2687. // Clicking on void disable focus
  2688. FocusWindow(NULL);
  2689. }
  2690. }
  2691. }
  2692.  
  2693. // Sort the window list so that all child windows are after their parent
  2694. // We cannot do that on FocusWindow() because childs may not exist yet
  2695. g.WindowsSortBuffer.resize(0);
  2696. g.WindowsSortBuffer.reserve(g.Windows.Size);
  2697. for (int i = 0; i != g.Windows.Size; i++)
  2698. {
  2699. ImGuiWindow* window = g.Windows[i];
  2700. if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
  2701. continue;
  2702. AddWindowToSortedBuffer(g.WindowsSortBuffer, window);
  2703. }
  2704. IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size); // we done something wrong
  2705. g.Windows.swap(g.WindowsSortBuffer);
  2706.  
  2707. // Clear Input data for next frame
  2708. g.IO.MouseWheel = 0.0f;
  2709. memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters));
  2710.  
  2711. g.FrameCountEnded = g.FrameCount;
  2712. }
  2713.  
  2714. void ImGui::Render()
  2715. {
  2716. ImGuiContext& g = *GImGui;
  2717. IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame()
  2718.  
  2719. if (g.FrameCountEnded != g.FrameCount)
  2720. ImGui::EndFrame();
  2721. g.FrameCountRendered = g.FrameCount;
  2722.  
  2723. // Skip render altogether if alpha is 0.0
  2724. // 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.
  2725. if (g.Style.Alpha > 0.0f)
  2726. {
  2727. // Gather windows to render
  2728. g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsActiveWindows = 0;
  2729. for (int i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
  2730. g.RenderDrawLists[i].resize(0);
  2731. for (int i = 0; i != g.Windows.Size; i++)
  2732. {
  2733. ImGuiWindow* window = g.Windows[i];
  2734. if (window->Active && window->HiddenFrames <= 0 && (window->Flags & (ImGuiWindowFlags_ChildWindow)) == 0)
  2735. {
  2736. // FIXME: Generalize this with a proper layering system so e.g. user can draw in specific layers, below text, ..
  2737. g.IO.MetricsActiveWindows++;
  2738. if (window->Flags & ImGuiWindowFlags_Popup)
  2739. AddWindowToRenderList(g.RenderDrawLists[1], window);
  2740. else if (window->Flags & ImGuiWindowFlags_Tooltip)
  2741. AddWindowToRenderList(g.RenderDrawLists[2], window);
  2742. else
  2743. AddWindowToRenderList(g.RenderDrawLists[0], window);
  2744. }
  2745. }
  2746.  
  2747. // Flatten layers
  2748. int n = g.RenderDrawLists[0].Size;
  2749. int flattened_size = n;
  2750. for (int i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
  2751. flattened_size += g.RenderDrawLists[i].Size;
  2752. g.RenderDrawLists[0].resize(flattened_size);
  2753. for (int i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
  2754. {
  2755. ImVector<ImDrawList*>& layer = g.RenderDrawLists[i];
  2756. if (layer.empty())
  2757. continue;
  2758. memcpy(&g.RenderDrawLists[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
  2759. n += layer.Size;
  2760. }
  2761.  
  2762. // Draw software mouse cursor if requested
  2763. if (g.IO.MouseDrawCursor)
  2764. {
  2765. const ImGuiMouseCursorData& cursor_data = g.MouseCursorData[g.MouseCursor];
  2766. const ImVec2 pos = g.IO.MousePos - cursor_data.HotOffset;
  2767. const ImVec2 size = cursor_data.Size;
  2768. const ImTextureID tex_id = g.IO.Fonts->TexID;
  2769. g.OverlayDrawList.PushTextureID(tex_id);
  2770. 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
  2771. 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
  2772. g.OverlayDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], IM_COL32(0,0,0,255)); // Black border
  2773. g.OverlayDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[0], cursor_data.TexUvMax[0], IM_COL32(255,255,255,255)); // White fill
  2774. g.OverlayDrawList.PopTextureID();
  2775. }
  2776. if (!g.OverlayDrawList.VtxBuffer.empty())
  2777. AddDrawListToRenderList(g.RenderDrawLists[0], &g.OverlayDrawList);
  2778.  
  2779. // Setup draw data
  2780. g.RenderDrawData.Valid = true;
  2781. g.RenderDrawData.CmdLists = (g.RenderDrawLists[0].Size > 0) ? &g.RenderDrawLists[0][0] : NULL;
  2782. g.RenderDrawData.CmdListsCount = g.RenderDrawLists[0].Size;
  2783. g.RenderDrawData.TotalVtxCount = g.IO.MetricsRenderVertices;
  2784. g.RenderDrawData.TotalIdxCount = g.IO.MetricsRenderIndices;
  2785.  
  2786. // Render. If user hasn't set a callback then they may retrieve the draw data via GetDrawData()
  2787. if (g.RenderDrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL)
  2788. g.IO.RenderDrawListsFn(&g.RenderDrawData);
  2789. }
  2790. }
  2791.  
  2792. const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
  2793. {
  2794. const char* text_display_end = text;
  2795. if (!text_end)
  2796. text_end = (const char*)-1;
  2797.  
  2798. while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
  2799. text_display_end++;
  2800. return text_display_end;
  2801. }
  2802.  
  2803. // Pass text data straight to log (without being displayed)
  2804. void ImGui::LogText(const char* fmt, ...)
  2805. {
  2806. ImGuiContext& g = *GImGui;
  2807. if (!g.LogEnabled)
  2808. return;
  2809.  
  2810. va_list args;
  2811. va_start(args, fmt);
  2812. if (g.LogFile)
  2813. {
  2814. vfprintf(g.LogFile, fmt, args);
  2815. }
  2816. else
  2817. {
  2818. g.LogClipboard->appendv(fmt, args);
  2819. }
  2820. va_end(args);
  2821. }
  2822.  
  2823. // Internal version that takes a position to decide on newline placement and pad items according to their depth.
  2824. // We split text into individual lines to add current tree level padding
  2825. static void LogRenderedText(const ImVec2& ref_pos, const char* text, const char* text_end)
  2826. {
  2827. ImGuiContext& g = *GImGui;
  2828. ImGuiWindow* window = ImGui::GetCurrentWindowRead();
  2829.  
  2830. if (!text_end)
  2831. text_end = ImGui::FindRenderedTextEnd(text, text_end);
  2832.  
  2833. const bool log_new_line = ref_pos.y > window->DC.LogLinePosY+1;
  2834. window->DC.LogLinePosY = ref_pos.y;
  2835.  
  2836. const char* text_remaining = text;
  2837. if (g.LogStartDepth > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth
  2838. g.LogStartDepth = window->DC.TreeDepth;
  2839. const int tree_depth = (window->DC.TreeDepth - g.LogStartDepth);
  2840. for (;;)
  2841. {
  2842. // Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry.
  2843. const char* line_end = text_remaining;
  2844. while (line_end < text_end)
  2845. if (*line_end == '\n')
  2846. break;
  2847. else
  2848. line_end++;
  2849. if (line_end >= text_end)
  2850. line_end = NULL;
  2851.  
  2852. const bool is_first_line = (text == text_remaining);
  2853. bool is_last_line = false;
  2854. if (line_end == NULL)
  2855. {
  2856. is_last_line = true;
  2857. line_end = text_end;
  2858. }
  2859. if (line_end != NULL && !(is_last_line && (line_end - text_remaining)==0))
  2860. {
  2861. const int char_count = (int)(line_end - text_remaining);
  2862. if (log_new_line || !is_first_line)
  2863. ImGui::LogText(IM_NEWLINE "%*s%.*s", tree_depth*4, "", char_count, text_remaining);
  2864. else
  2865. ImGui::LogText(" %.*s", char_count, text_remaining);
  2866. }
  2867.  
  2868. if (is_last_line)
  2869. break;
  2870. text_remaining = line_end + 1;
  2871. }
  2872. }
  2873.  
  2874. // Internal ImGui functions to render text
  2875. // RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
  2876. void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
  2877. {
  2878. ImGuiContext& g = *GImGui;
  2879. ImGuiWindow* window = GetCurrentWindow();
  2880.  
  2881. // Hide anything after a '##' string
  2882. const char* text_display_end;
  2883. if (hide_text_after_hash)
  2884. {
  2885. text_display_end = FindRenderedTextEnd(text, text_end);
  2886. }
  2887. else
  2888. {
  2889. if (!text_end)
  2890. text_end = text + strlen(text); // FIXME-OPT
  2891. text_display_end = text_end;
  2892. }
  2893.  
  2894. const int text_len = (int)(text_display_end - text);
  2895. if (text_len > 0)
  2896. {
  2897. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
  2898. if (g.LogEnabled)
  2899. LogRenderedText(pos, text, text_display_end);
  2900. }
  2901. }
  2902.  
  2903. void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
  2904. {
  2905. ImGuiContext& g = *GImGui;
  2906. ImGuiWindow* window = GetCurrentWindow();
  2907.  
  2908. if (!text_end)
  2909. text_end = text + strlen(text); // FIXME-OPT
  2910.  
  2911. const int text_len = (int)(text_end - text);
  2912. if (text_len > 0)
  2913. {
  2914. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
  2915. if (g.LogEnabled)
  2916. LogRenderedText(pos, text, text_end);
  2917. }
  2918. }
  2919.  
  2920. // Default clip_rect uses (pos_min,pos_max)
  2921. // Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
  2922. 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)
  2923. {
  2924. // Hide anything after a '##' string
  2925. const char* text_display_end = FindRenderedTextEnd(text, text_end);
  2926. const int text_len = (int)(text_display_end - text);
  2927. if (text_len == 0)
  2928. return;
  2929.  
  2930. ImGuiContext& g = *GImGui;
  2931. ImGuiWindow* window = GetCurrentWindow();
  2932.  
  2933. // Perform CPU side clipping for single clipped element to avoid using scissor state
  2934. ImVec2 pos = pos_min;
  2935. const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
  2936.  
  2937. const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
  2938. const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
  2939. bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
  2940. if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
  2941. need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
  2942.  
  2943. // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
  2944. if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
  2945. if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
  2946.  
  2947. // Render
  2948. if (need_clipping)
  2949. {
  2950. ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
  2951. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
  2952. }
  2953. else
  2954. {
  2955. window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
  2956. }
  2957. if (g.LogEnabled)
  2958. LogRenderedText(pos, text, text_display_end);
  2959. }
  2960.  
  2961. // Render a rectangle shaped with optional rounding and borders
  2962. void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
  2963. {
  2964. ImGuiWindow* window = GetCurrentWindow();
  2965.  
  2966. window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
  2967. if (border && (window->Flags & ImGuiWindowFlags_ShowBorders))
  2968. {
  2969. window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding);
  2970. window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding);
  2971. }
  2972. }
  2973.  
  2974. // Render a triangle to denote expanded/collapsed state
  2975. void ImGui::RenderCollapseTriangle(ImVec2 p_min, bool is_open, float scale)
  2976. {
  2977. ImGuiContext& g = *GImGui;
  2978. ImGuiWindow* window = GetCurrentWindow();
  2979.  
  2980. const float h = g.FontSize * 1.00f;
  2981. const float r = h * 0.40f * scale;
  2982. ImVec2 center = p_min + ImVec2(h*0.50f, h*0.50f*scale);
  2983.  
  2984. ImVec2 a, b, c;
  2985. if (is_open)
  2986. {
  2987. center.y -= r*0.25f;
  2988. a = center + ImVec2(0,1)*r;
  2989. b = center + ImVec2(-0.866f,-0.5f)*r;
  2990. c = center + ImVec2(0.866f,-0.5f)*r;
  2991. }
  2992. else
  2993. {
  2994. a = center + ImVec2(1,0)*r;
  2995. b = center + ImVec2(-0.500f,0.866f)*r;
  2996. c = center + ImVec2(-0.500f,-0.866f)*r;
  2997. }
  2998.  
  2999. window->DrawList->AddTriangleFilled(a, b, c, GetColorU32(ImGuiCol_Text));
  3000. }
  3001.  
  3002. void ImGui::RenderBullet(ImVec2 pos)
  3003. {
  3004. ImGuiWindow* window = GetCurrentWindow();
  3005. window->DrawList->AddCircleFilled(pos, GImGui->FontSize*0.20f, GetColorU32(ImGuiCol_Text), 8);
  3006. }
  3007.  
  3008. void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col)
  3009. {
  3010. ImGuiContext& g = *GImGui;
  3011. ImGuiWindow* window = GetCurrentWindow();
  3012.  
  3013. ImVec2 a, b, c;
  3014. float start_x = (float)(int)(g.FontSize * 0.307f + 0.5f);
  3015. float rem_third = (float)(int)((g.FontSize - start_x) / 3.0f);
  3016. a.x = pos.x + 0.5f + start_x;
  3017. b.x = a.x + rem_third;
  3018. c.x = a.x + rem_third * 3.0f;
  3019. b.y = pos.y - 1.0f + (float)(int)(g.Font->Ascent * (g.FontSize / g.Font->FontSize) + 0.5f) + (float)(int)(g.Font->DisplayOffset.y);
  3020. a.y = b.y - rem_third;
  3021. c.y = b.y - rem_third * 2.0f;
  3022.  
  3023. window->DrawList->PathLineTo(a);
  3024. window->DrawList->PathLineTo(b);
  3025. window->DrawList->PathLineTo(c);
  3026. window->DrawList->PathStroke(col, false);
  3027. }
  3028.  
  3029. // Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
  3030. // CalcTextSize("") should return ImVec2(0.0f, GImGui->FontSize)
  3031. ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
  3032. {
  3033. ImGuiContext& g = *GImGui;
  3034.  
  3035. const char* text_display_end;
  3036. if (hide_text_after_double_hash)
  3037. text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string
  3038. else
  3039. text_display_end = text_end;
  3040.  
  3041. ImFont* font = g.Font;
  3042. const float font_size = g.FontSize;
  3043. if (text == text_display_end)
  3044. return ImVec2(0.0f, font_size);
  3045. ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
  3046.  
  3047. // Cancel out character spacing for the last character of a line (it is baked into glyph->XAdvance field)
  3048. const float font_scale = font_size / font->FontSize;
  3049. const float character_spacing_x = 1.0f * font_scale;
  3050. if (text_size.x > 0.0f)
  3051. text_size.x -= character_spacing_x;
  3052. text_size.x = (float)(int)(text_size.x + 0.95f);
  3053.  
  3054. return text_size;
  3055. }
  3056.  
  3057. // Helper to calculate coarse clipping of large list of evenly sized items.
  3058. // NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern.
  3059. // NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX
  3060. void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
  3061. {
  3062. ImGuiContext& g = *GImGui;
  3063. ImGuiWindow* window = GetCurrentWindowRead();
  3064. if (g.LogEnabled)
  3065. {
  3066. // If logging is active, do not perform any clipping
  3067. *out_items_display_start = 0;
  3068. *out_items_display_end = items_count;
  3069. return;
  3070. }
  3071. if (window->SkipItems)
  3072. {
  3073. *out_items_display_start = *out_items_display_end = 0;
  3074. return;
  3075. }
  3076.  
  3077. const ImVec2 pos = window->DC.CursorPos;
  3078. int start = (int)((window->ClipRect.Min.y - pos.y) / items_height);
  3079. int end = (int)((window->ClipRect.Max.y - pos.y) / items_height);
  3080. start = ImClamp(start, 0, items_count);
  3081. end = ImClamp(end + 1, start, items_count);
  3082. *out_items_display_start = start;
  3083. *out_items_display_end = end;
  3084. }
  3085.  
  3086. // Find window given position, search front-to-back
  3087. // 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.
  3088. static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs)
  3089. {
  3090. ImGuiContext& g = *GImGui;
  3091. for (int i = g.Windows.Size-1; i >= 0; i--)
  3092. {
  3093. ImGuiWindow* window = g.Windows[i];
  3094. if (!window->Active)
  3095. continue;
  3096. if (window->Flags & ImGuiWindowFlags_NoInputs)
  3097. continue;
  3098. if (excluding_childs && (window->Flags & ImGuiWindowFlags_ChildWindow) != 0)
  3099. continue;
  3100.  
  3101. // Using the clipped AABB so a child window will typically be clipped by its parent.
  3102. ImRect bb(window->WindowRectClipped.Min - g.Style.TouchExtraPadding, window->WindowRectClipped.Max + g.Style.TouchExtraPadding);
  3103. if (bb.Contains(pos))
  3104. return window;
  3105. }
  3106. return NULL;
  3107. }
  3108.  
  3109. // Test if mouse cursor is hovering given rectangle
  3110. // NB- Rectangle is clipped by our current clip setting
  3111. // NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
  3112. bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
  3113. {
  3114. ImGuiContext& g = *GImGui;
  3115. ImGuiWindow* window = GetCurrentWindowRead();
  3116.  
  3117. // Clip
  3118. ImRect rect_clipped(r_min, r_max);
  3119. if (clip)
  3120. rect_clipped.Clip(window->ClipRect);
  3121.  
  3122. // Expand for touch input
  3123. const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
  3124. return rect_for_touch.Contains(g.IO.MousePos);
  3125. }
  3126.  
  3127. bool ImGui::IsMouseHoveringWindow()
  3128. {
  3129. ImGuiContext& g = *GImGui;
  3130. return g.HoveredWindow == g.CurrentWindow;
  3131. }
  3132.  
  3133. bool ImGui::IsMouseHoveringAnyWindow()
  3134. {
  3135. ImGuiContext& g = *GImGui;
  3136. return g.HoveredWindow != NULL;
  3137. }
  3138.  
  3139. bool ImGui::IsPosHoveringAnyWindow(const ImVec2& pos)
  3140. {
  3141. return FindHoveredWindow(pos, false) != NULL;
  3142. }
  3143.  
  3144. static bool IsKeyPressedMap(ImGuiKey key, bool repeat)
  3145. {
  3146. const int key_index = GImGui->IO.KeyMap[key];
  3147. return ImGui::IsKeyPressed(key_index, repeat);
  3148. }
  3149.  
  3150. int ImGui::GetKeyIndex(ImGuiKey key)
  3151. {
  3152. IM_ASSERT(key >= 0 && key < ImGuiKey_COUNT);
  3153. return GImGui->IO.KeyMap[key];
  3154. }
  3155.  
  3156. bool ImGui::IsKeyDown(int key_index)
  3157. {
  3158. if (key_index < 0) return false;
  3159. IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(GImGui->IO.KeysDown));
  3160. return GImGui->IO.KeysDown[key_index];
  3161. }
  3162.  
  3163. bool ImGui::IsKeyPressed(int key_index, bool repeat)
  3164. {
  3165. ImGuiContext& g = *GImGui;
  3166. if (key_index < 0) return false;
  3167. IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown));
  3168. const float t = g.IO.KeysDownDuration[key_index];
  3169. if (t == 0.0f)
  3170. return true;
  3171.  
  3172. if (repeat && t > g.IO.KeyRepeatDelay)
  3173. {
  3174. float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate;
  3175. if ((fmodf(t - delay, rate) > rate*0.5f) != (fmodf(t - delay - g.IO.DeltaTime, rate) > rate*0.5f))
  3176. return true;
  3177. }
  3178. return false;
  3179. }
  3180.  
  3181. bool ImGui::IsKeyReleased(int key_index)
  3182. {
  3183. ImGuiContext& g = *GImGui;
  3184. if (key_index < 0) return false;
  3185. IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown));
  3186. if (g.IO.KeysDownDurationPrev[key_index] >= 0.0f && !g.IO.KeysDown[key_index])
  3187. return true;
  3188. return false;
  3189. }
  3190.  
  3191. bool ImGui::IsMouseDown(int button)
  3192. {
  3193. ImGuiContext& g = *GImGui;
  3194. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3195. return g.IO.MouseDown[button];
  3196. }
  3197.  
  3198. bool ImGui::IsMouseClicked(int button, bool repeat)
  3199. {
  3200. ImGuiContext& g = *GImGui;
  3201. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3202. const float t = g.IO.MouseDownDuration[button];
  3203. if (t == 0.0f)
  3204. return true;
  3205.  
  3206. if (repeat && t > g.IO.KeyRepeatDelay)
  3207. {
  3208. float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate;
  3209. if ((fmodf(t - delay, rate) > rate*0.5f) != (fmodf(t - delay - g.IO.DeltaTime, rate) > rate*0.5f))
  3210. return true;
  3211. }
  3212.  
  3213. return false;
  3214. }
  3215.  
  3216. bool ImGui::IsMouseReleased(int button)
  3217. {
  3218. ImGuiContext& g = *GImGui;
  3219. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3220. return g.IO.MouseReleased[button];
  3221. }
  3222.  
  3223. bool ImGui::IsMouseDoubleClicked(int button)
  3224. {
  3225. ImGuiContext& g = *GImGui;
  3226. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3227. return g.IO.MouseDoubleClicked[button];
  3228. }
  3229.  
  3230. bool ImGui::IsMouseDragging(int button, float lock_threshold)
  3231. {
  3232. ImGuiContext& g = *GImGui;
  3233. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3234. if (!g.IO.MouseDown[button])
  3235. return false;
  3236. if (lock_threshold < 0.0f)
  3237. lock_threshold = g.IO.MouseDragThreshold;
  3238. return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
  3239. }
  3240.  
  3241. ImVec2 ImGui::GetMousePos()
  3242. {
  3243. return GImGui->IO.MousePos;
  3244. }
  3245.  
  3246. // NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
  3247. ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
  3248. {
  3249. ImGuiContext& g = *GImGui;
  3250. if (g.CurrentPopupStack.Size > 0)
  3251. return g.OpenPopupStack[g.CurrentPopupStack.Size-1].MousePosOnOpen;
  3252. return g.IO.MousePos;
  3253. }
  3254.  
  3255. ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold)
  3256. {
  3257. ImGuiContext& g = *GImGui;
  3258. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3259. if (lock_threshold < 0.0f)
  3260. lock_threshold = g.IO.MouseDragThreshold;
  3261. if (g.IO.MouseDown[button])
  3262. if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
  3263. return g.IO.MousePos - g.IO.MouseClickedPos[button]; // Assume we can only get active with left-mouse button (at the moment).
  3264. return ImVec2(0.0f, 0.0f);
  3265. }
  3266.  
  3267. void ImGui::ResetMouseDragDelta(int button)
  3268. {
  3269. ImGuiContext& g = *GImGui;
  3270. IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
  3271. // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
  3272. g.IO.MouseClickedPos[button] = g.IO.MousePos;
  3273. }
  3274.  
  3275. ImGuiMouseCursor ImGui::GetMouseCursor()
  3276. {
  3277. return GImGui->MouseCursor;
  3278. }
  3279.  
  3280. void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
  3281. {
  3282. GImGui->MouseCursor = cursor_type;
  3283. }
  3284.  
  3285. void ImGui::CaptureKeyboardFromApp(bool capture)
  3286. {
  3287. GImGui->CaptureKeyboardNextFrame = capture ? 1 : 0;
  3288. }
  3289.  
  3290. void ImGui::CaptureMouseFromApp(bool capture)
  3291. {
  3292. GImGui->CaptureMouseNextFrame = capture ? 1 : 0;
  3293. }
  3294.  
  3295. bool ImGui::IsItemHovered()
  3296. {
  3297. ImGuiWindow* window = GetCurrentWindowRead();
  3298. return window->DC.LastItemHoveredAndUsable;
  3299. }
  3300.  
  3301. bool ImGui::IsItemHoveredRect()
  3302. {
  3303. ImGuiWindow* window = GetCurrentWindowRead();
  3304. return window->DC.LastItemHoveredRect;
  3305. }
  3306.  
  3307. bool ImGui::IsItemActive()
  3308. {
  3309. ImGuiContext& g = *GImGui;
  3310. if (g.ActiveId)
  3311. {
  3312. ImGuiWindow* window = GetCurrentWindowRead();
  3313. return g.ActiveId == window->DC.LastItemId;
  3314. }
  3315. return false;
  3316. }
  3317.  
  3318. bool ImGui::IsItemClicked(int mouse_button)
  3319. {
  3320. return IsMouseClicked(mouse_button) && IsItemHovered();
  3321. }
  3322.  
  3323. bool ImGui::IsAnyItemHovered()
  3324. {
  3325. return GImGui->HoveredId != 0 || GImGui->HoveredIdPreviousFrame != 0;
  3326. }
  3327.  
  3328. bool ImGui::IsAnyItemActive()
  3329. {
  3330. return GImGui->ActiveId != 0;
  3331. }
  3332.  
  3333. bool ImGui::IsItemVisible()
  3334. {
  3335. ImGuiWindow* window = GetCurrentWindowRead();
  3336. ImRect r(window->ClipRect);
  3337. return r.Overlaps(window->DC.LastItemRect);
  3338. }
  3339.  
  3340. // Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
  3341. void ImGui::SetItemAllowOverlap()
  3342. {
  3343. ImGuiContext& g = *GImGui;
  3344. if (g.HoveredId == g.CurrentWindow->DC.LastItemId)
  3345. g.HoveredIdAllowOverlap = true;
  3346. if (g.ActiveId == g.CurrentWindow->DC.LastItemId)
  3347. g.ActiveIdAllowOverlap = true;
  3348. }
  3349.  
  3350. ImVec2 ImGui::GetItemRectMin()
  3351. {
  3352. ImGuiWindow* window = GetCurrentWindowRead();
  3353. return window->DC.LastItemRect.Min;
  3354. }
  3355.  
  3356. ImVec2 ImGui::GetItemRectMax()
  3357. {
  3358. ImGuiWindow* window = GetCurrentWindowRead();
  3359. return window->DC.LastItemRect.Max;
  3360. }
  3361.  
  3362. ImVec2 ImGui::GetItemRectSize()
  3363. {
  3364. ImGuiWindow* window = GetCurrentWindowRead();
  3365. return window->DC.LastItemRect.GetSize();
  3366. }
  3367.  
  3368. ImVec2 ImGui::CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge, float outward)
  3369. {
  3370. ImGuiWindow* window = GetCurrentWindowRead();
  3371. ImRect rect = window->DC.LastItemRect;
  3372. rect.Expand(outward);
  3373. return rect.GetClosestPoint(pos, on_edge);
  3374. }
  3375.  
  3376. // Tooltip is stored and turned into a BeginTooltip()/EndTooltip() sequence at the end of the frame. Each call override previous value.
  3377. void ImGui::SetTooltipV(const char* fmt, va_list args)
  3378. {
  3379. ImGuiContext& g = *GImGui;
  3380. ImFormatStringV(g.Tooltip, IM_ARRAYSIZE(g.Tooltip), fmt, args);
  3381. }
  3382.  
  3383. void ImGui::SetTooltip(const char* fmt, ...)
  3384. {
  3385. va_list args;
  3386. va_start(args, fmt);
  3387. SetTooltipV(fmt, args);
  3388. va_end(args);
  3389. }
  3390.  
  3391. static ImRect GetVisibleRect()
  3392. {
  3393. ImGuiContext& g = *GImGui;
  3394. if (g.IO.DisplayVisibleMin.x != g.IO.DisplayVisibleMax.x && g.IO.DisplayVisibleMin.y != g.IO.DisplayVisibleMax.y)
  3395. return ImRect(g.IO.DisplayVisibleMin, g.IO.DisplayVisibleMax);
  3396. return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
  3397. }
  3398.  
  3399. void ImGui::BeginTooltip()
  3400. {
  3401. ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize;
  3402. ImGui::Begin("##Tooltip", NULL, flags);
  3403. }
  3404.  
  3405. void ImGui::EndTooltip()
  3406. {
  3407. IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
  3408. ImGui::End();
  3409. }
  3410.  
  3411. static bool IsPopupOpen(ImGuiID id)
  3412. {
  3413. ImGuiContext& g = *GImGui;
  3414. return g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupId == id;
  3415. }
  3416.  
  3417. // Mark popup as open (toggle toward open state).
  3418. // Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
  3419. // Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
  3420. // One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
  3421. void ImGui::OpenPopupEx(const char* str_id, bool reopen_existing)
  3422. {
  3423. ImGuiContext& g = *GImGui;
  3424. ImGuiWindow* window = g.CurrentWindow;
  3425. ImGuiID id = window->GetID(str_id);
  3426. int current_stack_size = g.CurrentPopupStack.Size;
  3427. 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)
  3428. if (g.OpenPopupStack.Size < current_stack_size + 1)
  3429. g.OpenPopupStack.push_back(popup_ref);
  3430. else if (reopen_existing || g.OpenPopupStack[current_stack_size].PopupId != id)
  3431. {
  3432. g.OpenPopupStack.resize(current_stack_size+1);
  3433. g.OpenPopupStack[current_stack_size] = popup_ref;
  3434. }
  3435. }
  3436.  
  3437. void ImGui::OpenPopup(const char* str_id)
  3438. {
  3439. ImGui::OpenPopupEx(str_id, false);
  3440. }
  3441.  
  3442. static void CloseInactivePopups()
  3443. {
  3444. ImGuiContext& g = *GImGui;
  3445. if (g.OpenPopupStack.empty())
  3446. return;
  3447.  
  3448. // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
  3449. // Don't close our own child popup windows
  3450. int n = 0;
  3451. if (g.FocusedWindow)
  3452. {
  3453. for (n = 0; n < g.OpenPopupStack.Size; n++)
  3454. {
  3455. ImGuiPopupRef& popup = g.OpenPopupStack[n];
  3456. if (!popup.Window)
  3457. continue;
  3458. IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
  3459. if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
  3460. continue;
  3461.  
  3462. bool has_focus = false;
  3463. for (int m = n; m < g.OpenPopupStack.Size && !has_focus; m++)
  3464. has_focus = (g.OpenPopupStack[m].Window && g.OpenPopupStack[m].Window->RootWindow == g.FocusedWindow->RootWindow);
  3465. if (!has_focus)
  3466. break;
  3467. }
  3468. }
  3469. if (n < g.OpenPopupStack.Size) // This test is not required but it allows to set a useful breakpoint on the line below
  3470. g.OpenPopupStack.resize(n);
  3471. }
  3472.  
  3473. static ImGuiWindow* GetFrontMostModalRootWindow()
  3474. {
  3475. ImGuiContext& g = *GImGui;
  3476. for (int n = g.OpenPopupStack.Size-1; n >= 0; n--)
  3477. if (ImGuiWindow* front_most_popup = g.OpenPopupStack.Data[n].Window)
  3478. if (front_most_popup->Flags & ImGuiWindowFlags_Modal)
  3479. return front_most_popup;
  3480. return NULL;
  3481. }
  3482.  
  3483. static void ClosePopupToLevel(int remaining)
  3484. {
  3485. ImGuiContext& g = *GImGui;
  3486. if (remaining > 0)
  3487. ImGui::FocusWindow(g.OpenPopupStack[remaining-1].Window);
  3488. else
  3489. ImGui::FocusWindow(g.OpenPopupStack[0].ParentWindow);
  3490. g.OpenPopupStack.resize(remaining);
  3491. }
  3492.  
  3493. static void ClosePopup(ImGuiID id)
  3494. {
  3495. if (!IsPopupOpen(id))
  3496. return;
  3497. ImGuiContext& g = *GImGui;
  3498. ClosePopupToLevel(g.OpenPopupStack.Size - 1);
  3499. }
  3500.  
  3501. // Close the popup we have begin-ed into.
  3502. void ImGui::CloseCurrentPopup()
  3503. {
  3504. ImGuiContext& g = *GImGui;
  3505. int popup_idx = g.CurrentPopupStack.Size - 1;
  3506. if (popup_idx < 0 || popup_idx > g.OpenPopupStack.Size || g.CurrentPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
  3507. return;
  3508. while (popup_idx > 0 && g.OpenPopupStack[popup_idx].Window && (g.OpenPopupStack[popup_idx].Window->Flags & ImGuiWindowFlags_ChildMenu))
  3509. popup_idx--;
  3510. ClosePopupToLevel(popup_idx);
  3511. }
  3512.  
  3513. static inline void ClearSetNextWindowData()
  3514. {
  3515. ImGuiContext& g = *GImGui;
  3516. g.SetNextWindowPosCond = g.SetNextWindowSizeCond = g.SetNextWindowContentSizeCond = g.SetNextWindowCollapsedCond = 0;
  3517. g.SetNextWindowSizeConstraint = g.SetNextWindowFocus = false;
  3518. }
  3519.  
  3520. static bool BeginPopupEx(const char* str_id, ImGuiWindowFlags extra_flags)
  3521. {
  3522. ImGuiContext& g = *GImGui;
  3523. ImGuiWindow* window = g.CurrentWindow;
  3524. const ImGuiID id = window->GetID(str_id);
  3525. if (!IsPopupOpen(id))
  3526. {
  3527. ClearSetNextWindowData(); // We behave like Begin() and need to consume those values
  3528. return false;
  3529. }
  3530.  
  3531. ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
  3532. ImGuiWindowFlags flags = extra_flags|ImGuiWindowFlags_Popup|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize;
  3533.  
  3534. char name[20];
  3535. if (flags & ImGuiWindowFlags_ChildMenu)
  3536. ImFormatString(name, IM_ARRAYSIZE(name), "##menu_%d", g.CurrentPopupStack.Size); // Recycle windows based on depth
  3537. else
  3538. ImFormatString(name, IM_ARRAYSIZE(name), "##popup_%08x", id); // Not recycling, so we can close/open during the same frame
  3539.  
  3540. bool is_open = ImGui::Begin(name, NULL, flags);
  3541. if (!(window->Flags & ImGuiWindowFlags_ShowBorders))
  3542. g.CurrentWindow->Flags &= ~ImGuiWindowFlags_ShowBorders;
  3543. if (!is_open) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
  3544. ImGui::EndPopup();
  3545.  
  3546. return is_open;
  3547. }
  3548.  
  3549. bool ImGui::BeginPopup(const char* str_id)
  3550. {
  3551. if (GImGui->OpenPopupStack.Size <= GImGui->CurrentPopupStack.Size) // Early out for performance
  3552. {
  3553. ClearSetNextWindowData(); // We behave like Begin() and need to consume those values
  3554. return false;
  3555. }
  3556. return BeginPopupEx(str_id, ImGuiWindowFlags_ShowBorders);
  3557. }
  3558.  
  3559. bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags extra_flags)
  3560. {
  3561. ImGuiContext& g = *GImGui;
  3562. ImGuiWindow* window = g.CurrentWindow;
  3563. const ImGuiID id = window->GetID(name);
  3564. if (!IsPopupOpen(id))
  3565. {
  3566. ClearSetNextWindowData(); // We behave like Begin() and need to consume those values
  3567. return false;
  3568. }
  3569.  
  3570. ImGuiWindowFlags flags = extra_flags|ImGuiWindowFlags_Popup|ImGuiWindowFlags_Modal|ImGuiWindowFlags_NoCollapse|ImGuiWindowFlags_NoSavedSettings;
  3571. bool is_open = ImGui::Begin(name, p_open, flags);
  3572. if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
  3573. {
  3574. ImGui::EndPopup();
  3575. if (is_open)
  3576. ClosePopup(id);
  3577. return false;
  3578. }
  3579.  
  3580. return is_open;
  3581. }
  3582.  
  3583. void ImGui::EndPopup()
  3584. {
  3585. ImGuiWindow* window = GetCurrentWindow();
  3586. IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
  3587. IM_ASSERT(GImGui->CurrentPopupStack.Size > 0);
  3588. ImGui::End();
  3589. if (!(window->Flags & ImGuiWindowFlags_Modal))
  3590. ImGui::PopStyleVar();
  3591. }
  3592.  
  3593. // This is a helper to handle the most simple case of associating one named popup to one given widget.
  3594. // 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
  3595. // this yourself so you can store data relative to the widget that opened the popup instead of choosing different popup identifiers.
  3596. // 2. If you want right-clicking on the same item to reopen the popup at new location, use the same code replacing IsItemHovered() with IsItemHoveredRect()
  3597. // and passing true to the OpenPopupEx().
  3598. // 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
  3599. // the item isn't interactable (because it is blocked by the active popup) may useful in some situation when e.g. large canvas as one item, content of menu
  3600. // driven by click position.
  3601. bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button)
  3602. {
  3603. if (IsItemHovered() && IsMouseClicked(mouse_button))
  3604. OpenPopupEx(str_id, false);
  3605. return BeginPopup(str_id);
  3606. }
  3607.  
  3608. bool ImGui::BeginPopupContextWindow(bool also_over_items, const char* str_id, int mouse_button)
  3609. {
  3610. if (!str_id) str_id = "window_context_menu";
  3611. if (IsMouseHoveringWindow() && IsMouseClicked(mouse_button))
  3612. if (also_over_items || !IsAnyItemHovered())
  3613. OpenPopupEx(str_id, true);
  3614. return BeginPopup(str_id);
  3615. }
  3616.  
  3617. bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button)
  3618. {
  3619. if (!str_id) str_id = "void_context_menu";
  3620. if (!IsMouseHoveringAnyWindow() && IsMouseClicked(mouse_button))
  3621. OpenPopupEx(str_id, true);
  3622. return BeginPopup(str_id);
  3623. }
  3624.  
  3625. static bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
  3626. {
  3627. ImGuiWindow* window = ImGui::GetCurrentWindow();
  3628. ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow;
  3629.  
  3630. const ImVec2 content_avail = ImGui::GetContentRegionAvail();
  3631. ImVec2 size = ImFloor(size_arg);
  3632. if (size.x <= 0.0f)
  3633. {
  3634. if (size.x == 0.0f)
  3635. flags |= ImGuiWindowFlags_ChildWindowAutoFitX;
  3636. 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)
  3637. }
  3638. if (size.y <= 0.0f)
  3639. {
  3640. if (size.y == 0.0f)
  3641. flags |= ImGuiWindowFlags_ChildWindowAutoFitY;
  3642. size.y = ImMax(content_avail.y, 4.0f) - fabsf(size.y);
  3643. }
  3644. if (border)
  3645. flags |= ImGuiWindowFlags_ShowBorders;
  3646. flags |= extra_flags;
  3647.  
  3648. char title[256];
  3649. if (name)
  3650. ImFormatString(title, IM_ARRAYSIZE(title), "%s.%s.%08X", window->Name, name, id);
  3651. else
  3652. ImFormatString(title, IM_ARRAYSIZE(title), "%s.%08X", window->Name, id);
  3653.  
  3654. bool ret = ImGui::Begin(title, NULL, size, -1.0f, flags);
  3655.  
  3656. if (!(window->Flags & ImGuiWindowFlags_ShowBorders))
  3657. ImGui::GetCurrentWindow()->Flags &= ~ImGuiWindowFlags_ShowBorders;
  3658.  
  3659. return ret;
  3660. }
  3661.  
  3662. bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
  3663. {
  3664. ImGuiWindow* window = GetCurrentWindow();
  3665. return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);
  3666. }
  3667.  
  3668. bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
  3669. {
  3670. return BeginChildEx(NULL, id, size_arg, border, extra_flags);
  3671. }
  3672.  
  3673. void ImGui::EndChild()
  3674. {
  3675. ImGuiWindow* window = GetCurrentWindow();
  3676.  
  3677. IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss
  3678. if ((window->Flags & ImGuiWindowFlags_ComboBox) || window->BeginCount > 1)
  3679. {
  3680. ImGui::End();
  3681. }
  3682. else
  3683. {
  3684. // 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.
  3685. ImVec2 sz = GetWindowSize();
  3686. if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitX) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
  3687. sz.x = ImMax(4.0f, sz.x);
  3688. if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitY)
  3689. sz.y = ImMax(4.0f, sz.y);
  3690.  
  3691. ImGui::End();
  3692.  
  3693. window = GetCurrentWindow();
  3694. ImRect bb(window->DC.CursorPos, window->DC.CursorPos + sz);
  3695. ItemSize(sz);
  3696. ItemAdd(bb, NULL);
  3697. }
  3698. }
  3699.  
  3700. // Helper to create a child window / scrolling region that looks like a normal widget frame.
  3701. bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
  3702. {
  3703. ImGuiContext& g = *GImGui;
  3704. const ImGuiStyle& style = g.Style;
  3705. ImGui::PushStyleColor(ImGuiCol_ChildWindowBg, style.Colors[ImGuiCol_FrameBg]);
  3706. ImGui::PushStyleVar(ImGuiStyleVar_ChildWindowRounding, style.FrameRounding);
  3707. ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
  3708. return ImGui::BeginChild(id, size, (g.CurrentWindow->Flags & ImGuiWindowFlags_ShowBorders) ? true : false, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
  3709. }
  3710.  
  3711. void ImGui::EndChildFrame()
  3712. {
  3713. ImGui::EndChild();
  3714. ImGui::PopStyleVar(2);
  3715. ImGui::PopStyleColor();
  3716. }
  3717.  
  3718. // Save and compare stack sizes on Begin()/End() to detect usage errors
  3719. static void CheckStacksSize(ImGuiWindow* window, bool write)
  3720. {
  3721. // 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)
  3722. ImGuiContext& g = *GImGui;
  3723. int* p_backup = &window->DC.StackSizesBackup[0];
  3724. { 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()
  3725. { 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()
  3726. { 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()
  3727. { 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()
  3728. { 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()
  3729. { 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()
  3730. IM_ASSERT(p_backup == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup));
  3731. }
  3732.  
  3733. static ImVec2 FindBestPopupWindowPos(const ImVec2& base_pos, const ImVec2& size, int* last_dir, const ImRect& r_inner)
  3734. {
  3735. const ImGuiStyle& style = GImGui->Style;
  3736.  
  3737. // Clamp into visible area while not overlapping the cursor. Safety padding is optional if our popup size won't fit without it.
  3738. ImVec2 safe_padding = style.DisplaySafeAreaPadding;
  3739. ImRect r_outer(GetVisibleRect());
  3740. r_outer.Reduce(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));
  3741. ImVec2 base_pos_clamped = ImClamp(base_pos, r_outer.Min, r_outer.Max - size);
  3742.  
  3743. for (int n = (*last_dir != -1) ? -1 : 0; n < 4; n++) // Last, Right, down, up, left. (Favor last used direction).
  3744. {
  3745. const int dir = (n == -1) ? *last_dir : n;
  3746. 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);
  3747. if (rect.GetWidth() < size.x || rect.GetHeight() < size.y)
  3748. continue;
  3749. *last_dir = dir;
  3750. 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);
  3751. }
  3752.  
  3753. // Fallback, try to keep within display
  3754. *last_dir = -1;
  3755. ImVec2 pos = base_pos;
  3756. pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
  3757. pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
  3758. return pos;
  3759. }
  3760.  
  3761. ImGuiWindow* ImGui::FindWindowByName(const char* name)
  3762. {
  3763. // FIXME-OPT: Store sorted hashes -> pointers so we can do a bissection in a contiguous block
  3764. ImGuiContext& g = *GImGui;
  3765. ImGuiID id = ImHash(name, 0);
  3766. for (int i = 0; i < g.Windows.Size; i++)
  3767. if (g.Windows[i]->ID == id)
  3768. return g.Windows[i];
  3769. return NULL;
  3770. }
  3771.  
  3772. static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags)
  3773. {
  3774. ImGuiContext& g = *GImGui;
  3775.  
  3776. // Create window the first time
  3777. ImGuiWindow* window = (ImGuiWindow*)ImGui::MemAlloc(sizeof(ImGuiWindow));
  3778. IM_PLACEMENT_NEW(window) ImGuiWindow(name);
  3779. window->Flags = flags;
  3780.  
  3781. if (flags & ImGuiWindowFlags_NoSavedSettings)
  3782. {
  3783. // User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
  3784. window->Size = window->SizeFull = size;
  3785. }
  3786. else
  3787. {
  3788. // Retrieve settings from .ini file
  3789. // Use SetWindowPos() or SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
  3790. window->PosFloat = ImVec2(60, 60);
  3791. window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
  3792.  
  3793. ImGuiIniData* settings = FindWindowSettings(name);
  3794. if (!settings)
  3795. {
  3796. settings = AddWindowSettings(name);
  3797. }
  3798. else
  3799. {
  3800. window->SetWindowPosAllowFlags &= ~ImGuiSetCond_FirstUseEver;
  3801. window->SetWindowSizeAllowFlags &= ~ImGuiSetCond_FirstUseEver;
  3802. window->SetWindowCollapsedAllowFlags &= ~ImGuiSetCond_FirstUseEver;
  3803. }
  3804.  
  3805. if (settings->Pos.x != FLT_MAX)
  3806. {
  3807. window->PosFloat = settings->Pos;
  3808. window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
  3809. window->Collapsed = settings->Collapsed;
  3810. }
  3811.  
  3812. if (ImLengthSqr(settings->Size) > 0.00001f && !(flags & ImGuiWindowFlags_NoResize))
  3813. size = settings->Size;
  3814. window->Size = window->SizeFull = size;
  3815. }
  3816.  
  3817. if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
  3818. {
  3819. window->AutoFitFramesX = window->AutoFitFramesY = 2;
  3820. window->AutoFitOnlyGrows = false;
  3821. }
  3822. else
  3823. {
  3824. if (window->Size.x <= 0.0f)
  3825. window->AutoFitFramesX = 2;
  3826. if (window->Size.y <= 0.0f)
  3827. window->AutoFitFramesY = 2;
  3828. window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
  3829. }
  3830.  
  3831. if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
  3832. g.Windows.insert(g.Windows.begin(), window); // Quite slow but rare and only once
  3833. else
  3834. g.Windows.push_back(window);
  3835. return window;
  3836. }
  3837.  
  3838. static void ApplySizeFullWithConstraint(ImGuiWindow* window, ImVec2 new_size)
  3839. {
  3840. ImGuiContext& g = *GImGui;
  3841. if (g.SetNextWindowSizeConstraint)
  3842. {
  3843. // Using -1,-1 on either X/Y axis to preserve the current size.
  3844. ImRect cr = g.SetNextWindowSizeConstraintRect;
  3845. new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
  3846. new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
  3847. if (g.SetNextWindowSizeConstraintCallback)
  3848. {
  3849. ImGuiSizeConstraintCallbackData data;
  3850. data.UserData = g.SetNextWindowSizeConstraintCallbackUserData;
  3851. data.Pos = window->Pos;
  3852. data.CurrentSize = window->SizeFull;
  3853. data.DesiredSize = new_size;
  3854. g.SetNextWindowSizeConstraintCallback(&data);
  3855. new_size = data.DesiredSize;
  3856. }
  3857. }
  3858. if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
  3859. new_size = ImMax(new_size, g.Style.WindowMinSize);
  3860. window->SizeFull = new_size;
  3861. }
  3862.  
  3863. // Push a new ImGui window to add widgets to.
  3864. // - 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.
  3865. // - Begin/End can be called multiple times during the frame with the same window name to append content.
  3866. // - '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.
  3867. // - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
  3868. // 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.
  3869. // - 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.
  3870. // - 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.
  3871. // - Passing non-zero 'size' is roughly equivalent to calling SetNextWindowSize(size, ImGuiSetCond_FirstUseEver) prior to calling Begin().
  3872. bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
  3873. {
  3874. return ImGui::Begin(name, p_open, ImVec2(0.f, 0.f), -1.0f, flags);
  3875. }
  3876.  
  3877. bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha, ImGuiWindowFlags flags)
  3878. {
  3879. ImGuiContext& g = *GImGui;
  3880. const ImGuiStyle& style = g.Style;
  3881. IM_ASSERT(name != NULL); // Window name required
  3882. IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame()
  3883. IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
  3884.  
  3885. if (flags & ImGuiWindowFlags_NoInputs)
  3886. flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
  3887.  
  3888. // Find or create
  3889. bool window_is_new = false;
  3890. ImGuiWindow* window = FindWindowByName(name);
  3891. if (!window)
  3892. {
  3893. window = CreateNewWindow(name, size_on_first_use, flags);
  3894. window_is_new = true;
  3895. }
  3896.  
  3897. const int current_frame = ImGui::GetFrameCount();
  3898. const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
  3899. if (first_begin_of_the_frame)
  3900. window->Flags = (ImGuiWindowFlags)flags;
  3901. else
  3902. flags = window->Flags;
  3903.  
  3904. // Add to stack
  3905. ImGuiWindow* parent_window = !g.CurrentWindowStack.empty() ? g.CurrentWindowStack.back() : NULL;
  3906. g.CurrentWindowStack.push_back(window);
  3907. SetCurrentWindow(window);
  3908. CheckStacksSize(window, true);
  3909. IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
  3910.  
  3911. bool window_was_active = (window->LastFrameActive == current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
  3912. if (flags & ImGuiWindowFlags_Popup)
  3913. {
  3914. ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size];
  3915. window_was_active &= (window->PopupId == popup_ref.PopupId);
  3916. window_was_active &= (window == popup_ref.Window);
  3917. popup_ref.Window = window;
  3918. g.CurrentPopupStack.push_back(popup_ref);
  3919. window->PopupId = popup_ref.PopupId;
  3920. }
  3921.  
  3922. const bool window_appearing_after_being_hidden = (window->HiddenFrames == 1);
  3923.  
  3924. // Process SetNextWindow***() calls
  3925. bool window_pos_set_by_api = false, window_size_set_by_api = false;
  3926. if (g.SetNextWindowPosCond)
  3927. {
  3928. 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.
  3929. if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowPosAllowFlags |= ImGuiSetCond_Appearing;
  3930. window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.SetNextWindowPosCond) != 0;
  3931. if (window_pos_set_by_api && ImLengthSqr(g.SetNextWindowPosVal - ImVec2(-FLT_MAX,-FLT_MAX)) < 0.001f)
  3932. {
  3933. window->SetWindowPosCenterWanted = true; // May be processed on the next frame if this is our first frame and we are measuring size
  3934. window->SetWindowPosAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing);
  3935. }
  3936. else
  3937. {
  3938. SetWindowPos(window, g.SetNextWindowPosVal, g.SetNextWindowPosCond);
  3939. }
  3940. window->DC.CursorPos = backup_cursor_pos;
  3941. g.SetNextWindowPosCond = 0;
  3942. }
  3943. if (g.SetNextWindowSizeCond)
  3944. {
  3945. if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowSizeAllowFlags |= ImGuiSetCond_Appearing;
  3946. window_size_set_by_api = (window->SetWindowSizeAllowFlags & g.SetNextWindowSizeCond) != 0;
  3947. SetWindowSize(window, g.SetNextWindowSizeVal, g.SetNextWindowSizeCond);
  3948. g.SetNextWindowSizeCond = 0;
  3949. }
  3950. if (g.SetNextWindowContentSizeCond)
  3951. {
  3952. window->SizeContentsExplicit = g.SetNextWindowContentSizeVal;
  3953. g.SetNextWindowContentSizeCond = 0;
  3954. }
  3955. else if (first_begin_of_the_frame)
  3956. {
  3957. window->SizeContentsExplicit = ImVec2(0.0f, 0.0f);
  3958. }
  3959. if (g.SetNextWindowCollapsedCond)
  3960. {
  3961. if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowCollapsedAllowFlags |= ImGuiSetCond_Appearing;
  3962. SetWindowCollapsed(window, g.SetNextWindowCollapsedVal, g.SetNextWindowCollapsedCond);
  3963. g.SetNextWindowCollapsedCond = 0;
  3964. }
  3965. if (g.SetNextWindowFocus)
  3966. {
  3967. ImGui::SetWindowFocus();
  3968. g.SetNextWindowFocus = false;
  3969. }
  3970.  
  3971. // Update known root window (if we are a child window, otherwise window == window->RootWindow)
  3972. int root_idx, root_non_popup_idx;
  3973. for (root_idx = g.CurrentWindowStack.Size - 1; root_idx > 0; root_idx--)
  3974. if (!(g.CurrentWindowStack[root_idx]->Flags & ImGuiWindowFlags_ChildWindow))
  3975. break;
  3976. for (root_non_popup_idx = root_idx; root_non_popup_idx > 0; root_non_popup_idx--)
  3977. if (!(g.CurrentWindowStack[root_non_popup_idx]->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
  3978. break;
  3979. window->ParentWindow = parent_window;
  3980. window->RootWindow = g.CurrentWindowStack[root_idx];
  3981. window->RootNonPopupWindow = g.CurrentWindowStack[root_non_popup_idx]; // This is merely for displaying the TitleBgActive color.
  3982.  
  3983. // When reusing window again multiple times a frame, just append content (don't need to setup again)
  3984. if (first_begin_of_the_frame)
  3985. {
  3986. window->Active = true;
  3987. window->IndexWithinParent = 0;
  3988. window->BeginCount = 0;
  3989. window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX);
  3990. window->LastFrameActive = current_frame;
  3991. window->IDStack.resize(1);
  3992.  
  3993. // Clear draw list, setup texture, outer clipping rectangle
  3994. window->DrawList->Clear();
  3995. window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
  3996. ImRect fullscreen_rect(GetVisibleRect());
  3997. if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_ComboBox|ImGuiWindowFlags_Popup)))
  3998. PushClipRect(parent_window->ClipRect.Min, parent_window->ClipRect.Max, true);
  3999. else
  4000. PushClipRect(fullscreen_rect.Min, fullscreen_rect.Max, true);
  4001.  
  4002. if (!window_was_active)
  4003. {
  4004. // Popup first latch mouse position, will position itself when it appears next frame
  4005. window->AutoPosLastDirection = -1;
  4006. if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api)
  4007. window->PosFloat = g.IO.MousePos;
  4008. }
  4009.  
  4010. // Collapse window by double-clicking on title bar
  4011. // 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
  4012. if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse))
  4013. {
  4014. ImRect title_bar_rect = window->TitleBarRect();
  4015. if (g.HoveredWindow == window && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0])
  4016. {
  4017. window->Collapsed = !window->Collapsed;
  4018. if (!(flags & ImGuiWindowFlags_NoSavedSettings))
  4019. MarkIniSettingsDirty();
  4020. FocusWindow(window);
  4021. }
  4022. }
  4023. else
  4024. {
  4025. window->Collapsed = false;
  4026. }
  4027.  
  4028. // SIZE
  4029.  
  4030. // Save contents size from last frame for auto-fitting (unless explicitly specified)
  4031. 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));
  4032. 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));
  4033.  
  4034. // Hide popup/tooltip window when first appearing while we measure size (because we recycle them)
  4035. if (window->HiddenFrames > 0)
  4036. window->HiddenFrames--;
  4037. if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0 && !window_was_active)
  4038. {
  4039. window->HiddenFrames = 1;
  4040. if (flags & ImGuiWindowFlags_AlwaysAutoResize)
  4041. {
  4042. if (!window_size_set_by_api)
  4043. window->Size = window->SizeFull = ImVec2(0.f, 0.f);
  4044. window->SizeContents = ImVec2(0.f, 0.f);
  4045. }
  4046. }
  4047.  
  4048. // Lock window padding so that altering the ShowBorders flag for children doesn't have side-effects.
  4049. window->WindowPadding = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_ShowBorders | ImGuiWindowFlags_ComboBox | ImGuiWindowFlags_Popup))) ? ImVec2(0,0) : style.WindowPadding;
  4050.  
  4051. // Calculate auto-fit size
  4052. ImVec2 size_auto_fit;
  4053. if ((flags & ImGuiWindowFlags_Tooltip) != 0)
  4054. {
  4055. // Tooltip always resize. We keep the spacing symmetric on both axises for aesthetic purpose.
  4056. size_auto_fit = window->SizeContents + window->WindowPadding - ImVec2(0.0f, style.ItemSpacing.y);
  4057. }
  4058. else
  4059. {
  4060. size_auto_fit = ImClamp(window->SizeContents + window->WindowPadding, style.WindowMinSize, ImMax(style.WindowMinSize, g.IO.DisplaySize - g.Style.DisplaySafeAreaPadding));
  4061.  
  4062. // 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.
  4063. if (size_auto_fit.x < window->SizeContents.x && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar))
  4064. size_auto_fit.y += style.ScrollbarSize;
  4065. if (size_auto_fit.y < window->SizeContents.y && !(flags & ImGuiWindowFlags_NoScrollbar))
  4066. size_auto_fit.x += style.ScrollbarSize;
  4067. size_auto_fit.y = ImMax(size_auto_fit.y - style.ItemSpacing.y, 0.0f);
  4068. }
  4069.  
  4070. // Handle automatic resize
  4071. if (window->Collapsed)
  4072. {
  4073. // We still process initial auto-fit on collapsed windows to get a window width,
  4074. // But otherwise we don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
  4075. if (window->AutoFitFramesX > 0)
  4076. window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
  4077. if (window->AutoFitFramesY > 0)
  4078. window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
  4079. }
  4080. else
  4081. {
  4082. if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window_size_set_by_api)
  4083. {
  4084. window->SizeFull = size_auto_fit;
  4085. }
  4086. else if ((window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) && !window_size_set_by_api)
  4087. {
  4088. // Auto-fit only grows during the first few frames
  4089. if (window->AutoFitFramesX > 0)
  4090. window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
  4091. if (window->AutoFitFramesY > 0)
  4092. window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
  4093. if (!(flags & ImGuiWindowFlags_NoSavedSettings))
  4094. MarkIniSettingsDirty();
  4095. }
  4096. }
  4097.  
  4098. // Apply minimum/maximum window size constraints and final size
  4099. ApplySizeFullWithConstraint(window, window->SizeFull);
  4100. window->Size = window->Collapsed ? window->TitleBarRect().GetSize() : window->SizeFull;
  4101.  
  4102. // POSITION
  4103.  
  4104. // Position child window
  4105. if (flags & ImGuiWindowFlags_ChildWindow)
  4106. {
  4107. window->IndexWithinParent = parent_window->DC.ChildWindows.Size;
  4108. parent_window->DC.ChildWindows.push_back(window);
  4109. }
  4110. if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup))
  4111. {
  4112. window->Pos = window->PosFloat = parent_window->DC.CursorPos;
  4113. 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().
  4114. }
  4115.  
  4116. bool window_pos_center = false;
  4117. window_pos_center |= (window->SetWindowPosCenterWanted && window->HiddenFrames == 0);
  4118. window_pos_center |= ((flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api && window_appearing_after_being_hidden);
  4119. if (window_pos_center)
  4120. {
  4121. // Center (any sort of window)
  4122. SetWindowPos(window, ImMax(style.DisplaySafeAreaPadding, fullscreen_rect.GetCenter() - window->SizeFull * 0.5f), 0);
  4123. }
  4124. else if (flags & ImGuiWindowFlags_ChildMenu)
  4125. {
  4126. // 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.
  4127. // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
  4128. IM_ASSERT(window_pos_set_by_api);
  4129. 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).
  4130. ImRect rect_to_avoid;
  4131. if (parent_window->DC.MenuBarAppending)
  4132. 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());
  4133. else
  4134. 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);
  4135. window->PosFloat = FindBestPopupWindowPos(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
  4136. }
  4137. else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_appearing_after_being_hidden)
  4138. {
  4139. ImRect rect_to_avoid(window->PosFloat.x - 1, window->PosFloat.y - 1, window->PosFloat.x + 1, window->PosFloat.y + 1);
  4140. window->PosFloat = FindBestPopupWindowPos(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
  4141. }
  4142.  
  4143. // Position tooltip (always follows mouse)
  4144. if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api)
  4145. {
  4146. ImRect rect_to_avoid(g.IO.MousePos.x - 16, g.IO.MousePos.y - 8, g.IO.MousePos.x + 24, g.IO.MousePos.y + 24); // FIXME: Completely hard-coded. Perhaps center on cursor hit-point instead?
  4147. window->PosFloat = FindBestPopupWindowPos(g.IO.MousePos, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
  4148. if (window->AutoPosLastDirection == -1)
  4149. window->PosFloat = g.IO.MousePos + 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.
  4150. }
  4151.  
  4152. // Clamp position so it stays visible
  4153. if (!(flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
  4154. {
  4155. 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.
  4156. {
  4157. ImVec2 padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
  4158. window->PosFloat = ImMax(window->PosFloat + window->Size, padding) - window->Size;
  4159. window->PosFloat = ImMin(window->PosFloat, g.IO.DisplaySize - padding);
  4160. }
  4161. }
  4162. window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
  4163.  
  4164. // Default item width. Make it proportional to window size if window manually resizes
  4165. if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
  4166. window->ItemWidthDefault = (float)(int)(window->Size.x * 0.65f);
  4167. else
  4168. window->ItemWidthDefault = (float)(int)(g.FontSize * 16.0f);
  4169.  
  4170. // Prepare for focus requests
  4171. window->FocusIdxAllRequestCurrent = (window->FocusIdxAllRequestNext == INT_MAX || window->FocusIdxAllCounter == -1) ? INT_MAX : (window->FocusIdxAllRequestNext + (window->FocusIdxAllCounter+1)) % (window->FocusIdxAllCounter+1);
  4172. window->FocusIdxTabRequestCurrent = (window->FocusIdxTabRequestNext == INT_MAX || window->FocusIdxTabCounter == -1) ? INT_MAX : (window->FocusIdxTabRequestNext + (window->FocusIdxTabCounter+1)) % (window->FocusIdxTabCounter+1);
  4173. window->FocusIdxAllCounter = window->FocusIdxTabCounter = -1;
  4174. window->FocusIdxAllRequestNext = window->FocusIdxTabRequestNext = INT_MAX;
  4175.  
  4176. // Apply scrolling
  4177. if (window->ScrollTarget.x < FLT_MAX)
  4178. {
  4179. window->Scroll.x = window->ScrollTarget.x;
  4180. window->ScrollTarget.x = FLT_MAX;
  4181. }
  4182. if (window->ScrollTarget.y < FLT_MAX)
  4183. {
  4184. float center_ratio = window->ScrollTargetCenterRatio.y;
  4185. window->Scroll.y = window->ScrollTarget.y - ((1.0f - center_ratio) * (window->TitleBarHeight() + window->MenuBarHeight())) - (center_ratio * window->SizeFull.y);
  4186. window->ScrollTarget.y = FLT_MAX;
  4187. }
  4188. window->Scroll = ImMax(window->Scroll, ImVec2(0.0f, 0.0f));
  4189. if (!window->Collapsed && !window->SkipItems)
  4190. window->Scroll = ImMin(window->Scroll, ImMax(ImVec2(0.0f, 0.0f), window->SizeContents - window->SizeFull + window->ScrollbarSizes));
  4191.  
  4192. // Modal window darkens what is behind them
  4193. if ((flags & ImGuiWindowFlags_Modal) != 0 && window == GetFrontMostModalRootWindow())
  4194. window->DrawList->AddRectFilled(fullscreen_rect.Min, fullscreen_rect.Max, GetColorU32(ImGuiCol_ModalWindowDarkening, g.ModalWindowDarkeningRatio));
  4195.  
  4196. // Draw window + handle manual resize
  4197. ImRect title_bar_rect = window->TitleBarRect();
  4198. const float window_rounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildWindowRounding : style.WindowRounding;
  4199. if (window->Collapsed)
  4200. {
  4201. // Draw title bar only
  4202. RenderFrame(title_bar_rect.GetTL(), title_bar_rect.GetBR(), GetColorU32(ImGuiCol_TitleBgCollapsed), true, window_rounding);
  4203. }
  4204. else
  4205. {
  4206. ImU32 resize_col = 0;
  4207. const float resize_corner_size = ImMax(g.FontSize * 1.35f, window_rounding + 1.0f + g.FontSize * 0.2f);
  4208. if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && !(flags & ImGuiWindowFlags_NoResize))
  4209. {
  4210. // Manual resize
  4211. const ImVec2 br = window->Rect().GetBR();
  4212. const ImRect resize_rect(br - ImVec2(resize_corner_size * 0.75f, resize_corner_size * 0.75f), br);
  4213. const ImGuiID resize_id = window->GetID("#RESIZE");
  4214. bool hovered, held;
  4215. ButtonBehavior(resize_rect, resize_id, &hovered, &held, ImGuiButtonFlags_FlattenChilds);
  4216. resize_col = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
  4217.  
  4218. if (hovered || held)
  4219. g.MouseCursor = ImGuiMouseCursor_ResizeNWSE;
  4220.  
  4221. if (g.HoveredWindow == window && held && g.IO.MouseDoubleClicked[0])
  4222. {
  4223. // Manual auto-fit when double-clicking
  4224. ApplySizeFullWithConstraint(window, size_auto_fit);
  4225. if (!(flags & ImGuiWindowFlags_NoSavedSettings))
  4226. MarkIniSettingsDirty();
  4227. ClearActiveID();
  4228. }
  4229. else if (held)
  4230. {
  4231. // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
  4232. ApplySizeFullWithConstraint(window, (g.IO.MousePos - g.ActiveIdClickOffset + resize_rect.GetSize()) - window->Pos);
  4233. if (!(flags & ImGuiWindowFlags_NoSavedSettings))
  4234. MarkIniSettingsDirty();
  4235. }
  4236.  
  4237. window->Size = window->SizeFull;
  4238. title_bar_rect = window->TitleBarRect();
  4239. }
  4240.  
  4241. // Scrollbars
  4242. window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->SizeContents.y > window->Size.y + style.ItemSpacing.y) && !(flags & ImGuiWindowFlags_NoScrollbar));
  4243. 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));
  4244. window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
  4245. window->BorderSize = (flags & ImGuiWindowFlags_ShowBorders) ? 1.0f : 0.0f;
  4246.  
  4247. // Window background, Default Alpha
  4248. ImGuiCol bg_color_idx = ImGuiCol_WindowBg;
  4249. if ((flags & ImGuiWindowFlags_ComboBox) != 0)
  4250. bg_color_idx = ImGuiCol_ComboBg;
  4251. else if ((flags & ImGuiWindowFlags_Tooltip) != 0 || (flags & ImGuiWindowFlags_Popup) != 0)
  4252. bg_color_idx = ImGuiCol_PopupBg;
  4253. else if ((flags & ImGuiWindowFlags_ChildWindow) != 0)
  4254. bg_color_idx = ImGuiCol_ChildWindowBg;
  4255. ImVec4 bg_color = style.Colors[bg_color_idx];
  4256. if (bg_alpha >= 0.0f)
  4257. bg_color.w = bg_alpha;
  4258. bg_color.w *= style.Alpha;
  4259. if (bg_color.w > 0.0f)
  4260. window->DrawList->AddRectFilled(window->Pos+ImVec2(0,window->TitleBarHeight()), window->Pos+window->Size, ColorConvertFloat4ToU32(bg_color), window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImGuiCorner_All : ImGuiCorner_BottomLeft|ImGuiCorner_BottomRight);
  4261.  
  4262. // Title bar
  4263. if (!(flags & ImGuiWindowFlags_NoTitleBar))
  4264. window->DrawList->AddRectFilled(title_bar_rect.GetTL(), title_bar_rect.GetBR(), GetColorU32((g.FocusedWindow && window->RootNonPopupWindow == g.FocusedWindow->RootNonPopupWindow) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg), window_rounding, ImGuiCorner_TopLeft|ImGuiCorner_TopRight);
  4265.  
  4266. // Menu bar
  4267. if (flags & ImGuiWindowFlags_MenuBar)
  4268. {
  4269. ImRect menu_bar_rect = window->MenuBarRect();
  4270. if (flags & ImGuiWindowFlags_ShowBorders)
  4271. window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border));
  4272. 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);
  4273. }
  4274.  
  4275. // Scrollbars
  4276. if (window->ScrollbarX)
  4277. Scrollbar(window, true);
  4278. if (window->ScrollbarY)
  4279. Scrollbar(window, false);
  4280.  
  4281. // Render resize grip
  4282. // (after the input handling so we don't have a frame of latency)
  4283. if (!(flags & ImGuiWindowFlags_NoResize))
  4284. {
  4285. const ImVec2 br = window->Rect().GetBR();
  4286. window->DrawList->PathLineTo(br + ImVec2(-resize_corner_size, -window->BorderSize));
  4287. window->DrawList->PathLineTo(br + ImVec2(-window->BorderSize, -resize_corner_size));
  4288. window->DrawList->PathArcToFast(ImVec2(br.x - window_rounding - window->BorderSize, br.y - window_rounding - window->BorderSize), window_rounding, 0, 3);
  4289. window->DrawList->PathFillConvex(resize_col);
  4290. }
  4291.  
  4292. // Borders
  4293. if (flags & ImGuiWindowFlags_ShowBorders)
  4294. {
  4295. window->DrawList->AddRect(window->Pos+ImVec2(1,1), window->Pos+window->Size+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), window_rounding);
  4296. window->DrawList->AddRect(window->Pos, window->Pos+window->Size, GetColorU32(ImGuiCol_Border), window_rounding);
  4297. if (!(flags & ImGuiWindowFlags_NoTitleBar))
  4298. window->DrawList->AddLine(title_bar_rect.GetBL()+ImVec2(1,0), title_bar_rect.GetBR()-ImVec2(1,0), GetColorU32(ImGuiCol_Border));
  4299. }
  4300. }
  4301.  
  4302. // Update ContentsRegionMax. All the variable it depends on are set above in this function.
  4303. window->ContentsRegionRect.Min.x = -window->Scroll.x + window->WindowPadding.x;
  4304. window->ContentsRegionRect.Min.y = -window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight();
  4305. window->ContentsRegionRect.Max.x = -window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x));
  4306. window->ContentsRegionRect.Max.y = -window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y));
  4307.  
  4308. // Setup drawing context
  4309. window->DC.IndentX = 0.0f + window->WindowPadding.x - window->Scroll.x;
  4310. window->DC.GroupOffsetX = 0.0f;
  4311. window->DC.ColumnsOffsetX = 0.0f;
  4312. window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.IndentX + window->DC.ColumnsOffsetX, window->TitleBarHeight() + window->MenuBarHeight() + window->WindowPadding.y - window->Scroll.y);
  4313. window->DC.CursorPos = window->DC.CursorStartPos;
  4314. window->DC.CursorPosPrevLine = window->DC.CursorPos;
  4315. window->DC.CursorMaxPos = window->DC.CursorStartPos;
  4316. window->DC.CurrentLineHeight = window->DC.PrevLineHeight = 0.0f;
  4317. window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
  4318. window->DC.MenuBarAppending = false;
  4319. window->DC.MenuBarOffsetX = ImMax(window->WindowPadding.x, style.ItemSpacing.x);
  4320. window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
  4321. window->DC.ChildWindows.resize(0);
  4322. window->DC.LayoutType = ImGuiLayoutType_Vertical;
  4323. window->DC.ItemWidth = window->ItemWidthDefault;
  4324. window->DC.TextWrapPos = -1.0f; // disabled
  4325. window->DC.AllowKeyboardFocus = true;
  4326. window->DC.ButtonRepeat = false;
  4327. window->DC.ItemWidthStack.resize(0);
  4328. window->DC.AllowKeyboardFocusStack.resize(0);
  4329. window->DC.ButtonRepeatStack.resize(0);
  4330. window->DC.TextWrapPosStack.resize(0);
  4331. window->DC.ColumnsCurrent = 0;
  4332. window->DC.ColumnsCount = 1;
  4333. window->DC.ColumnsStartPosY = window->DC.CursorPos.y;
  4334. window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.ColumnsStartPosY;
  4335. window->DC.TreeDepth = 0;
  4336. window->DC.StateStorage = &window->StateStorage;
  4337. window->DC.GroupStack.resize(0);
  4338. window->DC.ColorEditMode = ImGuiColorEditMode_UserSelect;
  4339. window->MenuColumns.Update(3, style.ItemSpacing.x, !window_was_active);
  4340.  
  4341. if (window->AutoFitFramesX > 0)
  4342. window->AutoFitFramesX--;
  4343. if (window->AutoFitFramesY > 0)
  4344. window->AutoFitFramesY--;
  4345.  
  4346. // New windows appears in front (we need to do that AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
  4347. if (!window_was_active && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
  4348. if (!(flags & (ImGuiWindowFlags_ChildWindow|ImGuiWindowFlags_Tooltip)) || (flags & ImGuiWindowFlags_Popup))
  4349. FocusWindow(window);
  4350.  
  4351. // Title bar
  4352. if (!(flags & ImGuiWindowFlags_NoTitleBar))
  4353. {
  4354. if (p_open != NULL)
  4355. {
  4356. const float pad = 2.0f;
  4357. const float rad = (window->TitleBarHeight() - pad*2.0f) * 0.5f;
  4358. if (CloseButton(window->GetID("#CLOSE"), window->Rect().GetTR() + ImVec2(-pad - rad, pad + rad), rad))
  4359. *p_open = false;
  4360. }
  4361.  
  4362. const ImVec2 text_size = CalcTextSize(name, NULL, true);
  4363. if (!(flags & ImGuiWindowFlags_NoCollapse))
  4364. RenderCollapseTriangle(window->Pos + style.FramePadding, !window->Collapsed, 1.0f);
  4365.  
  4366. ImVec2 text_min = window->Pos;
  4367. ImVec2 text_max = window->Pos + ImVec2(window->Size.x, style.FramePadding.y*2 + text_size.y);
  4368. ImRect clip_rect;
  4369. 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()
  4370. float pad_left = (flags & ImGuiWindowFlags_NoCollapse) == 0 ? (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x) : style.FramePadding.x;
  4371. float pad_right = (p_open != NULL) ? (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x) : style.FramePadding.x;
  4372. if (style.WindowTitleAlign.x > 0.0f) pad_right = ImLerp(pad_right, pad_left, style.WindowTitleAlign.x);
  4373. text_min.x += pad_left;
  4374. text_max.x -= pad_right;
  4375. clip_rect.Min = ImVec2(text_min.x, window->Pos.y);
  4376. RenderTextClipped(text_min, text_max, name, NULL, &text_size, style.WindowTitleAlign, &clip_rect);
  4377. }
  4378.  
  4379. // Save clipped aabb so we can access it in constant-time in FindHoveredWindow()
  4380. window->WindowRectClipped = window->Rect();
  4381. window->WindowRectClipped.Clip(window->ClipRect);
  4382.  
  4383. // Pressing CTRL+C while holding on a window copy its content to the clipboard
  4384. // 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.
  4385. // Maybe we can support CTRL+C on every element?
  4386. /*
  4387. if (g.ActiveId == move_id)
  4388. if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C))
  4389. ImGui::LogToClipboard();
  4390. */
  4391. }
  4392.  
  4393. // Inner clipping rectangle
  4394. // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame
  4395. // Note that if our window is collapsed we will end up with a null clipping rectangle which is the correct behavior.
  4396. const ImRect title_bar_rect = window->TitleBarRect();
  4397. const float border_size = window->BorderSize;
  4398. ImRect clip_rect; // Force round to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
  4399. clip_rect.Min.x = ImFloor(0.5f + title_bar_rect.Min.x + ImMax(border_size, ImFloor(window->WindowPadding.x*0.5f)));
  4400. clip_rect.Min.y = ImFloor(0.5f + title_bar_rect.Max.y + window->MenuBarHeight() + border_size);
  4401. 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)));
  4402. clip_rect.Max.y = ImFloor(0.5f + window->Pos.y + window->Size.y - window->ScrollbarSizes.y - border_size);
  4403. PushClipRect(clip_rect.Min, clip_rect.Max, true);
  4404.  
  4405. // Clear 'accessed' flag last thing
  4406. if (first_begin_of_the_frame)
  4407. window->Accessed = false;
  4408. window->BeginCount++;
  4409. g.SetNextWindowSizeConstraint = false;
  4410.  
  4411. // Child window can be out of sight and have "negative" clip windows.
  4412. // Mark them as collapsed so commands are skipped earlier (we can't manually collapse because they have no title bar).
  4413. if (flags & ImGuiWindowFlags_ChildWindow)
  4414. {
  4415. IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0);
  4416. window->Collapsed = parent_window && parent_window->Collapsed;
  4417.  
  4418. if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
  4419. window->Collapsed |= (window->WindowRectClipped.Min.x >= window->WindowRectClipped.Max.x || window->WindowRectClipped.Min.y >= window->WindowRectClipped.Max.y);
  4420.  
  4421. // We also hide the window from rendering because we've already added its border to the command list.
  4422. // (we could perform the check earlier in the function but it is simpler at this point)
  4423. if (window->Collapsed)
  4424. window->Active = false;
  4425. }
  4426. if (style.Alpha <= 0.0f)
  4427. window->Active = false;
  4428.  
  4429. // Return false if we don't intend to display anything to allow user to perform an early out optimization
  4430. window->SkipItems = (window->Collapsed || !window->Active) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0;
  4431. return !window->SkipItems;
  4432. }
  4433.  
  4434. void ImGui::End()
  4435. {
  4436. ImGuiContext& g = *GImGui;
  4437. ImGuiWindow* window = g.CurrentWindow;
  4438.  
  4439. if (window->DC.ColumnsCount != 1) // close columns set if any is open
  4440. Columns(1, "#CLOSECOLUMNS");
  4441. PopClipRect(); // inner window clip rectangle
  4442.  
  4443. // Stop logging
  4444. if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging
  4445. LogFinish();
  4446.  
  4447. // Pop
  4448. // NB: we don't clear 'window->RootWindow'. The pointer is allowed to live until the next call to Begin().
  4449. g.CurrentWindowStack.pop_back();
  4450. if (window->Flags & ImGuiWindowFlags_Popup)
  4451. g.CurrentPopupStack.pop_back();
  4452. CheckStacksSize(window, false);
  4453. SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back());
  4454. }
  4455.  
  4456. // Vertical scrollbar
  4457. // The entire piece of code below is rather confusing because:
  4458. // - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab)
  4459. // - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar
  4460. // - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal.
  4461. static void Scrollbar(ImGuiWindow* window, bool horizontal)
  4462. {
  4463. ImGuiContext& g = *GImGui;
  4464. const ImGuiStyle& style = g.Style;
  4465. const ImGuiID id = window->GetID(horizontal ? "#SCROLLX" : "#SCROLLY");
  4466.  
  4467. // Render background
  4468. bool other_scrollbar = (horizontal ? window->ScrollbarY : window->ScrollbarX);
  4469. float other_scrollbar_size_w = other_scrollbar ? style.ScrollbarSize : 0.0f;
  4470. const ImRect window_rect = window->Rect();
  4471. const float border_size = window->BorderSize;
  4472. ImRect bb = horizontal
  4473. ? 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)
  4474. : 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);
  4475. if (!horizontal)
  4476. bb.Min.y += window->TitleBarHeight() + ((window->Flags & ImGuiWindowFlags_MenuBar) ? window->MenuBarHeight() : 0.0f);
  4477. if (bb.GetWidth() <= 0.0f || bb.GetHeight() <= 0.0f)
  4478. return;
  4479.  
  4480. float window_rounding = (window->Flags & ImGuiWindowFlags_ChildWindow) ? style.ChildWindowRounding : style.WindowRounding;
  4481. int window_rounding_corners;
  4482. if (horizontal)
  4483. window_rounding_corners = ImGuiCorner_BottomLeft | (other_scrollbar ? 0 : ImGuiCorner_BottomRight);
  4484. else
  4485. window_rounding_corners = (((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImGuiCorner_TopRight : 0) | (other_scrollbar ? 0 : ImGuiCorner_BottomRight);
  4486. window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_ScrollbarBg), window_rounding, window_rounding_corners);
  4487. bb.Reduce(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)));
  4488.  
  4489. // V denote the main axis of the scrollbar
  4490. float scrollbar_size_v = horizontal ? bb.GetWidth() : bb.GetHeight();
  4491. float scroll_v = horizontal ? window->Scroll.x : window->Scroll.y;
  4492. float win_size_avail_v = (horizontal ? window->Size.x : window->Size.y) - other_scrollbar_size_w;
  4493. float win_size_contents_v = horizontal ? window->SizeContents.x : window->SizeContents.y;
  4494.  
  4495. // The grabable box size generally represent the amount visible (vs the total scrollable amount)
  4496. // But we maintain a minimum size in pixel to allow for the user to still aim inside.
  4497. const float grab_h_pixels = ImMin(ImMax(scrollbar_size_v * ImSaturate(win_size_avail_v / ImMax(win_size_contents_v, win_size_avail_v)), style.GrabMinSize), scrollbar_size_v);
  4498. const float grab_h_norm = grab_h_pixels / scrollbar_size_v;
  4499.  
  4500. // Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar().
  4501. bool held = false;
  4502. bool hovered = false;
  4503. const bool previously_held = (g.ActiveId == id);
  4504. ImGui::ButtonBehavior(bb, id, &hovered, &held);
  4505.  
  4506. float scroll_max = ImMax(1.0f, win_size_contents_v - win_size_avail_v);
  4507. float scroll_ratio = ImSaturate(scroll_v / scroll_max);
  4508. float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v;
  4509. if (held && grab_h_norm < 1.0f)
  4510. {
  4511. float scrollbar_pos_v = horizontal ? bb.Min.x : bb.Min.y;
  4512. float mouse_pos_v = horizontal ? g.IO.MousePos.x : g.IO.MousePos.y;
  4513. float* click_delta_to_grab_center_v = horizontal ? &g.ScrollbarClickDeltaToGrabCenter.x : &g.ScrollbarClickDeltaToGrabCenter.y;
  4514.  
  4515. // Click position in scrollbar normalized space (0.0f->1.0f)
  4516. const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v);
  4517. ImGui::SetHoveredID(id);
  4518.  
  4519. bool seek_absolute = false;
  4520. if (!previously_held)
  4521. {
  4522. // On initial click calculate the distance between mouse and the center of the grab
  4523. if (clicked_v_norm >= grab_v_norm && clicked_v_norm <= grab_v_norm + grab_h_norm)
  4524. {
  4525. *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f;
  4526. }
  4527. else
  4528. {
  4529. seek_absolute = true;
  4530. *click_delta_to_grab_center_v = 0.0f;
  4531. }
  4532. }
  4533.  
  4534. // Apply scroll
  4535. // 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
  4536. 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));
  4537. scroll_v = (float)(int)(0.5f + scroll_v_norm * scroll_max);//(win_size_contents_v - win_size_v));
  4538. if (horizontal)
  4539. window->Scroll.x = scroll_v;
  4540. else
  4541. window->Scroll.y = scroll_v;
  4542.  
  4543. // Update values for rendering
  4544. scroll_ratio = ImSaturate(scroll_v / scroll_max);
  4545. grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v;
  4546.  
  4547. // Update distance to grab now that we have seeked and saturated
  4548. if (seek_absolute)
  4549. *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f;
  4550. }
  4551.  
  4552. // Render
  4553. const ImU32 grab_col = ImGui::GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab);
  4554. if (horizontal)
  4555. 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);
  4556. else
  4557. 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);
  4558. }
  4559.  
  4560. // Moving window to front of display (which happens to be back of our sorted list)
  4561. void ImGui::FocusWindow(ImGuiWindow* window)
  4562. {
  4563. ImGuiContext& g = *GImGui;
  4564.  
  4565. // Always mark the window we passed as focused. This is used for keyboard interactions such as tabbing.
  4566. g.FocusedWindow = window;
  4567.  
  4568. // Passing NULL allow to disable keyboard focus
  4569. if (!window)
  4570. return;
  4571.  
  4572. // And move its root window to the top of the pile
  4573. if (window->RootWindow)
  4574. window = window->RootWindow;
  4575.  
  4576. // Steal focus on active widgets
  4577. if (window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement should be unnecessary. Need further testing before removing it..
  4578. if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != window)
  4579. ClearActiveID();
  4580.  
  4581. // Bring to front
  4582. if ((window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) || g.Windows.back() == window)
  4583. return;
  4584. for (int i = 0; i < g.Windows.Size; i++)
  4585. if (g.Windows[i] == window)
  4586. {
  4587. g.Windows.erase(g.Windows.begin() + i);
  4588. break;
  4589. }
  4590. g.Windows.push_back(window);
  4591. }
  4592.  
  4593. void ImGui::PushItemWidth(float item_width)
  4594. {
  4595. ImGuiWindow* window = GetCurrentWindow();
  4596. window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
  4597. window->DC.ItemWidthStack.push_back(window->DC.ItemWidth);
  4598. }
  4599.  
  4600. static void PushMultiItemsWidths(int components, float w_full)
  4601. {
  4602. ImGuiWindow* window = ImGui::GetCurrentWindow();
  4603. const ImGuiStyle& style = GImGui->Style;
  4604. if (w_full <= 0.0f)
  4605. w_full = ImGui::CalcItemWidth();
  4606. const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
  4607. const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
  4608. window->DC.ItemWidthStack.push_back(w_item_last);
  4609. for (int i = 0; i < components-1; i++)
  4610. window->DC.ItemWidthStack.push_back(w_item_one);
  4611. window->DC.ItemWidth = window->DC.ItemWidthStack.back();
  4612. }
  4613.  
  4614. void ImGui::PopItemWidth()
  4615. {
  4616. ImGuiWindow* window = GetCurrentWindow();
  4617. window->DC.ItemWidthStack.pop_back();
  4618. window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back();
  4619. }
  4620.  
  4621. float ImGui::CalcItemWidth()
  4622. {
  4623. ImGuiWindow* window = GetCurrentWindowRead();
  4624. float w = window->DC.ItemWidth;
  4625. if (w < 0.0f)
  4626. {
  4627. // 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.
  4628. float width_to_right_edge = GetContentRegionAvail().x;
  4629. w = ImMax(1.0f, width_to_right_edge + w);
  4630. }
  4631. w = (float)(int)w;
  4632. return w;
  4633. }
  4634.  
  4635. static ImFont* GetDefaultFont()
  4636. {
  4637. ImGuiContext& g = *GImGui;
  4638. return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0];
  4639. }
  4640.  
  4641. static void SetCurrentFont(ImFont* font)
  4642. {
  4643. ImGuiContext& g = *GImGui;
  4644. IM_ASSERT(font && font->IsLoaded());
  4645. IM_ASSERT(font->Scale > 0.0f);
  4646. g.Font = font;
  4647. g.FontBaseSize = g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale;
  4648. g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
  4649. g.FontTexUvWhitePixel = g.Font->ContainerAtlas->TexUvWhitePixel;
  4650. }
  4651.  
  4652. void ImGui::PushFont(ImFont* font)
  4653. {
  4654. ImGuiContext& g = *GImGui;
  4655. if (!font)
  4656. font = GetDefaultFont();
  4657. SetCurrentFont(font);
  4658. g.FontStack.push_back(font);
  4659. g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
  4660. }
  4661.  
  4662. void ImGui::PopFont()
  4663. {
  4664. ImGuiContext& g = *GImGui;
  4665. g.CurrentWindow->DrawList->PopTextureID();
  4666. g.FontStack.pop_back();
  4667. SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
  4668. }
  4669.  
  4670. void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
  4671. {
  4672. ImGuiWindow* window = GetCurrentWindow();
  4673. window->DC.AllowKeyboardFocus = allow_keyboard_focus;
  4674. window->DC.AllowKeyboardFocusStack.push_back(allow_keyboard_focus);
  4675. }
  4676.  
  4677. void ImGui::PopAllowKeyboardFocus()
  4678. {
  4679. ImGuiWindow* window = GetCurrentWindow();
  4680. window->DC.AllowKeyboardFocusStack.pop_back();
  4681. window->DC.AllowKeyboardFocus = window->DC.AllowKeyboardFocusStack.empty() ? true : window->DC.AllowKeyboardFocusStack.back();
  4682. }
  4683.  
  4684. void ImGui::PushButtonRepeat(bool repeat)
  4685. {
  4686. ImGuiWindow* window = GetCurrentWindow();
  4687. window->DC.ButtonRepeat = repeat;
  4688. window->DC.ButtonRepeatStack.push_back(repeat);
  4689. }
  4690.  
  4691. void ImGui::PopButtonRepeat()
  4692. {
  4693. ImGuiWindow* window = GetCurrentWindow();
  4694. window->DC.ButtonRepeatStack.pop_back();
  4695. window->DC.ButtonRepeat = window->DC.ButtonRepeatStack.empty() ? false : window->DC.ButtonRepeatStack.back();
  4696. }
  4697.  
  4698. void ImGui::PushTextWrapPos(float wrap_pos_x)
  4699. {
  4700. ImGuiWindow* window = GetCurrentWindow();
  4701. window->DC.TextWrapPos = wrap_pos_x;
  4702. window->DC.TextWrapPosStack.push_back(wrap_pos_x);
  4703. }
  4704.  
  4705. void ImGui::PopTextWrapPos()
  4706. {
  4707. ImGuiWindow* window = GetCurrentWindow();
  4708. window->DC.TextWrapPosStack.pop_back();
  4709. window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back();
  4710. }
  4711.  
  4712. void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
  4713. {
  4714. ImGuiContext& g = *GImGui;
  4715. ImGuiColMod backup;
  4716. backup.Col = idx;
  4717. backup.BackupValue = g.Style.Colors[idx];
  4718. g.ColorModifiers.push_back(backup);
  4719. g.Style.Colors[idx] = col;
  4720. }
  4721.  
  4722. void ImGui::PopStyleColor(int count)
  4723. {
  4724. ImGuiContext& g = *GImGui;
  4725. while (count > 0)
  4726. {
  4727. ImGuiColMod& backup = g.ColorModifiers.back();
  4728. g.Style.Colors[backup.Col] = backup.BackupValue;
  4729. g.ColorModifiers.pop_back();
  4730. count--;
  4731. }
  4732. }
  4733.  
  4734. struct ImGuiStyleVarInfo
  4735. {
  4736. ImGuiDataType Type;
  4737. ImU32 Offset;
  4738. void* GetVarPtr() const { return (void*)((unsigned char*)&GImGui->Style + Offset); }
  4739. };
  4740.  
  4741. static const ImGuiStyleVarInfo GStyleVarInfo[ImGuiStyleVar_Count_] =
  4742. {
  4743. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) },
  4744. { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) },
  4745. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) },
  4746. { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) },
  4747. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildWindowRounding) },
  4748. { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) },
  4749. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) },
  4750. { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) },
  4751. { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) },
  4752. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) },
  4753. { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) },
  4754. { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) },
  4755. };
  4756.  
  4757. static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)
  4758. {
  4759. IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_Count_);
  4760. return &GStyleVarInfo[idx];
  4761. }
  4762.  
  4763. void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
  4764. {
  4765. const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
  4766. if (var_info->Type == ImGuiDataType_Float)
  4767. {
  4768. float* pvar = (float*)var_info->GetVarPtr();
  4769. GImGui->StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
  4770. *pvar = val;
  4771. return;
  4772. }
  4773. IM_ASSERT(0); // Called function with wrong-type? Variable is not a float.
  4774. }
  4775.  
  4776. void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
  4777. {
  4778. const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
  4779. if (var_info->Type == ImGuiDataType_Float2)
  4780. {
  4781. ImVec2* pvar = (ImVec2*)var_info->GetVarPtr();
  4782. GImGui->StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
  4783. *pvar = val;
  4784. return;
  4785. }
  4786. IM_ASSERT(0); // Called function with wrong-type? Variable is not a ImVec2.
  4787. }
  4788.  
  4789. void ImGui::PopStyleVar(int count)
  4790. {
  4791. ImGuiContext& g = *GImGui;
  4792. while (count > 0)
  4793. {
  4794. ImGuiStyleMod& backup = g.StyleModifiers.back();
  4795. const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx);
  4796. if (info->Type == ImGuiDataType_Float) (*(float*)info->GetVarPtr()) = backup.BackupFloat[0];
  4797. else if (info->Type == ImGuiDataType_Float2) (*(ImVec2*)info->GetVarPtr()) = ImVec2(backup.BackupFloat[0], backup.BackupFloat[1]);
  4798. else if (info->Type == ImGuiDataType_Int) (*(int*)info->GetVarPtr()) = backup.BackupInt[0];
  4799. g.StyleModifiers.pop_back();
  4800. count--;
  4801. }
  4802. }
  4803.  
  4804. const char* ImGui::GetStyleColName(ImGuiCol idx)
  4805. {
  4806. // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
  4807. switch (idx)
  4808. {
  4809. case ImGuiCol_Text: return "Text";
  4810. case ImGuiCol_TextDisabled: return "TextDisabled";
  4811. case ImGuiCol_WindowBg: return "WindowBg";
  4812. case ImGuiCol_ChildWindowBg: return "ChildWindowBg";
  4813. case ImGuiCol_PopupBg: return "PopupBg";
  4814. case ImGuiCol_Border: return "Border";
  4815. case ImGuiCol_BorderShadow: return "BorderShadow";
  4816. case ImGuiCol_FrameBg: return "FrameBg";
  4817. case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
  4818. case ImGuiCol_FrameBgActive: return "FrameBgActive";
  4819. case ImGuiCol_TitleBg: return "TitleBg";
  4820. case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
  4821. case ImGuiCol_TitleBgActive: return "TitleBgActive";
  4822. case ImGuiCol_MenuBarBg: return "MenuBarBg";
  4823. case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
  4824. case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
  4825. case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
  4826. case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
  4827. case ImGuiCol_ComboBg: return "ComboBg";
  4828. case ImGuiCol_CheckMark: return "CheckMark";
  4829. case ImGuiCol_SliderGrab: return "SliderGrab";
  4830. case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
  4831. case ImGuiCol_Button: return "Button";
  4832. case ImGuiCol_ButtonHovered: return "ButtonHovered";
  4833. case ImGuiCol_ButtonActive: return "ButtonActive";
  4834. case ImGuiCol_Header: return "Header";
  4835. case ImGuiCol_HeaderHovered: return "HeaderHovered";
  4836. case ImGuiCol_HeaderActive: return "HeaderActive";
  4837. case ImGuiCol_Column: return "Column";
  4838. case ImGuiCol_ColumnHovered: return "ColumnHovered";
  4839. case ImGuiCol_ColumnActive: return "ColumnActive";
  4840. case ImGuiCol_ResizeGrip: return "ResizeGrip";
  4841. case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
  4842. case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
  4843. case ImGuiCol_CloseButton: return "CloseButton";
  4844. case ImGuiCol_CloseButtonHovered: return "CloseButtonHovered";
  4845. case ImGuiCol_CloseButtonActive: return "CloseButtonActive";
  4846. case ImGuiCol_PlotLines: return "PlotLines";
  4847. case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
  4848. case ImGuiCol_PlotHistogram: return "PlotHistogram";
  4849. case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
  4850. case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
  4851. case ImGuiCol_ModalWindowDarkening: return "ModalWindowDarkening";
  4852. }
  4853. IM_ASSERT(0);
  4854. return "Unknown";
  4855. }
  4856.  
  4857. bool ImGui::IsWindowHovered()
  4858. {
  4859. ImGuiContext& g = *GImGui;
  4860. return g.HoveredWindow == g.CurrentWindow && IsWindowContentHoverable(g.HoveredRootWindow);
  4861. }
  4862.  
  4863. bool ImGui::IsWindowFocused()
  4864. {
  4865. ImGuiContext& g = *GImGui;
  4866. return g.FocusedWindow == g.CurrentWindow;
  4867. }
  4868.  
  4869. bool ImGui::IsRootWindowFocused()
  4870. {
  4871. ImGuiContext& g = *GImGui;
  4872. return g.FocusedWindow == g.CurrentWindow->RootWindow;
  4873. }
  4874.  
  4875. bool ImGui::IsRootWindowOrAnyChildFocused()
  4876. {
  4877. ImGuiContext& g = *GImGui;
  4878. return g.FocusedWindow && g.FocusedWindow->RootWindow == g.CurrentWindow->RootWindow;
  4879. }
  4880.  
  4881. bool ImGui::IsRootWindowOrAnyChildHovered()
  4882. {
  4883. ImGuiContext& g = *GImGui;
  4884. return g.HoveredRootWindow && (g.HoveredRootWindow == g.CurrentWindow->RootWindow) && IsWindowContentHoverable(g.HoveredRootWindow);
  4885. }
  4886.  
  4887. float ImGui::GetWindowWidth()
  4888. {
  4889. ImGuiWindow* window = GImGui->CurrentWindow;
  4890. return window->Size.x;
  4891. }
  4892.  
  4893. float ImGui::GetWindowHeight()
  4894. {
  4895. ImGuiWindow* window = GImGui->CurrentWindow;
  4896. return window->Size.y;
  4897. }
  4898.  
  4899. ImVec2 ImGui::GetWindowPos()
  4900. {
  4901. ImGuiContext& g = *GImGui;
  4902. ImGuiWindow* window = g.CurrentWindow;
  4903. return window->Pos;
  4904. }
  4905.  
  4906. static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y)
  4907. {
  4908. window->DC.CursorMaxPos.y += window->Scroll.y;
  4909. window->Scroll.y = new_scroll_y;
  4910. window->DC.CursorMaxPos.y -= window->Scroll.y;
  4911. }
  4912.  
  4913. static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiSetCond cond)
  4914. {
  4915. // Test condition (NB: bit 0 is always true) and clear flags for next time
  4916. if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
  4917. return;
  4918. window->SetWindowPosAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing);
  4919. window->SetWindowPosCenterWanted = false;
  4920.  
  4921. // Set
  4922. const ImVec2 old_pos = window->Pos;
  4923. window->PosFloat = pos;
  4924. window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
  4925. 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
  4926. window->DC.CursorMaxPos += (window->Pos - old_pos); // And more importantly we need to adjust this so size calculation doesn't get affected.
  4927. }
  4928.  
  4929. void ImGui::SetWindowPos(const ImVec2& pos, ImGuiSetCond cond)
  4930. {
  4931. ImGuiWindow* window = GetCurrentWindowRead();
  4932. SetWindowPos(window, pos, cond);
  4933. }
  4934.  
  4935. void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiSetCond cond)
  4936. {
  4937. if (ImGuiWindow* window = FindWindowByName(name))
  4938. SetWindowPos(window, pos, cond);
  4939. }
  4940.  
  4941. ImVec2 ImGui::GetWindowSize()
  4942. {
  4943. ImGuiWindow* window = GetCurrentWindowRead();
  4944. return window->Size;
  4945. }
  4946.  
  4947. static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiSetCond cond)
  4948. {
  4949. // Test condition (NB: bit 0 is always true) and clear flags for next time
  4950. if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
  4951. return;
  4952. window->SetWindowSizeAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing);
  4953.  
  4954. // Set
  4955. if (size.x > 0.0f)
  4956. {
  4957. window->AutoFitFramesX = 0;
  4958. window->SizeFull.x = size.x;
  4959. }
  4960. else
  4961. {
  4962. window->AutoFitFramesX = 2;
  4963. window->AutoFitOnlyGrows = false;
  4964. }
  4965. if (size.y > 0.0f)
  4966. {
  4967. window->AutoFitFramesY = 0;
  4968. window->SizeFull.y = size.y;
  4969. }
  4970. else
  4971. {
  4972. window->AutoFitFramesY = 2;
  4973. window->AutoFitOnlyGrows = false;
  4974. }
  4975. }
  4976.  
  4977. void ImGui::SetWindowSize(const ImVec2& size, ImGuiSetCond cond)
  4978. {
  4979. SetWindowSize(GImGui->CurrentWindow, size, cond);
  4980. }
  4981.  
  4982. void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiSetCond cond)
  4983. {
  4984. ImGuiWindow* window = FindWindowByName(name);
  4985. if (window)
  4986. SetWindowSize(window, size, cond);
  4987. }
  4988.  
  4989. static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiSetCond cond)
  4990. {
  4991. // Test condition (NB: bit 0 is always true) and clear flags for next time
  4992. if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
  4993. return;
  4994. window->SetWindowCollapsedAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing);
  4995.  
  4996. // Set
  4997. window->Collapsed = collapsed;
  4998. }
  4999.  
  5000. void ImGui::SetWindowCollapsed(bool collapsed, ImGuiSetCond cond)
  5001. {
  5002. SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
  5003. }
  5004.  
  5005. bool ImGui::IsWindowCollapsed()
  5006. {
  5007. return GImGui->CurrentWindow->Collapsed;
  5008. }
  5009.  
  5010. void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiSetCond cond)
  5011. {
  5012. ImGuiWindow* window = FindWindowByName(name);
  5013. if (window)
  5014. SetWindowCollapsed(window, collapsed, cond);
  5015. }
  5016.  
  5017. void ImGui::SetWindowFocus()
  5018. {
  5019. FocusWindow(GImGui->CurrentWindow);
  5020. }
  5021.  
  5022. void ImGui::SetWindowFocus(const char* name)
  5023. {
  5024. if (name)
  5025. {
  5026. if (ImGuiWindow* window = FindWindowByName(name))
  5027. FocusWindow(window);
  5028. }
  5029. else
  5030. {
  5031. FocusWindow(NULL);
  5032. }
  5033. }
  5034.  
  5035. void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiSetCond cond)
  5036. {
  5037. ImGuiContext& g = *GImGui;
  5038. g.SetNextWindowPosVal = pos;
  5039. g.SetNextWindowPosCond = cond ? cond : ImGuiSetCond_Always;
  5040. }
  5041.  
  5042. void ImGui::SetNextWindowPosCenter(ImGuiSetCond cond)
  5043. {
  5044. ImGuiContext& g = *GImGui;
  5045. g.SetNextWindowPosVal = ImVec2(-FLT_MAX, -FLT_MAX);
  5046. g.SetNextWindowPosCond = cond ? cond : ImGuiSetCond_Always;
  5047. }
  5048.  
  5049. void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiSetCond cond)
  5050. {
  5051. ImGuiContext& g = *GImGui;
  5052. g.SetNextWindowSizeVal = size;
  5053. g.SetNextWindowSizeCond = cond ? cond : ImGuiSetCond_Always;
  5054. }
  5055.  
  5056. void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeConstraintCallback custom_callback, void* custom_callback_user_data)
  5057. {
  5058. ImGuiContext& g = *GImGui;
  5059. g.SetNextWindowSizeConstraint = true;
  5060. g.SetNextWindowSizeConstraintRect = ImRect(size_min, size_max);
  5061. g.SetNextWindowSizeConstraintCallback = custom_callback;
  5062. g.SetNextWindowSizeConstraintCallbackUserData = custom_callback_user_data;
  5063. }
  5064.  
  5065. void ImGui::SetNextWindowContentSize(const ImVec2& size)
  5066. {
  5067. ImGuiContext& g = *GImGui;
  5068. g.SetNextWindowContentSizeVal = size;
  5069. g.SetNextWindowContentSizeCond = ImGuiSetCond_Always;
  5070. }
  5071.  
  5072. void ImGui::SetNextWindowContentWidth(float width)
  5073. {
  5074. ImGuiContext& g = *GImGui;
  5075. g.SetNextWindowContentSizeVal = ImVec2(width, g.SetNextWindowContentSizeCond ? g.SetNextWindowContentSizeVal.y : 0.0f);
  5076. g.SetNextWindowContentSizeCond = ImGuiSetCond_Always;
  5077. }
  5078.  
  5079. void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiSetCond cond)
  5080. {
  5081. ImGuiContext& g = *GImGui;
  5082. g.SetNextWindowCollapsedVal = collapsed;
  5083. g.SetNextWindowCollapsedCond = cond ? cond : ImGuiSetCond_Always;
  5084. }
  5085.  
  5086. void ImGui::SetNextWindowFocus()
  5087. {
  5088. ImGuiContext& g = *GImGui;
  5089. g.SetNextWindowFocus = true;
  5090. }
  5091.  
  5092. // In window space (not screen space!)
  5093. ImVec2 ImGui::GetContentRegionMax()
  5094. {
  5095. ImGuiWindow* window = GetCurrentWindowRead();
  5096. ImVec2 mx = window->ContentsRegionRect.Max;
  5097. if (window->DC.ColumnsCount != 1)
  5098. mx.x = GetColumnOffset(window->DC.ColumnsCurrent + 1) - window->WindowPadding.x;
  5099. return mx;
  5100. }
  5101.  
  5102. ImVec2 ImGui::GetContentRegionAvail()
  5103. {
  5104. ImGuiWindow* window = GetCurrentWindowRead();
  5105. return GetContentRegionMax() - (window->DC.CursorPos - window->Pos);
  5106. }
  5107.  
  5108. float ImGui::GetContentRegionAvailWidth()
  5109. {
  5110. return GetContentRegionAvail().x;
  5111. }
  5112.  
  5113. // In window space (not screen space!)
  5114. ImVec2 ImGui::GetWindowContentRegionMin()
  5115. {
  5116. ImGuiWindow* window = GetCurrentWindowRead();
  5117. return window->ContentsRegionRect.Min;
  5118. }
  5119.  
  5120. ImVec2 ImGui::GetWindowContentRegionMax()
  5121. {
  5122. ImGuiWindow* window = GetCurrentWindowRead();
  5123. return window->ContentsRegionRect.Max;
  5124. }
  5125.  
  5126. float ImGui::GetWindowContentRegionWidth()
  5127. {
  5128. ImGuiWindow* window = GetCurrentWindowRead();
  5129. return window->ContentsRegionRect.Max.x - window->ContentsRegionRect.Min.x;
  5130. }
  5131.  
  5132. float ImGui::GetTextLineHeight()
  5133. {
  5134. ImGuiContext& g = *GImGui;
  5135. return g.FontSize;
  5136. }
  5137.  
  5138. float ImGui::GetTextLineHeightWithSpacing()
  5139. {
  5140. ImGuiContext& g = *GImGui;
  5141. return g.FontSize + g.Style.ItemSpacing.y;
  5142. }
  5143.  
  5144. float ImGui::GetItemsLineHeightWithSpacing()
  5145. {
  5146. ImGuiContext& g = *GImGui;
  5147. return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
  5148. }
  5149.  
  5150. ImDrawList* ImGui::GetWindowDrawList()
  5151. {
  5152. ImGuiWindow* window = GetCurrentWindow();
  5153. return window->DrawList;
  5154. }
  5155.  
  5156. ImFont* ImGui::GetFont()
  5157. {
  5158. return GImGui->Font;
  5159. }
  5160.  
  5161. float ImGui::GetFontSize()
  5162. {
  5163. return GImGui->FontSize;
  5164. }
  5165.  
  5166. ImVec2 ImGui::GetFontTexUvWhitePixel()
  5167. {
  5168. return GImGui->FontTexUvWhitePixel;
  5169. }
  5170.  
  5171. void ImGui::SetWindowFontScale(float scale)
  5172. {
  5173. ImGuiContext& g = *GImGui;
  5174. ImGuiWindow* window = GetCurrentWindow();
  5175. window->FontWindowScale = scale;
  5176. g.FontSize = window->CalcFontSize();
  5177. }
  5178.  
  5179. // User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
  5180. // 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'.
  5181. ImVec2 ImGui::GetCursorPos()
  5182. {
  5183. ImGuiWindow* window = GetCurrentWindowRead();
  5184. return window->DC.CursorPos - window->Pos + window->Scroll;
  5185. }
  5186.  
  5187. float ImGui::GetCursorPosX()
  5188. {
  5189. ImGuiWindow* window = GetCurrentWindowRead();
  5190. return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
  5191. }
  5192.  
  5193. float ImGui::GetCursorPosY()
  5194. {
  5195. ImGuiWindow* window = GetCurrentWindowRead();
  5196. return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
  5197. }
  5198.  
  5199. void ImGui::SetCursorPos(const ImVec2& local_pos)
  5200. {
  5201. ImGuiWindow* window = GetCurrentWindow();
  5202. window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
  5203. window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
  5204. }
  5205.  
  5206. void ImGui::SetCursorPosX(float x)
  5207. {
  5208. ImGuiWindow* window = GetCurrentWindow();
  5209. window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
  5210. window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
  5211. }
  5212.  
  5213. void ImGui::SetCursorPosY(float y)
  5214. {
  5215. ImGuiWindow* window = GetCurrentWindow();
  5216. window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
  5217. window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
  5218. }
  5219.  
  5220. ImVec2 ImGui::GetCursorStartPos()
  5221. {
  5222. ImGuiWindow* window = GetCurrentWindowRead();
  5223. return window->DC.CursorStartPos - window->Pos;
  5224. }
  5225.  
  5226. ImVec2 ImGui::GetCursorScreenPos()
  5227. {
  5228. ImGuiWindow* window = GetCurrentWindowRead();
  5229. return window->DC.CursorPos;
  5230. }
  5231.  
  5232. void ImGui::SetCursorScreenPos(const ImVec2& screen_pos)
  5233. {
  5234. ImGuiWindow* window = GetCurrentWindow();
  5235. window->DC.CursorPos = screen_pos;
  5236. window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
  5237. }
  5238.  
  5239. float ImGui::GetScrollX()
  5240. {
  5241. return GImGui->CurrentWindow->Scroll.x;
  5242. }
  5243.  
  5244. float ImGui::GetScrollY()
  5245. {
  5246. return GImGui->CurrentWindow->Scroll.y;
  5247. }
  5248.  
  5249. float ImGui::GetScrollMaxX()
  5250. {
  5251. ImGuiWindow* window = GetCurrentWindowRead();
  5252. return window->SizeContents.x - window->SizeFull.x - window->ScrollbarSizes.x;
  5253. }
  5254.  
  5255. float ImGui::GetScrollMaxY()
  5256. {
  5257. ImGuiWindow* window = GetCurrentWindowRead();
  5258. return window->SizeContents.y - window->SizeFull.y - window->ScrollbarSizes.y;
  5259. }
  5260.  
  5261. void ImGui::SetScrollX(float scroll_x)
  5262. {
  5263. ImGuiWindow* window = GetCurrentWindow();
  5264. window->ScrollTarget.x = scroll_x;
  5265. window->ScrollTargetCenterRatio.x = 0.0f;
  5266. }
  5267.  
  5268. void ImGui::SetScrollY(float scroll_y)
  5269. {
  5270. ImGuiWindow* window = GetCurrentWindow();
  5271. window->ScrollTarget.y = scroll_y + window->TitleBarHeight() + window->MenuBarHeight(); // title bar height canceled out when using ScrollTargetRelY
  5272. window->ScrollTargetCenterRatio.y = 0.0f;
  5273. }
  5274.  
  5275. void ImGui::SetScrollFromPosY(float pos_y, float center_y_ratio)
  5276. {
  5277. // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size
  5278. ImGuiWindow* window = GetCurrentWindow();
  5279. IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
  5280. window->ScrollTarget.y = (float)(int)(pos_y + window->Scroll.y);
  5281. 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)
  5282. window->ScrollTarget.y = 0.0f;
  5283. window->ScrollTargetCenterRatio.y = center_y_ratio;
  5284. }
  5285.  
  5286. // center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
  5287. void ImGui::SetScrollHere(float center_y_ratio)
  5288. {
  5289. ImGuiWindow* window = GetCurrentWindow();
  5290. float target_y = window->DC.CursorPosPrevLine.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.
  5291. SetScrollFromPosY(target_y - window->Pos.y, center_y_ratio);
  5292. }
  5293.  
  5294. void ImGui::SetKeyboardFocusHere(int offset)
  5295. {
  5296. ImGuiWindow* window = GetCurrentWindow();
  5297. window->FocusIdxAllRequestNext = window->FocusIdxAllCounter + 1 + offset;
  5298. window->FocusIdxTabRequestNext = INT_MAX;
  5299. }
  5300.  
  5301. void ImGui::SetStateStorage(ImGuiStorage* tree)
  5302. {
  5303. ImGuiWindow* window = GetCurrentWindow();
  5304. window->DC.StateStorage = tree ? tree : &window->StateStorage;
  5305. }
  5306.  
  5307. ImGuiStorage* ImGui::GetStateStorage()
  5308. {
  5309. ImGuiWindow* window = GetCurrentWindowRead();
  5310. return window->DC.StateStorage;
  5311. }
  5312.  
  5313. void ImGui::TextV(const char* fmt, va_list args)
  5314. {
  5315. ImGuiWindow* window = GetCurrentWindow();
  5316. if (window->SkipItems)
  5317. return;
  5318.  
  5319. ImGuiContext& g = *GImGui;
  5320. const char* text_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
  5321. TextUnformatted(g.TempBuffer, text_end);
  5322. }
  5323.  
  5324. void ImGui::Text(const char* fmt, ...)
  5325. {
  5326. va_list args;
  5327. va_start(args, fmt);
  5328. TextV(fmt, args);
  5329. va_end(args);
  5330. }
  5331.  
  5332. void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args)
  5333. {
  5334. PushStyleColor(ImGuiCol_Text, col);
  5335. TextV(fmt, args);
  5336. PopStyleColor();
  5337. }
  5338.  
  5339. void ImGui::TextColored(const ImVec4& col, const char* fmt, ...)
  5340. {
  5341. va_list args;
  5342. va_start(args, fmt);
  5343. TextColoredV(col, fmt, args);
  5344. va_end(args);
  5345. }
  5346.  
  5347. void ImGui::TextDisabledV(const char* fmt, va_list args)
  5348. {
  5349. PushStyleColor(ImGuiCol_Text, GImGui->Style.Colors[ImGuiCol_TextDisabled]);
  5350. TextV(fmt, args);
  5351. PopStyleColor();
  5352. }
  5353.  
  5354. void ImGui::TextDisabled(const char* fmt, ...)
  5355. {
  5356. va_list args;
  5357. va_start(args, fmt);
  5358. TextDisabledV(fmt, args);
  5359. va_end(args);
  5360. }
  5361.  
  5362. void ImGui::TextWrappedV(const char* fmt, va_list args)
  5363. {
  5364. bool need_wrap = (GImGui->CurrentWindow->DC.TextWrapPos < 0.0f); // Keep existing wrap position is one ia already set
  5365. if (need_wrap) PushTextWrapPos(0.0f);
  5366. TextV(fmt, args);
  5367. if (need_wrap) PopTextWrapPos();
  5368. }
  5369.  
  5370. void ImGui::TextWrapped(const char* fmt, ...)
  5371. {
  5372. va_list args;
  5373. va_start(args, fmt);
  5374. TextWrappedV(fmt, args);
  5375. va_end(args);
  5376. }
  5377.  
  5378. void ImGui::TextUnformatted(const char* text, const char* text_end)
  5379. {
  5380. ImGuiWindow* window = GetCurrentWindow();
  5381. if (window->SkipItems)
  5382. return;
  5383.  
  5384. ImGuiContext& g = *GImGui;
  5385. IM_ASSERT(text != NULL);
  5386. const char* text_begin = text;
  5387. if (text_end == NULL)
  5388. text_end = text + strlen(text); // FIXME-OPT
  5389.  
  5390. const float wrap_pos_x = window->DC.TextWrapPos;
  5391. const bool wrap_enabled = wrap_pos_x >= 0.0f;
  5392. if (text_end - text > 2000 && !wrap_enabled)
  5393. {
  5394. // Long text!
  5395. // Perform manual coarse clipping to optimize for long multi-line text
  5396. // From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled.
  5397. // 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.
  5398. const char* line = text;
  5399. const float line_height = GetTextLineHeight();
  5400. const ImVec2 text_pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrentLineTextBaseOffset);
  5401. const ImRect clip_rect = window->ClipRect;
  5402. ImVec2 text_size(0,0);
  5403.  
  5404. if (text_pos.y <= clip_rect.Max.y)
  5405. {
  5406. ImVec2 pos = text_pos;
  5407.  
  5408. // Lines to skip (can't skip when logging text)
  5409. if (!g.LogEnabled)
  5410. {
  5411. int lines_skippable = (int)((clip_rect.Min.y - text_pos.y) / line_height);
  5412. if (lines_skippable > 0)
  5413. {
  5414. int lines_skipped = 0;
  5415. while (line < text_end && lines_skipped < lines_skippable)
  5416. {
  5417. const char* line_end = strchr(line, '\n');
  5418. if (!line_end)
  5419. line_end = text_end;
  5420. line = line_end + 1;
  5421. lines_skipped++;
  5422. }
  5423. pos.y += lines_skipped * line_height;
  5424. }
  5425. }
  5426.  
  5427. // Lines to render
  5428. if (line < text_end)
  5429. {
  5430. ImRect line_rect(pos, pos + ImVec2(FLT_MAX, line_height));
  5431. while (line < text_end)
  5432. {
  5433. const char* line_end = strchr(line, '\n');
  5434. if (IsClippedEx(line_rect, NULL, false))
  5435. break;
  5436.  
  5437. const ImVec2 line_size = CalcTextSize(line, line_end, false);
  5438. text_size.x = ImMax(text_size.x, line_size.x);
  5439. RenderText(pos, line, line_end, false);
  5440. if (!line_end)
  5441. line_end = text_end;
  5442. line = line_end + 1;
  5443. line_rect.Min.y += line_height;
  5444. line_rect.Max.y += line_height;
  5445. pos.y += line_height;
  5446. }
  5447.  
  5448. // Count remaining lines
  5449. int lines_skipped = 0;
  5450. while (line < text_end)
  5451. {
  5452. const char* line_end = strchr(line, '\n');
  5453. if (!line_end)
  5454. line_end = text_end;
  5455. line = line_end + 1;
  5456. lines_skipped++;
  5457. }
  5458. pos.y += lines_skipped * line_height;
  5459. }
  5460.  
  5461. text_size.y += (pos - text_pos).y;
  5462. }
  5463.  
  5464. ImRect bb(text_pos, text_pos + text_size);
  5465. ItemSize(bb);
  5466. ItemAdd(bb, NULL);
  5467. }
  5468. else
  5469. {
  5470. const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f;
  5471. const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width);
  5472.  
  5473. // Account of baseline offset
  5474. ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrentLineTextBaseOffset);
  5475. ImRect bb(text_pos, text_pos + text_size);
  5476. ItemSize(text_size);
  5477. if (!ItemAdd(bb, NULL))
  5478. return;
  5479.  
  5480. // Render (we don't hide text after ## in this end-user function)
  5481. RenderTextWrapped(bb.Min, text_begin, text_end, wrap_width);
  5482. }
  5483. }
  5484.  
  5485. void ImGui::AlignFirstTextHeightToWidgets()
  5486. {
  5487. ImGuiWindow* window = GetCurrentWindow();
  5488. if (window->SkipItems)
  5489. return;
  5490.  
  5491. // Declare a dummy item size to that upcoming items that are smaller will center-align on the newly expanded line height.
  5492. ImGuiContext& g = *GImGui;
  5493. ItemSize(ImVec2(0, g.FontSize + g.Style.FramePadding.y*2), g.Style.FramePadding.y);
  5494. SameLine(0, 0);
  5495. }
  5496.  
  5497. // Add a label+text combo aligned to other label+value widgets
  5498. void ImGui::LabelTextV(const char* label, const char* fmt, va_list args)
  5499. {
  5500. ImGuiWindow* window = GetCurrentWindow();
  5501. if (window->SkipItems)
  5502. return;
  5503.  
  5504. ImGuiContext& g = *GImGui;
  5505. const ImGuiStyle& style = g.Style;
  5506. const float w = CalcItemWidth();
  5507.  
  5508. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  5509. const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2));
  5510. 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);
  5511. ItemSize(total_bb, style.FramePadding.y);
  5512. if (!ItemAdd(total_bb, NULL))
  5513. return;
  5514.  
  5515. // Render
  5516. const char* value_text_begin = &g.TempBuffer[0];
  5517. const char* value_text_end = value_text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
  5518. RenderTextClipped(value_bb.Min, value_bb.Max, value_text_begin, value_text_end, NULL, ImVec2(0.0f,0.5f));
  5519. if (label_size.x > 0.0f)
  5520. RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label);
  5521. }
  5522.  
  5523. void ImGui::LabelText(const char* label, const char* fmt, ...)
  5524. {
  5525. va_list args;
  5526. va_start(args, fmt);
  5527. LabelTextV(label, fmt, args);
  5528. va_end(args);
  5529. }
  5530.  
  5531. static inline bool IsWindowContentHoverable(ImGuiWindow* window)
  5532. {
  5533. // An active popup disable hovering on other windows (apart from its own children)
  5534. ImGuiContext& g = *GImGui;
  5535. if (ImGuiWindow* focused_window = g.FocusedWindow)
  5536. if (ImGuiWindow* focused_root_window = focused_window->RootWindow)
  5537. if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) != 0 && focused_root_window->WasActive && focused_root_window != window->RootWindow)
  5538. return false;
  5539.  
  5540. return true;
  5541. }
  5542.  
  5543. bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags)
  5544. {
  5545. ImGuiContext& g = *GImGui;
  5546. ImGuiWindow* window = GetCurrentWindow();
  5547.  
  5548. if (flags & ImGuiButtonFlags_Disabled)
  5549. {
  5550. if (out_hovered) *out_hovered = false;
  5551. if (out_held) *out_held = false;
  5552. if (g.ActiveId == id) ClearActiveID();
  5553. return false;
  5554. }
  5555.  
  5556. if ((flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick)) == 0)
  5557. flags |= ImGuiButtonFlags_PressedOnClickRelease;
  5558.  
  5559. bool pressed = false;
  5560. bool hovered = IsHovered(bb, id, (flags & ImGuiButtonFlags_FlattenChilds) != 0);
  5561. if (hovered)
  5562. {
  5563. SetHoveredID(id);
  5564. if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt))
  5565. {
  5566. // | CLICKING | HOLDING with ImGuiButtonFlags_Repeat
  5567. // PressedOnClickRelease | <on release>* | <on repeat> <on repeat> .. (NOT on release) <-- MOST COMMON! (*) only if both click/release were over bounds
  5568. // PressedOnClick | <on click> | <on click> <on repeat> <on repeat> ..
  5569. // PressedOnRelease | <on release> | <on repeat> <on repeat> .. (NOT on release)
  5570. // PressedOnDoubleClick | <on dclick> | <on dclick> <on repeat> <on repeat> ..
  5571. if ((flags & ImGuiButtonFlags_PressedOnClickRelease) && g.IO.MouseClicked[0])
  5572. {
  5573. SetActiveID(id, window); // Hold on ID
  5574. FocusWindow(window);
  5575. g.ActiveIdClickOffset = g.IO.MousePos - bb.Min;
  5576. }
  5577. if (((flags & ImGuiButtonFlags_PressedOnClick) && g.IO.MouseClicked[0]) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDoubleClicked[0]))
  5578. {
  5579. pressed = true;
  5580. ClearActiveID();
  5581. FocusWindow(window);
  5582. }
  5583. if ((flags & ImGuiButtonFlags_PressedOnRelease) && g.IO.MouseReleased[0])
  5584. {
  5585. if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps <on release>
  5586. pressed = true;
  5587. ClearActiveID();
  5588. }
  5589.  
  5590. // 'Repeat' mode acts when held regardless of _PressedOn flags (see table above).
  5591. // Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings.
  5592. if ((flags & ImGuiButtonFlags_Repeat) && g.ActiveId == id && g.IO.MouseDownDuration[0] > 0.0f && IsMouseClicked(0, true))
  5593. pressed = true;
  5594. }
  5595. }
  5596.  
  5597. bool held = false;
  5598. if (g.ActiveId == id)
  5599. {
  5600. if (g.IO.MouseDown[0])
  5601. {
  5602. held = true;
  5603. }
  5604. else
  5605. {
  5606. if (hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease))
  5607. if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps <on release>
  5608. pressed = true;
  5609. ClearActiveID();
  5610. }
  5611. }
  5612.  
  5613. // 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.
  5614. if (hovered && (flags & ImGuiButtonFlags_AllowOverlapMode) && (g.HoveredIdPreviousFrame != id && g.HoveredIdPreviousFrame != 0))
  5615. hovered = pressed = held = false;
  5616.  
  5617. if (out_hovered) *out_hovered = hovered;
  5618. if (out_held) *out_held = held;
  5619.  
  5620. return pressed;
  5621. }
  5622.  
  5623. bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags)
  5624. {
  5625. ImGuiWindow* window = GetCurrentWindow();
  5626. if (window->SkipItems)
  5627. return false;
  5628.  
  5629. ImGuiContext& g = *GImGui;
  5630. const ImGuiStyle& style = g.Style;
  5631. const ImGuiID id = window->GetID(label);
  5632. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  5633.  
  5634. ImVec2 pos = window->DC.CursorPos;
  5635. 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)
  5636. pos.y += window->DC.CurrentLineTextBaseOffset - style.FramePadding.y;
  5637. ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f);
  5638.  
  5639. const ImRect bb(pos, pos + size);
  5640. ItemSize(bb, style.FramePadding.y);
  5641. if (!ItemAdd(bb, &id))
  5642. return false;
  5643.  
  5644. if (window->DC.ButtonRepeat) flags |= ImGuiButtonFlags_Repeat;
  5645. bool hovered, held;
  5646. bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
  5647.  
  5648. // Render
  5649. const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
  5650. RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
  5651. RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb);
  5652.  
  5653. // Automatically close popups
  5654. //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
  5655. // CloseCurrentPopup();
  5656.  
  5657. return pressed;
  5658. }
  5659.  
  5660. bool ImGui::Button(const char* label, const ImVec2& size_arg)
  5661. {
  5662. return ButtonEx(label, size_arg, 0);
  5663. }
  5664.  
  5665. // Small buttons fits within text without additional vertical spacing.
  5666. bool ImGui::SmallButton(const char* label)
  5667. {
  5668. ImGuiContext& g = *GImGui;
  5669. float backup_padding_y = g.Style.FramePadding.y;
  5670. g.Style.FramePadding.y = 0.0f;
  5671. bool pressed = ButtonEx(label, ImVec2(0,0), ImGuiButtonFlags_AlignTextBaseLine);
  5672. g.Style.FramePadding.y = backup_padding_y;
  5673. return pressed;
  5674. }
  5675.  
  5676. // Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack.
  5677. // 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)
  5678. bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg)
  5679. {
  5680. ImGuiWindow* window = GetCurrentWindow();
  5681. if (window->SkipItems)
  5682. return false;
  5683.  
  5684. const ImGuiID id = window->GetID(str_id);
  5685. ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f);
  5686. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
  5687. ItemSize(bb);
  5688. if (!ItemAdd(bb, &id))
  5689. return false;
  5690.  
  5691. bool hovered, held;
  5692. bool pressed = ButtonBehavior(bb, id, &hovered, &held);
  5693.  
  5694. return pressed;
  5695. }
  5696.  
  5697. // Upper-right button to close a window.
  5698. bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos, float radius)
  5699. {
  5700. ImGuiWindow* window = GetCurrentWindow();
  5701.  
  5702. const ImRect bb(pos - ImVec2(radius,radius), pos + ImVec2(radius,radius));
  5703.  
  5704. bool hovered, held;
  5705. bool pressed = ButtonBehavior(bb, id, &hovered, &held);
  5706.  
  5707. // Render
  5708. const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_CloseButtonActive : hovered ? ImGuiCol_CloseButtonHovered : ImGuiCol_CloseButton);
  5709. const ImVec2 center = bb.GetCenter();
  5710. window->DrawList->AddCircleFilled(center, ImMax(2.0f, radius), col, 12);
  5711.  
  5712. const float cross_extent = (radius * 0.7071f) - 1.0f;
  5713. if (hovered)
  5714. {
  5715. window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), GetColorU32(ImGuiCol_Text));
  5716. window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), GetColorU32(ImGuiCol_Text));
  5717. }
  5718.  
  5719. return pressed;
  5720. }
  5721.  
  5722. void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col)
  5723. {
  5724. ImGuiWindow* window = GetCurrentWindow();
  5725. if (window->SkipItems)
  5726. return;
  5727.  
  5728. ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
  5729. if (border_col.w > 0.0f)
  5730. bb.Max += ImVec2(2,2);
  5731. ItemSize(bb);
  5732. if (!ItemAdd(bb, NULL))
  5733. return;
  5734.  
  5735. if (border_col.w > 0.0f)
  5736. {
  5737. window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(border_col), 0.0f);
  5738. window->DrawList->AddImage(user_texture_id, bb.Min+ImVec2(1,1), bb.Max-ImVec2(1,1), uv0, uv1, GetColorU32(tint_col));
  5739. }
  5740. else
  5741. {
  5742. window->DrawList->AddImage(user_texture_id, bb.Min, bb.Max, uv0, uv1, GetColorU32(tint_col));
  5743. }
  5744. }
  5745.  
  5746. // frame_padding < 0: uses FramePadding from style (default)
  5747. // frame_padding = 0: no framing
  5748. // frame_padding > 0: set framing size
  5749. // The color used are the button colors.
  5750. 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)
  5751. {
  5752. ImGuiWindow* window = GetCurrentWindow();
  5753. if (window->SkipItems)
  5754. return false;
  5755.  
  5756. ImGuiContext& g = *GImGui;
  5757. const ImGuiStyle& style = g.Style;
  5758.  
  5759. // Default to using texture ID as ID. User can still push string/integer prefixes.
  5760. // We could hash the size/uv to create a unique ID but that would prevent the user from animating UV.
  5761. PushID((void *)user_texture_id);
  5762. const ImGuiID id = window->GetID("#image");
  5763. PopID();
  5764.  
  5765. const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : style.FramePadding;
  5766. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size + padding*2);
  5767. const ImRect image_bb(window->DC.CursorPos + padding, window->DC.CursorPos + padding + size);
  5768. ItemSize(bb);
  5769. if (!ItemAdd(bb, &id))
  5770. return false;
  5771.  
  5772. bool hovered, held;
  5773. bool pressed = ButtonBehavior(bb, id, &hovered, &held);
  5774.  
  5775. // Render
  5776. const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
  5777. RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, style.FrameRounding));
  5778. if (bg_col.w > 0.0f)
  5779. window->DrawList->AddRectFilled(image_bb.Min, image_bb.Max, GetColorU32(bg_col));
  5780. window->DrawList->AddImage(user_texture_id, image_bb.Min, image_bb.Max, uv0, uv1, GetColorU32(tint_col));
  5781.  
  5782. return pressed;
  5783. }
  5784.  
  5785. // Start logging ImGui output to TTY
  5786. void ImGui::LogToTTY(int max_depth)
  5787. {
  5788. ImGuiContext& g = *GImGui;
  5789. if (g.LogEnabled)
  5790. return;
  5791. ImGuiWindow* window = GetCurrentWindowRead();
  5792.  
  5793. g.LogEnabled = true;
  5794. g.LogFile = stdout;
  5795. g.LogStartDepth = window->DC.TreeDepth;
  5796. if (max_depth >= 0)
  5797. g.LogAutoExpandMaxDepth = max_depth;
  5798. }
  5799.  
  5800. // Start logging ImGui output to given file
  5801. void ImGui::LogToFile(int max_depth, const char* filename)
  5802. {
  5803. ImGuiContext& g = *GImGui;
  5804. if (g.LogEnabled)
  5805. return;
  5806. ImGuiWindow* window = GetCurrentWindowRead();
  5807.  
  5808. if (!filename)
  5809. {
  5810. filename = g.IO.LogFilename;
  5811. if (!filename)
  5812. return;
  5813. }
  5814.  
  5815. g.LogFile = ImFileOpen(filename, "ab");
  5816. if (!g.LogFile)
  5817. {
  5818. IM_ASSERT(g.LogFile != NULL); // Consider this an error
  5819. return;
  5820. }
  5821. g.LogEnabled = true;
  5822. g.LogStartDepth = window->DC.TreeDepth;
  5823. if (max_depth >= 0)
  5824. g.LogAutoExpandMaxDepth = max_depth;
  5825. }
  5826.  
  5827. // Start logging ImGui output to clipboard
  5828. void ImGui::LogToClipboard(int max_depth)
  5829. {
  5830. ImGuiContext& g = *GImGui;
  5831. if (g.LogEnabled)
  5832. return;
  5833. ImGuiWindow* window = GetCurrentWindowRead();
  5834.  
  5835. g.LogEnabled = true;
  5836. g.LogFile = NULL;
  5837. g.LogStartDepth = window->DC.TreeDepth;
  5838. if (max_depth >= 0)
  5839. g.LogAutoExpandMaxDepth = max_depth;
  5840. }
  5841.  
  5842. void ImGui::LogFinish()
  5843. {
  5844. ImGuiContext& g = *GImGui;
  5845. if (!g.LogEnabled)
  5846. return;
  5847.  
  5848. LogText(IM_NEWLINE);
  5849. g.LogEnabled = false;
  5850. if (g.LogFile != NULL)
  5851. {
  5852. if (g.LogFile == stdout)
  5853. fflush(g.LogFile);
  5854. else
  5855. fclose(g.LogFile);
  5856. g.LogFile = NULL;
  5857. }
  5858. if (g.LogClipboard->size() > 1)
  5859. {
  5860. SetClipboardText(g.LogClipboard->begin());
  5861. g.LogClipboard->clear();
  5862. }
  5863. }
  5864.  
  5865. // Helper to display logging buttons
  5866. void ImGui::LogButtons()
  5867. {
  5868. ImGuiContext& g = *GImGui;
  5869.  
  5870. PushID("LogButtons");
  5871. const bool log_to_tty = Button("Log To TTY"); SameLine();
  5872. const bool log_to_file = Button("Log To File"); SameLine();
  5873. const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
  5874. PushItemWidth(80.0f);
  5875. PushAllowKeyboardFocus(false);
  5876. SliderInt("Depth", &g.LogAutoExpandMaxDepth, 0, 9, NULL);
  5877. PopAllowKeyboardFocus();
  5878. PopItemWidth();
  5879. PopID();
  5880.  
  5881. // Start logging at the end of the function so that the buttons don't appear in the log
  5882. if (log_to_tty)
  5883. LogToTTY(g.LogAutoExpandMaxDepth);
  5884. if (log_to_file)
  5885. LogToFile(g.LogAutoExpandMaxDepth, g.IO.LogFilename);
  5886. if (log_to_clipboard)
  5887. LogToClipboard(g.LogAutoExpandMaxDepth);
  5888. }
  5889.  
  5890. bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags)
  5891. {
  5892. if (flags & ImGuiTreeNodeFlags_Leaf)
  5893. return true;
  5894.  
  5895. // We only write to the tree storage if the user clicks (or explicitely use SetNextTreeNode*** functions)
  5896. ImGuiContext& g = *GImGui;
  5897. ImGuiWindow* window = g.CurrentWindow;
  5898. ImGuiStorage* storage = window->DC.StateStorage;
  5899.  
  5900. bool is_open;
  5901. if (g.SetNextTreeNodeOpenCond != 0)
  5902. {
  5903. if (g.SetNextTreeNodeOpenCond & ImGuiSetCond_Always)
  5904. {
  5905. is_open = g.SetNextTreeNodeOpenVal;
  5906. storage->SetInt(id, is_open);
  5907. }
  5908. else
  5909. {
  5910. // We treat ImGuiSetCondition_Once and ImGuiSetCondition_FirstUseEver the same because tree node state are not saved persistently.
  5911. const int stored_value = storage->GetInt(id, -1);
  5912. if (stored_value == -1)
  5913. {
  5914. is_open = g.SetNextTreeNodeOpenVal;
  5915. storage->SetInt(id, is_open);
  5916. }
  5917. else
  5918. {
  5919. is_open = stored_value != 0;
  5920. }
  5921. }
  5922. g.SetNextTreeNodeOpenCond = 0;
  5923. }
  5924. else
  5925. {
  5926. is_open = storage->GetInt(id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0;
  5927. }
  5928.  
  5929. // When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior).
  5930. // NB- If we are above max depth we still allow manually opened nodes to be logged.
  5931. if (g.LogEnabled && !(flags & ImGuiTreeNodeFlags_NoAutoOpenOnLog) && window->DC.TreeDepth < g.LogAutoExpandMaxDepth)
  5932. is_open = true;
  5933.  
  5934. return is_open;
  5935. }
  5936.  
  5937. bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end)
  5938. {
  5939. ImGuiWindow* window = GetCurrentWindow();
  5940. if (window->SkipItems)
  5941. return false;
  5942.  
  5943. ImGuiContext& g = *GImGui;
  5944. const ImGuiStyle& style = g.Style;
  5945. const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0;
  5946. const ImVec2 padding = display_frame ? style.FramePadding : ImVec2(style.FramePadding.x, 0.0f);
  5947.  
  5948. if (!label_end)
  5949. label_end = FindRenderedTextEnd(label);
  5950. const ImVec2 label_size = CalcTextSize(label, label_end, false);
  5951.  
  5952. // We vertically grow up to current line height up the typical widget height.
  5953. const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset - padding.y); // Latch before ItemSize changes it
  5954. const float frame_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2);
  5955. ImRect bb = ImRect(window->DC.CursorPos, ImVec2(window->Pos.x + GetContentRegionMax().x, window->DC.CursorPos.y + frame_height));
  5956. if (display_frame)
  5957. {
  5958. // Framed header expand a little outside the default padding
  5959. bb.Min.x -= (float)(int)(window->WindowPadding.x*0.5f) - 1;
  5960. bb.Max.x += (float)(int)(window->WindowPadding.x*0.5f) - 1;
  5961. }
  5962.  
  5963. const float text_offset_x = (g.FontSize + (display_frame ? padding.x*3 : padding.x*2)); // Collapser arrow width + Spacing
  5964. const float text_width = g.FontSize + (label_size.x > 0.0f ? label_size.x + padding.x*2 : 0.0f); // Include collapser
  5965. ItemSize(ImVec2(text_width, frame_height), text_base_offset_y);
  5966.  
  5967. // For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing
  5968. // (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)
  5969. 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);
  5970. bool is_open = TreeNodeBehaviorIsOpen(id, flags);
  5971. if (!ItemAdd(interact_bb, &id))
  5972. {
  5973. if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
  5974. TreePushRawID(id);
  5975. return is_open;
  5976. }
  5977.  
  5978. // Flags that affects opening behavior:
  5979. // - 0(default) ..................... single-click anywhere to open
  5980. // - OpenOnDoubleClick .............. double-click anywhere to open
  5981. // - OpenOnArrow .................... single-click on arrow to open
  5982. // - OpenOnDoubleClick|OpenOnArrow .. single-click on arrow or double-click anywhere to open
  5983. ImGuiButtonFlags button_flags = ImGuiButtonFlags_NoKeyModifiers | ((flags & ImGuiTreeNodeFlags_AllowOverlapMode) ? ImGuiButtonFlags_AllowOverlapMode : 0);
  5984. if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
  5985. button_flags |= ImGuiButtonFlags_PressedOnDoubleClick | ((flags & ImGuiTreeNodeFlags_OpenOnArrow) ? ImGuiButtonFlags_PressedOnClickRelease : 0);
  5986. bool hovered, held, pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags);
  5987. if (pressed && !(flags & ImGuiTreeNodeFlags_Leaf))
  5988. {
  5989. bool toggled = !(flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick));
  5990. if (flags & ImGuiTreeNodeFlags_OpenOnArrow)
  5991. toggled |= IsMouseHoveringRect(interact_bb.Min, ImVec2(interact_bb.Min.x + text_offset_x, interact_bb.Max.y));
  5992. if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
  5993. toggled |= g.IO.MouseDoubleClicked[0];
  5994. if (toggled)
  5995. {
  5996. is_open = !is_open;
  5997. window->DC.StateStorage->SetInt(id, is_open);
  5998. }
  5999. }
  6000. if (flags & ImGuiTreeNodeFlags_AllowOverlapMode)
  6001. SetItemAllowOverlap();
  6002.  
  6003. // Render
  6004. const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
  6005. const ImVec2 text_pos = bb.Min + ImVec2(text_offset_x, padding.y + text_base_offset_y);
  6006. if (display_frame)
  6007. {
  6008. // Framed type
  6009. RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
  6010. RenderCollapseTriangle(bb.Min + padding + ImVec2(0.0f, text_base_offset_y), is_open, 1.0f);
  6011. if (g.LogEnabled)
  6012. {
  6013. // 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.
  6014. const char log_prefix[] = "\n##";
  6015. const char log_suffix[] = "##";
  6016. LogRenderedText(text_pos, log_prefix, log_prefix+3);
  6017. RenderTextClipped(text_pos, bb.Max, label, label_end, &label_size);
  6018. LogRenderedText(text_pos, log_suffix+1, log_suffix+3);
  6019. }
  6020. else
  6021. {
  6022. RenderTextClipped(text_pos, bb.Max, label, label_end, &label_size);
  6023. }
  6024. }
  6025. else
  6026. {
  6027. // Unframed typed for tree nodes
  6028. if (hovered || (flags & ImGuiTreeNodeFlags_Selected))
  6029. RenderFrame(bb.Min, bb.Max, col, false);
  6030.  
  6031. if (flags & ImGuiTreeNodeFlags_Bullet)
  6032. RenderBullet(bb.Min + ImVec2(text_offset_x * 0.5f, g.FontSize*0.50f + text_base_offset_y));
  6033. else if (!(flags & ImGuiTreeNodeFlags_Leaf))
  6034. RenderCollapseTriangle(bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), is_open, 0.70f);
  6035. if (g.LogEnabled)
  6036. LogRenderedText(text_pos, ">");
  6037. RenderText(text_pos, label, label_end, false);
  6038. }
  6039.  
  6040. if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
  6041. TreePushRawID(id);
  6042. return is_open;
  6043. }
  6044.  
  6045. // CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags_NoTreePushOnOpen flag).
  6046. // 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().
  6047. bool ImGui::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags)
  6048. {
  6049. ImGuiWindow* window = GetCurrentWindow();
  6050. if (window->SkipItems)
  6051. return false;
  6052.  
  6053. return TreeNodeBehavior(window->GetID(label), flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen, label);
  6054. }
  6055.  
  6056. bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags)
  6057. {
  6058. ImGuiWindow* window = GetCurrentWindow();
  6059. if (window->SkipItems)
  6060. return false;
  6061.  
  6062. if (p_open && !*p_open)
  6063. return false;
  6064.  
  6065. ImGuiID id = window->GetID(label);
  6066. bool is_open = TreeNodeBehavior(id, flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen | (p_open ? ImGuiTreeNodeFlags_AllowOverlapMode : 0), label);
  6067. if (p_open)
  6068. {
  6069. // Create a small overlapping close button // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc.
  6070. ImGuiContext& g = *GImGui;
  6071. float button_sz = g.FontSize * 0.5f;
  6072. 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))
  6073. *p_open = false;
  6074. }
  6075.  
  6076. return is_open;
  6077. }
  6078.  
  6079. bool ImGui::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags)
  6080. {
  6081. ImGuiWindow* window = GetCurrentWindow();
  6082. if (window->SkipItems)
  6083. return false;
  6084.  
  6085. return TreeNodeBehavior(window->GetID(label), flags, label, NULL);
  6086. }
  6087.  
  6088. bool ImGui::TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args)
  6089. {
  6090. ImGuiWindow* window = GetCurrentWindow();
  6091. if (window->SkipItems)
  6092. return false;
  6093.  
  6094. ImGuiContext& g = *GImGui;
  6095. const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
  6096. return TreeNodeBehavior(window->GetID(str_id), flags, g.TempBuffer, label_end);
  6097. }
  6098.  
  6099. bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args)
  6100. {
  6101. ImGuiWindow* window = GetCurrentWindow();
  6102. if (window->SkipItems)
  6103. return false;
  6104.  
  6105. ImGuiContext& g = *GImGui;
  6106. const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
  6107. return TreeNodeBehavior(window->GetID(ptr_id), flags, g.TempBuffer, label_end);
  6108. }
  6109.  
  6110. bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args)
  6111. {
  6112. return TreeNodeExV(str_id, 0, fmt, args);
  6113. }
  6114.  
  6115. bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args)
  6116. {
  6117. return TreeNodeExV(ptr_id, 0, fmt, args);
  6118. }
  6119.  
  6120. bool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...)
  6121. {
  6122. va_list args;
  6123. va_start(args, fmt);
  6124. bool is_open = TreeNodeExV(str_id, flags, fmt, args);
  6125. va_end(args);
  6126. return is_open;
  6127. }
  6128.  
  6129. bool ImGui::TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...)
  6130. {
  6131. va_list args;
  6132. va_start(args, fmt);
  6133. bool is_open = TreeNodeExV(ptr_id, flags, fmt, args);
  6134. va_end(args);
  6135. return is_open;
  6136. }
  6137.  
  6138. bool ImGui::TreeNode(const char* str_id, const char* fmt, ...)
  6139. {
  6140. va_list args;
  6141. va_start(args, fmt);
  6142. bool is_open = TreeNodeExV(str_id, 0, fmt, args);
  6143. va_end(args);
  6144. return is_open;
  6145. }
  6146.  
  6147. bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...)
  6148. {
  6149. va_list args;
  6150. va_start(args, fmt);
  6151. bool is_open = TreeNodeExV(ptr_id, 0, fmt, args);
  6152. va_end(args);
  6153. return is_open;
  6154. }
  6155.  
  6156. bool ImGui::TreeNode(const char* label)
  6157. {
  6158. ImGuiWindow* window = GetCurrentWindow();
  6159. if (window->SkipItems)
  6160. return false;
  6161. return TreeNodeBehavior(window->GetID(label), 0, label, NULL);
  6162. }
  6163.  
  6164. void ImGui::TreeAdvanceToLabelPos()
  6165. {
  6166. ImGuiContext& g = *GImGui;
  6167. g.CurrentWindow->DC.CursorPos.x += GetTreeNodeToLabelSpacing();
  6168. }
  6169.  
  6170. // Horizontal distance preceding label when using TreeNode() or Bullet()
  6171. float ImGui::GetTreeNodeToLabelSpacing()
  6172. {
  6173. ImGuiContext& g = *GImGui;
  6174. return g.FontSize + (g.Style.FramePadding.x * 2.0f);
  6175. }
  6176.  
  6177. void ImGui::SetNextTreeNodeOpen(bool is_open, ImGuiSetCond cond)
  6178. {
  6179. ImGuiContext& g = *GImGui;
  6180. g.SetNextTreeNodeOpenVal = is_open;
  6181. g.SetNextTreeNodeOpenCond = cond ? cond : ImGuiSetCond_Always;
  6182. }
  6183.  
  6184. void ImGui::PushID(const char* str_id)
  6185. {
  6186. ImGuiWindow* window = GetCurrentWindow();
  6187. window->IDStack.push_back(window->GetID(str_id));
  6188. }
  6189.  
  6190. void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
  6191. {
  6192. ImGuiWindow* window = GetCurrentWindow();
  6193. window->IDStack.push_back(window->GetID(str_id_begin, str_id_end));
  6194. }
  6195.  
  6196. void ImGui::PushID(const void* ptr_id)
  6197. {
  6198. ImGuiWindow* window = GetCurrentWindow();
  6199. window->IDStack.push_back(window->GetID(ptr_id));
  6200. }
  6201.  
  6202. void ImGui::PushID(int int_id)
  6203. {
  6204. const void* ptr_id = (void*)(intptr_t)int_id;
  6205. ImGuiWindow* window = GetCurrentWindow();
  6206. window->IDStack.push_back(window->GetID(ptr_id));
  6207. }
  6208.  
  6209. void ImGui::PopID()
  6210. {
  6211. ImGuiWindow* window = GetCurrentWindow();
  6212. window->IDStack.pop_back();
  6213. }
  6214.  
  6215. ImGuiID ImGui::GetID(const char* str_id)
  6216. {
  6217. return GImGui->CurrentWindow->GetID(str_id);
  6218. }
  6219.  
  6220. ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
  6221. {
  6222. return GImGui->CurrentWindow->GetID(str_id_begin, str_id_end);
  6223. }
  6224.  
  6225. ImGuiID ImGui::GetID(const void* ptr_id)
  6226. {
  6227. return GImGui->CurrentWindow->GetID(ptr_id);
  6228. }
  6229.  
  6230. void ImGui::Bullet()
  6231. {
  6232. ImGuiWindow* window = GetCurrentWindow();
  6233. if (window->SkipItems)
  6234. return;
  6235.  
  6236. ImGuiContext& g = *GImGui;
  6237. const ImGuiStyle& style = g.Style;
  6238. const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y*2), g.FontSize);
  6239. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height));
  6240. ItemSize(bb);
  6241. if (!ItemAdd(bb, NULL))
  6242. {
  6243. SameLine(0, style.FramePadding.x*2);
  6244. return;
  6245. }
  6246.  
  6247. // Render and stay on same line
  6248. RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f));
  6249. SameLine(0, style.FramePadding.x*2);
  6250. }
  6251.  
  6252. // Text with a little bullet aligned to the typical tree node.
  6253. void ImGui::BulletTextV(const char* fmt, va_list args)
  6254. {
  6255. ImGuiWindow* window = GetCurrentWindow();
  6256. if (window->SkipItems)
  6257. return;
  6258.  
  6259. ImGuiContext& g = *GImGui;
  6260. const ImGuiStyle& style = g.Style;
  6261.  
  6262. const char* text_begin = g.TempBuffer;
  6263. const char* text_end = text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
  6264. const ImVec2 label_size = CalcTextSize(text_begin, text_end, false);
  6265. const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it
  6266. const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y*2), g.FontSize);
  6267. 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
  6268. ItemSize(bb);
  6269. if (!ItemAdd(bb, NULL))
  6270. return;
  6271.  
  6272. // Render
  6273. RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f));
  6274. RenderText(bb.Min+ImVec2(g.FontSize + style.FramePadding.x*2, text_base_offset_y), text_begin, text_end, false);
  6275. }
  6276.  
  6277. void ImGui::BulletText(const char* fmt, ...)
  6278. {
  6279. va_list args;
  6280. va_start(args, fmt);
  6281. BulletTextV(fmt, args);
  6282. va_end(args);
  6283. }
  6284.  
  6285. static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size)
  6286. {
  6287. if (data_type == ImGuiDataType_Int)
  6288. ImFormatString(buf, buf_size, display_format, *(int*)data_ptr);
  6289. else if (data_type == ImGuiDataType_Float)
  6290. ImFormatString(buf, buf_size, display_format, *(float*)data_ptr);
  6291. }
  6292.  
  6293. static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size)
  6294. {
  6295. if (data_type == ImGuiDataType_Int)
  6296. {
  6297. if (decimal_precision < 0)
  6298. ImFormatString(buf, buf_size, "%d", *(int*)data_ptr);
  6299. else
  6300. ImFormatString(buf, buf_size, "%.*d", decimal_precision, *(int*)data_ptr);
  6301. }
  6302. else if (data_type == ImGuiDataType_Float)
  6303. {
  6304. if (decimal_precision < 0)
  6305. 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?
  6306. else
  6307. ImFormatString(buf, buf_size, "%.*f", decimal_precision, *(float*)data_ptr);
  6308. }
  6309. }
  6310.  
  6311. static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2)// Store into value1
  6312. {
  6313. if (data_type == ImGuiDataType_Int)
  6314. {
  6315. if (op == '+')
  6316. *(int*)value1 = *(int*)value1 + *(const int*)value2;
  6317. else if (op == '-')
  6318. *(int*)value1 = *(int*)value1 - *(const int*)value2;
  6319. }
  6320. else if (data_type == ImGuiDataType_Float)
  6321. {
  6322. if (op == '+')
  6323. *(float*)value1 = *(float*)value1 + *(const float*)value2;
  6324. else if (op == '-')
  6325. *(float*)value1 = *(float*)value1 - *(const float*)value2;
  6326. }
  6327. }
  6328.  
  6329. // User can input math operators (e.g. +100) to edit a numerical values.
  6330. static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format)
  6331. {
  6332. while (ImCharIsSpace(*buf))
  6333. buf++;
  6334.  
  6335. // We don't support '-' op because it would conflict with inputing negative value.
  6336. // Instead you can use +-100 to subtract from an existing value
  6337. char op = buf[0];
  6338. if (op == '+' || op == '*' || op == '/')
  6339. {
  6340. buf++;
  6341. while (ImCharIsSpace(*buf))
  6342. buf++;
  6343. }
  6344. else
  6345. {
  6346. op = 0;
  6347. }
  6348. if (!buf[0])
  6349. return false;
  6350.  
  6351. if (data_type == ImGuiDataType_Int)
  6352. {
  6353. if (!scalar_format)
  6354. scalar_format = "%d";
  6355. int* v = (int*)data_ptr;
  6356. const int old_v = *v;
  6357. int arg0 = *v;
  6358. if (op && sscanf(initial_value_buf, scalar_format, &arg0) < 1)
  6359. return false;
  6360.  
  6361. // 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
  6362. float arg1 = 0.0f;
  6363. if (op == '+') { if (sscanf(buf, "%f", &arg1) == 1) *v = (int)(arg0 + arg1); } // Add (use "+-" to subtract)
  6364. else if (op == '*') { if (sscanf(buf, "%f", &arg1) == 1) *v = (int)(arg0 * arg1); } // Multiply
  6365. else if (op == '/') { if (sscanf(buf, "%f", &arg1) == 1 && arg1 != 0.0f) *v = (int)(arg0 / arg1); }// Divide
  6366. else { if (sscanf(buf, scalar_format, &arg0) == 1) *v = arg0; } // Assign constant
  6367. return (old_v != *v);
  6368. }
  6369. else if (data_type == ImGuiDataType_Float)
  6370. {
  6371. // For floats we have to ignore format with precision (e.g. "%.2f") because sscanf doesn't take them in
  6372. scalar_format = "%f";
  6373. float* v = (float*)data_ptr;
  6374. const float old_v = *v;
  6375. float arg0 = *v;
  6376. if (op && sscanf(initial_value_buf, scalar_format, &arg0) < 1)
  6377. return false;
  6378.  
  6379. float arg1 = 0.0f;
  6380. if (sscanf(buf, scalar_format, &arg1) < 1)
  6381. return false;
  6382. if (op == '+') { *v = arg0 + arg1; } // Add (use "+-" to subtract)
  6383. else if (op == '*') { *v = arg0 * arg1; } // Multiply
  6384. else if (op == '/') { if (arg1 != 0.0f) *v = arg0 / arg1; } // Divide
  6385. else { *v = arg1; } // Assign constant
  6386. return (old_v != *v);
  6387. }
  6388.  
  6389. return false;
  6390. }
  6391.  
  6392. // Create text input in place of a slider (when CTRL+Clicking on slider)
  6393. bool ImGui::InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label, ImGuiDataType data_type, void* data_ptr, ImGuiID id, int decimal_precision)
  6394. {
  6395. ImGuiContext& g = *GImGui;
  6396. ImGuiWindow* window = GetCurrentWindow();
  6397.  
  6398. // Our replacement widget will override the focus ID (registered previously to allow for a TAB focus to happen)
  6399. SetActiveID(g.ScalarAsInputTextId, window);
  6400. SetHoveredID(0);
  6401. FocusableItemUnregister(window);
  6402.  
  6403. char buf[32];
  6404. DataTypeFormatString(data_type, data_ptr, decimal_precision, buf, IM_ARRAYSIZE(buf));
  6405. bool text_value_changed = InputTextEx(label, buf, IM_ARRAYSIZE(buf), aabb.GetSize(), ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_AutoSelectAll);
  6406. if (g.ScalarAsInputTextId == 0)
  6407. {
  6408. // First frame
  6409. 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)
  6410. g.ScalarAsInputTextId = g.ActiveId;
  6411. SetHoveredID(id);
  6412. }
  6413. else if (g.ActiveId != g.ScalarAsInputTextId)
  6414. {
  6415. // Release
  6416. g.ScalarAsInputTextId = 0;
  6417. }
  6418. if (text_value_changed)
  6419. return DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, NULL);
  6420. return false;
  6421. }
  6422.  
  6423. // Parse display precision back from the display format string
  6424. int ImGui::ParseFormatPrecision(const char* fmt, int default_precision)
  6425. {
  6426. int precision = default_precision;
  6427. while ((fmt = strchr(fmt, '%')) != NULL)
  6428. {
  6429. fmt++;
  6430. if (fmt[0] == '%') { fmt++; continue; } // Ignore "%%"
  6431. while (*fmt >= '0' && *fmt <= '9')
  6432. fmt++;
  6433. if (*fmt == '.')
  6434. {
  6435. precision = atoi(fmt + 1);
  6436. if (precision < 0 || precision > 10)
  6437. precision = default_precision;
  6438. }
  6439. break;
  6440. }
  6441. return precision;
  6442. }
  6443.  
  6444. float ImGui::RoundScalar(float value, int decimal_precision)
  6445. {
  6446. // Round past decimal precision
  6447. // So when our value is 1.99999 with a precision of 0.001 we'll end up rounding to 2.0
  6448. // FIXME: Investigate better rounding methods
  6449. 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 };
  6450. float min_step = (decimal_precision >= 0 && decimal_precision < 10) ? min_steps[decimal_precision] : powf(10.0f, (float)-decimal_precision);
  6451. bool negative = value < 0.0f;
  6452. value = fabsf(value);
  6453. float remainder = fmodf(value, min_step);
  6454. if (remainder <= min_step*0.5f)
  6455. value -= remainder;
  6456. else
  6457. value += (min_step - remainder);
  6458. return negative ? -value : value;
  6459. }
  6460.  
  6461. static inline float SliderBehaviorCalcRatioFromValue(float v, float v_min, float v_max, float power, float linear_zero_pos)
  6462. {
  6463. if (v_min == v_max)
  6464. return 0.0f;
  6465.  
  6466. const bool is_non_linear = (power < 1.0f-0.00001f) || (power > 1.0f+0.00001f);
  6467. const float v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min);
  6468. if (is_non_linear)
  6469. {
  6470. if (v_clamped < 0.0f)
  6471. {
  6472. const float f = 1.0f - (v_clamped - v_min) / (ImMin(0.0f,v_max) - v_min);
  6473. return (1.0f - powf(f, 1.0f/power)) * linear_zero_pos;
  6474. }
  6475. else
  6476. {
  6477. const float f = (v_clamped - ImMax(0.0f,v_min)) / (v_max - ImMax(0.0f,v_min));
  6478. return linear_zero_pos + powf(f, 1.0f/power) * (1.0f - linear_zero_pos);
  6479. }
  6480. }
  6481.  
  6482. // Linear slider
  6483. return (v_clamped - v_min) / (v_max - v_min);
  6484. }
  6485.  
  6486. bool ImGui::SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, ImGuiSliderFlags flags)
  6487. {
  6488. ImGuiContext& g = *GImGui;
  6489. ImGuiWindow* window = GetCurrentWindow();
  6490. const ImGuiStyle& style = g.Style;
  6491.  
  6492. // Draw frame
  6493. RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
  6494.  
  6495. const bool is_non_linear = (power < 1.0f-0.00001f) || (power > 1.0f+0.00001f);
  6496. const bool is_horizontal = (flags & ImGuiSliderFlags_Vertical) == 0;
  6497.  
  6498. const float grab_padding = 2.0f;
  6499. const float slider_sz = is_horizontal ? (frame_bb.GetWidth() - grab_padding * 2.0f) : (frame_bb.GetHeight() - grab_padding * 2.0f);
  6500. float grab_sz;
  6501. if (decimal_precision > 0)
  6502. grab_sz = ImMin(style.GrabMinSize, slider_sz);
  6503. else
  6504. 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
  6505. const float slider_usable_sz = slider_sz - grab_sz;
  6506. const float slider_usable_pos_min = (is_horizontal ? frame_bb.Min.x : frame_bb.Min.y) + grab_padding + grab_sz*0.5f;
  6507. const float slider_usable_pos_max = (is_horizontal ? frame_bb.Max.x : frame_bb.Max.y) - grab_padding - grab_sz*0.5f;
  6508.  
  6509. // For logarithmic sliders that cross over sign boundary we want the exponential increase to be symmetric around 0.0f
  6510. float linear_zero_pos = 0.0f; // 0.0->1.0f
  6511. if (v_min * v_max < 0.0f)
  6512. {
  6513. // Different sign
  6514. const float linear_dist_min_to_0 = powf(fabsf(0.0f - v_min), 1.0f/power);
  6515. const float linear_dist_max_to_0 = powf(fabsf(v_max - 0.0f), 1.0f/power);
  6516. linear_zero_pos = linear_dist_min_to_0 / (linear_dist_min_to_0+linear_dist_max_to_0);
  6517. }
  6518. else
  6519. {
  6520. // Same sign
  6521. linear_zero_pos = v_min < 0.0f ? 1.0f : 0.0f;
  6522. }
  6523.  
  6524. // Process clicking on the slider
  6525. bool value_changed = false;
  6526. if (g.ActiveId == id)
  6527. {
  6528. if (g.IO.MouseDown[0])
  6529. {
  6530. const float mouse_abs_pos = is_horizontal ? g.IO.MousePos.x : g.IO.MousePos.y;
  6531. float clicked_t = (slider_usable_sz > 0.0f) ? ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f) : 0.0f;
  6532. if (!is_horizontal)
  6533. clicked_t = 1.0f - clicked_t;
  6534.  
  6535. float new_value;
  6536. if (is_non_linear)
  6537. {
  6538. // Account for logarithmic scale on both sides of the zero
  6539. if (clicked_t < linear_zero_pos)
  6540. {
  6541. // Negative: rescale to the negative range before powering
  6542. float a = 1.0f - (clicked_t / linear_zero_pos);
  6543. a = powf(a, power);
  6544. new_value = ImLerp(ImMin(v_max,0.0f), v_min, a);
  6545. }
  6546. else
  6547. {
  6548. // Positive: rescale to the positive range before powering
  6549. float a;
  6550. if (fabsf(linear_zero_pos - 1.0f) > 1.e-6f)
  6551. a = (clicked_t - linear_zero_pos) / (1.0f - linear_zero_pos);
  6552. else
  6553. a = clicked_t;
  6554. a = powf(a, power);
  6555. new_value = ImLerp(ImMax(v_min,0.0f), v_max, a);
  6556. }
  6557. }
  6558. else
  6559. {
  6560. // Linear slider
  6561. new_value = ImLerp(v_min, v_max, clicked_t);
  6562. }
  6563.  
  6564. // Round past decimal precision
  6565. new_value = RoundScalar(new_value, decimal_precision);
  6566. if (*v != new_value)
  6567. {
  6568. *v = new_value;
  6569. value_changed = true;
  6570. }
  6571. }
  6572. else
  6573. {
  6574. ClearActiveID();
  6575. }
  6576. }
  6577.  
  6578. // Calculate slider grab positioning
  6579. float grab_t = SliderBehaviorCalcRatioFromValue(*v, v_min, v_max, power, linear_zero_pos);
  6580.  
  6581. // Draw
  6582. if (!is_horizontal)
  6583. grab_t = 1.0f - grab_t;
  6584. const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t);
  6585. ImRect grab_bb;
  6586. if (is_horizontal)
  6587. 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));
  6588. else
  6589. 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));
  6590. window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding);
  6591.  
  6592. return value_changed;
  6593. }
  6594.  
  6595. // Use power!=1.0 for logarithmic sliders.
  6596. // Adjust display_format to decorate the value with a prefix or a suffix.
  6597. // "%.3f" 1.234
  6598. // "%5.2f secs" 01.23 secs
  6599. // "Gold: %.0f" Gold: 1
  6600. bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format, float power)
  6601. {
  6602. ImGuiWindow* window = GetCurrentWindow();
  6603. if (window->SkipItems)
  6604. return false;
  6605.  
  6606. ImGuiContext& g = *GImGui;
  6607. const ImGuiStyle& style = g.Style;
  6608. const ImGuiID id = window->GetID(label);
  6609. const float w = CalcItemWidth();
  6610.  
  6611. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  6612. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
  6613. 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));
  6614.  
  6615. // NB- we don't call ItemSize() yet because we may turn into a text edit box below
  6616. if (!ItemAdd(total_bb, &id))
  6617. {
  6618. ItemSize(total_bb, style.FramePadding.y);
  6619. return false;
  6620. }
  6621.  
  6622. const bool hovered = IsHovered(frame_bb, id);
  6623. if (hovered)
  6624. SetHoveredID(id);
  6625.  
  6626. if (!display_format)
  6627. display_format = "%.3f";
  6628. int decimal_precision = ParseFormatPrecision(display_format, 3);
  6629.  
  6630. // Tabbing or CTRL-clicking on Slider turns it into an input box
  6631. bool start_text_input = false;
  6632. const bool tab_focus_requested = FocusableItemRegister(window, g.ActiveId == id);
  6633. if (tab_focus_requested || (hovered && g.IO.MouseClicked[0]))
  6634. {
  6635. SetActiveID(id, window);
  6636. FocusWindow(window);
  6637.  
  6638. if (tab_focus_requested || g.IO.KeyCtrl)
  6639. {
  6640. start_text_input = true;
  6641. g.ScalarAsInputTextId = 0;
  6642. }
  6643. }
  6644. if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id))
  6645. return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision);
  6646.  
  6647. ItemSize(total_bb, style.FramePadding.y);
  6648.  
  6649. // Actual slider behavior + render grab
  6650. const bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision);
  6651.  
  6652. // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
  6653. char value_buf[64];
  6654. const char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v);
  6655. RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.5f));
  6656.  
  6657. if (label_size.x > 0.0f)
  6658. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
  6659.  
  6660. return value_changed;
  6661. }
  6662.  
  6663. bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* display_format, float power)
  6664. {
  6665. ImGuiWindow* window = GetCurrentWindow();
  6666. if (window->SkipItems)
  6667. return false;
  6668.  
  6669. ImGuiContext& g = *GImGui;
  6670. const ImGuiStyle& style = g.Style;
  6671. const ImGuiID id = window->GetID(label);
  6672.  
  6673. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  6674. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size);
  6675. 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));
  6676.  
  6677. ItemSize(bb, style.FramePadding.y);
  6678. if (!ItemAdd(frame_bb, &id))
  6679. return false;
  6680.  
  6681. const bool hovered = IsHovered(frame_bb, id);
  6682. if (hovered)
  6683. SetHoveredID(id);
  6684.  
  6685. if (!display_format)
  6686. display_format = "%.3f";
  6687. int decimal_precision = ParseFormatPrecision(display_format, 3);
  6688.  
  6689. if (hovered && g.IO.MouseClicked[0])
  6690. {
  6691. SetActiveID(id, window);
  6692. FocusWindow(window);
  6693. }
  6694.  
  6695. // Actual slider behavior + render grab
  6696. bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision, ImGuiSliderFlags_Vertical);
  6697.  
  6698. // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
  6699. // For the vertical slider we allow centered text to overlap the frame padding
  6700. char value_buf[64];
  6701. char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v);
  6702. 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));
  6703. if (label_size.x > 0.0f)
  6704. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
  6705.  
  6706. return value_changed;
  6707. }
  6708.  
  6709. bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max)
  6710. {
  6711. float v_deg = (*v_rad) * 360.0f / (2*IM_PI);
  6712. bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, "%.0f deg", 1.0f);
  6713. *v_rad = v_deg * (2*IM_PI) / 360.0f;
  6714. return value_changed;
  6715. }
  6716.  
  6717. bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* display_format)
  6718. {
  6719. if (!display_format)
  6720. display_format = "%.0f";
  6721. float v_f = (float)*v;
  6722. bool value_changed = SliderFloat(label, &v_f, (float)v_min, (float)v_max, display_format, 1.0f);
  6723. *v = (int)v_f;
  6724. return value_changed;
  6725. }
  6726.  
  6727. bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* display_format)
  6728. {
  6729. if (!display_format)
  6730. display_format = "%.0f";
  6731. float v_f = (float)*v;
  6732. bool value_changed = VSliderFloat(label, size, &v_f, (float)v_min, (float)v_max, display_format, 1.0f);
  6733. *v = (int)v_f;
  6734. return value_changed;
  6735. }
  6736.  
  6737. // Add multiple sliders on 1 line for compact edition of multiple components
  6738. bool ImGui::SliderFloatN(const char* label, float* v, int components, float v_min, float v_max, const char* display_format, float power)
  6739. {
  6740. ImGuiWindow* window = GetCurrentWindow();
  6741. if (window->SkipItems)
  6742. return false;
  6743.  
  6744. ImGuiContext& g = *GImGui;
  6745. bool value_changed = false;
  6746. BeginGroup();
  6747. PushID(label);
  6748. PushMultiItemsWidths(components);
  6749. for (int i = 0; i < components; i++)
  6750. {
  6751. PushID(i);
  6752. value_changed |= SliderFloat("##v", &v[i], v_min, v_max, display_format, power);
  6753. SameLine(0, g.Style.ItemInnerSpacing.x);
  6754. PopID();
  6755. PopItemWidth();
  6756. }
  6757. PopID();
  6758.  
  6759. TextUnformatted(label, FindRenderedTextEnd(label));
  6760. EndGroup();
  6761.  
  6762. return value_changed;
  6763. }
  6764.  
  6765. bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format, float power)
  6766. {
  6767. return SliderFloatN(label, v, 2, v_min, v_max, display_format, power);
  6768. }
  6769.  
  6770. bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format, float power)
  6771. {
  6772. return SliderFloatN(label, v, 3, v_min, v_max, display_format, power);
  6773. }
  6774.  
  6775. bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* display_format, float power)
  6776. {
  6777. return SliderFloatN(label, v, 4, v_min, v_max, display_format, power);
  6778. }
  6779.  
  6780. bool ImGui::SliderIntN(const char* label, int* v, int components, int v_min, int v_max, const char* display_format)
  6781. {
  6782. ImGuiWindow* window = GetCurrentWindow();
  6783. if (window->SkipItems)
  6784. return false;
  6785.  
  6786. ImGuiContext& g = *GImGui;
  6787. bool value_changed = false;
  6788. BeginGroup();
  6789. PushID(label);
  6790. PushMultiItemsWidths(components);
  6791. for (int i = 0; i < components; i++)
  6792. {
  6793. PushID(i);
  6794. value_changed |= SliderInt("##v", &v[i], v_min, v_max, display_format);
  6795. SameLine(0, g.Style.ItemInnerSpacing.x);
  6796. PopID();
  6797. PopItemWidth();
  6798. }
  6799. PopID();
  6800.  
  6801. TextUnformatted(label, FindRenderedTextEnd(label));
  6802. EndGroup();
  6803.  
  6804. return value_changed;
  6805. }
  6806.  
  6807. bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* display_format)
  6808. {
  6809. return SliderIntN(label, v, 2, v_min, v_max, display_format);
  6810. }
  6811.  
  6812. bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* display_format)
  6813. {
  6814. return SliderIntN(label, v, 3, v_min, v_max, display_format);
  6815. }
  6816.  
  6817. bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* display_format)
  6818. {
  6819. return SliderIntN(label, v, 4, v_min, v_max, display_format);
  6820. }
  6821.  
  6822. 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)
  6823. {
  6824. ImGuiContext& g = *GImGui;
  6825. const ImGuiStyle& style = g.Style;
  6826.  
  6827. // Draw frame
  6828. const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
  6829. RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding);
  6830.  
  6831. bool value_changed = false;
  6832.  
  6833. // Process clicking on the drag
  6834. if (g.ActiveId == id)
  6835. {
  6836. if (g.IO.MouseDown[0])
  6837. {
  6838. if (g.ActiveIdIsJustActivated)
  6839. {
  6840. // Lock current value on click
  6841. g.DragCurrentValue = *v;
  6842. g.DragLastMouseDelta = ImVec2(0.f, 0.f);
  6843. }
  6844.  
  6845. float v_cur = g.DragCurrentValue;
  6846. const ImVec2 mouse_drag_delta = GetMouseDragDelta(0, 1.0f);
  6847. if (fabsf(mouse_drag_delta.x - g.DragLastMouseDelta.x) > 0.0f)
  6848. {
  6849. float speed = v_speed;
  6850. if (speed == 0.0f && (v_max - v_min) != 0.0f && (v_max - v_min) < FLT_MAX)
  6851. speed = (v_max - v_min) * g.DragSpeedDefaultRatio;
  6852. if (g.IO.KeyShift && g.DragSpeedScaleFast >= 0.0f)
  6853. speed = speed * g.DragSpeedScaleFast;
  6854. if (g.IO.KeyAlt && g.DragSpeedScaleSlow >= 0.0f)
  6855. speed = speed * g.DragSpeedScaleSlow;
  6856.  
  6857. float delta = (mouse_drag_delta.x - g.DragLastMouseDelta.x) * speed;
  6858. if (fabsf(power - 1.0f) > 0.001f)
  6859. {
  6860. // Logarithmic curve on both side of 0.0
  6861. float v0_abs = v_cur >= 0.0f ? v_cur : -v_cur;
  6862. float v0_sign = v_cur >= 0.0f ? 1.0f : -1.0f;
  6863. float v1 = powf(v0_abs, 1.0f / power) + (delta * v0_sign);
  6864. float v1_abs = v1 >= 0.0f ? v1 : -v1;
  6865. float v1_sign = v1 >= 0.0f ? 1.0f : -1.0f; // Crossed sign line
  6866. v_cur = powf(v1_abs, power) * v0_sign * v1_sign; // Reapply sign
  6867. }
  6868. else
  6869. {
  6870. v_cur += delta;
  6871. }
  6872. g.DragLastMouseDelta.x = mouse_drag_delta.x;
  6873.  
  6874. // Clamp
  6875. if (v_min < v_max)
  6876. v_cur = ImClamp(v_cur, v_min, v_max);
  6877. g.DragCurrentValue = v_cur;
  6878. }
  6879.  
  6880. // Round to user desired precision, then apply
  6881. v_cur = RoundScalar(v_cur, decimal_precision);
  6882. if (*v != v_cur)
  6883. {
  6884. *v = v_cur;
  6885. value_changed = true;
  6886. }
  6887. }
  6888. else
  6889. {
  6890. ClearActiveID();
  6891. }
  6892. }
  6893.  
  6894. return value_changed;
  6895. }
  6896.  
  6897. bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* display_format, float power)
  6898. {
  6899. ImGuiWindow* window = GetCurrentWindow();
  6900. if (window->SkipItems)
  6901. return false;
  6902.  
  6903. ImGuiContext& g = *GImGui;
  6904. const ImGuiStyle& style = g.Style;
  6905. const ImGuiID id = window->GetID(label);
  6906. const float w = CalcItemWidth();
  6907.  
  6908. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  6909. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
  6910. const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding);
  6911. 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));
  6912.  
  6913. // NB- we don't call ItemSize() yet because we may turn into a text edit box below
  6914. if (!ItemAdd(total_bb, &id))
  6915. {
  6916. ItemSize(total_bb, style.FramePadding.y);
  6917. return false;
  6918. }
  6919.  
  6920. const bool hovered = IsHovered(frame_bb, id);
  6921. if (hovered)
  6922. SetHoveredID(id);
  6923.  
  6924. if (!display_format)
  6925. display_format = "%.3f";
  6926. int decimal_precision = ParseFormatPrecision(display_format, 3);
  6927.  
  6928. // Tabbing or CTRL-clicking on Drag turns it into an input box
  6929. bool start_text_input = false;
  6930. const bool tab_focus_requested = FocusableItemRegister(window, g.ActiveId == id);
  6931. if (tab_focus_requested || (hovered && (g.IO.MouseClicked[0] | g.IO.MouseDoubleClicked[0])))
  6932. {
  6933. SetActiveID(id, window);
  6934. FocusWindow(window);
  6935.  
  6936. if (tab_focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0])
  6937. {
  6938. start_text_input = true;
  6939. g.ScalarAsInputTextId = 0;
  6940. }
  6941. }
  6942. if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id))
  6943. return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision);
  6944.  
  6945. // Actual drag behavior
  6946. ItemSize(total_bb, style.FramePadding.y);
  6947. const bool value_changed = DragBehavior(frame_bb, id, v, v_speed, v_min, v_max, decimal_precision, power);
  6948.  
  6949. // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
  6950. char value_buf[64];
  6951. const char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v);
  6952. RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.5f));
  6953.  
  6954. if (label_size.x > 0.0f)
  6955. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label);
  6956.  
  6957. return value_changed;
  6958. }
  6959.  
  6960. 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)
  6961. {
  6962. ImGuiWindow* window = GetCurrentWindow();
  6963. if (window->SkipItems)
  6964. return false;
  6965.  
  6966. ImGuiContext& g = *GImGui;
  6967. bool value_changed = false;
  6968. BeginGroup();
  6969. PushID(label);
  6970. PushMultiItemsWidths(components);
  6971. for (int i = 0; i < components; i++)
  6972. {
  6973. PushID(i);
  6974. value_changed |= DragFloat("##v", &v[i], v_speed, v_min, v_max, display_format, power);
  6975. SameLine(0, g.Style.ItemInnerSpacing.x);
  6976. PopID();
  6977. PopItemWidth();
  6978. }
  6979. PopID();
  6980.  
  6981. TextUnformatted(label, FindRenderedTextEnd(label));
  6982. EndGroup();
  6983.  
  6984. return value_changed;
  6985. }
  6986.  
  6987. bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* display_format, float power)
  6988. {
  6989. return DragFloatN(label, v, 2, v_speed, v_min, v_max, display_format, power);
  6990. }
  6991.  
  6992. bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* display_format, float power)
  6993. {
  6994. return DragFloatN(label, v, 3, v_speed, v_min, v_max, display_format, power);
  6995. }
  6996.  
  6997. bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* display_format, float power)
  6998. {
  6999. return DragFloatN(label, v, 4, v_speed, v_min, v_max, display_format, power);
  7000. }
  7001.  
  7002. 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)
  7003. {
  7004. ImGuiWindow* window = GetCurrentWindow();
  7005. if (window->SkipItems)
  7006. return false;
  7007.  
  7008. ImGuiContext& g = *GImGui;
  7009. PushID(label);
  7010. BeginGroup();
  7011. PushMultiItemsWidths(2);
  7012.  
  7013. 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);
  7014. PopItemWidth();
  7015. SameLine(0, g.Style.ItemInnerSpacing.x);
  7016. 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);
  7017. PopItemWidth();
  7018. SameLine(0, g.Style.ItemInnerSpacing.x);
  7019.  
  7020. TextUnformatted(label, FindRenderedTextEnd(label));
  7021. EndGroup();
  7022. PopID();
  7023.  
  7024. return value_changed;
  7025. }
  7026.  
  7027. // NB: v_speed is float to allow adjusting the drag speed with more precision
  7028. bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* display_format)
  7029. {
  7030. if (!display_format)
  7031. display_format = "%.0f";
  7032. float v_f = (float)*v;
  7033. bool value_changed = DragFloat(label, &v_f, v_speed, (float)v_min, (float)v_max, display_format);
  7034. *v = (int)v_f;
  7035. return value_changed;
  7036. }
  7037.  
  7038. bool ImGui::DragIntN(const char* label, int* v, int components, float v_speed, int v_min, int v_max, const char* display_format)
  7039. {
  7040. ImGuiWindow* window = GetCurrentWindow();
  7041. if (window->SkipItems)
  7042. return false;
  7043.  
  7044. ImGuiContext& g = *GImGui;
  7045. bool value_changed = false;
  7046. BeginGroup();
  7047. PushID(label);
  7048. PushMultiItemsWidths(components);
  7049. for (int i = 0; i < components; i++)
  7050. {
  7051. PushID(i);
  7052. value_changed |= DragInt("##v", &v[i], v_speed, v_min, v_max, display_format);
  7053. SameLine(0, g.Style.ItemInnerSpacing.x);
  7054. PopID();
  7055. PopItemWidth();
  7056. }
  7057. PopID();
  7058.  
  7059. TextUnformatted(label, FindRenderedTextEnd(label));
  7060. EndGroup();
  7061.  
  7062. return value_changed;
  7063. }
  7064.  
  7065. bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* display_format)
  7066. {
  7067. return DragIntN(label, v, 2, v_speed, v_min, v_max, display_format);
  7068. }
  7069.  
  7070. bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* display_format)
  7071. {
  7072. return DragIntN(label, v, 3, v_speed, v_min, v_max, display_format);
  7073. }
  7074.  
  7075. bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* display_format)
  7076. {
  7077. return DragIntN(label, v, 4, v_speed, v_min, v_max, display_format);
  7078. }
  7079.  
  7080. 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)
  7081. {
  7082. ImGuiWindow* window = GetCurrentWindow();
  7083. if (window->SkipItems)
  7084. return false;
  7085.  
  7086. ImGuiContext& g = *GImGui;
  7087. PushID(label);
  7088. BeginGroup();
  7089. PushMultiItemsWidths(2);
  7090.  
  7091. 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);
  7092. PopItemWidth();
  7093. SameLine(0, g.Style.ItemInnerSpacing.x);
  7094. 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);
  7095. PopItemWidth();
  7096. SameLine(0, g.Style.ItemInnerSpacing.x);
  7097.  
  7098. TextUnformatted(label, FindRenderedTextEnd(label));
  7099. EndGroup();
  7100. PopID();
  7101.  
  7102. return value_changed;
  7103. }
  7104.  
  7105. 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)
  7106. {
  7107. ImGuiWindow* window = GetCurrentWindow();
  7108. if (window->SkipItems)
  7109. return;
  7110.  
  7111. ImGuiContext& g = *GImGui;
  7112. const ImGuiStyle& style = g.Style;
  7113.  
  7114. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  7115. if (graph_size.x == 0.0f)
  7116. graph_size.x = CalcItemWidth();
  7117. if (graph_size.y == 0.0f)
  7118. graph_size.y = label_size.y + (style.FramePadding.y * 2);
  7119.  
  7120. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(graph_size.x, graph_size.y));
  7121. const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding);
  7122. 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));
  7123. ItemSize(total_bb, style.FramePadding.y);
  7124. if (!ItemAdd(total_bb, NULL))
  7125. return;
  7126.  
  7127. // Determine scale from values if not specified
  7128. if (scale_min == FLT_MAX || scale_max == FLT_MAX)
  7129. {
  7130. float v_min = FLT_MAX;
  7131. float v_max = -FLT_MAX;
  7132. for (int i = 0; i < values_count; i++)
  7133. {
  7134. const float v = values_getter(data, i);
  7135. v_min = ImMin(v_min, v);
  7136. v_max = ImMax(v_max, v);
  7137. }
  7138. if (scale_min == FLT_MAX)
  7139. scale_min = v_min;
  7140. if (scale_max == FLT_MAX)
  7141. scale_max = v_max;
  7142. }
  7143.  
  7144. RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
  7145.  
  7146. if (values_count > 0)
  7147. {
  7148. int res_w = ImMin((int)graph_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0);
  7149. int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0);
  7150.  
  7151. // Tooltip on hover
  7152. int v_hovered = -1;
  7153. if (IsHovered(inner_bb, 0))
  7154. {
  7155. const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f);
  7156. const int v_idx = (int)(t * item_count);
  7157. IM_ASSERT(v_idx >= 0 && v_idx < values_count);
  7158.  
  7159. const float v0 = values_getter(data, (v_idx + values_offset) % values_count);
  7160. const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count);
  7161. if (plot_type == ImGuiPlotType_Lines)
  7162. SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx+1, v1);
  7163. else if (plot_type == ImGuiPlotType_Histogram)
  7164. SetTooltip("%d: %8.4g", v_idx, v0);
  7165. v_hovered = v_idx;
  7166. }
  7167.  
  7168. const float t_step = 1.0f / (float)res_w;
  7169.  
  7170. float v0 = values_getter(data, (0 + values_offset) % values_count);
  7171. float t0 = 0.0f;
  7172. ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) / (scale_max - scale_min)) ); // Point in the normalized space of our target rectangle
  7173.  
  7174. const ImU32 col_base = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram);
  7175. const ImU32 col_hovered = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered);
  7176.  
  7177. for (int n = 0; n < res_w; n++)
  7178. {
  7179. const float t1 = t0 + t_step;
  7180. const int v1_idx = (int)(t0 * item_count + 0.5f);
  7181. IM_ASSERT(v1_idx >= 0 && v1_idx < values_count);
  7182. const float v1 = values_getter(data, (v1_idx + values_offset + 1) % values_count);
  7183. const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) / (scale_max - scale_min)) );
  7184.  
  7185. // 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.
  7186. ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0);
  7187. ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, 1.0f));
  7188. if (plot_type == ImGuiPlotType_Lines)
  7189. {
  7190. window->DrawList->AddLine(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base);
  7191. }
  7192. else if (plot_type == ImGuiPlotType_Histogram)
  7193. {
  7194. if (pos1.x >= pos0.x + 2.0f)
  7195. pos1.x -= 1.0f;
  7196. window->DrawList->AddRectFilled(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base);
  7197. }
  7198.  
  7199. t0 = t1;
  7200. tp0 = tp1;
  7201. }
  7202. }
  7203.  
  7204. // Text overlay
  7205. if (overlay_text)
  7206. 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));
  7207.  
  7208. if (label_size.x > 0.0f)
  7209. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label);
  7210. }
  7211.  
  7212. struct ImGuiPlotArrayGetterData
  7213. {
  7214. const float* Values;
  7215. int Stride;
  7216.  
  7217. ImGuiPlotArrayGetterData(const float* values, int stride) { Values = values; Stride = stride; }
  7218. };
  7219.  
  7220. static float Plot_ArrayGetter(void* data, int idx)
  7221. {
  7222. ImGuiPlotArrayGetterData* plot_data = (ImGuiPlotArrayGetterData*)data;
  7223. const float v = *(float*)(void*)((unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride);
  7224. return v;
  7225. }
  7226.  
  7227. 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)
  7228. {
  7229. ImGuiPlotArrayGetterData data(values, stride);
  7230. PlotEx(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
  7231. }
  7232.  
  7233. 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)
  7234. {
  7235. PlotEx(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
  7236. }
  7237.  
  7238. 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)
  7239. {
  7240. ImGuiPlotArrayGetterData data(values, stride);
  7241. PlotEx(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
  7242. }
  7243.  
  7244. 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)
  7245. {
  7246. PlotEx(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
  7247. }
  7248.  
  7249. // size_arg (for each axis) < 0.0f: align to end, 0.0f: auto, > 0.0f: specified size
  7250. void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* overlay)
  7251. {
  7252. ImGuiWindow* window = GetCurrentWindow();
  7253. if (window->SkipItems)
  7254. return;
  7255.  
  7256. ImGuiContext& g = *GImGui;
  7257. const ImGuiStyle& style = g.Style;
  7258.  
  7259. ImVec2 pos = window->DC.CursorPos;
  7260. ImRect bb(pos, pos + CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f));
  7261. ItemSize(bb, style.FramePadding.y);
  7262. if (!ItemAdd(bb, NULL))
  7263. return;
  7264.  
  7265. // Render
  7266. fraction = ImSaturate(fraction);
  7267. RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
  7268. bb.Reduce(ImVec2(window->BorderSize, window->BorderSize));
  7269. const ImVec2 fill_br = ImVec2(ImLerp(bb.Min.x, bb.Max.x, fraction), bb.Max.y);
  7270. RenderFrame(bb.Min, fill_br, GetColorU32(ImGuiCol_PlotHistogram), false, style.FrameRounding);
  7271.  
  7272. // Default displaying the fraction as percentage string, but user can override it
  7273. char overlay_buf[32];
  7274. if (!overlay)
  7275. {
  7276. ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction*100+0.01f);
  7277. overlay = overlay_buf;
  7278. }
  7279.  
  7280. ImVec2 overlay_size = CalcTextSize(overlay, NULL);
  7281. if (overlay_size.x > 0.0f)
  7282. 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);
  7283. }
  7284.  
  7285. bool ImGui::Checkbox(const char* label, bool* v)
  7286. {
  7287. ImGuiWindow* window = GetCurrentWindow();
  7288. if (window->SkipItems)
  7289. return false;
  7290. ImGuiContext& g = *GImGui;
  7291. const ImGuiStyle& style = ImGuiStyle::ImGuiStyle();
  7292. const ImGuiID id = window->GetID(label);
  7293. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  7294. const ImVec2 pading = ImVec2(2, 2);
  7295. const ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.x * 6, label_size.y + style.FramePadding.y / 2));
  7296. ItemSize(check_bb, style.FramePadding.y);
  7297. ImRect total_bb = check_bb;
  7298. if (label_size.x > 0)
  7299. SameLine(0, style.ItemInnerSpacing.x);
  7300. const ImRect text_bb(window->DC.CursorPos + ImVec2(0, style.FramePadding.y), window->DC.CursorPos + ImVec2(0, style.FramePadding.y) + label_size);
  7301. if (label_size.x > 0)
  7302. {
  7303. ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y);
  7304. total_bb = ImRect(ImMin(check_bb.Min, text_bb.Min), ImMax(check_bb.Max, text_bb.Max));
  7305. }
  7306. if (!ItemAdd(total_bb, &id))
  7307. return false;
  7308. bool hovered, held;
  7309. bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
  7310. if (pressed)
  7311. *v = !(*v);
  7312. const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight());
  7313. const float check_sz2 = check_sz / 2;
  7314. const float pad = ImMax(1.0f, (float)(int)(check_sz / 4.f));
  7315. //window->DrawList->AddRectFilled(check_bb.Min+ImVec2(pad,pad), check_bb.Max-ImVec2(pad,pad), GetColorU32(ImGuiCol_CheckMark), style.FrameRounding);
  7316. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2 + 6, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(1.0f, 0.0f, 0.0f, 1.0f)), 12);
  7317. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2 + 5, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(1.0f, 0.0f, 0.0f, 1.0f)), 12);
  7318. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2 + 4, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(1.0f, 0.0f, 0.0f, 1.0f)), 12);
  7319. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2 + 3, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(1.0f, 0.0f, 0.0f, 1.0f)), 12);
  7320. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2 + 2, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(1.0f, 0.0f, 0.0f, 1.0f)), 12);
  7321. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2 + 1, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(1.0f, 0.0f, 0.0f, 1.0f)), 12);
  7322. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(1.0f, 0.0f, 0.0f, 1.0f)), 12);
  7323. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2 - 1, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(1.0f, 0.0f, 0.0f, 1.0f)), 12);
  7324. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2 - 2, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(1.0f, 0.0f, 0.0f, 1.0f)), 12);
  7325. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2 - 3, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(1.0f, 0.0f, 0.0f, 1.0f)), 12);
  7326. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2 - 4, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(1.0f, 0.0f, 0.0f, 1.0f)), 12);
  7327. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2 - 5, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(1.0f, 0.0f, 0.0f, 1.0f)), 12);
  7328. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2 - 6, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(1.0f, 1.0f, 1.0f, 1.0f)), 12);
  7329. if (*v)//от исовка галочки
  7330. {
  7331. //window->DrawList->AddRectFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2, check_bb.Min.y), check_bb.Max, GetColorU32(ImVec4(0.34f, 1.0f, 0.54f, 1.0f)), 0);
  7332. //window->DrawList->AddRectFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2, check_bb.Min.y), check_bb.Max, GetColorU32(ImVec4(0.34f, 1.0f, 0.54f, 1.0f)), 0);
  7333.  
  7334. //Ikfakof, [13.10.17 20:37]
  7335. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2 + 6, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(0.0f, 1.0f, 0.0f, 1.0f)), 12);
  7336. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2 + 5, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(0.0f, 1.0f, 0.0f, 1.0f)), 12);
  7337. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2 + 4, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(0.0f, 1.0f, 0.0f, 1.0f)), 12);
  7338. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2 + 3, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(0.0f, 1.0f, 0.0f, 1.0f)), 12);
  7339. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2 + 2, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(0.0f, 1.0f, 0.0f, 1.0f)), 12);
  7340. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2 + 1, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(0.0f, 1.0f, 0.0f, 1.0f)), 12);
  7341. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(0.0f, 1.0f, 0.0f, 1.0f)), 12);
  7342. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2 - 1, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(0.0f, 1.0f, 0.0f, 1.0f)), 12);
  7343. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2 - 2, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(0.0f, 1.0f, 0.0f, 1.0f)), 12);
  7344. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2 - 3, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(0.0f, 1.0f, 0.0f, 1.0f)), 12);
  7345. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2 - 4, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(0.0f, 1.0f, 0.0f, 1.0f)), 12);
  7346. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2 - 5, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(0.0f, 1.0f, 0.0f, 1.0f)), 12);
  7347. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2 - 6, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(0.0f, 1.0f, 0.0f, 1.0f)), 12);
  7348. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2 + 6, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(1.0f, 1.0f, 1.0f, 1.0f)), 12);
  7349. }
  7350. else
  7351. {
  7352. window->DrawList->AddCircleFilled(ImVec2(check_bb.Min.x + (check_bb.Max.x - check_bb.Min.x) / 2 - 6, check_bb.Min.y + 9), 7, GetColorU32(ImVec4(1.0f, 1.0f, 1.0f, 1.0f)), 12);
  7353. }
  7354. if (label_size.x > 0.0f)
  7355. RenderText(text_bb.GetTL(), label);
  7356. return pressed;
  7357. }
  7358.  
  7359. bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value)
  7360. {
  7361. bool v = ((*flags & flags_value) == flags_value);
  7362. bool pressed = Checkbox(label, &v);
  7363. if (pressed)
  7364. {
  7365. if (v)
  7366. *flags |= flags_value;
  7367. else
  7368. *flags &= ~flags_value;
  7369. }
  7370.  
  7371. return pressed;
  7372. }
  7373.  
  7374. bool ImGui::RadioButton(const char* label, bool active)
  7375. {
  7376. ImGuiWindow* window = GetCurrentWindow();
  7377. if (window->SkipItems)
  7378. return false;
  7379.  
  7380. ImGuiContext& g = *GImGui;
  7381. const ImGuiStyle& style = g.Style;
  7382. const ImGuiID id = window->GetID(label);
  7383. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  7384.  
  7385. 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));
  7386. ItemSize(check_bb, style.FramePadding.y);
  7387.  
  7388. ImRect total_bb = check_bb;
  7389. if (label_size.x > 0)
  7390. SameLine(0, style.ItemInnerSpacing.x);
  7391. const ImRect text_bb(window->DC.CursorPos + ImVec2(0, style.FramePadding.y), window->DC.CursorPos + ImVec2(0, style.FramePadding.y) + label_size);
  7392. if (label_size.x > 0)
  7393. {
  7394. ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y);
  7395. total_bb.Add(text_bb);
  7396. }
  7397.  
  7398. if (!ItemAdd(total_bb, &id))
  7399. return false;
  7400.  
  7401. ImVec2 center = check_bb.GetCenter();
  7402. center.x = (float)(int)center.x + 0.5f;
  7403. center.y = (float)(int)center.y + 0.5f;
  7404. const float radius = check_bb.GetHeight() * 0.5f;
  7405.  
  7406. bool hovered, held;
  7407. bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
  7408.  
  7409. window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16);
  7410. if (active)
  7411. {
  7412. const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight());
  7413. const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f));
  7414. window->DrawList->AddCircleFilled(center, radius-pad, GetColorU32(ImGuiCol_CheckMark), 16);
  7415. }
  7416.  
  7417. if (window->Flags & ImGuiWindowFlags_ShowBorders)
  7418. {
  7419. window->DrawList->AddCircle(center+ImVec2(1,1), radius, GetColorU32(ImGuiCol_BorderShadow), 16);
  7420. window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), 16);
  7421. }
  7422.  
  7423. if (g.LogEnabled)
  7424. LogRenderedText(text_bb.GetTL(), active ? "(x)" : "( )");
  7425. if (label_size.x > 0.0f)
  7426. RenderText(text_bb.GetTL(), label);
  7427.  
  7428. return pressed;
  7429. }
  7430.  
  7431. bool ImGui::RadioButton(const char* label, int* v, int v_button)
  7432. {
  7433. const bool pressed = RadioButton(label, *v == v_button);
  7434. if (pressed)
  7435. {
  7436. *v = v_button;
  7437. }
  7438. return pressed;
  7439. }
  7440.  
  7441. static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end)
  7442. {
  7443. int line_count = 0;
  7444. const char* s = text_begin;
  7445. while (char c = *s++) // We are only matching for \n so we can ignore UTF-8 decoding
  7446. if (c == '\n')
  7447. line_count++;
  7448. s--;
  7449. if (s[0] != '\n' && s[0] != '\r')
  7450. line_count++;
  7451. *out_text_end = s;
  7452. return line_count;
  7453. }
  7454.  
  7455. static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining, ImVec2* out_offset, bool stop_on_new_line)
  7456. {
  7457. ImFont* font = GImGui->Font;
  7458. const float line_height = GImGui->FontSize;
  7459. const float scale = line_height / font->FontSize;
  7460.  
  7461. ImVec2 text_size = ImVec2(0,0);
  7462. float line_width = 0.0f;
  7463.  
  7464. const ImWchar* s = text_begin;
  7465. while (s < text_end)
  7466. {
  7467. unsigned int c = (unsigned int)(*s++);
  7468. if (c == '\n')
  7469. {
  7470. text_size.x = ImMax(text_size.x, line_width);
  7471. text_size.y += line_height;
  7472. line_width = 0.0f;
  7473. if (stop_on_new_line)
  7474. break;
  7475. continue;
  7476. }
  7477. if (c == '\r')
  7478. continue;
  7479.  
  7480. const float char_width = font->GetCharAdvance((unsigned short)c) * scale;
  7481. line_width += char_width;
  7482. }
  7483.  
  7484. if (text_size.x < line_width)
  7485. text_size.x = line_width;
  7486.  
  7487. if (out_offset)
  7488. *out_offset = ImVec2(line_width, text_size.y + line_height); // offset allow for the possibility of sitting after a trailing \n
  7489.  
  7490. if (line_width > 0 || text_size.y == 0.0f) // whereas size.y will ignore the trailing \n
  7491. text_size.y += line_height;
  7492.  
  7493. if (remaining)
  7494. *remaining = s;
  7495.  
  7496. return text_size;
  7497. }
  7498.  
  7499. // 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)
  7500. namespace ImGuiStb
  7501. {
  7502.  
  7503. static int STB_TEXTEDIT_STRINGLEN(const STB_TEXTEDIT_STRING* obj) { return obj->CurLenW; }
  7504. static ImWchar STB_TEXTEDIT_GETCHAR(const STB_TEXTEDIT_STRING* obj, int idx) { return obj->Text[idx]; }
  7505. 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); }
  7506. static int STB_TEXTEDIT_KEYTOTEXT(int key) { return key >= 0x10000 ? 0 : key; }
  7507. static ImWchar STB_TEXTEDIT_NEWLINE = '\n';
  7508. static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, STB_TEXTEDIT_STRING* obj, int line_start_idx)
  7509. {
  7510. const ImWchar* text = obj->Text.Data;
  7511. const ImWchar* text_remaining = NULL;
  7512. const ImVec2 size = InputTextCalcTextSizeW(text + line_start_idx, text + obj->CurLenW, &text_remaining, NULL, true);
  7513. r->x0 = 0.0f;
  7514. r->x1 = size.x;
  7515. r->baseline_y_delta = size.y;
  7516. r->ymin = 0.0f;
  7517. r->ymax = size.y;
  7518. r->num_chars = (int)(text_remaining - (text + line_start_idx));
  7519. }
  7520.  
  7521. static bool is_separator(unsigned int c) { return ImCharIsSpace(c) || c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|'; }
  7522. 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; }
  7523. 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; }
  7524. #ifdef __APPLE__ // FIXME: Move setting to IO structure
  7525. 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; }
  7526. 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; }
  7527. #else
  7528. 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; }
  7529. #endif
  7530. #define STB_TEXTEDIT_MOVEWORDLEFT STB_TEXTEDIT_MOVEWORDLEFT_IMPL // They need to be #define for stb_textedit.h
  7531. #define STB_TEXTEDIT_MOVEWORDRIGHT STB_TEXTEDIT_MOVEWORDRIGHT_IMPL
  7532.  
  7533. static void STB_TEXTEDIT_DELETECHARS(STB_TEXTEDIT_STRING* obj, int pos, int n)
  7534. {
  7535. ImWchar* dst = obj->Text.Data + pos;
  7536.  
  7537. // We maintain our buffer length in both UTF-8 and wchar formats
  7538. obj->CurLenA -= ImTextCountUtf8BytesFromStr(dst, dst + n);
  7539. obj->CurLenW -= n;
  7540.  
  7541. // Offset remaining text
  7542. const ImWchar* src = obj->Text.Data + pos + n;
  7543. while (ImWchar c = *src++)
  7544. *dst++ = c;
  7545. *dst = '\0';
  7546. }
  7547.  
  7548. static bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int pos, const ImWchar* new_text, int new_text_len)
  7549. {
  7550. const int text_len = obj->CurLenW;
  7551. IM_ASSERT(pos <= text_len);
  7552. if (new_text_len + text_len + 1 > obj->Text.Size)
  7553. return false;
  7554.  
  7555. const int new_text_len_utf8 = ImTextCountUtf8BytesFromStr(new_text, new_text + new_text_len);
  7556. if (new_text_len_utf8 + obj->CurLenA + 1 > obj->BufSizeA)
  7557. return false;
  7558.  
  7559. ImWchar* text = obj->Text.Data;
  7560. if (pos != text_len)
  7561. memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos) * sizeof(ImWchar));
  7562. memcpy(text + pos, new_text, (size_t)new_text_len * sizeof(ImWchar));
  7563.  
  7564. obj->CurLenW += new_text_len;
  7565. obj->CurLenA += new_text_len_utf8;
  7566. obj->Text[obj->CurLenW] = '\0';
  7567.  
  7568. return true;
  7569. }
  7570.  
  7571. // 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)
  7572. #define STB_TEXTEDIT_K_LEFT 0x10000 // keyboard input to move cursor left
  7573. #define STB_TEXTEDIT_K_RIGHT 0x10001 // keyboard input to move cursor right
  7574. #define STB_TEXTEDIT_K_UP 0x10002 // keyboard input to move cursor up
  7575. #define STB_TEXTEDIT_K_DOWN 0x10003 // keyboard input to move cursor down
  7576. #define STB_TEXTEDIT_K_LINESTART 0x10004 // keyboard input to move cursor to start of line
  7577. #define STB_TEXTEDIT_K_LINEEND 0x10005 // keyboard input to move cursor to end of line
  7578. #define STB_TEXTEDIT_K_TEXTSTART 0x10006 // keyboard input to move cursor to start of text
  7579. #define STB_TEXTEDIT_K_TEXTEND 0x10007 // keyboard input to move cursor to end of text
  7580. #define STB_TEXTEDIT_K_DELETE 0x10008 // keyboard input to delete selection or character under cursor
  7581. #define STB_TEXTEDIT_K_BACKSPACE 0x10009 // keyboard input to delete selection or character left of cursor
  7582. #define STB_TEXTEDIT_K_UNDO 0x1000A // keyboard input to perform undo
  7583. #define STB_TEXTEDIT_K_REDO 0x1000B // keyboard input to perform redo
  7584. #define STB_TEXTEDIT_K_WORDLEFT 0x1000C // keyboard input to move cursor left one word
  7585. #define STB_TEXTEDIT_K_WORDRIGHT 0x1000D // keyboard input to move cursor right one word
  7586. #define STB_TEXTEDIT_K_SHIFT 0x20000
  7587.  
  7588. #define STB_TEXTEDIT_IMPLEMENTATION
  7589. #include "stb_textedit.h"
  7590.  
  7591. }
  7592.  
  7593. void ImGuiTextEditState::OnKeyPressed(int key)
  7594. {
  7595. stb_textedit_key(this, &StbState, key);
  7596. CursorFollow = true;
  7597. CursorAnimReset();
  7598. }
  7599.  
  7600. // Public API to manipulate UTF-8 text
  7601. // We expose UTF-8 to the user (unlike the STB_TEXTEDIT_* functions which are manipulating wchar)
  7602. // FIXME: The existence of this rarely exercised code path is a bit of a nuisance.
  7603. void ImGuiTextEditCallbackData::DeleteChars(int pos, int bytes_count)
  7604. {
  7605. IM_ASSERT(pos + bytes_count <= BufTextLen);
  7606. char* dst = Buf + pos;
  7607. const char* src = Buf + pos + bytes_count;
  7608. while (char c = *src++)
  7609. *dst++ = c;
  7610. *dst = '\0';
  7611.  
  7612. if (CursorPos + bytes_count >= pos)
  7613. CursorPos -= bytes_count;
  7614. else if (CursorPos >= pos)
  7615. CursorPos = pos;
  7616. SelectionStart = SelectionEnd = CursorPos;
  7617. BufDirty = true;
  7618. BufTextLen -= bytes_count;
  7619. }
  7620.  
  7621. void ImGuiTextEditCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end)
  7622. {
  7623. const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)strlen(new_text);
  7624. if (new_text_len + BufTextLen + 1 >= BufSize)
  7625. return;
  7626.  
  7627. if (BufTextLen != pos)
  7628. memmove(Buf + pos + new_text_len, Buf + pos, (size_t)(BufTextLen - pos));
  7629. memcpy(Buf + pos, new_text, (size_t)new_text_len * sizeof(char));
  7630. Buf[BufTextLen + new_text_len] = '\0';
  7631.  
  7632. if (CursorPos >= pos)
  7633. CursorPos += new_text_len;
  7634. SelectionStart = SelectionEnd = CursorPos;
  7635. BufDirty = true;
  7636. BufTextLen += new_text_len;
  7637. }
  7638.  
  7639. // Return false to discard a character.
  7640. static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
  7641. {
  7642. unsigned int c = *p_char;
  7643.  
  7644. if (c < 128 && c != ' ' && !isprint((int)(c & 0xFF)))
  7645. {
  7646. bool pass = false;
  7647. pass |= (c == '\n' && (flags & ImGuiInputTextFlags_Multiline));
  7648. pass |= (c == '\t' && (flags & ImGuiInputTextFlags_AllowTabInput));
  7649. if (!pass)
  7650. return false;
  7651. }
  7652.  
  7653. 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.
  7654. return false;
  7655.  
  7656. if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank))
  7657. {
  7658. if (flags & ImGuiInputTextFlags_CharsDecimal)
  7659. if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/'))
  7660. return false;
  7661.  
  7662. if (flags & ImGuiInputTextFlags_CharsHexadecimal)
  7663. if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F'))
  7664. return false;
  7665.  
  7666. if (flags & ImGuiInputTextFlags_CharsUppercase)
  7667. if (c >= 'a' && c <= 'z')
  7668. *p_char = (c += (unsigned int)('A'-'a'));
  7669.  
  7670. if (flags & ImGuiInputTextFlags_CharsNoBlank)
  7671. if (ImCharIsSpace(c))
  7672. return false;
  7673. }
  7674.  
  7675. if (flags & ImGuiInputTextFlags_CallbackCharFilter)
  7676. {
  7677. ImGuiTextEditCallbackData callback_data;
  7678. memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData));
  7679. callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter;
  7680. callback_data.EventChar = (ImWchar)c;
  7681. callback_data.Flags = flags;
  7682. callback_data.UserData = user_data;
  7683. if (callback(&callback_data) != 0)
  7684. return false;
  7685. *p_char = callback_data.EventChar;
  7686. if (!callback_data.EventChar)
  7687. return false;
  7688. }
  7689.  
  7690. return true;
  7691. }
  7692.  
  7693. // Edit a string of text
  7694. // 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.
  7695. // 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
  7696. bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
  7697. {
  7698. ImGuiWindow* window = GetCurrentWindow();
  7699. if (window->SkipItems)
  7700. return false;
  7701.  
  7702. IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys)
  7703. IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key)
  7704.  
  7705. ImGuiContext& g = *GImGui;
  7706. const ImGuiIO& io = g.IO;
  7707. const ImGuiStyle& style = g.Style;
  7708.  
  7709. const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0;
  7710. const bool is_editable = (flags & ImGuiInputTextFlags_ReadOnly) == 0;
  7711. const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0;
  7712.  
  7713. if (is_multiline) // Open group before calling GetID() because groups tracks id created during their spawn
  7714. BeginGroup();
  7715. const ImGuiID id = window->GetID(label);
  7716. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  7717. 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
  7718. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size);
  7719. 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));
  7720.  
  7721. ImGuiWindow* draw_window = window;
  7722. if (is_multiline)
  7723. {
  7724. if (!BeginChildFrame(id, frame_bb.GetSize()))
  7725. {
  7726. EndChildFrame();
  7727. EndGroup();
  7728. return false;
  7729. }
  7730. draw_window = GetCurrentWindow();
  7731. size.x -= draw_window->ScrollbarSizes.x;
  7732. }
  7733. else
  7734. {
  7735. ItemSize(total_bb, style.FramePadding.y);
  7736. if (!ItemAdd(total_bb, &id))
  7737. return false;
  7738. }
  7739.  
  7740. // Password pushes a temporary font with only a fallback glyph
  7741. if (is_password)
  7742. {
  7743. const ImFont::Glyph* glyph = g.Font->FindGlyph('*');
  7744. ImFont* password_font = &g.InputTextPasswordFont;
  7745. password_font->FontSize = g.Font->FontSize;
  7746. password_font->Scale = g.Font->Scale;
  7747. password_font->DisplayOffset = g.Font->DisplayOffset;
  7748. password_font->Ascent = g.Font->Ascent;
  7749. password_font->Descent = g.Font->Descent;
  7750. password_font->ContainerAtlas = g.Font->ContainerAtlas;
  7751. password_font->FallbackGlyph = glyph;
  7752. password_font->FallbackXAdvance = glyph->XAdvance;
  7753. IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexXAdvance.empty() && password_font->IndexLookup.empty());
  7754. PushFont(password_font);
  7755. }
  7756.  
  7757. // NB: we are only allowed to access 'edit_state' if we are the active widget.
  7758. ImGuiTextEditState& edit_state = g.InputTextState;
  7759.  
  7760. const bool focus_requested = FocusableItemRegister(window, g.ActiveId == id, (flags & (ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_AllowTabInput)) == 0); // Using completion callback disable keyboard tabbing
  7761. const bool focus_requested_by_code = focus_requested && (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent);
  7762. const bool focus_requested_by_tab = focus_requested && !focus_requested_by_code;
  7763.  
  7764. const bool hovered = IsHovered(frame_bb, id);
  7765. if (hovered)
  7766. {
  7767. SetHoveredID(id);
  7768. g.MouseCursor = ImGuiMouseCursor_TextInput;
  7769. }
  7770. const bool user_clicked = hovered && io.MouseClicked[0];
  7771. const bool user_scrolled = is_multiline && g.ActiveId == 0 && edit_state.Id == id && g.ActiveIdPreviousFrame == draw_window->GetIDNoKeepAlive("#SCROLLY");
  7772.  
  7773. bool select_all = (g.ActiveId != id) && (flags & ImGuiInputTextFlags_AutoSelectAll) != 0;
  7774. if (focus_requested || user_clicked || user_scrolled)
  7775. {
  7776. if (g.ActiveId != id)
  7777. {
  7778. // Start edition
  7779. // Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar)
  7780. // From the moment we focused we are ignoring the content of 'buf' (unless we are in read-only mode)
  7781. const int prev_len_w = edit_state.CurLenW;
  7782. 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.
  7783. 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.
  7784. ImStrncpy(edit_state.InitialText.Data, buf, edit_state.InitialText.Size);
  7785. const char* buf_end = NULL;
  7786. edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end);
  7787. 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.
  7788. edit_state.CursorAnimReset();
  7789.  
  7790. // Preserve cursor position and undo/redo stack if we come back to same widget
  7791. // FIXME: We should probably compare the whole buffer to be on the safety side. Comparing buf (utf8) and edit_state.Text (wchar).
  7792. const bool recycle_state = (edit_state.Id == id) && (prev_len_w == edit_state.CurLenW);
  7793. if (recycle_state)
  7794. {
  7795. // Recycle existing cursor/selection/undo stack but clamp position
  7796. // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler.
  7797. edit_state.CursorClamp();
  7798. }
  7799. else
  7800. {
  7801. edit_state.Id = id;
  7802. edit_state.ScrollX = 0.0f;
  7803. stb_textedit_initialize_state(&edit_state.StbState, !is_multiline);
  7804. if (!is_multiline && focus_requested_by_code)
  7805. select_all = true;
  7806. }
  7807. if (flags & ImGuiInputTextFlags_AlwaysInsertMode)
  7808. edit_state.StbState.insert_mode = true;
  7809. if (!is_multiline && (focus_requested_by_tab || (user_clicked && io.KeyCtrl)))
  7810. select_all = true;
  7811. }
  7812. SetActiveID(id, window);
  7813. FocusWindow(window);
  7814. }
  7815. else if (io.MouseClicked[0])
  7816. {
  7817. // Release focus when we click outside
  7818. if (g.ActiveId == id)
  7819. ClearActiveID();
  7820. }
  7821.  
  7822. bool value_changed = false;
  7823. bool enter_pressed = false;
  7824.  
  7825. if (g.ActiveId == id)
  7826. {
  7827. if (!is_editable && !g.ActiveIdIsJustActivated)
  7828. {
  7829. // When read-only we always use the live data passed to the function
  7830. edit_state.Text.resize(buf_size+1);
  7831. const char* buf_end = NULL;
  7832. edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end);
  7833. edit_state.CurLenA = (int)(buf_end - buf);
  7834. edit_state.CursorClamp();
  7835. }
  7836.  
  7837. edit_state.BufSizeA = buf_size;
  7838.  
  7839. // Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget.
  7840. // Down the line we should have a cleaner library-wide concept of Selected vs Active.
  7841. g.ActiveIdAllowOverlap = !io.MouseDown[0];
  7842.  
  7843. // Edit in progress
  7844. const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + edit_state.ScrollX;
  7845. const float mouse_y = (is_multiline ? (io.MousePos.y - draw_window->DC.CursorPos.y - style.FramePadding.y) : (g.FontSize*0.5f));
  7846.  
  7847. const bool osx_double_click_selects_words = io.OSXBehaviors; // OS X style: Double click selects by word instead of selecting whole text
  7848. if (select_all || (hovered && !osx_double_click_selects_words && io.MouseDoubleClicked[0]))
  7849. {
  7850. edit_state.SelectAll();
  7851. edit_state.SelectedAllMouseLock = true;
  7852. }
  7853. else if (hovered && osx_double_click_selects_words && io.MouseDoubleClicked[0])
  7854. {
  7855. // Select a word only, OS X style (by simulating keystrokes)
  7856. edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT);
  7857. edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT);
  7858. }
  7859. else if (io.MouseClicked[0] && !edit_state.SelectedAllMouseLock)
  7860. {
  7861. stb_textedit_click(&edit_state, &edit_state.StbState, mouse_x, mouse_y);
  7862. edit_state.CursorAnimReset();
  7863. }
  7864. else if (io.MouseDown[0] && !edit_state.SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f))
  7865. {
  7866. stb_textedit_drag(&edit_state, &edit_state.StbState, mouse_x, mouse_y);
  7867. edit_state.CursorAnimReset();
  7868. edit_state.CursorFollow = true;
  7869. }
  7870. if (edit_state.SelectedAllMouseLock && !io.MouseDown[0])
  7871. edit_state.SelectedAllMouseLock = false;
  7872.  
  7873. if (io.InputCharacters[0])
  7874. {
  7875. // Process text input (before we check for Return because using some IME will effectively send a Return?)
  7876. // 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.
  7877. if (!(io.KeyCtrl && !io.KeyAlt) && is_editable)
  7878. {
  7879. for (int n = 0; n < IM_ARRAYSIZE(io.InputCharacters) && io.InputCharacters[n]; n++)
  7880. if (unsigned int c = (unsigned int)io.InputCharacters[n])
  7881. {
  7882. // Insert character if they pass filtering
  7883. if (!InputTextFilterCharacter(&c, flags, callback, user_data))
  7884. continue;
  7885. edit_state.OnKeyPressed((int)c);
  7886. }
  7887. }
  7888.  
  7889. // Consume characters
  7890. memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters));
  7891. }
  7892.  
  7893. // Handle various key-presses
  7894. bool cancel_edit = false;
  7895. const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0);
  7896. 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
  7897. const bool is_wordmove_key_down = io.OSXBehaviors ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl
  7898. 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
  7899.  
  7900. 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); }
  7901. 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); }
  7902. 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); }
  7903. 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); }
  7904. else if (IsKeyPressedMap(ImGuiKey_Home)) { edit_state.OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); }
  7905. else if (IsKeyPressedMap(ImGuiKey_End)) { edit_state.OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); }
  7906. else if (IsKeyPressedMap(ImGuiKey_Delete) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); }
  7907. else if (IsKeyPressedMap(ImGuiKey_Backspace) && is_editable)
  7908. {
  7909. if (!edit_state.HasSelection())
  7910. {
  7911. if (is_wordmove_key_down) edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT|STB_TEXTEDIT_K_SHIFT);
  7912. else if (io.OSXBehaviors && io.KeySuper && !io.KeyAlt && !io.KeyCtrl) edit_state.OnKeyPressed(STB_TEXTEDIT_K_LINESTART|STB_TEXTEDIT_K_SHIFT);
  7913. }
  7914. edit_state.OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask);
  7915. }
  7916. else if (IsKeyPressedMap(ImGuiKey_Enter))
  7917. {
  7918. bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0;
  7919. if (!is_multiline || (ctrl_enter_for_new_line && !io.KeyCtrl) || (!ctrl_enter_for_new_line && io.KeyCtrl))
  7920. {
  7921. ClearActiveID();
  7922. enter_pressed = true;
  7923. }
  7924. else if (is_editable)
  7925. {
  7926. unsigned int c = '\n'; // Insert new line
  7927. if (InputTextFilterCharacter(&c, flags, callback, user_data))
  7928. edit_state.OnKeyPressed((int)c);
  7929. }
  7930. }
  7931. else if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressedMap(ImGuiKey_Tab) && !io.KeyCtrl && !io.KeyShift && !io.KeyAlt && is_editable)
  7932. {
  7933. unsigned int c = '\t'; // Insert TAB
  7934. if (InputTextFilterCharacter(&c, flags, callback, user_data))
  7935. edit_state.OnKeyPressed((int)c);
  7936. }
  7937. else if (IsKeyPressedMap(ImGuiKey_Escape)) { ClearActiveID(); cancel_edit = true; }
  7938. else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Z) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_UNDO); edit_state.ClearSelection(); }
  7939. else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Y) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_REDO); edit_state.ClearSelection(); }
  7940. else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_A)) { edit_state.SelectAll(); edit_state.CursorFollow = true; }
  7941. else if (is_shortcut_key_only && !is_password && ((IsKeyPressedMap(ImGuiKey_X) && is_editable) || IsKeyPressedMap(ImGuiKey_C)) && (!is_multiline || edit_state.HasSelection()))
  7942. {
  7943. // Cut, Copy
  7944. const bool cut = IsKeyPressedMap(ImGuiKey_X);
  7945. if (cut && !edit_state.HasSelection())
  7946. edit_state.SelectAll();
  7947.  
  7948. if (io.SetClipboardTextFn)
  7949. {
  7950. const int ib = edit_state.HasSelection() ? ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end) : 0;
  7951. const int ie = edit_state.HasSelection() ? ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end) : edit_state.CurLenW;
  7952. edit_state.TempTextBuffer.resize((ie-ib) * 4 + 1);
  7953. ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.Data+ib, edit_state.Text.Data+ie);
  7954. SetClipboardText(edit_state.TempTextBuffer.Data);
  7955. }
  7956.  
  7957. if (cut)
  7958. {
  7959. edit_state.CursorFollow = true;
  7960. stb_textedit_cut(&edit_state, &edit_state.StbState);
  7961. }
  7962. }
  7963. else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_V) && is_editable)
  7964. {
  7965. // Paste
  7966. if (const char* clipboard = GetClipboardText())
  7967. {
  7968. // Filter pasted buffer
  7969. const int clipboard_len = (int)strlen(clipboard);
  7970. ImWchar* clipboard_filtered = (ImWchar*)ImGui::MemAlloc((clipboard_len+1) * sizeof(ImWchar));
  7971. int clipboard_filtered_len = 0;
  7972. for (const char* s = clipboard; *s; )
  7973. {
  7974. unsigned int c;
  7975. s += ImTextCharFromUtf8(&c, s, NULL);
  7976. if (c == 0)
  7977. break;
  7978. if (c >= 0x10000 || !InputTextFilterCharacter(&c, flags, callback, user_data))
  7979. continue;
  7980. clipboard_filtered[clipboard_filtered_len++] = (ImWchar)c;
  7981. }
  7982. clipboard_filtered[clipboard_filtered_len] = 0;
  7983. if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation
  7984. {
  7985. stb_textedit_paste(&edit_state, &edit_state.StbState, clipboard_filtered, clipboard_filtered_len);
  7986. edit_state.CursorFollow = true;
  7987. }
  7988. ImGui::MemFree(clipboard_filtered);
  7989. }
  7990. }
  7991.  
  7992. if (cancel_edit)
  7993. {
  7994. // Restore initial value
  7995. if (is_editable)
  7996. {
  7997. ImStrncpy(buf, edit_state.InitialText.Data, buf_size);
  7998. value_changed = true;
  7999. }
  8000. }
  8001. else
  8002. {
  8003. // Apply new value immediately - copy modified buffer back
  8004. // Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer
  8005. // FIXME: We actually always render 'buf' when calling DrawList->AddText, making the comment above incorrect.
  8006. // FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks.
  8007. if (is_editable)
  8008. {
  8009. edit_state.TempTextBuffer.resize(edit_state.Text.Size * 4);
  8010. ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.Data, NULL);
  8011. }
  8012.  
  8013. // User callback
  8014. if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackAlways)) != 0)
  8015. {
  8016. IM_ASSERT(callback != NULL);
  8017.  
  8018. // The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment.
  8019. ImGuiInputTextFlags event_flag = 0;
  8020. ImGuiKey event_key = ImGuiKey_COUNT;
  8021. if ((flags & ImGuiInputTextFlags_CallbackCompletion) != 0 && IsKeyPressedMap(ImGuiKey_Tab))
  8022. {
  8023. event_flag = ImGuiInputTextFlags_CallbackCompletion;
  8024. event_key = ImGuiKey_Tab;
  8025. }
  8026. else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_UpArrow))
  8027. {
  8028. event_flag = ImGuiInputTextFlags_CallbackHistory;
  8029. event_key = ImGuiKey_UpArrow;
  8030. }
  8031. else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_DownArrow))
  8032. {
  8033. event_flag = ImGuiInputTextFlags_CallbackHistory;
  8034. event_key = ImGuiKey_DownArrow;
  8035. }
  8036. else if (flags & ImGuiInputTextFlags_CallbackAlways)
  8037. event_flag = ImGuiInputTextFlags_CallbackAlways;
  8038.  
  8039. if (event_flag)
  8040. {
  8041. ImGuiTextEditCallbackData callback_data;
  8042. memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData));
  8043. callback_data.EventFlag = event_flag;
  8044. callback_data.Flags = flags;
  8045. callback_data.UserData = user_data;
  8046. callback_data.ReadOnly = !is_editable;
  8047.  
  8048. callback_data.EventKey = event_key;
  8049. callback_data.Buf = edit_state.TempTextBuffer.Data;
  8050. callback_data.BufTextLen = edit_state.CurLenA;
  8051. callback_data.BufSize = edit_state.BufSizeA;
  8052. callback_data.BufDirty = false;
  8053.  
  8054. // 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)
  8055. ImWchar* text = edit_state.Text.Data;
  8056. const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.cursor);
  8057. const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_start);
  8058. const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_end);
  8059.  
  8060. // Call user code
  8061. callback(&callback_data);
  8062.  
  8063. // Read back what user may have modified
  8064. IM_ASSERT(callback_data.Buf == edit_state.TempTextBuffer.Data); // Invalid to modify those fields
  8065. IM_ASSERT(callback_data.BufSize == edit_state.BufSizeA);
  8066. IM_ASSERT(callback_data.Flags == flags);
  8067. if (callback_data.CursorPos != utf8_cursor_pos) edit_state.StbState.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos);
  8068. if (callback_data.SelectionStart != utf8_selection_start) edit_state.StbState.select_start = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart);
  8069. if (callback_data.SelectionEnd != utf8_selection_end) edit_state.StbState.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd);
  8070. if (callback_data.BufDirty)
  8071. {
  8072. IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text!
  8073. edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, callback_data.Buf, NULL);
  8074. edit_state.CurLenA = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen()
  8075. edit_state.CursorAnimReset();
  8076. }
  8077. }
  8078. }
  8079.  
  8080. // Copy back to user buffer
  8081. if (is_editable && strcmp(edit_state.TempTextBuffer.Data, buf) != 0)
  8082. {
  8083. ImStrncpy(buf, edit_state.TempTextBuffer.Data, buf_size);
  8084. value_changed = true;
  8085. }
  8086. }
  8087. }
  8088.  
  8089. // Render
  8090. // 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.
  8091. const char* buf_display = (g.ActiveId == id && is_editable) ? edit_state.TempTextBuffer.Data : buf; buf = NULL;
  8092.  
  8093. if (!is_multiline)
  8094. RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
  8095.  
  8096. 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
  8097. ImVec2 render_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding;
  8098. ImVec2 text_size(0.f, 0.f);
  8099. const bool is_currently_scrolling = (edit_state.Id == id && is_multiline && g.ActiveId == draw_window->GetIDNoKeepAlive("#SCROLLY"));
  8100. if (g.ActiveId == id || is_currently_scrolling)
  8101. {
  8102. edit_state.CursorAnim += io.DeltaTime;
  8103.  
  8104. // This is going to be messy. We need to:
  8105. // - Display the text (this alone can be more easily clipped)
  8106. // - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation)
  8107. // - Measure text height (for scrollbar)
  8108. // 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)
  8109. // FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8.
  8110. const ImWchar* text_begin = edit_state.Text.Data;
  8111. ImVec2 cursor_offset, select_start_offset;
  8112.  
  8113. {
  8114. // Count lines + find lines numbers straddling 'cursor' and 'select_start' position.
  8115. const ImWchar* searches_input_ptr[2];
  8116. searches_input_ptr[0] = text_begin + edit_state.StbState.cursor;
  8117. searches_input_ptr[1] = NULL;
  8118. int searches_remaining = 1;
  8119. int searches_result_line_number[2] = { -1, -999 };
  8120. if (edit_state.StbState.select_start != edit_state.StbState.select_end)
  8121. {
  8122. searches_input_ptr[1] = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end);
  8123. searches_result_line_number[1] = -1;
  8124. searches_remaining++;
  8125. }
  8126.  
  8127. // Iterate all lines to find our line numbers
  8128. // In multi-line mode, we never exit the loop until all lines are counted, so add one extra to the searches_remaining counter.
  8129. searches_remaining += is_multiline ? 1 : 0;
  8130. int line_count = 0;
  8131. for (const ImWchar* s = text_begin; *s != 0; s++)
  8132. if (*s == '\n')
  8133. {
  8134. line_count++;
  8135. if (searches_result_line_number[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_number[0] = line_count; if (--searches_remaining <= 0) break; }
  8136. if (searches_result_line_number[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_number[1] = line_count; if (--searches_remaining <= 0) break; }
  8137. }
  8138. line_count++;
  8139. if (searches_result_line_number[0] == -1) searches_result_line_number[0] = line_count;
  8140. if (searches_result_line_number[1] == -1) searches_result_line_number[1] = line_count;
  8141.  
  8142. // Calculate 2d position by finding the beginning of the line and measuring distance
  8143. cursor_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[0], text_begin), searches_input_ptr[0]).x;
  8144. cursor_offset.y = searches_result_line_number[0] * g.FontSize;
  8145. if (searches_result_line_number[1] >= 0)
  8146. {
  8147. select_start_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[1], text_begin), searches_input_ptr[1]).x;
  8148. select_start_offset.y = searches_result_line_number[1] * g.FontSize;
  8149. }
  8150.  
  8151. // Calculate text height
  8152. if (is_multiline)
  8153. text_size = ImVec2(size.x, line_count * g.FontSize);
  8154. }
  8155.  
  8156. // Scroll
  8157. if (edit_state.CursorFollow)
  8158. {
  8159. // Horizontal scroll in chunks of quarter width
  8160. if (!(flags & ImGuiInputTextFlags_NoHorizontalScroll))
  8161. {
  8162. const float scroll_increment_x = size.x * 0.25f;
  8163. if (cursor_offset.x < edit_state.ScrollX)
  8164. edit_state.ScrollX = (float)(int)ImMax(0.0f, cursor_offset.x - scroll_increment_x);
  8165. else if (cursor_offset.x - size.x >= edit_state.ScrollX)
  8166. edit_state.ScrollX = (float)(int)(cursor_offset.x - size.x + scroll_increment_x);
  8167. }
  8168. else
  8169. {
  8170. edit_state.ScrollX = 0.0f;
  8171. }
  8172.  
  8173. // Vertical scroll
  8174. if (is_multiline)
  8175. {
  8176. float scroll_y = draw_window->Scroll.y;
  8177. if (cursor_offset.y - g.FontSize < scroll_y)
  8178. scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize);
  8179. else if (cursor_offset.y - size.y >= scroll_y)
  8180. scroll_y = cursor_offset.y - size.y;
  8181. draw_window->DC.CursorPos.y += (draw_window->Scroll.y - scroll_y); // To avoid a frame of lag
  8182. draw_window->Scroll.y = scroll_y;
  8183. render_pos.y = draw_window->DC.CursorPos.y;
  8184. }
  8185. }
  8186. edit_state.CursorFollow = false;
  8187. const ImVec2 render_scroll = ImVec2(edit_state.ScrollX, 0.0f);
  8188.  
  8189. // Draw selection
  8190. if (edit_state.StbState.select_start != edit_state.StbState.select_end)
  8191. {
  8192. const ImWchar* text_selected_begin = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end);
  8193. const ImWchar* text_selected_end = text_begin + ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end);
  8194.  
  8195. 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.
  8196. float bg_offy_dn = is_multiline ? 0.0f : 2.0f;
  8197. ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg);
  8198. ImVec2 rect_pos = render_pos + select_start_offset - render_scroll;
  8199. for (const ImWchar* p = text_selected_begin; p < text_selected_end; )
  8200. {
  8201. if (rect_pos.y > clip_rect.w + g.FontSize)
  8202. break;
  8203. if (rect_pos.y < clip_rect.y)
  8204. {
  8205. while (p < text_selected_end)
  8206. if (*p++ == '\n')
  8207. break;
  8208. }
  8209. else
  8210. {
  8211. ImVec2 rect_size = InputTextCalcTextSizeW(p, text_selected_end, &p, NULL, true);
  8212. 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
  8213. ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos +ImVec2(rect_size.x, bg_offy_dn));
  8214. rect.Clip(clip_rect);
  8215. if (rect.Overlaps(clip_rect))
  8216. draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color);
  8217. }
  8218. rect_pos.x = render_pos.x - render_scroll.x;
  8219. rect_pos.y += g.FontSize;
  8220. }
  8221. }
  8222.  
  8223. 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);
  8224.  
  8225. // Draw blinking cursor
  8226. bool cursor_is_visible = (g.InputTextState.CursorAnim <= 0.0f) || fmodf(g.InputTextState.CursorAnim, 1.20f) <= 0.80f;
  8227. ImVec2 cursor_screen_pos = render_pos + cursor_offset - render_scroll;
  8228. 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);
  8229. if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect))
  8230. draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text));
  8231.  
  8232. // 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.)
  8233. if (is_editable)
  8234. g.OsImePosRequest = ImVec2(cursor_screen_pos.x - 1, cursor_screen_pos.y - g.FontSize);
  8235. }
  8236. else
  8237. {
  8238. // Render text only
  8239. const char* buf_end = NULL;
  8240. if (is_multiline)
  8241. text_size = ImVec2(size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_end) * g.FontSize); // We don't need width
  8242. draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos, GetColorU32(ImGuiCol_Text), buf_display, buf_end, 0.0f, is_multiline ? NULL : &clip_rect);
  8243. }
  8244.  
  8245. if (is_multiline)
  8246. {
  8247. Dummy(text_size + ImVec2(0.0f, g.FontSize)); // Always add room to scroll an extra line
  8248. EndChildFrame();
  8249. EndGroup();
  8250. }
  8251.  
  8252. if (is_password)
  8253. PopFont();
  8254.  
  8255. // Log as text
  8256. if (g.LogEnabled && !is_password)
  8257. LogRenderedText(render_pos, buf_display, NULL);
  8258.  
  8259. if (label_size.x > 0)
  8260. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
  8261.  
  8262. if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0)
  8263. return enter_pressed;
  8264. else
  8265. return value_changed;
  8266. }
  8267.  
  8268. bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
  8269. {
  8270. IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline()
  8271. return InputTextEx(label, buf, (int)buf_size, ImVec2(0,0), flags, callback, user_data);
  8272. }
  8273.  
  8274. bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
  8275. {
  8276. return InputTextEx(label, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data);
  8277. }
  8278.  
  8279. // NB: scalar_format here must be a simple "%xx" format string with no prefix/suffix (unlike the Drag/Slider functions "display_format" argument)
  8280. 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)
  8281. {
  8282. ImGuiWindow* window = GetCurrentWindow();
  8283. if (window->SkipItems)
  8284. return false;
  8285.  
  8286. ImGuiContext& g = *GImGui;
  8287. const ImGuiStyle& style = g.Style;
  8288. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  8289.  
  8290. BeginGroup();
  8291. PushID(label);
  8292. const ImVec2 button_sz = ImVec2(g.FontSize, g.FontSize) + style.FramePadding*2.0f;
  8293. if (step_ptr)
  8294. PushItemWidth(ImMax(1.0f, CalcItemWidth() - (button_sz.x + style.ItemInnerSpacing.x)*2));
  8295.  
  8296. char buf[64];
  8297. DataTypeFormatString(data_type, data_ptr, scalar_format, buf, IM_ARRAYSIZE(buf));
  8298.  
  8299. bool value_changed = false;
  8300. if (!(extra_flags & ImGuiInputTextFlags_CharsHexadecimal))
  8301. extra_flags |= ImGuiInputTextFlags_CharsDecimal;
  8302. extra_flags |= ImGuiInputTextFlags_AutoSelectAll;
  8303. if (InputText("", buf, IM_ARRAYSIZE(buf), extra_flags)) // PushId(label) + "" gives us the expected ID from outside point of view
  8304. value_changed = DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, scalar_format);
  8305.  
  8306. // Step buttons
  8307. if (step_ptr)
  8308. {
  8309. PopItemWidth();
  8310. SameLine(0, style.ItemInnerSpacing.x);
  8311. if (ButtonEx("-", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups))
  8312. {
  8313. DataTypeApplyOp(data_type, '-', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr);
  8314. value_changed = true;
  8315. }
  8316. SameLine(0, style.ItemInnerSpacing.x);
  8317. if (ButtonEx("+", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups))
  8318. {
  8319. DataTypeApplyOp(data_type, '+', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr);
  8320. value_changed = true;
  8321. }
  8322. }
  8323. PopID();
  8324.  
  8325. if (label_size.x > 0)
  8326. {
  8327. SameLine(0, style.ItemInnerSpacing.x);
  8328. RenderText(ImVec2(window->DC.CursorPos.x, window->DC.CursorPos.y + style.FramePadding.y), label);
  8329. ItemSize(label_size, style.FramePadding.y);
  8330. }
  8331. EndGroup();
  8332.  
  8333. return value_changed;
  8334. }
  8335.  
  8336. bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags extra_flags)
  8337. {
  8338. char display_format[16];
  8339. if (decimal_precision < 0)
  8340. 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
  8341. else
  8342. ImFormatString(display_format, IM_ARRAYSIZE(display_format), "%%.%df", decimal_precision);
  8343. 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);
  8344. }
  8345.  
  8346. bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags extra_flags)
  8347. {
  8348. // 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.
  8349. const char* scalar_format = (extra_flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d";
  8350. 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);
  8351. }
  8352.  
  8353. bool ImGui::InputFloatN(const char* label, float* v, int components, int decimal_precision, ImGuiInputTextFlags extra_flags)
  8354. {
  8355. ImGuiWindow* window = GetCurrentWindow();
  8356. if (window->SkipItems)
  8357. return false;
  8358.  
  8359. ImGuiContext& g = *GImGui;
  8360. bool value_changed = false;
  8361. BeginGroup();
  8362. PushID(label);
  8363. PushMultiItemsWidths(components);
  8364. for (int i = 0; i < components; i++)
  8365. {
  8366. PushID(i);
  8367. value_changed |= InputFloat("##v", &v[i], 0, 0, decimal_precision, extra_flags);
  8368. SameLine(0, g.Style.ItemInnerSpacing.x);
  8369. PopID();
  8370. PopItemWidth();
  8371. }
  8372. PopID();
  8373.  
  8374. window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y);
  8375. TextUnformatted(label, FindRenderedTextEnd(label));
  8376. EndGroup();
  8377.  
  8378. return value_changed;
  8379. }
  8380.  
  8381. bool ImGui::InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags extra_flags)
  8382. {
  8383. return InputFloatN(label, v, 2, decimal_precision, extra_flags);
  8384. }
  8385.  
  8386. bool ImGui::InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags extra_flags)
  8387. {
  8388. return InputFloatN(label, v, 3, decimal_precision, extra_flags);
  8389. }
  8390.  
  8391. bool ImGui::InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags extra_flags)
  8392. {
  8393. return InputFloatN(label, v, 4, decimal_precision, extra_flags);
  8394. }
  8395.  
  8396. bool ImGui::InputIntN(const char* label, int* v, int components, ImGuiInputTextFlags extra_flags)
  8397. {
  8398. ImGuiWindow* window = GetCurrentWindow();
  8399. if (window->SkipItems)
  8400. return false;
  8401.  
  8402. ImGuiContext& g = *GImGui;
  8403. bool value_changed = false;
  8404. BeginGroup();
  8405. PushID(label);
  8406. PushMultiItemsWidths(components);
  8407. for (int i = 0; i < components; i++)
  8408. {
  8409. PushID(i);
  8410. value_changed |= InputInt("##v", &v[i], 0, 0, extra_flags);
  8411. SameLine(0, g.Style.ItemInnerSpacing.x);
  8412. PopID();
  8413. PopItemWidth();
  8414. }
  8415. PopID();
  8416.  
  8417. window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y);
  8418. TextUnformatted(label, FindRenderedTextEnd(label));
  8419. EndGroup();
  8420.  
  8421. return value_changed;
  8422. }
  8423.  
  8424. bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags extra_flags)
  8425. {
  8426. return InputIntN(label, v, 2, extra_flags);
  8427. }
  8428.  
  8429. bool ImGui::InputInt3(const char* label, int v[3], ImGuiInputTextFlags extra_flags)
  8430. {
  8431. return InputIntN(label, v, 3, extra_flags);
  8432. }
  8433.  
  8434. bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags)
  8435. {
  8436. return InputIntN(label, v, 4, extra_flags);
  8437. }
  8438.  
  8439. static bool Items_ArrayGetter(void* data, int idx, const char** out_text)
  8440. {
  8441. const char* const* items = (const char* const*)data;
  8442. if (out_text)
  8443. *out_text = items[idx];
  8444. return true;
  8445. }
  8446.  
  8447. static bool Items_SingleStringGetter(void* data, int idx, const char** out_text)
  8448. {
  8449. // FIXME-OPT: we could pre-compute the indices to fasten this. But only 1 active combo means the waste is limited.
  8450. const char* items_separated_by_zeros = (const char*)data;
  8451. int items_count = 0;
  8452. const char* p = items_separated_by_zeros;
  8453. while (*p)
  8454. {
  8455. if (idx == items_count)
  8456. break;
  8457. p += strlen(p) + 1;
  8458. items_count++;
  8459. }
  8460. if (!*p)
  8461. return false;
  8462. if (out_text)
  8463. *out_text = p;
  8464. return true;
  8465. }
  8466.  
  8467. // Combo box helper allowing to pass an array of strings.
  8468. bool ImGui::Combo(const char* label, int* current_item, const char* const* items, int items_count, int height_in_items)
  8469. {
  8470. const bool value_changed = Combo(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_in_items);
  8471. return value_changed;
  8472. }
  8473.  
  8474. // Combo box helper allowing to pass all items in a single string.
  8475. bool ImGui::Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items)
  8476. {
  8477. int items_count = 0;
  8478. const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this, or at least only when combo is open
  8479. while (*p)
  8480. {
  8481. p += strlen(p) + 1;
  8482. items_count++;
  8483. }
  8484. bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items);
  8485. return value_changed;
  8486. }
  8487.  
  8488. // Combo box function.
  8489. 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)
  8490. {
  8491. ImGuiWindow* window = GetCurrentWindow();
  8492. if (window->SkipItems)
  8493. return false;
  8494.  
  8495. ImGuiContext& g = *GImGui;
  8496. const ImGuiStyle& style = g.Style;
  8497. const ImGuiID id = window->GetID(label);
  8498. const float w = CalcItemWidth();
  8499.  
  8500. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  8501. const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
  8502. 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));
  8503. ItemSize(total_bb, style.FramePadding.y);
  8504. if (!ItemAdd(total_bb, &id))
  8505. return false;
  8506.  
  8507. const float arrow_size = (g.FontSize + style.FramePadding.x * 2.0f);
  8508. const bool hovered = IsHovered(frame_bb, id);
  8509. bool popup_open = IsPopupOpen(id);
  8510. bool popup_opened_now = false;
  8511.  
  8512. const ImRect value_bb(frame_bb.Min, frame_bb.Max - ImVec2(arrow_size, 0.0f));
  8513. RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
  8514. 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
  8515. RenderCollapseTriangle(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y) + style.FramePadding, true);
  8516.  
  8517. if (*current_item >= 0 && *current_item < items_count)
  8518. {
  8519. const char* item_text;
  8520. if (items_getter(data, *current_item, &item_text))
  8521. RenderTextClipped(frame_bb.Min + style.FramePadding, value_bb.Max, item_text, NULL, NULL, ImVec2(0.0f,0.0f));
  8522. }
  8523.  
  8524. if (label_size.x > 0)
  8525. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
  8526.  
  8527. if (hovered)
  8528. {
  8529. SetHoveredID(id);
  8530. if (g.IO.MouseClicked[0])
  8531. {
  8532. ClearActiveID();
  8533. if (IsPopupOpen(id))
  8534. {
  8535. ClosePopup(id);
  8536. }
  8537. else
  8538. {
  8539. FocusWindow(window);
  8540. OpenPopup(label);
  8541. popup_open = popup_opened_now = true;
  8542. }
  8543. }
  8544. }
  8545.  
  8546. bool value_changed = false;
  8547. if (IsPopupOpen(id))
  8548. {
  8549. // Size default to hold ~7 items
  8550. if (height_in_items < 0)
  8551. height_in_items = 7;
  8552.  
  8553. float popup_height = (label_size.y + style.ItemSpacing.y) * ImMin(items_count, height_in_items) + (style.FramePadding.y * 3);
  8554. float popup_y1 = frame_bb.Max.y;
  8555. float popup_y2 = ImClamp(popup_y1 + popup_height, popup_y1, g.IO.DisplaySize.y - style.DisplaySafeAreaPadding.y);
  8556. if ((popup_y2 - popup_y1) < ImMin(popup_height, frame_bb.Min.y - style.DisplaySafeAreaPadding.y))
  8557. {
  8558. // 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)
  8559. popup_y1 = ImClamp(frame_bb.Min.y - popup_height, style.DisplaySafeAreaPadding.y, frame_bb.Min.y);
  8560. popup_y2 = frame_bb.Min.y;
  8561. }
  8562. ImRect popup_rect(ImVec2(frame_bb.Min.x, popup_y1), ImVec2(frame_bb.Max.x, popup_y2));
  8563. SetNextWindowPos(popup_rect.Min);
  8564. SetNextWindowSize(popup_rect.GetSize());
  8565. PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
  8566.  
  8567. const ImGuiWindowFlags flags = ImGuiWindowFlags_ComboBox | ((window->Flags & ImGuiWindowFlags_ShowBorders) ? ImGuiWindowFlags_ShowBorders : 0);
  8568. if (BeginPopupEx(label, flags))
  8569. {
  8570. // Display items
  8571. Spacing();
  8572. for (int i = 0; i < items_count; i++)
  8573. {
  8574. PushID((void*)(intptr_t)i);
  8575. const bool item_selected = (i == *current_item);
  8576. const char* item_text;
  8577. if (!items_getter(data, i, &item_text))
  8578. item_text = "*Unknown item*";
  8579. if (Selectable(item_text, item_selected))
  8580. {
  8581. ClearActiveID();
  8582. value_changed = true;
  8583. *current_item = i;
  8584. }
  8585. if (item_selected && popup_opened_now)
  8586. SetScrollHere();
  8587. PopID();
  8588. }
  8589. EndPopup();
  8590. }
  8591. PopStyleVar();
  8592. }
  8593. return value_changed;
  8594. }
  8595.  
  8596. // Tip: pass an empty label (e.g. "##dummy") then you can use the space to draw other text or image.
  8597. // But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID.
  8598. bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)
  8599. {
  8600. ImGuiWindow* window = GetCurrentWindow();
  8601. if (window->SkipItems)
  8602. return false;
  8603.  
  8604. ImGuiContext& g = *GImGui;
  8605. const ImGuiStyle& style = g.Style;
  8606.  
  8607. if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1)
  8608. PopClipRect();
  8609.  
  8610. ImGuiID id = window->GetID(label);
  8611. ImVec2 label_size = CalcTextSize(label, NULL, true);
  8612. ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y);
  8613. ImVec2 pos = window->DC.CursorPos;
  8614. pos.y += window->DC.CurrentLineTextBaseOffset;
  8615. ImRect bb(pos, pos + size);
  8616. ItemSize(bb);
  8617.  
  8618. // Fill horizontal space.
  8619. ImVec2 window_padding = window->WindowPadding;
  8620. float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? GetWindowContentRegionMax().x : GetContentRegionMax().x;
  8621. float w_draw = ImMax(label_size.x, window->Pos.x + max_x - window_padding.x - window->DC.CursorPos.x);
  8622. 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);
  8623. ImRect bb_with_spacing(pos, pos + size_draw);
  8624. if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_DrawFillAvailWidth))
  8625. bb_with_spacing.Max.x += window_padding.x;
  8626.  
  8627. // Selectables are tightly packed together, we extend the box to cover spacing between selectable.
  8628. float spacing_L = (float)(int)(style.ItemSpacing.x * 0.5f);
  8629. float spacing_U = (float)(int)(style.ItemSpacing.y * 0.5f);
  8630. float spacing_R = style.ItemSpacing.x - spacing_L;
  8631. float spacing_D = style.ItemSpacing.y - spacing_U;
  8632. bb_with_spacing.Min.x -= spacing_L;
  8633. bb_with_spacing.Min.y -= spacing_U;
  8634. bb_with_spacing.Max.x += spacing_R;
  8635. bb_with_spacing.Max.y += spacing_D;
  8636. if (!ItemAdd(bb_with_spacing, &id))
  8637. {
  8638. if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1)
  8639. PushColumnClipRect();
  8640. return false;
  8641. }
  8642.  
  8643. ImGuiButtonFlags button_flags = 0;
  8644. if (flags & ImGuiSelectableFlags_Menu) button_flags |= ImGuiButtonFlags_PressedOnClick;
  8645. if (flags & ImGuiSelectableFlags_MenuItem) button_flags |= ImGuiButtonFlags_PressedOnClick|ImGuiButtonFlags_PressedOnRelease;
  8646. if (flags & ImGuiSelectableFlags_Disabled) button_flags |= ImGuiButtonFlags_Disabled;
  8647. if (flags & ImGuiSelectableFlags_AllowDoubleClick) button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick;
  8648. bool hovered, held;
  8649. bool pressed = ButtonBehavior(bb_with_spacing, id, &hovered, &held, button_flags);
  8650. if (flags & ImGuiSelectableFlags_Disabled)
  8651. selected = false;
  8652.  
  8653. // Render
  8654. if (hovered || selected)
  8655. {
  8656. const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
  8657. RenderFrame(bb_with_spacing.Min, bb_with_spacing.Max, col, false, 0.0f);
  8658. }
  8659.  
  8660. if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1)
  8661. {
  8662. PushColumnClipRect();
  8663. bb_with_spacing.Max.x -= (GetContentRegionMax().x - max_x);
  8664. }
  8665.  
  8666. if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
  8667. RenderTextClipped(bb.Min, bb_with_spacing.Max, label, NULL, &label_size, ImVec2(0.0f,0.0f));
  8668. if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor();
  8669.  
  8670. // Automatically close popups
  8671. if (pressed && !(flags & ImGuiSelectableFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
  8672. CloseCurrentPopup();
  8673. return pressed;
  8674. }
  8675.  
  8676. bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)
  8677. {
  8678. if (Selectable(label, *p_selected, flags, size_arg))
  8679. {
  8680. *p_selected = !*p_selected;
  8681. return true;
  8682. }
  8683. return false;
  8684. }
  8685.  
  8686. // Helper to calculate the size of a listbox and display a label on the right.
  8687. // Tip: To have a list filling the entire window width, PushItemWidth(-1) and pass an empty label "##empty"
  8688. bool ImGui::ListBoxHeader(const char* label, const ImVec2& size_arg)
  8689. {
  8690. ImGuiWindow* window = GetCurrentWindow();
  8691. if (window->SkipItems)
  8692. return false;
  8693.  
  8694. const ImGuiStyle& style = GetStyle();
  8695. const ImGuiID id = GetID(label);
  8696. const ImVec2 label_size = CalcTextSize(label, NULL, true);
  8697.  
  8698. // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar.
  8699. ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), GetTextLineHeightWithSpacing() * 7.4f + style.ItemSpacing.y);
  8700. ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y));
  8701. ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size);
  8702. ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
  8703. window->DC.LastItemRect = bb;
  8704.  
  8705. BeginGroup();
  8706. if (label_size.x > 0)
  8707. RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
  8708.  
  8709. BeginChildFrame(id, frame_bb.GetSize());
  8710. return true;
  8711. }
  8712.  
  8713. bool ImGui::ListBoxHeader(const char* label, int items_count, int height_in_items)
  8714. {
  8715. // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar.
  8716. // 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.
  8717. // I am expecting that someone will come and complain about this behavior in a remote future, then we can advise on a better solution.
  8718. if (height_in_items < 0)
  8719. height_in_items = ImMin(items_count, 7);
  8720. float height_in_items_f = height_in_items < items_count ? (height_in_items + 0.40f) : (height_in_items + 0.00f);
  8721.  
  8722. // 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().
  8723. ImVec2 size;
  8724. size.x = 0.0f;
  8725. size.y = GetTextLineHeightWithSpacing() * height_in_items_f + GetStyle().ItemSpacing.y;
  8726. return ListBoxHeader(label, size);
  8727. }
  8728.  
  8729. void ImGui::ListBoxFooter()
  8730. {
  8731. ImGuiWindow* parent_window = GetParentWindow();
  8732. const ImRect bb = parent_window->DC.LastItemRect;
  8733. const ImGuiStyle& style = GetStyle();
  8734.  
  8735. EndChildFrame();
  8736.  
  8737. // Redeclare item size so that it includes the label (we have stored the full size in LastItemRect)
  8738. // We call SameLine() to restore DC.CurrentLine* data
  8739. SameLine();
  8740. parent_window->DC.CursorPos = bb.Min;
  8741. ItemSize(bb, style.FramePadding.y);
  8742. EndGroup();
  8743. }
  8744.  
  8745. bool ImGui::ListBox(const char* label, int* current_item, const char* const* items, int items_count, int height_items)
  8746. {
  8747. const bool value_changed = ListBox(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_items);
  8748. return value_changed;
  8749. }
  8750.  
  8751. 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)
  8752. {
  8753. if (!ListBoxHeader(label, items_count, height_in_items))
  8754. return false;
  8755.  
  8756. // 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.
  8757. bool value_changed = false;
  8758. ImGuiListClipper clipper(items_count, GetTextLineHeightWithSpacing());
  8759. while (clipper.Step())
  8760. for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
  8761. {
  8762. const bool item_selected = (i == *current_item);
  8763. const char* item_text;
  8764. if (!items_getter(data, i, &item_text))
  8765. item_text = "*Unknown item*";
  8766.  
  8767. PushID(i);
  8768. if (Selectable(item_text, item_selected))
  8769. {
  8770. *current_item = i;
  8771. value_changed = true;
  8772. }
  8773. PopID();
  8774. }
  8775. ListBoxFooter();
  8776. return value_changed;
  8777. }
  8778.  
  8779. bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, bool enabled)
  8780. {
  8781. ImGuiWindow* window = GetCurrentWindow();
  8782. if (window->SkipItems)
  8783. return false;
  8784.  
  8785. ImGuiContext& g = *GImGui;
  8786. ImVec2 pos = window->DC.CursorPos;
  8787. ImVec2 label_size = CalcTextSize(label, NULL, true);
  8788. ImVec2 shortcut_size = shortcut ? CalcTextSize(shortcut, NULL) : ImVec2(0.0f, 0.0f);
  8789. float w = window->MenuColumns.DeclColumns(label_size.x, shortcut_size.x, (float)(int)(g.FontSize * 1.20f)); // Feedback for next frame
  8790. float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w);
  8791.  
  8792. bool pressed = Selectable(label, false, ImGuiSelectableFlags_MenuItem | ImGuiSelectableFlags_DrawFillAvailWidth | (enabled ? 0 : ImGuiSelectableFlags_Disabled), ImVec2(w, 0.0f));
  8793. if (shortcut_size.x > 0.0f)
  8794. {
  8795. PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
  8796. RenderText(pos + ImVec2(window->MenuColumns.Pos[1] + extra_w, 0.0f), shortcut, NULL, false);
  8797. PopStyleColor();
  8798. }
  8799.  
  8800. if (selected)
  8801. RenderCheckMark(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.20f, 0.0f), GetColorU32(enabled ? ImGuiCol_Text : ImGuiCol_TextDisabled));
  8802.  
  8803. return pressed;
  8804. }
  8805.  
  8806. bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled)
  8807. {
  8808. if (MenuItem(label, shortcut, p_selected ? *p_selected : false, enabled))
  8809. {
  8810. if (p_selected)
  8811. *p_selected = !*p_selected;
  8812. return true;
  8813. }
  8814. return false;
  8815. }
  8816.  
  8817. bool ImGui::BeginMainMenuBar()
  8818. {
  8819. ImGuiContext& g = *GImGui;
  8820. SetNextWindowPos(ImVec2(0.0f, 0.0f));
  8821. SetNextWindowSize(ImVec2(g.IO.DisplaySize.x, g.FontBaseSize + g.Style.FramePadding.y * 2.0f));
  8822. PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
  8823. PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0,0));
  8824. if (!Begin("##MainMenuBar", NULL, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoScrollbar|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_MenuBar)
  8825. || !BeginMenuBar())
  8826. {
  8827. End();
  8828. PopStyleVar(2);
  8829. return false;
  8830. }
  8831. g.CurrentWindow->DC.MenuBarOffsetX += g.Style.DisplaySafeAreaPadding.x;
  8832. return true;
  8833. }
  8834.  
  8835. void ImGui::EndMainMenuBar()
  8836. {
  8837. EndMenuBar();
  8838. End();
  8839. PopStyleVar(2);
  8840. }
  8841.  
  8842. bool ImGui::BeginMenuBar()
  8843. {
  8844. ImGuiWindow* window = GetCurrentWindow();
  8845. if (window->SkipItems)
  8846. return false;
  8847. if (!(window->Flags & ImGuiWindowFlags_MenuBar))
  8848. return false;
  8849.  
  8850. IM_ASSERT(!window->DC.MenuBarAppending);
  8851. BeginGroup(); // Save position
  8852. PushID("##menubar");
  8853. ImRect rect = window->MenuBarRect();
  8854. 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);
  8855. window->DC.CursorPos = ImVec2(rect.Min.x + window->DC.MenuBarOffsetX, rect.Min.y);// + g.Style.FramePadding.y);
  8856. window->DC.LayoutType = ImGuiLayoutType_Horizontal;
  8857. window->DC.MenuBarAppending = true;
  8858. AlignFirstTextHeightToWidgets();
  8859. return true;
  8860. }
  8861.  
  8862. void ImGui::EndMenuBar()
  8863. {
  8864. ImGuiWindow* window = GetCurrentWindow();
  8865. if (window->SkipItems)
  8866. return;
  8867.  
  8868. IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar);
  8869. IM_ASSERT(window->DC.MenuBarAppending);
  8870. PopClipRect();
  8871. PopID();
  8872. window->DC.MenuBarOffsetX = window->DC.CursorPos.x - window->MenuBarRect().Min.x;
  8873. window->DC.GroupStack.back().AdvanceCursor = false;
  8874. EndGroup();
  8875. window->DC.LayoutType = ImGuiLayoutType_Vertical;
  8876. window->DC.MenuBarAppending = false;
  8877. }
  8878.  
  8879. bool ImGui::BeginMenu(const char* label, bool enabled)
  8880. {
  8881. ImGuiWindow* window = GetCurrentWindow();
  8882. if (window->SkipItems)
  8883. return false;
  8884.  
  8885. ImGuiContext& g = *GImGui;
  8886. const ImGuiStyle& style = g.Style;
  8887. const ImGuiID id = window->GetID(label);
  8888.  
  8889. ImVec2 label_size = CalcTextSize(label, NULL, true);
  8890. ImGuiWindow* backed_focused_window = g.FocusedWindow;
  8891.  
  8892. bool pressed;
  8893. bool menu_is_open = IsPopupOpen(id);
  8894. bool menuset_is_open = !(window->Flags & ImGuiWindowFlags_Popup) && (g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].ParentMenuSet == window->GetID("##menus"));
  8895. if (menuset_is_open)
  8896. g.FocusedWindow = window;
  8897.  
  8898. // The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu (using FindBestPopupWindowPos).
  8899. ImVec2 popup_pos, pos = window->DC.CursorPos;
  8900. if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
  8901. {
  8902. popup_pos = ImVec2(pos.x - window->WindowPadding.x, pos.y - style.FramePadding.y + window->MenuBarHeight());
  8903. window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f);
  8904. PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f);
  8905. float w = label_size.x;
  8906. pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f));
  8907. PopStyleVar();
  8908. SameLine();
  8909. window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f);
  8910. }
  8911. else
  8912. {
  8913. popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y);
  8914. float w = window->MenuColumns.DeclColumns(label_size.x, 0.0f, (float)(int)(g.FontSize * 1.20f)); // Feedback to next frame
  8915. float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w);
  8916. pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | ImGuiSelectableFlags_DrawFillAvailWidth | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f));
  8917. if (!enabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
  8918. RenderCollapseTriangle(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.20f, 0.0f), false);
  8919. if (!enabled) PopStyleColor();
  8920. }
  8921.  
  8922. bool hovered = enabled && IsHovered(window->DC.LastItemRect, id);
  8923. if (menuset_is_open)
  8924. g.FocusedWindow = backed_focused_window;
  8925.  
  8926. bool want_open = false, want_close = false;
  8927. if (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu))
  8928. {
  8929. // Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive.
  8930. bool moving_within_opened_triangle = false;
  8931. if (g.HoveredWindow == window && g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].ParentWindow == window)
  8932. {
  8933. if (ImGuiWindow* next_window = g.OpenPopupStack[g.CurrentPopupStack.Size].Window)
  8934. {
  8935. ImRect next_window_rect = next_window->Rect();
  8936. ImVec2 ta = g.IO.MousePos - g.IO.MouseDelta;
  8937. ImVec2 tb = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetTL() : next_window_rect.GetTR();
  8938. ImVec2 tc = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetBL() : next_window_rect.GetBR();
  8939. float extra = ImClamp(fabsf(ta.x - tb.x) * 0.30f, 5.0f, 30.0f); // add a bit of extra slack.
  8940. ta.x += (window->Pos.x < next_window->Pos.x) ? -0.5f : +0.5f; // to avoid numerical issues
  8941. 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?
  8942. tc.y = ta.y + ImMin((tc.y + extra) - ta.y, +100.0f);
  8943. moving_within_opened_triangle = ImIsPointInTriangle(g.IO.MousePos, ta, tb, tc);
  8944. //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
  8945. }
  8946. }
  8947.  
  8948. want_close = (menu_is_open && !hovered && g.HoveredWindow == window && g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrame != id && !moving_within_opened_triangle);
  8949. want_open = (!menu_is_open && hovered && !moving_within_opened_triangle) || (!menu_is_open && hovered && pressed);
  8950. }
  8951. else if (menu_is_open && pressed && menuset_is_open) // menu-bar: click open menu to close
  8952. {
  8953. want_close = true;
  8954. want_open = menu_is_open = false;
  8955. }
  8956. else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // menu-bar: first click to open, then hover to open others
  8957. want_open = true;
  8958. 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.. }'
  8959. want_close = true;
  8960. if (want_close && IsPopupOpen(id))
  8961. ClosePopupToLevel(GImGui->CurrentPopupStack.Size);
  8962.  
  8963. if (!menu_is_open && want_open && g.OpenPopupStack.Size > g.CurrentPopupStack.Size)
  8964. {
  8965. // Don't recycle same menu level in the same frame, first close the other menu and yield for a frame.
  8966. OpenPopup(label);
  8967. return false;
  8968. }
  8969.  
  8970. menu_is_open |= want_open;
  8971. if (want_open)
  8972. OpenPopup(label);
  8973.  
  8974. if (menu_is_open)
  8975. {
  8976. SetNextWindowPos(popup_pos, ImGuiSetCond_Always);
  8977. ImGuiWindowFlags flags = ImGuiWindowFlags_ShowBorders | ((window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) ? ImGuiWindowFlags_ChildMenu|ImGuiWindowFlags_ChildWindow : ImGuiWindowFlags_ChildMenu);
  8978. menu_is_open = BeginPopupEx(label, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
  8979. }
  8980.  
  8981. return menu_is_open;
  8982. }
  8983.  
  8984. void ImGui::EndMenu()
  8985. {
  8986. EndPopup();
  8987. }
  8988.  
  8989. // A little colored square. Return true when clicked.
  8990. // FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip.
  8991. bool ImGui::ColorButton(const ImVec4& col, bool small_height, bool outline_border)
  8992. {
  8993. ImGuiWindow* window = GetCurrentWindow();
  8994. if (window->SkipItems)
  8995. return false;
  8996.  
  8997. ImGuiContext& g = *GImGui;
  8998. const ImGuiStyle& style = g.Style;
  8999. const ImGuiID id = window->GetID("#colorbutton");
  9000. const float square_size = g.FontSize;
  9001. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(square_size + style.FramePadding.y*2, square_size + (small_height ? 0 : style.FramePadding.y*2)));
  9002. ItemSize(bb, small_height ? 0.0f : style.FramePadding.y);
  9003. if (!ItemAdd(bb, &id))
  9004. return false;
  9005.  
  9006. bool hovered, held;
  9007. bool pressed = ButtonBehavior(bb, id, &hovered, &held);
  9008. RenderFrame(bb.Min, bb.Max, GetColorU32(col), outline_border, style.FrameRounding);
  9009.  
  9010. if (hovered)
  9011. SetTooltip("Color:\n(%.2f,%.2f,%.2f,%.2f)\n#%02X%02X%02X%02X", col.x, col.y, col.z, col.w, IM_F32_TO_INT8_SAT(col.x), IM_F32_TO_INT8_SAT(col.y), IM_F32_TO_INT8_SAT(col.z), IM_F32_TO_INT8_SAT(col.w));
  9012.  
  9013. return pressed;
  9014. }
  9015.  
  9016. bool ImGui::ColorEdit3(const char* label, float col[3])
  9017. {
  9018. float col4[4];
  9019. col4[0] = col[0];
  9020. col4[1] = col[1];
  9021. col4[2] = col[2];
  9022. col4[3] = 1.0f;
  9023. const bool value_changed = ColorEdit4(label, col4, false);
  9024. col[0] = col4[0];
  9025. col[1] = col4[1];
  9026. col[2] = col4[2];
  9027. return value_changed;
  9028. }
  9029.  
  9030. // Edit colors components (each component in 0.0f..1.0f range
  9031. // Use CTRL-Click to input value and TAB to go to next item.
  9032. bool ImGui::ColorEdit4(const char* label, float col[4], bool alpha)
  9033. {
  9034. ImGuiWindow* window = GetCurrentWindow();
  9035. if (window->SkipItems)
  9036. return false;
  9037.  
  9038. ImGuiContext& g = *GImGui;
  9039. const ImGuiStyle& style = g.Style;
  9040. const ImGuiID id = window->GetID(label);
  9041. const float w_full = CalcItemWidth();
  9042. const float square_sz = (g.FontSize + style.FramePadding.y * 2.0f);
  9043.  
  9044. ImGuiColorEditMode edit_mode = window->DC.ColorEditMode;
  9045. if (edit_mode == ImGuiColorEditMode_UserSelect || edit_mode == ImGuiColorEditMode_UserSelectShowButton)
  9046. edit_mode = g.ColorEditModeStorage.GetInt(id, 0) % 3;
  9047.  
  9048. float f[4] = { col[0], col[1], col[2], col[3] };
  9049. if (edit_mode == ImGuiColorEditMode_HSV)
  9050. ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]);
  9051.  
  9052. 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]) };
  9053.  
  9054. int components = alpha ? 4 : 3;
  9055. bool value_changed = false;
  9056.  
  9057. BeginGroup();
  9058. PushID(label);
  9059.  
  9060. const bool hsv = (edit_mode == 1);
  9061. switch (edit_mode)
  9062. {
  9063. case ImGuiColorEditMode_RGB:
  9064. case ImGuiColorEditMode_HSV:
  9065. {
  9066. // RGB/HSV 0..255 Sliders
  9067. const float w_items_all = w_full - (square_sz + style.ItemInnerSpacing.x);
  9068. const float w_item_one = ImMax(1.0f, (float)(int)((w_items_all - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
  9069. const float w_item_last = ImMax(1.0f, (float)(int)(w_items_all - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
  9070.  
  9071. const bool hide_prefix = (w_item_one <= CalcTextSize("M:999").x);
  9072. const char* ids[4] = { "##X", "##Y", "##Z", "##W" };
  9073. const char* fmt_table[3][4] =
  9074. {
  9075. { "%3.0f", "%3.0f", "%3.0f", "%3.0f" },
  9076. { "R:%3.0f", "G:%3.0f", "B:%3.0f", "A:%3.0f" },
  9077. { "H:%3.0f", "S:%3.0f", "V:%3.0f", "A:%3.0f" }
  9078. };
  9079. const char** fmt = hide_prefix ? fmt_table[0] : hsv ? fmt_table[2] : fmt_table[1];
  9080.  
  9081. PushItemWidth(w_item_one);
  9082. for (int n = 0; n < components; n++)
  9083. {
  9084. if (n > 0)
  9085. SameLine(0, style.ItemInnerSpacing.x);
  9086. if (n + 1 == components)
  9087. PushItemWidth(w_item_last);
  9088. value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, 255, fmt[n]);
  9089. }
  9090. PopItemWidth();
  9091. PopItemWidth();
  9092. }
  9093. break;
  9094. case ImGuiColorEditMode_HEX:
  9095. {
  9096. // RGB Hexadecimal Input
  9097. const float w_slider_all = w_full - square_sz;
  9098. char buf[64];
  9099. if (alpha)
  9100. ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", i[0], i[1], i[2], i[3]);
  9101. else
  9102. ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", i[0], i[1], i[2]);
  9103. PushItemWidth(w_slider_all - style.ItemInnerSpacing.x);
  9104. if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase))
  9105. {
  9106. value_changed |= true;
  9107. char* p = buf;
  9108. while (*p == '#' || ImCharIsSpace(*p))
  9109. p++;
  9110. i[0] = i[1] = i[2] = i[3] = 0;
  9111. if (alpha)
  9112. sscanf(p, "%02X%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2], (unsigned int*)&i[3]); // Treat at unsigned (%X is unsigned)
  9113. else
  9114. sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]);
  9115. }
  9116. PopItemWidth();
  9117. }
  9118. break;
  9119. }
  9120.  
  9121. SameLine(0, style.ItemInnerSpacing.x);
  9122.  
  9123. const ImVec4 col_display(col[0], col[1], col[2], 1.0f);
  9124. if (ColorButton(col_display))
  9125. g.ColorEditModeStorage.SetInt(id, (edit_mode + 1) % 3); // Don't set local copy of 'edit_mode' right away!
  9126.  
  9127. // Recreate our own tooltip over's ColorButton() one because we want to display correct alpha here
  9128. if (IsItemHovered())
  9129. SetTooltip("Color:\n(%.2f,%.2f,%.2f,%.2f)\n#%02X%02X%02X%02X", col[0], col[1], col[2], col[3], IM_F32_TO_INT8_SAT(col[0]), IM_F32_TO_INT8_SAT(col[1]), IM_F32_TO_INT8_SAT(col[2]), IM_F32_TO_INT8_SAT(col[3]));
  9130.  
  9131. if (window->DC.ColorEditMode == ImGuiColorEditMode_UserSelectShowButton)
  9132. {
  9133. SameLine(0, style.ItemInnerSpacing.x);
  9134. const char* button_titles[3] = { "RGB", "HSV", "HEX" };
  9135. if (ButtonEx(button_titles[edit_mode], ImVec2(0,0), ImGuiButtonFlags_DontClosePopups))
  9136. g.ColorEditModeStorage.SetInt(id, (edit_mode + 1) % 3); // Don't set local copy of 'edit_mode' right away!
  9137. }
  9138.  
  9139. const char* label_display_end = FindRenderedTextEnd(label);
  9140. if (label != label_display_end)
  9141. {
  9142. SameLine(0, (window->DC.ColorEditMode == ImGuiColorEditMode_UserSelectShowButton) ? -1.0f : style.ItemInnerSpacing.x);
  9143. TextUnformatted(label, label_display_end);
  9144. }
  9145.  
  9146. // Convert back
  9147. for (int n = 0; n < 4; n++)
  9148. f[n] = i[n] / 255.0f;
  9149. if (edit_mode == 1)
  9150. ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]);
  9151.  
  9152. if (value_changed)
  9153. {
  9154. col[0] = f[0];
  9155. col[1] = f[1];
  9156. col[2] = f[2];
  9157. if (alpha)
  9158. col[3] = f[3];
  9159. }
  9160.  
  9161. PopID();
  9162. EndGroup();
  9163.  
  9164. return value_changed;
  9165. }
  9166.  
  9167. void ImGui::ColorEditMode(ImGuiColorEditMode mode)
  9168. {
  9169. ImGuiWindow* window = GetCurrentWindow();
  9170. window->DC.ColorEditMode = mode;
  9171. }
  9172.  
  9173. // Horizontal separating line.
  9174. void ImGui::Separator()
  9175. {
  9176. ImGuiWindow* window = GetCurrentWindow();
  9177. if (window->SkipItems)
  9178. return;
  9179.  
  9180. if (window->DC.ColumnsCount > 1)
  9181. PopClipRect();
  9182.  
  9183. float x1 = window->Pos.x;
  9184. float x2 = window->Pos.x + window->Size.x;
  9185. if (!window->DC.GroupStack.empty())
  9186. x1 += window->DC.IndentX;
  9187.  
  9188. const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y+1.0f));
  9189. 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.
  9190. if (!ItemAdd(bb, NULL))
  9191. {
  9192. if (window->DC.ColumnsCount > 1)
  9193. PushColumnClipRect();
  9194. return;
  9195. }
  9196.  
  9197. window->DrawList->AddLine(bb.Min, ImVec2(bb.Max.x,bb.Min.y), GetColorU32(ImGuiCol_Border));
  9198.  
  9199. ImGuiContext& g = *GImGui;
  9200. if (g.LogEnabled)
  9201. LogText(IM_NEWLINE "--------------------------------");
  9202.  
  9203. if (window->DC.ColumnsCount > 1)
  9204. {
  9205. PushColumnClipRect();
  9206. window->DC.ColumnsCellMinY = window->DC.CursorPos.y;
  9207. }
  9208. }
  9209.  
  9210. void ImGui::Spacing()
  9211. {
  9212. ImGuiWindow* window = GetCurrentWindow();
  9213. if (window->SkipItems)
  9214. return;
  9215. ItemSize(ImVec2(0,0));
  9216. }
  9217.  
  9218. void ImGui::Dummy(const ImVec2& size)
  9219. {
  9220. ImGuiWindow* window = GetCurrentWindow();
  9221. if (window->SkipItems)
  9222. return;
  9223.  
  9224. const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
  9225. ItemSize(bb);
  9226. ItemAdd(bb, NULL);
  9227. }
  9228.  
  9229. bool ImGui::IsRectVisible(const ImVec2& size)
  9230. {
  9231. ImGuiWindow* window = GetCurrentWindowRead();
  9232. return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
  9233. }
  9234.  
  9235. bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
  9236. {
  9237. ImGuiWindow* window = GetCurrentWindowRead();
  9238. return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
  9239. }
  9240.  
  9241. // 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.)
  9242. void ImGui::BeginGroup()
  9243. {
  9244. ImGuiWindow* window = GetCurrentWindow();
  9245.  
  9246. window->DC.GroupStack.resize(window->DC.GroupStack.Size + 1);
  9247. ImGuiGroupData& group_data = window->DC.GroupStack.back();
  9248. group_data.BackupCursorPos = window->DC.CursorPos;
  9249. group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
  9250. group_data.BackupIndentX = window->DC.IndentX;
  9251. group_data.BackupGroupOffsetX = window->DC.GroupOffsetX;
  9252. group_data.BackupCurrentLineHeight = window->DC.CurrentLineHeight;
  9253. group_data.BackupCurrentLineTextBaseOffset = window->DC.CurrentLineTextBaseOffset;
  9254. group_data.BackupLogLinePosY = window->DC.LogLinePosY;
  9255. group_data.BackupActiveIdIsAlive = GImGui->ActiveIdIsAlive;
  9256. group_data.AdvanceCursor = true;
  9257.  
  9258. window->DC.GroupOffsetX = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffsetX;
  9259. window->DC.IndentX = window->DC.GroupOffsetX;
  9260. window->DC.CursorMaxPos = window->DC.CursorPos;
  9261. window->DC.CurrentLineHeight = 0.0f;
  9262. window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
  9263. }
  9264.  
  9265. void ImGui::EndGroup()
  9266. {
  9267. ImGuiContext& g = *GImGui;
  9268. ImGuiWindow* window = GetCurrentWindow();
  9269.  
  9270. IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls
  9271.  
  9272. ImGuiGroupData& group_data = window->DC.GroupStack.back();
  9273.  
  9274. ImRect group_bb(group_data.BackupCursorPos, window->DC.CursorMaxPos);
  9275. group_bb.Max.y -= g.Style.ItemSpacing.y; // Cancel out last vertical spacing because we are adding one ourselves.
  9276. group_bb.Max = ImMax(group_bb.Min, group_bb.Max);
  9277.  
  9278. window->DC.CursorPos = group_data.BackupCursorPos;
  9279. window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
  9280. window->DC.CurrentLineHeight = group_data.BackupCurrentLineHeight;
  9281. window->DC.CurrentLineTextBaseOffset = group_data.BackupCurrentLineTextBaseOffset;
  9282. window->DC.IndentX = group_data.BackupIndentX;
  9283. window->DC.GroupOffsetX = group_data.BackupGroupOffsetX;
  9284. window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
  9285.  
  9286. if (group_data.AdvanceCursor)
  9287. {
  9288. 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.
  9289. ItemSize(group_bb.GetSize(), group_data.BackupCurrentLineTextBaseOffset);
  9290. ItemAdd(group_bb, NULL);
  9291. }
  9292.  
  9293. // 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.
  9294. // 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.
  9295. const bool active_id_within_group = (!group_data.BackupActiveIdIsAlive && g.ActiveIdIsAlive && g.ActiveId && g.ActiveIdWindow->RootWindow == window->RootWindow);
  9296. if (active_id_within_group)
  9297. window->DC.LastItemId = g.ActiveId;
  9298. if (active_id_within_group && g.HoveredId == g.ActiveId)
  9299. window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = true;
  9300.  
  9301. window->DC.GroupStack.pop_back();
  9302.  
  9303. //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // Debug
  9304. }
  9305.  
  9306. // Gets back to previous line and continue with horizontal layout
  9307. // pos_x == 0 : follow right after previous item
  9308. // pos_x != 0 : align to specified x position (relative to window/group left)
  9309. // spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0
  9310. // spacing_w >= 0 : enforce spacing amount
  9311. void ImGui::SameLine(float pos_x, float spacing_w)
  9312. {
  9313. ImGuiWindow* window = GetCurrentWindow();
  9314. if (window->SkipItems)
  9315. return;
  9316.  
  9317. ImGuiContext& g = *GImGui;
  9318. if (pos_x != 0.0f)
  9319. {
  9320. if (spacing_w < 0.0f) spacing_w = 0.0f;
  9321. window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + pos_x + spacing_w + window->DC.GroupOffsetX + window->DC.ColumnsOffsetX;
  9322. window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
  9323. }
  9324. else
  9325. {
  9326. if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x;
  9327. window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
  9328. window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
  9329. }
  9330. window->DC.CurrentLineHeight = window->DC.PrevLineHeight;
  9331. window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
  9332. }
  9333.  
  9334. void ImGui::NewLine()
  9335. {
  9336. ImGuiWindow* window = GetCurrentWindow();
  9337. if (window->SkipItems)
  9338. return;
  9339. 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.
  9340. ItemSize(ImVec2(0,0));
  9341. else
  9342. ItemSize(ImVec2(0.0f, GImGui->FontSize));
  9343. }
  9344.  
  9345. void ImGui::NextColumn()
  9346. {
  9347. ImGuiWindow* window = GetCurrentWindow();
  9348. if (window->SkipItems || window->DC.ColumnsCount <= 1)
  9349. return;
  9350.  
  9351. ImGuiContext& g = *GImGui;
  9352. PopItemWidth();
  9353. PopClipRect();
  9354.  
  9355. window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y);
  9356. if (++window->DC.ColumnsCurrent < window->DC.ColumnsCount)
  9357. {
  9358. // Columns 1+ cancel out IndentX
  9359. window->DC.ColumnsOffsetX = GetColumnOffset(window->DC.ColumnsCurrent) - window->DC.IndentX + g.Style.ItemSpacing.x;
  9360. window->DrawList->ChannelsSetCurrent(window->DC.ColumnsCurrent);
  9361. }
  9362. else
  9363. {
  9364. window->DC.ColumnsCurrent = 0;
  9365. window->DC.ColumnsOffsetX = 0.0f;
  9366. window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY;
  9367. window->DrawList->ChannelsSetCurrent(0);
  9368. }
  9369. window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX);
  9370. window->DC.CursorPos.y = window->DC.ColumnsCellMinY;
  9371. window->DC.CurrentLineHeight = 0.0f;
  9372. window->DC.CurrentLineTextBaseOffset = 0.0f;
  9373.  
  9374. PushColumnClipRect();
  9375. PushItemWidth(GetColumnWidth() * 0.65f); // FIXME: Move on columns setup
  9376. }
  9377.  
  9378. int ImGui::GetColumnIndex()
  9379. {
  9380. ImGuiWindow* window = GetCurrentWindowRead();
  9381. return window->DC.ColumnsCurrent;
  9382. }
  9383.  
  9384. int ImGui::GetColumnsCount()
  9385. {
  9386. ImGuiWindow* window = GetCurrentWindowRead();
  9387. return window->DC.ColumnsCount;
  9388. }
  9389.  
  9390. static float GetDraggedColumnOffset(int column_index)
  9391. {
  9392. // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing
  9393. // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning.
  9394. ImGuiContext& g = *GImGui;
  9395. ImGuiWindow* window = ImGui::GetCurrentWindowRead();
  9396. 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.
  9397. IM_ASSERT(g.ActiveId == window->DC.ColumnsSetId + ImGuiID(column_index));
  9398.  
  9399. float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x - window->Pos.x;
  9400. x = ImClamp(x, ImGui::GetColumnOffset(column_index-1)+g.Style.ColumnsMinSpacing, ImGui::GetColumnOffset(column_index+1)-g.Style.ColumnsMinSpacing);
  9401.  
  9402. return (float)(int)x;
  9403. }
  9404.  
  9405. float ImGui::GetColumnOffset(int column_index)
  9406. {
  9407. ImGuiContext& g = *GImGui;
  9408. ImGuiWindow* window = GetCurrentWindowRead();
  9409. if (column_index < 0)
  9410. column_index = window->DC.ColumnsCurrent;
  9411.  
  9412. if (g.ActiveId)
  9413. {
  9414. const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index);
  9415. if (g.ActiveId == column_id)
  9416. return GetDraggedColumnOffset(column_index);
  9417. }
  9418.  
  9419. IM_ASSERT(column_index < window->DC.ColumnsData.Size);
  9420. const float t = window->DC.ColumnsData[column_index].OffsetNorm;
  9421. const float x_offset = window->DC.ColumnsMinX + t * (window->DC.ColumnsMaxX - window->DC.ColumnsMinX);
  9422. return (float)(int)x_offset;
  9423. }
  9424.  
  9425. void ImGui::SetColumnOffset(int column_index, float offset)
  9426. {
  9427. ImGuiWindow* window = GetCurrentWindow();
  9428. if (column_index < 0)
  9429. column_index = window->DC.ColumnsCurrent;
  9430.  
  9431. IM_ASSERT(column_index < window->DC.ColumnsData.Size);
  9432. const float t = (offset - window->DC.ColumnsMinX) / (window->DC.ColumnsMaxX - window->DC.ColumnsMinX);
  9433. window->DC.ColumnsData[column_index].OffsetNorm = t;
  9434.  
  9435. const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index);
  9436. window->DC.StateStorage->SetFloat(column_id, t);
  9437. }
  9438.  
  9439. float ImGui::GetColumnWidth(int column_index)
  9440. {
  9441. ImGuiWindow* window = GetCurrentWindowRead();
  9442. if (column_index < 0)
  9443. column_index = window->DC.ColumnsCurrent;
  9444.  
  9445. float w = GetColumnOffset(column_index+1) - GetColumnOffset(column_index);
  9446. return w;
  9447. }
  9448.  
  9449. static void PushColumnClipRect(int column_index)
  9450. {
  9451. ImGuiWindow* window = ImGui::GetCurrentWindow();
  9452. if (column_index < 0)
  9453. column_index = window->DC.ColumnsCurrent;
  9454.  
  9455. float x1 = ImFloor(0.5f + window->Pos.x + ImGui::GetColumnOffset(column_index) - 1.0f);
  9456. float x2 = ImFloor(0.5f + window->Pos.x + ImGui::GetColumnOffset(column_index+1) - 1.0f);
  9457. ImGui::PushClipRect(ImVec2(x1,-FLT_MAX), ImVec2(x2,+FLT_MAX), true);
  9458. }
  9459.  
  9460. void ImGui::Columns(int columns_count, const char* id, bool border)
  9461. {
  9462. ImGuiContext& g = *GImGui;
  9463. ImGuiWindow* window = GetCurrentWindow();
  9464. IM_ASSERT(columns_count >= 1);
  9465.  
  9466. if (window->DC.ColumnsCount != 1)
  9467. {
  9468. if (window->DC.ColumnsCurrent != 0)
  9469. ItemSize(ImVec2(0,0)); // Advance to column 0
  9470. PopItemWidth();
  9471. PopClipRect();
  9472. window->DrawList->ChannelsMerge();
  9473.  
  9474. window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y);
  9475. window->DC.CursorPos.y = window->DC.ColumnsCellMaxY;
  9476. }
  9477.  
  9478. // Draw columns borders and handle resize at the time of "closing" a columns set
  9479. if (window->DC.ColumnsCount != columns_count && window->DC.ColumnsCount != 1 && window->DC.ColumnsShowBorders && !window->SkipItems)
  9480. {
  9481. const float y1 = window->DC.ColumnsStartPosY;
  9482. const float y2 = window->DC.CursorPos.y;
  9483. for (int i = 1; i < window->DC.ColumnsCount; i++)
  9484. {
  9485. float x = window->Pos.x + GetColumnOffset(i);
  9486. const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(i);
  9487. const ImRect column_rect(ImVec2(x-4,y1),ImVec2(x+4,y2));
  9488. if (IsClippedEx(column_rect, &column_id, false))
  9489. continue;
  9490.  
  9491. bool hovered, held;
  9492. ButtonBehavior(column_rect, column_id, &hovered, &held);
  9493. if (hovered || held)
  9494. g.MouseCursor = ImGuiMouseCursor_ResizeEW;
  9495.  
  9496. // Draw before resize so our items positioning are in sync with the line being drawn
  9497. const ImU32 col = GetColorU32(held ? ImGuiCol_ColumnActive : hovered ? ImGuiCol_ColumnHovered : ImGuiCol_Column);
  9498. const float xi = (float)(int)x;
  9499. window->DrawList->AddLine(ImVec2(xi, y1+1.0f), ImVec2(xi, y2), col);
  9500.  
  9501. if (held)
  9502. {
  9503. if (g.ActiveIdIsJustActivated)
  9504. g.ActiveIdClickOffset.x -= 4; // Store from center of column line (we used a 8 wide rect for columns clicking)
  9505. x = GetDraggedColumnOffset(i);
  9506. SetColumnOffset(i, x);
  9507. }
  9508. }
  9509. }
  9510.  
  9511. // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget.
  9512. // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer.
  9513. PushID(0x11223347 + (id ? 0 : columns_count));
  9514. window->DC.ColumnsSetId = window->GetID(id ? id : "columns");
  9515. PopID();
  9516.  
  9517. // Set state for first column
  9518. window->DC.ColumnsCurrent = 0;
  9519. window->DC.ColumnsCount = columns_count;
  9520. window->DC.ColumnsShowBorders = border;
  9521.  
  9522. const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : window->Size.x;
  9523. window->DC.ColumnsMinX = window->DC.IndentX; // Lock our horizontal range
  9524. window->DC.ColumnsMaxX = content_region_width - window->Scroll.x - ((window->Flags & ImGuiWindowFlags_NoScrollbar) ? 0 : g.Style.ScrollbarSize);// - window->WindowPadding().x;
  9525. window->DC.ColumnsStartPosY = window->DC.CursorPos.y;
  9526. window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.CursorPos.y;
  9527. window->DC.ColumnsOffsetX = 0.0f;
  9528. window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX);
  9529.  
  9530. if (window->DC.ColumnsCount != 1)
  9531. {
  9532. // Cache column offsets
  9533. window->DC.ColumnsData.resize(columns_count + 1);
  9534. for (int column_index = 0; column_index < columns_count + 1; column_index++)
  9535. {
  9536. const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index);
  9537. KeepAliveID(column_id);
  9538. const float default_t = column_index / (float)window->DC.ColumnsCount;
  9539. const float t = window->DC.StateStorage->GetFloat(column_id, default_t); // Cheaply store our floating point value inside the integer (could store a union into the map?)
  9540. window->DC.ColumnsData[column_index].OffsetNorm = t;
  9541. }
  9542. window->DrawList->ChannelsSplit(window->DC.ColumnsCount);
  9543. PushColumnClipRect();
  9544. PushItemWidth(GetColumnWidth() * 0.65f);
  9545. }
  9546. else
  9547. {
  9548. window->DC.ColumnsData.resize(0);
  9549. }
  9550. }
  9551.  
  9552. void ImGui::Indent(float indent_w)
  9553. {
  9554. ImGuiContext& g = *GImGui;
  9555. ImGuiWindow* window = GetCurrentWindow();
  9556. window->DC.IndentX += (indent_w > 0.0f) ? indent_w : g.Style.IndentSpacing;
  9557. window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX;
  9558. }
  9559.  
  9560. void ImGui::Unindent(float indent_w)
  9561. {
  9562. ImGuiContext& g = *GImGui;
  9563. ImGuiWindow* window = GetCurrentWindow();
  9564. window->DC.IndentX -= (indent_w > 0.0f) ? indent_w : g.Style.IndentSpacing;
  9565. window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX;
  9566. }
  9567.  
  9568. void ImGui::TreePush(const char* str_id)
  9569. {
  9570. ImGuiWindow* window = GetCurrentWindow();
  9571. Indent();
  9572. window->DC.TreeDepth++;
  9573. PushID(str_id ? str_id : "#TreePush");
  9574. }
  9575.  
  9576. void ImGui::TreePush(const void* ptr_id)
  9577. {
  9578. ImGuiWindow* window = GetCurrentWindow();
  9579. Indent();
  9580. window->DC.TreeDepth++;
  9581. PushID(ptr_id ? ptr_id : (const void*)"#TreePush");
  9582. }
  9583.  
  9584. void ImGui::TreePushRawID(ImGuiID id)
  9585. {
  9586. ImGuiWindow* window = GetCurrentWindow();
  9587. Indent();
  9588. window->DC.TreeDepth++;
  9589. window->IDStack.push_back(id);
  9590. }
  9591.  
  9592. void ImGui::TreePop()
  9593. {
  9594. ImGuiWindow* window = GetCurrentWindow();
  9595. Unindent();
  9596. window->DC.TreeDepth--;
  9597. PopID();
  9598. }
  9599.  
  9600. void ImGui::Value(const char* prefix, bool b)
  9601. {
  9602. Text("%s: %s", prefix, (b ? "true" : "false"));
  9603. }
  9604.  
  9605. void ImGui::Value(const char* prefix, int v)
  9606. {
  9607. Text("%s: %d", prefix, v);
  9608. }
  9609.  
  9610. void ImGui::Value(const char* prefix, unsigned int v)
  9611. {
  9612. Text("%s: %d", prefix, v);
  9613. }
  9614.  
  9615. void ImGui::Value(const char* prefix, float v, const char* float_format)
  9616. {
  9617. if (float_format)
  9618. {
  9619. char fmt[64];
  9620. ImFormatString(fmt, IM_ARRAYSIZE(fmt), "%%s: %s", float_format);
  9621. Text(fmt, prefix, v);
  9622. }
  9623. else
  9624. {
  9625. Text("%s: %.3f", prefix, v);
  9626. }
  9627. }
  9628.  
  9629. // FIXME: May want to remove those helpers?
  9630. void ImGui::ValueColor(const char* prefix, const ImVec4& v)
  9631. {
  9632. Text("%s: (%.2f,%.2f,%.2f,%.2f)", prefix, v.x, v.y, v.z, v.w);
  9633. SameLine();
  9634. ColorButton(v, true);
  9635. }
  9636.  
  9637. void ImGui::ValueColor(const char* prefix, ImU32 v)
  9638. {
  9639. Text("%s: %08X", prefix, v);
  9640. SameLine();
  9641. ColorButton(ColorConvertU32ToFloat4(v), true);
  9642. }
  9643.  
  9644. //-----------------------------------------------------------------------------
  9645. // PLATFORM DEPENDENT HELPERS
  9646. //-----------------------------------------------------------------------------
  9647.  
  9648. #if defined(_WIN32) && !defined(_WINDOWS_) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS))
  9649. #undef WIN32_LEAN_AND_MEAN
  9650. #define WIN32_LEAN_AND_MEAN
  9651. #include <windows.h>
  9652. #endif
  9653.  
  9654. // Win32 API clipboard implementation
  9655. #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS)
  9656.  
  9657. #ifdef _MSC_VER
  9658. #pragma comment(lib, "user32")
  9659. #endif
  9660.  
  9661. static const char* GetClipboardTextFn_DefaultImpl(void*)
  9662. {
  9663. static ImVector<char> buf_local;
  9664. buf_local.clear();
  9665. if (!OpenClipboard(NULL))
  9666. return NULL;
  9667. HANDLE wbuf_handle = GetClipboardData(CF_UNICODETEXT);
  9668. if (wbuf_handle == NULL)
  9669. return NULL;
  9670. if (ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle))
  9671. {
  9672. int buf_len = ImTextCountUtf8BytesFromStr(wbuf_global, NULL) + 1;
  9673. buf_local.resize(buf_len);
  9674. ImTextStrToUtf8(buf_local.Data, buf_len, wbuf_global, NULL);
  9675. }
  9676. GlobalUnlock(wbuf_handle);
  9677. CloseClipboard();
  9678. return buf_local.Data;
  9679. }
  9680.  
  9681. static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
  9682. {
  9683. if (!OpenClipboard(NULL))
  9684. return;
  9685. const int wbuf_length = ImTextCountCharsFromUtf8(text, NULL) + 1;
  9686. HGLOBAL wbuf_handle = GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar));
  9687. if (wbuf_handle == NULL)
  9688. return;
  9689. ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle);
  9690. ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL);
  9691. GlobalUnlock(wbuf_handle);
  9692. EmptyClipboard();
  9693. SetClipboardData(CF_UNICODETEXT, wbuf_handle);
  9694. CloseClipboard();
  9695. }
  9696.  
  9697. #else
  9698.  
  9699. // Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers
  9700. static const char* GetClipboardTextFn_DefaultImpl(void*)
  9701. {
  9702. return GImGui->PrivateClipboard;
  9703. }
  9704.  
  9705. // Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers
  9706. static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
  9707. {
  9708. ImGuiContext& g = *GImGui;
  9709. if (g.PrivateClipboard)
  9710. {
  9711. ImGui::MemFree(g.PrivateClipboard);
  9712. g.PrivateClipboard = NULL;
  9713. }
  9714. const char* text_end = text + strlen(text);
  9715. g.PrivateClipboard = (char*)ImGui::MemAlloc((size_t)(text_end - text) + 1);
  9716. memcpy(g.PrivateClipboard, text, (size_t)(text_end - text));
  9717. g.PrivateClipboard[(int)(text_end - text)] = 0;
  9718. }
  9719.  
  9720. #endif
  9721.  
  9722. // Win32 API IME support (for Asian languages, etc.)
  9723. #if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS)
  9724.  
  9725. #include <imm.h>
  9726. #ifdef _MSC_VER
  9727. #pragma comment(lib, "imm32")
  9728. #endif
  9729.  
  9730. static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y)
  9731. {
  9732. // Notify OS Input Method Editor of text input position
  9733. if (HWND hwnd = (HWND)GImGui->IO.ImeWindowHandle)
  9734. if (HIMC himc = ImmGetContext(hwnd))
  9735. {
  9736. COMPOSITIONFORM cf;
  9737. cf.ptCurrentPos.x = x;
  9738. cf.ptCurrentPos.y = y;
  9739. cf.dwStyle = CFS_FORCE_POSITION;
  9740. ImmSetCompositionWindow(himc, &cf);
  9741. }
  9742. }
  9743.  
  9744. #else
  9745.  
  9746. static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {}
  9747.  
  9748. #endif
  9749.  
  9750. //-----------------------------------------------------------------------------
  9751. // HELP
  9752. //-----------------------------------------------------------------------------
  9753.  
  9754. void ImGui::ShowMetricsWindow(bool* p_open)
  9755. {
  9756. if (ImGui::Begin("ImGui Metrics", p_open))
  9757. {
  9758. ImGui::Text("ImGui %s", ImGui::GetVersion());
  9759. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
  9760. ImGui::Text("%d vertices, %d indices (%d triangles)", ImGui::GetIO().MetricsRenderVertices, ImGui::GetIO().MetricsRenderIndices, ImGui::GetIO().MetricsRenderIndices / 3);
  9761. ImGui::Text("%d allocations", ImGui::GetIO().MetricsAllocs);
  9762. static bool show_clip_rects = true;
  9763. ImGui::Checkbox("Show clipping rectangles when hovering a ImDrawCmd", &show_clip_rects);
  9764. ImGui::Separator();
  9765.  
  9766. struct Funcs
  9767. {
  9768. static void NodeDrawList(ImDrawList* draw_list, const char* label)
  9769. {
  9770. 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);
  9771. if (draw_list == ImGui::GetWindowDrawList())
  9772. {
  9773. ImGui::SameLine();
  9774. ImGui::TextColored(ImColor(255,100,100), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
  9775. if (node_open) ImGui::TreePop();
  9776. return;
  9777. }
  9778. if (!node_open)
  9779. return;
  9780.  
  9781. ImDrawList* overlay_draw_list = &GImGui->OverlayDrawList; // Render additional visuals into the top-most draw list
  9782. overlay_draw_list->PushClipRectFullScreen();
  9783. int elem_offset = 0;
  9784. for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++)
  9785. {
  9786. if (pcmd->UserCallback)
  9787. {
  9788. ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
  9789. continue;
  9790. }
  9791. ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
  9792. 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);
  9793. if (show_clip_rects && ImGui::IsItemHovered())
  9794. {
  9795. ImRect clip_rect = pcmd->ClipRect;
  9796. ImRect vtxs_rect;
  9797. for (int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++)
  9798. vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos);
  9799. clip_rect.Floor(); overlay_draw_list->AddRect(clip_rect.Min, clip_rect.Max, IM_COL32(255,255,0,255));
  9800. vtxs_rect.Floor(); overlay_draw_list->AddRect(vtxs_rect.Min, vtxs_rect.Max, IM_COL32(255,0,255,255));
  9801. }
  9802. if (!pcmd_node_open)
  9803. continue;
  9804. ImGuiListClipper clipper(pcmd->ElemCount/3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
  9805. while (clipper.Step())
  9806. for (int prim = clipper.DisplayStart, vtx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++)
  9807. {
  9808. char buf[300], *buf_p = buf;
  9809. ImVec2 triangles_pos[3];
  9810. for (int n = 0; n < 3; n++, vtx_i++)
  9811. {
  9812. ImDrawVert& v = draw_list->VtxBuffer[idx_buffer ? idx_buffer[vtx_i] : vtx_i];
  9813. triangles_pos[n] = v.pos;
  9814. 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);
  9815. }
  9816. ImGui::Selectable(buf, false);
  9817. if (ImGui::IsItemHovered())
  9818. 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
  9819. }
  9820. ImGui::TreePop();
  9821. }
  9822. overlay_draw_list->PopClipRect();
  9823. ImGui::TreePop();
  9824. }
  9825.  
  9826. static void NodeWindows(ImVector<ImGuiWindow*>& windows, const char* label)
  9827. {
  9828. if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size))
  9829. return;
  9830. for (int i = 0; i < windows.Size; i++)
  9831. Funcs::NodeWindow(windows[i], "Window");
  9832. ImGui::TreePop();
  9833. }
  9834.  
  9835. static void NodeWindow(ImGuiWindow* window, const char* label)
  9836. {
  9837. if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Active || window->WasActive, window))
  9838. return;
  9839. NodeDrawList(window->DrawList, "DrawList");
  9840. ImGui::BulletText("Pos: (%.1f,%.1f)", window->Pos.x, window->Pos.y);
  9841. ImGui::BulletText("Size: (%.1f,%.1f), SizeContents (%.1f,%.1f)", window->Size.x, window->Size.y, window->SizeContents.x, window->SizeContents.y);
  9842. ImGui::BulletText("Scroll: (%.2f,%.2f)", window->Scroll.x, window->Scroll.y);
  9843. if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow");
  9844. if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows");
  9845. ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.Size * (int)sizeof(ImGuiStorage::Pair));
  9846. ImGui::TreePop();
  9847. }
  9848. };
  9849.  
  9850. ImGuiContext& g = *GImGui; // Access private state
  9851. Funcs::NodeWindows(g.Windows, "Windows");
  9852. if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", g.RenderDrawLists[0].Size))
  9853. {
  9854. for (int i = 0; i < g.RenderDrawLists[0].Size; i++)
  9855. Funcs::NodeDrawList(g.RenderDrawLists[0][i], "DrawList");
  9856. ImGui::TreePop();
  9857. }
  9858. if (ImGui::TreeNode("Popups", "Open Popups Stack (%d)", g.OpenPopupStack.Size))
  9859. {
  9860. for (int i = 0; i < g.OpenPopupStack.Size; i++)
  9861. {
  9862. ImGuiWindow* window = g.OpenPopupStack[i].Window;
  9863. 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" : "");
  9864. }
  9865. ImGui::TreePop();
  9866. }
  9867. if (ImGui::TreeNode("Basic state"))
  9868. {
  9869. ImGui::Text("FocusedWindow: '%s'", g.FocusedWindow ? g.FocusedWindow->Name : "NULL");
  9870. ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
  9871. ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL");
  9872. 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
  9873. ImGui::Text("ActiveID: 0x%08X/0x%08X", g.ActiveId, g.ActiveIdPreviousFrame);
  9874. ImGui::TreePop();
  9875. }
  9876. }
  9877. ImGui::End();
  9878. }
  9879.  
  9880. //-----------------------------------------------------------------------------
  9881.  
  9882. // Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
  9883. // 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.
  9884. #ifdef IMGUI_INCLUDE_IMGUI_USER_INL
  9885. #include "imgui_user.inl"
  9886. #endif
  9887.  
  9888. //-----------------------------------------------------------------------------
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement