diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 5f0acd670..5717f5262 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -639,7 +639,7 @@ jobs: if: github.event_name == 'workflow_run' Build-iOS: - runs-on: macos-26 + runs-on: macos-14 name: Build - iOS steps: diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index d092fd714..231d3a972 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -23,16 +23,9 @@ jobs: run: | if [[ "$PVS_STUDIO_LICENSE" != "" ]]; then - wget -qO pvs-key.asc https://files.pvs-studio.com/etc/pubkey.txt - gpg --dearmor -o pvs-key.gpg pvs-key.asc - sudo install -D -m 644 pvs-key.gpg /etc/apt/keyrings/pvs-studio.gpg - wget -qO viva64.list https://files.pvs-studio.com/etc/viva64.list - sed -E \ - -e 's|^deb \[|deb [signed-by=/etc/apt/keyrings/pvs-studio.gpg |; t' \ - -e 's|^deb |deb [signed-by=/etc/apt/keyrings/pvs-studio.gpg] |' \ - viva64.list > viva64-scoped.list - sudo install -m 644 viva64-scoped.list /etc/apt/sources.list.d/viva64.list - + wget -q https://files.pvs-studio.com/etc/pubkey.txt + sudo apt-key add pubkey.txt + sudo wget -O /etc/apt/sources.list.d/viva64.list https://files.pvs-studio.com/etc/viva64.list sudo apt-get update sudo apt-get install -y pvs-studio pvs-studio-analyzer credentials -o pvs-studio.lic $PVS_STUDIO_LICENSE diff --git a/.gitignore b/.gitignore index 730857c1b..009e61ede 100644 --- a/.gitignore +++ b/.gitignore @@ -66,7 +66,6 @@ cmake-build-* ## Unix executables from our example Makefiles examples/example_apple_metal/example_apple_metal -examples/example_apple_metal4/example_apple_metal4 examples/example_apple_opengl2/example_apple_opengl2 examples/example_apple_opengl3/example_apple_opengl3 examples/example_glfw_metal/example_glfw_metal diff --git a/backends/imgui_impl_dx9.cpp b/backends/imgui_impl_dx9.cpp index 10d0dc21e..360398f04 100644 --- a/backends/imgui_impl_dx9.cpp +++ b/backends/imgui_impl_dx9.cpp @@ -17,7 +17,6 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2026-11-13: DirectX9: Pre-transforming vertices and using `D3DFVF_XYZRHW` vertex format, largely increasing performances when in `D3DCREATE_SOFTWARE_VERTEXPROCESSING` mode. (#9628) // 2026-04-23: Added support for standard draw callbacks (in platform_io): DrawCallback_ResetRenderState, DrawCallback_SetSamplerLinear, DrawCallback_SetSamplerNearest. (#9378) // 2026-03-19: Fixed issue in ImGui_ImplDX9_UpdateTexture() if ImTextureID_Invalid is defined to be != 0, which became the default since 2026-03-12. (#9295, #9310) // 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. @@ -72,11 +71,10 @@ struct ImGui_ImplDX9_Data struct CUSTOMVERTEX { float pos[3]; - float rhw; D3DCOLOR col; float uv[2]; }; -#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZRHW|D3DFVF_DIFFUSE|D3DFVF_TEX1) +#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1) #ifdef IMGUI_USE_BGRA_PACKED_COLOR #define IMGUI_COL_TO_DX9_ARGB(_COL) (_COL) @@ -143,7 +141,7 @@ static void ImGui_ImplDX9_SetupRenderState(ImDrawData* draw_data) device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP); device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP); - // Setup orthographic projection matrix for custom draw callbacks. Our pretransformed vertices bypass these transforms. + // Setup orthographic projection matrix // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. // Being agnostic of whether or can be used, we aren't relying on D3DXMatrixIdentity()/D3DXMatrixOrthoOffCenterLH() or DirectX::XMMatrixIdentity()/DirectX::XMMatrixOrthographicOffCenterLH() { @@ -234,19 +232,18 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) return; } - // Copy and pre-transform all vertices into a single contiguous buffer, convert colors to DX9 default format. - // XYZRHW bypasses vertex processing, avoiding repeated software transforms for each draw command. Apply DX9's half-pixel offset here. - // Define IMGUI_USE_BGRA_PACKED_COLOR in imconfig.h to avoid repacking colors. - const ImVec2 pos_offset(draw_data->DisplayPos.x + 0.5f, draw_data->DisplayPos.y + 0.5f); + // Copy and convert all vertices into a single contiguous buffer, convert colors to DX9 default format. + // FIXME-OPT: This is a minor waste of resource, the ideal is to use imconfig.h and + // 1) to avoid repacking colors: #define IMGUI_USE_BGRA_PACKED_COLOR + // 2) to avoid repacking vertices: #define IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT struct ImDrawVert { ImVec2 pos; float z; ImU32 col; ImVec2 uv; } for (const ImDrawList* draw_list : draw_data->CmdLists) { const ImDrawVert* vtx_src = draw_list->VtxBuffer.Data; for (int i = 0; i < draw_list->VtxBuffer.Size; i++) { - vtx_dst->pos[0] = vtx_src->pos.x - pos_offset.x; - vtx_dst->pos[1] = vtx_src->pos.y - pos_offset.y; - vtx_dst->pos[2] = 0.5f; - vtx_dst->rhw = 1.0f; + vtx_dst->pos[0] = vtx_src->pos.x; + vtx_dst->pos[1] = vtx_src->pos.y; + vtx_dst->pos[2] = 0.0f; vtx_dst->col = IMGUI_COL_TO_DX9_ARGB(vtx_src->col); vtx_dst->uv[0] = vtx_src->uv.x; vtx_dst->uv[1] = vtx_src->uv.y; diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 9cbffafb6..678129a07 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -663,7 +663,7 @@ void ImGui_ImplGlfw_SetCallbacksChainForAllWindows(bool chain_for_all_windows) #if EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3 >= 34020240817 void ImGui_ImplGlfw_EmscriptenOpenURL(const char* url) { if (url) emscripten::glfw3::OpenURL(url); } #else -EM_JS(void, ImGui_ImplGlfw_EmscriptenOpenURL, (const char* url), { url = url ? UTF8ToString(url) : null; if (url) window.open(url, '_blank', 'noopener'); }); +EM_JS(void, ImGui_ImplGlfw_EmscriptenOpenURL, (const char* url), { url = url ? UTF8ToString(url) : null; if (url) window.open(url, '_blank'); }); #endif #endif @@ -748,13 +748,11 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw // Windows: register a WndProc hook so we can intercept some messages. #ifdef _WIN32 - if (HWND hwnd = (HWND)main_viewport->PlatformHandleRaw) - { - ::SetPropA(hwnd, "IMGUI_BACKEND_DATA", bd); - bd->PrevWndProc = (WNDPROC)::GetWindowLongPtrW(hwnd, GWLP_WNDPROC); - IM_ASSERT(bd->PrevWndProc != nullptr); - ::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)ImGui_ImplGlfw_WndProc); - } + HWND hwnd = (HWND)main_viewport->PlatformHandleRaw; + ::SetPropA(hwnd, "IMGUI_BACKEND_DATA", bd); + bd->PrevWndProc = (WNDPROC)::GetWindowLongPtrW(hwnd, GWLP_WNDPROC); + IM_ASSERT(bd->PrevWndProc != nullptr); + ::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)ImGui_ImplGlfw_WndProc); #endif // Emscripten: the same application can run on various platforms, so we detect the Apple platform at runtime @@ -814,12 +812,9 @@ void ImGui_ImplGlfw_Shutdown() // Windows: restore our WndProc hook #ifdef _WIN32 ImGuiViewport* main_viewport = ImGui::GetMainViewport(); - if (HWND hwnd = (HWND)main_viewport->PlatformHandleRaw) - { - ::SetPropA(hwnd, "IMGUI_BACKEND_DATA", nullptr); - ::SetWindowLongPtrW(hwnd, GWLP_WNDPROC, (LONG_PTR)bd->PrevWndProc); - bd->PrevWndProc = nullptr; - } + ::SetPropA((HWND)main_viewport->PlatformHandleRaw, "IMGUI_BACKEND_DATA", nullptr); + ::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)bd->PrevWndProc); + bd->PrevWndProc = nullptr; #endif io.BackendPlatformName = nullptr; diff --git a/backends/imgui_impl_metal4.h b/backends/imgui_impl_metal4.h index 9ef6e06ef..b5b54cad0 100644 --- a/backends/imgui_impl_metal4.h +++ b/backends/imgui_impl_metal4.h @@ -38,7 +38,6 @@ IMGUI_IMPL_API bool ImGui_ImplMetal4_Init(id device, id commandBuffer, diff --git a/backends/imgui_impl_metal4.mm b/backends/imgui_impl_metal4.mm index e5d3e3472..2f9a53bdb 100644 --- a/backends/imgui_impl_metal4.mm +++ b/backends/imgui_impl_metal4.mm @@ -19,7 +19,6 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2026-11-16: Worked around rendering artifacts by aligning 16-bit index buffer addresses to 4 bytes. / Fixed vertex/index buffers being reused by a later draw in the same frame. (#9622, #9625) / Remove the residency set from the command queue on shutdown so the queue can be reused. // 2026-10-06: Added support for render passes with multiple color attachments: we render to the first one and leave the others untouched. (#9574) // 2026-09-07: Round framebuffer dimensions to the nearest integer instead of truncating them. (#9538, 9515, #8628) // 2026-07-07: Metal 4: Added metal-cpp support. (#9461) @@ -37,14 +36,12 @@ #pragma mark - Support classes and structs -#define MEMALIGN(_SIZE,_ALIGN) (((_SIZE) + ((_ALIGN) - 1)) & ~((_ALIGN) - 1)) - struct ImGui_Metal4_ConstantData { float ModelViewProjectionMatrix[4][4]; }; -@interface Metal4Buffer : NSObject +@interface MetalBuffer : NSObject @property (nonatomic, strong) id buffer; @property (nonatomic, assign) double lastReuseTime; - (instancetype)initWithBuffer:(id)buffer; @@ -54,7 +51,7 @@ struct ImGui_Metal4_ConstantData // An object that encapsulates the data necessary to uniquely identify a // render pipeline state. These are used as cache keys. -@interface Metal4FramebufferDescriptor : NSObject +@interface FramebufferDescriptor : NSObject @property (nonatomic, assign) unsigned long sampleCount; @property (nonatomic, assign) MTLPixelFormat depthPixelFormat; @property (nonatomic, assign) MTLPixelFormat stencilPixelFormat; @@ -62,7 +59,7 @@ struct ImGui_Metal4_ConstantData - (MTLPixelFormat)colorPixelFormatAtIndex:(NSUInteger)index; @end -@interface Metal4Texture : NSObject +@interface MetalTexture : NSObject @property (nonatomic, strong) id metalTexture; - (instancetype)initWithTexture:(id)metalTexture; @end @@ -70,7 +67,7 @@ struct ImGui_Metal4_ConstantData // A singleton that stores long-lived objects that are needed by the Metal // renderer backend. Stores the render pipeline state cache and the default // font texture, and manages the reusable buffer cache. -@interface Metal4Context : NSObject +@interface MetalContext : NSObject @property (nonatomic, strong) id device; @property (nonatomic, strong) id commandQueue; @property (nonatomic, strong) id depthStencilState; @@ -78,25 +75,24 @@ struct ImGui_Metal4_ConstantData @property (nonatomic, strong) id samplerStateLinear; @property (nonatomic, strong) id samplerStateNearest; @property (nonatomic, strong) id residencySet; -@property (nonatomic, strong) Metal4FramebufferDescriptor* framebufferDescriptor; +@property (nonatomic, strong) FramebufferDescriptor* framebufferDescriptor; @property (nonatomic, strong) NSMutableDictionary* renderPipelineStateCache; @property (nonatomic, assign) NSUInteger framesInFlight; @property (nonatomic, assign) NSUInteger currentFrameSlot; @property (nonatomic, strong) NSArray>* constantBuffers; @property (nonatomic, assign) ImGui_Metal4_ConstantData** constantBufferContentsArray; -@property (nonatomic, strong) NSMutableArray*>* bufferCaches; -@property (nonatomic, strong) NSMutableArray*>* buffersInFlight; // per frame slot: buffers used since its last NewFrame(), may still be read by the GPU +@property (nonatomic, strong) NSMutableArray*>* bufferCaches; @property (nonatomic, strong) NSObject* bufferCacheLock; @property (nonatomic, assign) double lastBufferCachePurge; - (id)currentConstantBuffer; - (ImGui_Metal4_ConstantData*)currentConstantBufferContents; -- (Metal4Buffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id)device; -- (id)renderPipelineStateForFramebufferDescriptor:(Metal4FramebufferDescriptor*)descriptor device:(id)device; +- (MetalBuffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id)device; +- (id)renderPipelineStateForFramebufferDescriptor:(FramebufferDescriptor*)descriptor device:(id)device; @end struct ImGui_ImplMetal4_Data { - Metal4Context* SharedMetalContext; + MetalContext* SharedMetalContext; id RenderCommandEncoder; ImGui_ImplMetal4_Data() { memset((void*)this, 0, sizeof(*this)); } @@ -130,7 +126,7 @@ void ImGui_ImplMetal4_RenderDrawData(ImDrawData* draw_data, (__bridge id)(commandEncoder)); } -bool ImGui_ImplMetal4_CreateDeviceObjects(MTL::Device* device) +bool ImGui_ImplMetal_CreateDeviceObjects(MTL::Device* device) { return ImGui_ImplMetal4_CreateDeviceObjects((__bridge id)(device)); } @@ -143,27 +139,20 @@ void ImGui_ImplMetal4_NewFrame(MTL4RenderPassDescriptor* renderPassDescriptor, i { ImGui_ImplMetal4_Data* bd = ImGui_ImplMetal4_GetBackendData(); IM_ASSERT(bd != nil && "Context or backend not initialized! Did you call ImGui_ImplMetal4_Init()?"); - IM_ASSERT(frameInFlightIndex < (int)bd->SharedMetalContext.framesInFlight && "frameInFlightIndex out of range! See framesInFlight passed to ImGui_ImplMetal4_Init()."); + IM_ASSERT(frameInFlightIndex < bd->SharedMetalContext.framesInFlight && "frameInFlightIndex out of range! See framesInFlight passed to ImGui_ImplMetal4_Init()."); #ifdef IMGUI_IMPL_METAL_CPP - bd->SharedMetalContext.framebufferDescriptor = [[[Metal4FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor]autorelease]; + bd->SharedMetalContext.framebufferDescriptor = [[[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor]autorelease]; #else - bd->SharedMetalContext.framebufferDescriptor = [[Metal4FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor]; + bd->SharedMetalContext.framebufferDescriptor = [[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor]; #endif bd->SharedMetalContext.currentFrameSlot = (NSUInteger)frameInFlightIndex; if (bd->SharedMetalContext.depthStencilState == nil) ImGui_ImplMetal4_CreateDeviceObjects(bd->SharedMetalContext.device); - - // The application has finished GPU work for this slot before reusing it. - @synchronized(bd->SharedMetalContext.bufferCacheLock) - { - [bd->SharedMetalContext.bufferCaches[frameInFlightIndex] addObjectsFromArray:bd->SharedMetalContext.buffersInFlight[frameInFlightIndex]]; - [bd->SharedMetalContext.buffersInFlight[frameInFlightIndex] removeAllObjects]; - } } static void ImGui_ImplMetal4_SetupRenderState(ImDrawData* draw_data, id commandBuffer, id commandEncoder, id renderPipelineState, - Metal4Buffer* vertexBuffer, size_t vertexBufferOffset) + MetalBuffer* vertexBuffer, size_t vertexBufferOffset) { IM_UNUSED(commandBuffer); ImGui_ImplMetal4_Data* bd = ImGui_ImplMetal4_GetBackendData(); @@ -215,7 +204,7 @@ static void ImGui_ImplMetal4_DrawCallback_SetSamplerNearest(const ImDrawList*, c void ImGui_ImplMetal4_RenderDrawData(ImDrawData* draw_data, id commandBuffer, id commandEncoder) { ImGui_ImplMetal4_Data* bd = ImGui_ImplMetal4_GetBackendData(); - Metal4Context* ctx = bd->SharedMetalContext; + MetalContext* ctx = bd->SharedMetalContext; // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x + 0.5f); @@ -244,18 +233,8 @@ void ImGui_ImplMetal4_RenderDrawData(ImDrawData* draw_data, idTotalVtxCount * sizeof(ImDrawVert); size_t indexBufferLength = (size_t)draw_data->TotalIdxCount * sizeof(ImDrawIdx); - // Work around Metal 4 corrupting draws whose 16-bit index buffer address is only 2-byte aligned. - // Pack each draw at a 4-byte boundary, with at most one padding index per draw. - if (sizeof(ImDrawIdx) == 2) - { - indexBufferLength = 0; - for (const ImDrawList* draw_list : draw_data->CmdLists) - for (const ImDrawCmd& cmd : draw_list->CmdBuffer) - if (cmd.UserCallback == nullptr) - indexBufferLength += MEMALIGN((size_t)cmd.ElemCount * sizeof(ImDrawIdx), 4); - } - Metal4Buffer* vertexBuffer = [ctx dequeueReusableBufferOfLength:vertexBufferLength device:commandBuffer.device]; - Metal4Buffer* indexBuffer = [ctx dequeueReusableBufferOfLength:indexBufferLength device:commandBuffer.device]; + MetalBuffer* vertexBuffer = [ctx dequeueReusableBufferOfLength:vertexBufferLength device:commandBuffer.device]; + MetalBuffer* indexBuffer = [ctx dequeueReusableBufferOfLength:indexBufferLength device:commandBuffer.device]; bd->RenderCommandEncoder = commandEncoder; ImGui_ImplMetal4_SetupRenderState(draw_data, commandBuffer, commandEncoder, renderPipelineState, vertexBuffer, 0); @@ -270,8 +249,7 @@ void ImGui_ImplMetal4_RenderDrawData(ImDrawData* draw_data, idCmdLists) { memcpy((char*)vertexBuffer.buffer.contents + vertexBufferOffset, draw_list->VtxBuffer.Data, (size_t)draw_list->VtxBuffer.Size * sizeof(ImDrawVert)); - if (sizeof(ImDrawIdx) == 4) - memcpy((char*)indexBuffer.buffer.contents + indexBufferOffset, draw_list->IdxBuffer.Data, (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx)); + memcpy((char*)indexBuffer.buffer.contents + indexBufferOffset, draw_list->IdxBuffer.Data, (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx)); for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++) { @@ -322,31 +300,22 @@ void ImGui_ImplMetal4_RenderDrawData(ImDrawData* draw_data, idSharedMetalContext.argumentTable setAddress:(vertexBuffer.buffer.gpuAddress + vertexBufferOffset + (pcmd->VtxOffset * sizeof(ImDrawVert))) attributeStride:sizeof(ImDrawVert) atIndex:0]; size_t indexBufferCmdOffset = indexBufferOffset + (pcmd->IdxOffset * sizeof(ImDrawIdx)); - size_t indexBufferCmdLength = (size_t)pcmd->ElemCount * sizeof(ImDrawIdx); - if (sizeof(ImDrawIdx) == 2) - { - indexBufferCmdOffset = indexBufferOffset; - memcpy((char*)indexBuffer.buffer.contents + indexBufferCmdOffset, draw_list->IdxBuffer.Data + pcmd->IdxOffset, indexBufferCmdLength); - indexBufferOffset += MEMALIGN(indexBufferCmdLength, 4); - } [commandEncoder drawIndexedPrimitives:MTLPrimitiveTypeTriangle indexCount:pcmd->ElemCount indexType:sizeof(ImDrawIdx) == 2 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32 indexBuffer:indexBuffer.buffer.gpuAddress + indexBufferCmdOffset - indexBufferLength:indexBufferCmdLength]; + indexBufferLength:indexBuffer.buffer.length - indexBufferCmdOffset]; } } vertexBufferOffset += (size_t)draw_list->VtxBuffer.Size * sizeof(ImDrawVert); - if (sizeof(ImDrawIdx) == 4) - indexBufferOffset += (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx); + indexBufferOffset += (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx); } - Metal4Context* sharedMetalContext = bd->SharedMetalContext; + MetalContext* sharedMetalContext = bd->SharedMetalContext; @synchronized(sharedMetalContext.bufferCacheLock) { - // Keep these buffers alive and out of the cache until the next NewFrame() for this slot. - NSMutableArray* slotCache = sharedMetalContext.buffersInFlight[sharedMetalContext.currentFrameSlot]; + NSMutableArray* slotCache = sharedMetalContext.bufferCaches[sharedMetalContext.currentFrameSlot]; [slotCache addObject:vertexBuffer]; [slotCache addObject:indexBuffer]; } @@ -358,7 +327,7 @@ void ImGui_ImplMetal4_RenderDrawData(ImDrawData* draw_data, idBackendUserData)) + if (MetalTexture* backend_tex = (__bridge_transfer MetalTexture*)(tex->BackendUserData)) { IM_ASSERT(backend_tex.metalTexture == (__bridge id)(void*)(intptr_t)tex->TexID); backend_tex.metalTexture = nil; @@ -394,7 +363,7 @@ void ImGui_ImplMetal4_UpdateTexture(ImTextureData* tex) id texture = [bd->SharedMetalContext.device newTextureWithDescriptor:textureDescriptor]; [bd->SharedMetalContext.residencySet addAllocation:texture]; [texture replaceRegion:MTLRegionMake2D(0, 0, (NSUInteger)tex->Width, (NSUInteger)tex->Height) mipmapLevel:0 withBytes:tex->Pixels bytesPerRow:(NSUInteger)tex->Width * 4]; - Metal4Texture* backend_tex = [[Metal4Texture alloc] initWithTexture:texture]; + MetalTexture* backend_tex = [[MetalTexture alloc] initWithTexture:texture]; // Store identifiers tex->SetTexID((ImTextureID)(intptr_t)texture); @@ -405,7 +374,7 @@ void ImGui_ImplMetal4_UpdateTexture(ImTextureData* tex) { // Update selected blocks. We only ever write to textures regions which have never been used before! // This backend choose to use tex->Updates[] but you can use tex->UpdateRect to upload a single region. - Metal4Texture* backend_tex = (__bridge Metal4Texture*)(tex->BackendUserData); + MetalTexture* backend_tex = (__bridge MetalTexture*)(tex->BackendUserData); for (ImTextureRect& r : tex->Updates) { [backend_tex.metalTexture replaceRegion:MTLRegionMake2D((NSUInteger)r.x, (NSUInteger)r.y, (NSUInteger)r.w, (NSUInteger)r.h) @@ -425,15 +394,14 @@ bool ImGui_ImplMetal4_CreateDeviceObjects(id device) { ImGui_ImplMetal4_Data* bd = ImGui_ImplMetal4_GetBackendData(); + MTLResidencySetDescriptor* residencySetDescriptor = [[MTLResidencySetDescriptor alloc] init]; + residencySetDescriptor.initialCapacity = 1000; + NSError* error = nil; - if (bd->SharedMetalContext.residencySet == nil) - { - MTLResidencySetDescriptor* residencySetDescriptor = [[MTLResidencySetDescriptor alloc] init]; - residencySetDescriptor.initialCapacity = 1000; - bd->SharedMetalContext.residencySet = [device newResidencySetWithDescriptor:residencySetDescriptor error:&error]; - IM_ASSERT(bd->SharedMetalContext.residencySet != nil && error == nil); - [bd->SharedMetalContext.commandQueue addResidencySet:bd->SharedMetalContext.residencySet]; - } + bd->SharedMetalContext.residencySet = [device newResidencySetWithDescriptor:residencySetDescriptor error:&error]; + IM_ASSERT(bd->SharedMetalContext.residencySet != nil && error == nil); + + [bd->SharedMetalContext.commandQueue addResidencySet:bd->SharedMetalContext.residencySet]; MTLDepthStencilDescriptor* depthStencilDescriptor = [[MTLDepthStencilDescriptor alloc] init]; depthStencilDescriptor.depthWriteEnabled = NO; @@ -506,19 +474,14 @@ bool ImGui_ImplMetal4_Init(id device, id commandQue platform_io.DrawCallback_SetSamplerLinear = ImGui_ImplMetal4_DrawCallback_SetSamplerLinear; platform_io.DrawCallback_SetSamplerNearest = ImGui_ImplMetal4_DrawCallback_SetSamplerNearest; - bd->SharedMetalContext = [[Metal4Context alloc] init]; + bd->SharedMetalContext = [[MetalContext alloc] init]; bd->SharedMetalContext.device = device; bd->SharedMetalContext.commandQueue = commandQueue; bd->SharedMetalContext.framesInFlight = (NSUInteger)framesInFlight; - NSMutableArray*>* bufferCaches = [NSMutableArray array]; - NSMutableArray*>* buffersInFlight = [NSMutableArray array]; - for (NSUInteger i = 0; i < (NSUInteger)framesInFlight; i++) - { + NSMutableArray*>* bufferCaches = [NSMutableArray array]; + for (NSUInteger i = 0; i < framesInFlight; i++) [bufferCaches addObject:[NSMutableArray array]]; - [buffersInFlight addObject:[NSMutableArray array]]; - } bd->SharedMetalContext.bufferCaches = bufferCaches; - bd->SharedMetalContext.buffersInFlight = buffersInFlight; return true; } @@ -531,8 +494,6 @@ void ImGui_ImplMetal4_Shutdown() ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); ImGui_ImplMetal4_DestroyDeviceObjects(); - if (bd->SharedMetalContext.residencySet != nil) - [bd->SharedMetalContext.commandQueue removeResidencySet:bd->SharedMetalContext.residencySet]; ImGui_ImplMetal4_DestroyBackendData(); io.BackendRendererName = nullptr; @@ -541,7 +502,7 @@ void ImGui_ImplMetal4_Shutdown() platform_io.ClearRendererHandlers(); } -@implementation Metal4Buffer +@implementation MetalBuffer - (instancetype)initWithBuffer:(id)buffer { if ((self = [super init])) @@ -553,9 +514,9 @@ void ImGui_ImplMetal4_Shutdown() } @end -#pragma mark - Metal4FramebufferDescriptor implementation +#pragma mark - FramebufferDescriptor implementation -@implementation Metal4FramebufferDescriptor +@implementation FramebufferDescriptor { MTLPixelFormat _colorPixelFormats[IMGUI_IMPL_METAL_MAX_COLOR_ATTACHMENTS]; } @@ -580,7 +541,7 @@ void ImGui_ImplMetal4_Shutdown() - (nonnull id)copyWithZone:(nullable NSZone*)zone { - Metal4FramebufferDescriptor* copy = [[Metal4FramebufferDescriptor allocWithZone:zone] init]; + FramebufferDescriptor* copy = [[FramebufferDescriptor allocWithZone:zone] init]; copy.sampleCount = self.sampleCount; memcpy(copy->_colorPixelFormats, _colorPixelFormats, sizeof(_colorPixelFormats)); copy.depthPixelFormat = self.depthPixelFormat; @@ -602,8 +563,8 @@ void ImGui_ImplMetal4_Shutdown() - (BOOL)isEqual:(id)object { - Metal4FramebufferDescriptor* other = object; - if (![other isKindOfClass:[Metal4FramebufferDescriptor class]]) + FramebufferDescriptor* other = object; + if (![other isKindOfClass:[FramebufferDescriptor class]]) return NO; return other.sampleCount == self.sampleCount && memcmp(other->_colorPixelFormats, _colorPixelFormats, sizeof(_colorPixelFormats)) == 0 && @@ -613,9 +574,9 @@ void ImGui_ImplMetal4_Shutdown() @end -#pragma mark - Metal4Texture implementation +#pragma mark - MetalTexture implementation -@implementation Metal4Texture +@implementation MetalTexture - (instancetype)initWithTexture:(id)metalTexture { if ((self = [super init])) @@ -625,9 +586,9 @@ void ImGui_ImplMetal4_Shutdown() @end -#pragma mark - Metal4Context implementation +#pragma mark - MetalContext implementation -@implementation Metal4Context +@implementation MetalContext - (instancetype)init { if ((self = [super init])) @@ -654,20 +615,20 @@ void ImGui_ImplMetal4_Shutdown() return self.constantBufferContentsArray[self.currentFrameSlot]; } -- (Metal4Buffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id)device +- (MetalBuffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id)device { double now = GetMachAbsoluteTimeInSeconds(); - NSMutableArray* slotCache = self.bufferCaches[self.currentFrameSlot]; + NSMutableArray* slotCache = self.bufferCaches[self.currentFrameSlot]; @synchronized(self.bufferCacheLock) { // Purge old buffers that haven't been useful for a while if (now - self.lastBufferCachePurge > 1.0) { - for (NSMutableArray* cache in self.bufferCaches) + for (NSMutableArray* cache in self.bufferCaches) { NSMutableArray* survivors = [NSMutableArray array]; - for (Metal4Buffer* candidate in cache) + for (MetalBuffer* candidate in cache) if (candidate.lastReuseTime > self.lastBufferCachePurge) [survivors addObject:candidate]; [cache setArray:survivors]; @@ -676,8 +637,8 @@ void ImGui_ImplMetal4_Shutdown() } // See if we have a buffer we can reuse, from this frame-in-flight slot's own cache - Metal4Buffer* bestCandidate = nil; - for (Metal4Buffer* candidate in slotCache) + MetalBuffer* bestCandidate = nil; + for (MetalBuffer* candidate in slotCache) if (candidate.buffer.length >= length && (bestCandidate == nil || bestCandidate.lastReuseTime > candidate.lastReuseTime)) bestCandidate = candidate; @@ -692,7 +653,7 @@ void ImGui_ImplMetal4_Shutdown() // No luck; make a new buffer id backing = [device newBufferWithLength:length options:MTLResourceStorageModeShared]; [self.residencySet addAllocation:backing]; - return [[Metal4Buffer alloc] initWithBuffer:backing]; + return [[MetalBuffer alloc] initWithBuffer:backing]; } const char* shaderCode = R"( @@ -734,7 +695,7 @@ fragment half4 fragment_main(VertexOut in [[stage_in]], } )"; -- (id)renderPipelineStateForFramebufferDescriptor:(Metal4FramebufferDescriptor*)descriptor device:(id)device +- (id)renderPipelineStateForFramebufferDescriptor:(FramebufferDescriptor*)descriptor device:(id)device { NSError* error = nil; diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 8281fa4ed..a93bcc29e 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -21,9 +21,8 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2026-11-09: Inputs: iOS: restore SDL_StartTextInput()/SDL_StopTextInput() in IME handler for on-screen keyboard support. (#7636, #9474, #9617) // 2026-08-06: Fixed querying framebuffer scale when using Metal. (#5592) -// 2026-07-15: Inputs: Android: restore SDL_StartTextInput()/SDL_StopTextInput() in IME handler for on-screen keyboard support. (#7636, #9474) +// 2026-07-15: Inputs: restore SDL_StartTextInput()/SDL_StopTextInput() in IME handler for on-screen keyboard support on Android/mobile. (#7636, #9474) // 2026-04-16: Made ImGui_ImplSDL2_GetContentScaleForWindow(), ImGui_ImplSDL2_GetContentScaleForDisplay() helpers return a minimum of 1.0f, as some Linux setup seems to report <1.0f value and this breaks scaling border size. (#9369) // 2026-02-13: Inputs: systems other than X11 are back to starting mouse capture on mouse down (reverts 2025-02-26 change). Only X11 requires waiting for a drag by default (not ideal, but a better default for X11 users). Added ImGui_ImplSDL2_SetMouseCaptureMode() for X11 debugger users. (#3650, #6410, #9235) // 2026-01-15: Changed GetClipboardText() handler to return nullptr on error aka clipboard contents is not text. Consistent with other backends. (#9168) @@ -217,15 +216,15 @@ static void ImGui_ImplSDL2_PlatformSetImeData(ImGuiContext*, ImGuiViewport*, ImG r.h = (int)data->InputLineHeight; SDL_SetTextInputRect(&r); -#if defined(__ANDROID__) || (defined(__APPLE__) && TARGET_OS_IOS) - // SDL_StartTextInput() is needed on Android and iOS to show the on-screen keyboard. (#7636, #9474, #6306) +#ifdef __ANDROID__ + // SDL_StartTextInput() is needed on Android (and some other platforms) to show the on-screen keyboard. (#7636, #9474, #6306) // It was removed in a7703fe6 due to concerns about its relation to desktop IME, but is required on mobile. SDL_StartTextInput(); #endif } else { -#if defined(__ANDROID__) || (defined(__APPLE__) && TARGET_OS_IOS) +#ifdef __ANDROID__ SDL_StopTextInput(); #endif } @@ -508,7 +507,7 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) } #ifdef __EMSCRIPTEN__ -EM_JS(void, ImGui_ImplSDL2_EmscriptenOpenURL, (char const* url), { url = url ? UTF8ToString(url) : null; if (url) window.open(url, '_blank', 'noopener'); }); +EM_JS(void, ImGui_ImplSDL2_EmscriptenOpenURL, (char const* url), { url = url ? UTF8ToString(url) : null; if (url) window.open(url, '_blank'); }); #endif static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void* sdl_gl_context) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index cf4d53537..7017a6fd1 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -27,7 +27,6 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2026-11-10: Don't transition swapchain images from VK_IMAGE_LAYOUT_UNDEFINED to VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` on window creation, prevent validation errors in examples and multi-viewport support. (#9553, #9496) // 2026-10-06: Added support for dynamic rendering with multiple color attachments (PipelineRenderingCreateInfo.colorAttachmentCount > 1): we render to the first one and leave the others untouched. (#9574) // 2026-09-07: Round framebuffer dimensions to the nearest integer instead of truncating them. (#9538, 9515, #8628) // 2026-09-03: Added for support for multiple Vulkan contexts with custom loaders. (#6616) @@ -1594,15 +1593,33 @@ VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physic avail_format.resize((int)avail_count); vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device, surface, &avail_count, avail_format.Data); - // When requesting several formats, the first found will be used - if (avail_count > 1) + // First check if only one format, VK_FORMAT_UNDEFINED, is available, which would imply that any format is available + if (avail_count == 1) + { + if (avail_format[0].format == VK_FORMAT_UNDEFINED) + { + VkSurfaceFormatKHR ret; + ret.format = request_formats[0]; + ret.colorSpace = request_color_space; + return ret; + } + else + { + // No point in searching another format + return avail_format[0]; + } + } + else + { + // Request several formats, the first found will be used for (int request_i = 0; request_i < request_formats_count; request_i++) for (uint32_t avail_i = 0; avail_i < avail_count; avail_i++) if (avail_format[avail_i].format == request_formats[request_i] && avail_format[avail_i].colorSpace == request_color_space) return avail_format[avail_i]; - // If none of the requested image formats could be found, use the first available - return avail_format[0]; + // If none of the requested image formats could be found, use the first available + return avail_format[0]; + } } VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkPresentModeKHR* request_modes, int request_modes_count) @@ -1901,7 +1918,6 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V // Create or resize window // - 2025/09/26: v1.92.4 added a trailing 'VkImageUsageFlags image_usage' parameter which is usually VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT. -// - 2026/11/10: v1.93.1 removed a bunch of code transitioning swapchain image layout from `VK_IMAGE_LAYOUT_UNDEFINED` to `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR`. (#9496) void ImGui_ImplVulkanH_CreateOrResizeWindow(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int width, int height, uint32_t min_image_count, VkImageUsageFlags image_usage) { IM_ASSERT(g_FunctionsLoaded && "Need to call ImGui_ImplVulkan_LoadFunctions() if IMGUI_IMPL_VULKAN_NO_PROTOTYPES or VK_NO_PROTOTYPES are set!"); @@ -1910,6 +1926,81 @@ void ImGui_ImplVulkanH_CreateOrResizeWindow(VkInstance instance, VkPhysicalDevic ImGui_ImplVulkanH_CreateWindowSwapChain(physical_device, device, wd, allocator, width, height, min_image_count, image_usage); ImGui_ImplVulkanH_CreateWindowCommandBuffers(physical_device, device, wd, queue_family, allocator); + + // FIXME: to submit the command buffer, we need a queue. In the examples folder, the ImGui_ImplVulkanH_CreateOrResizeWindow function is called + // before the ImGui_ImplVulkan_Init function, so we don't have access to the queue yet. Here we have the queue_family that we can use to grab + // a queue from the device and submit the command buffer. It would be better to have access to the queue as suggested in the FIXME below. + VkCommandPool command_pool; + VkCommandPoolCreateInfo pool_info = {}; + pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; + pool_info.queueFamilyIndex = queue_family; + VkResult err = vkCreateCommandPool(device, &pool_info, allocator, &command_pool); + check_vk_result(err); + + VkFenceCreateInfo fence_info = {}; + fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; + VkFence fence; + err = vkCreateFence(device, &fence_info, allocator, &fence); + check_vk_result(err); + + VkCommandBufferAllocateInfo alloc_info = {}; + alloc_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + alloc_info.commandPool = command_pool; + alloc_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + alloc_info.commandBufferCount = 1; + VkCommandBuffer command_buffer; + err = vkAllocateCommandBuffers(device, &alloc_info, &command_buffer); + check_vk_result(err); + + VkCommandBufferBeginInfo begin_info = {}; + begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + begin_info.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + err = vkBeginCommandBuffer(command_buffer, &begin_info); + check_vk_result(err); + + // Transition the images to the correct layout for rendering + for (uint32_t i = 0; i < wd->ImageCount; i++) + { + VkImageMemoryBarrier barrier = {}; + barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + barrier.image = wd->Frames[i].Backbuffer; + barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + barrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + barrier.subresourceRange.levelCount = 1; + barrier.subresourceRange.layerCount = 1; + vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier); + } + + err = vkEndCommandBuffer(command_buffer); + check_vk_result(err); + VkSubmitInfo submit_info = {}; + submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submit_info.commandBufferCount = 1; + submit_info.pCommandBuffers = &command_buffer; + + VkQueue queue; + vkGetDeviceQueue(device, queue_family, 0, &queue); + err = vkQueueSubmit(queue, 1, &submit_info, fence); + check_vk_result(err); + err = vkWaitForFences(device, 1, &fence, VK_TRUE, UINT64_MAX); + check_vk_result(err); + err = vkResetFences(device, 1, &fence); + check_vk_result(err); + + err = vkResetCommandPool(device, command_pool, 0); + check_vk_result(err); + + // Destroy command buffer and fence and command pool + vkFreeCommandBuffers(device, command_pool, 1, &command_buffer); + vkDestroyCommandPool(device, command_pool, allocator); + vkDestroyFence(device, fence, allocator); + command_pool = VK_NULL_HANDLE; + command_buffer = VK_NULL_HANDLE; + fence = VK_NULL_HANDLE; + queue = VK_NULL_HANDLE; } void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9788196ce..724e40f03 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -63,89 +63,17 @@ Autumn cleanup of stuff marked obsolete more than two years ago: and `GetWindowContentRegionMax()` will may be removed soon-ish: you should not ever need those functions. See #7838. + Other Changes: -- Style: - - `StyleColorsDark()`: tweaked WindowBg, PopupBg, ChildBg to be darker than in 1.93.0. - - Added `style.SymbolArrowSizeFactor`, `style.SymbolArrowThicknessFactor` to tweak the - shape and look of arrows. Made default arrow stroked. (#5233, #2431, #2235, #6730, #8243) - Legacy arrow: size: (0.60f,0.70f), thickness: 0.0f - New arrow: size: (0.72f,0.40f), thickness: 0.30f -- Windows: - - Using `SetNextWindowPos()` with a pivot while a window is hidden and measuring - size will still apply temporary position until size is figured out. (#9568) -- TreeNode: - - TreeNodeGetOpen(): added flags parameter to allow passing `ImGuiTreeNodeFlags_DefaultOpen` - or `ImGuiTreeNodeFlags_Leaf`. (#9569, #9592, #3823, #9251) [@adalisk-emikhaylov, @Yaki-Blake] -- Popups: - - Modals: fixed an assert displaying a modal in an environment where - `io.DisplayFramebufferScale` is not an integer (regression in 1.93.0). (#9598) -- Tables: - - Added "Reset->Reset Sizes" context-menu option. (#9523, #9605) - - Fixed various border overshooting issues, some mostly visible with transparent - borders and under specific conditions: (#4678) - - On non-scrolling tables, inner horizontal borders slightly overlapped - outer vertical ones with certain settings. - - On non-scrolling tables, clamping lower border coordinates to stay within - visible range (no visible change, but it makes ImDrawCmd AABB more sensible). - - Fixed vertical inner borders slightly overlapping bottom outer border. - - Fixed various issues using `ImGuiTableFlags_NoHostExtendX`/`_NoHostExtendY`: - - Fixed selectable highlight straying off the X2/Y2 clipping limit. - - Fixed parent window work rectangle affecting the Y2 clipping limit. - - Fixed the Y2 clipping limit overlapping bottom outer border. - - Fixed layout of items submitted while in horizontal layout mode (e.g. a menu bar). - `BeginTable()` resets layout mode to vertical. (#9589) [@themd] -- Multi-Select: - - Fixed `ImGuiSelectionBasicStorage::GetNextSelectedItem()` reading one past the - end of storage when trailing items are unselected (#9604) [@MilosLord] -- Drags: fixed handling of `ImGuiSliderFlags_WrapAround`: value could temporarily - escape the range when dragging fast. (#9612, #9611, #7749) [@swayie, @ocornut] -- Checkbox: indeterminate/mixed value inner rectangle never has rounding, - to reduce confusion with a radio button. (#5518, #5677, #6865, #2644) -- ColorEdit: - - ColorButton, ColorEdit, ColorPicker: fixed an issue rendering colors when - inside a `BeginDisabled(false)` block, caused by the alpha cancelling-out - code in 1.93.0. (#9511, #9613, #9614) [@tksuoran] -- Fonts: - - Detect if the parameters leading `AddFontDefault()` to implicitly select either - `AddFontDefaultBitmap()` or `AddFontDefaultVector()` have changed between init - time and first frame. (#9591) - ImVec2: added a check for cases where a custom `IM_VEC2_CLASS_EXTRA` macro adds an extra `operator=` to ImVec2. This isn't supported but should not be needed as you should have a constructor to convert from your type to ImVec2. -- Misc: update stb_textedit 1.14->1.15. - - InputText: Up/PageUp on the first line now moves the cursor to the beginning - of the line, including when extending a selection. [@blackedout01] -- Misc: update stb_truetype 1.26->1.27. - - Fonts: fixed incorrect glyph mapping with certain character maps, loading fonts - with only a Microsoft Symbol character map, and rendering scaled composite glyphs. - - Fixed an out-of-bounds read with single-point off-curve contours. -- Misc: update stb_rect_pack 1.01->1.02. - - Fixed packing determinism by not depending on qsort() tiebreak. - CI: added some ARM64 builds. (#9593) [@Harishmcw] - Examples: renamed various helper batch files from build_win32.bat to build_win.bat to reflect that they can also build X64 or ARM64, given the right environment. Made the script detect the environment when needed (e.g. to specify library path). - Examples: added support for ARM64 in selected build_win.bat helpers. (#9593) [@Harishmcw] -- Backends: - - DirectX9: pre-transforming vertices and using `D3DFVF_XYZRHW` vertex format, largely - increasing performances when in `D3DCREATE_SOFTWARE_VERTEXPROCESSING` mode. (#9628) - - GLFW: allow initialization with missing HWND. (#9619) [@djohansson] - - GLFW, SDL2: Emscripten implementation of `Platform_OpenInShellFn` calls - `window.open()` with `noopener`: prevents newly opened tab from keeping a - reference to opening page. (#9615, #7660, #7851) [@pthom] - - SDL2: on iOS, also restore calling `SDL_StartTextInput()/SDL_StopTextInput()` - in IME handler. Match Android change in 1.93.0. [@pthom] (#7636, #9474, #9617) - - Metal4: worked around rendering artifacts (e.g. flickering diagonal lines) with - 16-bit indices by aligning each draw command index buffer address to 4 bytes. - - Metal4: fixed vertex/index buffers being reused by a later draw in the same frame - before the GPU had processed them. (#9622, #9625) [@lailoken] - - Metal4: remove the residency set from the command queue on shutdown to avoid - hitting Metal's residency set limit when reinitializing on the same queue. - - Vulkan: don't transition swapchain images from `VK_IMAGE_LAYOUT_UNDEFINED` to - `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` on window creation, prevent validation errors in - examples and multi-viewport support. (#9553, #9496, #9152) [@sarpsenturk, @LewisJustin] - ----------------------------------------------------------------------- diff --git a/examples/example_apple_metal/main.mm b/examples/example_apple_metal/main.mm index cb27f3330..cddc1093c 100644 --- a/examples/example_apple_metal/main.mm +++ b/examples/example_apple_metal/main.mm @@ -111,6 +111,7 @@ #if TARGET_OS_OSX ImGui_ImplOSX_Init(self.view); + [NSApp activateIgnoringOtherApps:YES]; #endif } @@ -272,22 +273,6 @@ @implementation AppDelegate --(void)applicationDidFinishLaunching:(NSNotification *)notification -{ - NSMenu* mainMenuBar = [[NSMenu alloc] init]; - NSMenu* appMenu = [[NSMenu alloc] initWithTitle:@"Dear ImGui OSX+Metal Example"]; - NSMenuItem* quitMenuItem = [appMenu addItemWithTitle:@"Quit" action:@selector(terminate:) keyEquivalent:@"q"]; - [quitMenuItem setTarget:NSApp]; - [quitMenuItem setKeyEquivalentModifierMask:NSEventModifierFlagCommand]; - - NSMenuItem* appMenuItem = [[NSMenuItem alloc] init]; - [appMenuItem setSubmenu:appMenu]; - [mainMenuBar addItem:appMenuItem]; - [NSApp setMainMenu:mainMenuBar]; - - [NSApp activateIgnoringOtherApps:YES]; -} - -(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender { return YES; @@ -302,7 +287,6 @@ styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable | NSWindowStyleMaskMiniaturizable backing:NSBackingStoreBuffered defer:NO]; - self.window.title = @"Dear ImGui OSX+Metal Example"; self.window.contentViewController = rootViewController; [self.window center]; [self.window makeKeyAndOrderFront:self]; @@ -350,6 +334,7 @@ int main(int, const char**) AppDelegate *appDelegate = [[AppDelegate alloc] init]; // creates window [NSApp setDelegate:appDelegate]; + [NSApp activateIgnoringOtherApps:YES]; [NSApp run]; } return 0; diff --git a/examples/example_apple_metal4/main.mm b/examples/example_apple_metal4/main.mm index 40fbbe764..553eeb34c 100644 --- a/examples/example_apple_metal4/main.mm +++ b/examples/example_apple_metal4/main.mm @@ -117,6 +117,7 @@ #if TARGET_OS_OSX ImGui_ImplOSX_Init(self.view); + [NSApp activateIgnoringOtherApps:YES]; #endif } @@ -288,22 +289,6 @@ @implementation AppDelegate --(void)applicationDidFinishLaunching:(NSNotification *)notification -{ - NSMenu* mainMenuBar = [[NSMenu alloc] init]; - NSMenu* appMenu = [[NSMenu alloc] initWithTitle:@"Dear ImGui OSX+Metal4 Example"]; - NSMenuItem* quitMenuItem = [appMenu addItemWithTitle:@"Quit" action:@selector(terminate:) keyEquivalent:@"q"]; - [quitMenuItem setTarget:NSApp]; - [quitMenuItem setKeyEquivalentModifierMask:NSEventModifierFlagCommand]; - - NSMenuItem* appMenuItem = [[NSMenuItem alloc] init]; - [appMenuItem setSubmenu:appMenu]; - [mainMenuBar addItem:appMenuItem]; - [NSApp setMainMenu:mainMenuBar]; - - [NSApp activateIgnoringOtherApps:YES]; -} - -(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender { return YES; @@ -318,7 +303,6 @@ styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable | NSWindowStyleMaskMiniaturizable backing:NSBackingStoreBuffered defer:NO]; - self.window.title = @"Dear ImGui OSX+Metal4 Example"; self.window.contentViewController = rootViewController; [self.window center]; [self.window makeKeyAndOrderFront:self]; @@ -366,6 +350,7 @@ int main(int, const char**) AppDelegate *appDelegate = [[AppDelegate alloc] init]; // creates window [NSApp setDelegate:appDelegate]; + [NSApp activateIgnoringOtherApps:YES]; [NSApp run]; } return 0; diff --git a/examples/example_apple_opengl2/main.mm b/examples/example_apple_opengl2/main.mm index 94e03c6d4..67b546ead 100644 --- a/examples/example_apple_opengl2/main.mm +++ b/examples/example_apple_opengl2/main.mm @@ -191,14 +191,19 @@ -(void)setupMenu { NSMenu* mainMenuBar = [[NSMenu alloc] init]; - NSMenu* appMenu = [[NSMenu alloc] initWithTitle:@"Dear ImGui OSX+OpenGL2 Example"]; - NSMenuItem* quitMenuItem = [appMenu addItemWithTitle:@"Quit" action:@selector(terminate:) keyEquivalent:@"q"]; - [quitMenuItem setTarget:NSApp]; - [quitMenuItem setKeyEquivalentModifierMask:NSEventModifierFlagCommand]; + NSMenu* appMenu; + NSMenuItem* menuItem; - NSMenuItem* appMenuItem = [[NSMenuItem alloc] init]; - [appMenuItem setSubmenu:appMenu]; - [mainMenuBar addItem:appMenuItem]; + appMenu = [[NSMenu alloc] initWithTitle:@"Dear ImGui OSX+OpenGL2 Example"]; + menuItem = [appMenu addItemWithTitle:@"Quit Dear ImGui OSX+OpenGL2 Example" action:@selector(terminate:) keyEquivalent:@"q"]; + [menuItem setKeyEquivalentModifierMask:NSEventModifierFlagCommand]; + + menuItem = [[NSMenuItem alloc] init]; + [menuItem setSubmenu:appMenu]; + + [mainMenuBar addItem:menuItem]; + + appMenu = nil; [NSApp setMainMenu:mainMenuBar]; } @@ -209,6 +214,10 @@ -(void)applicationDidFinishLaunching:(NSNotification *)aNotification { + // Make the application a foreground application (else it won't receive keyboard events) + ProcessSerialNumber psn = {0, kCurrentProcess}; + TransformProcessType(&psn, kProcessTransformToForegroundApplication); + // Menu [self setupMenu]; @@ -232,8 +241,6 @@ NSLog(@"No OpenGL Context!"); [view initialize]; - - [NSApp activateIgnoringOtherApps:YES]; } @end @@ -242,17 +249,14 @@ // Application main() function //----------------------------------------------------------------------------------- -int main(int, const char**) +int main(int argc, const char* argv[]) { @autoreleasepool { - [NSApplication sharedApplication]; - [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; - - AppDelegate* appDelegate = [[AppDelegate alloc] init]; - [NSApp setDelegate:appDelegate]; - + NSApp = [NSApplication sharedApplication]; + AppDelegate* delegate = [[AppDelegate alloc] init]; + [[NSApplication sharedApplication] setDelegate:delegate]; [NSApp run]; } - return 0; + return NSApplicationMain(argc, argv); } diff --git a/examples/example_apple_opengl3/main.mm b/examples/example_apple_opengl3/main.mm index 77c95a90e..7cb2e2a33 100644 --- a/examples/example_apple_opengl3/main.mm +++ b/examples/example_apple_opengl3/main.mm @@ -191,14 +191,19 @@ -(void)setupMenu { NSMenu* mainMenuBar = [[NSMenu alloc] init]; - NSMenu* appMenu = [[NSMenu alloc] initWithTitle:@"Dear ImGui OSX+OpenGL3 Example"]; - NSMenuItem* quitMenuItem = [appMenu addItemWithTitle:@"Quit" action:@selector(terminate:) keyEquivalent:@"q"]; - [quitMenuItem setTarget:NSApp]; - [quitMenuItem setKeyEquivalentModifierMask:NSEventModifierFlagCommand]; + NSMenu* appMenu; + NSMenuItem* menuItem; - NSMenuItem* appMenuItem = [[NSMenuItem alloc] init]; - [appMenuItem setSubmenu:appMenu]; - [mainMenuBar addItem:appMenuItem]; + appMenu = [[NSMenu alloc] initWithTitle:@"Dear ImGui OSX+OpenGL3 Example"]; + menuItem = [appMenu addItemWithTitle:@"Quit Dear ImGui OSX+OpenGL3 Example" action:@selector(terminate:) keyEquivalent:@"q"]; + [menuItem setKeyEquivalentModifierMask:NSEventModifierFlagCommand]; + + menuItem = [[NSMenuItem alloc] init]; + [menuItem setSubmenu:appMenu]; + + [mainMenuBar addItem:menuItem]; + + appMenu = nil; [NSApp setMainMenu:mainMenuBar]; } @@ -209,6 +214,10 @@ -(void)applicationDidFinishLaunching:(NSNotification *)aNotification { + // Make the application a foreground application (else it won't receive keyboard events) + ProcessSerialNumber psn = {0, kCurrentProcess}; + TransformProcessType(&psn, kProcessTransformToForegroundApplication); + // Menu [self setupMenu]; @@ -233,8 +242,6 @@ NSLog(@"No OpenGL Context!"); [view initialize]; - - [NSApp activateIgnoringOtherApps:YES]; } @end @@ -243,17 +250,14 @@ // Application main() function //----------------------------------------------------------------------------------- -int main(int, const char**) +int main(int argc, const char* argv[]) { @autoreleasepool { - [NSApplication sharedApplication]; - [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; - - AppDelegate* appDelegate = [[AppDelegate alloc] init]; - [NSApp setDelegate:appDelegate]; - + NSApp = [NSApplication sharedApplication]; + AppDelegate* delegate = [[AppDelegate alloc] init]; + [[NSApplication sharedApplication] setDelegate:delegate]; [NSApp run]; } - return 0; + return NSApplicationMain(argc, argv); } diff --git a/imconfig.h b/imconfig.h index d9c05692f..69f5f000a 100644 --- a/imconfig.h +++ b/imconfig.h @@ -122,6 +122,15 @@ //#endif //---- ...Or manually '#define IMGUI_DEFINE_MATH_OPERATORS' before '#include "imgui.h"' to use from one file. +//---- Define constructor to convert your string type to ImStrv (which is a non-owning begin/end pair) +// This will be inlined as part of ImStrv class declaration. +// This has two benefits: you won't need to use .c_str(), if length is already computed it is faster. +//#include +//#include +//#define IM_STRV_CLASS_EXTRA ImStrv(const std::string& s) { Begin = s.c_str(); End = Begin + s.length(); } +//#define IM_STRV_CLASS_EXTRA ImStrv(const std::string_view& s) { Begin = s.data(); End = Begin + s.length(); } +//#define IM_STRV_CLASS_EXTRA ImStrv(const MyString& s) { Begin = s.Data; End = s.end(); } + //---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices. // Your renderer backend will need to support it (most example renderer backends support both 16/32-bit indices). // Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer. diff --git a/imgui.cpp b/imgui.cpp index 3e6549e30..3fb73cc00 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1429,7 +1429,7 @@ static const ImVec2 TOOLTIP_DEFAULT_PIVOT_TOUCH = ImVec2(0.5f, 1.0f); // Multi //------------------------------------------------------------------------- static void SetCurrentWindow(ImGuiWindow* window); -static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags); +static ImGuiWindow* CreateNewWindow(ImStrv name, ImGuiWindowFlags flags); static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window); static void AddWindowToSortBuffer(ImVector* out_sorted_windows, ImGuiWindow* window); @@ -1503,7 +1503,7 @@ static void UpdateSettings(); static int UpdateWindowManualResize(ImGuiWindow* window, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect); static void RenderWindowOuterBorders(ImGuiWindow* window); static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size); -static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open); +static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, ImStrv name, bool* p_open); static void RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col); static void RenderDimmedBackgrounds(); static void SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect); @@ -1628,10 +1628,6 @@ ImGuiStyle::ImGuiStyle() DisplaySafeAreaPadding = ImVec2(3,3); // 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. MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. - // Symbols - SymbolArrowSizeFactor = ImVec2(0.72f,0.40f); // Width/height factor of arrows (0.0f..1.0f). Legacy arrows use (0.60f,0.70f) - SymbolArrowThicknessFactor = 0.30f; // Thickness factor of arrows (0.0f..0.5f). 0.0f=Fill. >0.0f=Stroke. Legacy arrows use 0.0f. - // Rendering & Tessellation AntiAliasedLines = true; // Enable anti-aliased lines/borders. Used at the beginning of the frame to set ImDrawFlags_AALines in all draw-lists. AntiAliasedLineEnds = false; // Enable anti-aliased lines/borders ends. Nicer for thick lines but more expensive. Used at the beginning of the frame to set ImDrawFlags_AALineEnds in all draw-lists. @@ -1920,7 +1916,7 @@ void ImGuiIO::ClearInputMouse() MouseWheel = MouseWheelH = 0.0f; } -ImGuiInputEvent* ImGui::FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg) +static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1) { ImGuiContext& g = *ctx; for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--) @@ -1965,7 +1961,7 @@ void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value) } // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed) - const ImGuiInputEvent* latest_event = ImGui::FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key); + const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key); const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key); const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down; const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue; @@ -2023,7 +2019,7 @@ void ImGuiIO::AddMousePosEvent(float x, float y) ImVec2 pos((x > -FLT_MAX) ? ImFloor(x) : x, (y > -FLT_MAX) ? ImFloor(y) : y); // Filter duplicate - const ImGuiInputEvent* latest_event = ImGui::FindLatestInputEvent(&g, ImGuiInputEventType_MousePos); + const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MousePos); const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos; if (latest_pos.x == pos.x && latest_pos.y == pos.y) return; @@ -2056,7 +2052,7 @@ void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down) } // Filter duplicate - const ImGuiInputEvent* latest_event = ImGui::FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button); + const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button); const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button]; if (latest_button_down == down) return; @@ -2066,7 +2062,7 @@ void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down) // - At this point we want from !down to down, so this is handling the initial press. if (ConfigMacOSXBehaviors && mouse_button == 0 && down) { - const ImGuiInputEvent* latest_super_event = ImGui::FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)ImGuiMod_Super); + const ImGuiInputEvent* latest_super_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)ImGuiMod_Super); if (latest_super_event ? latest_super_event->Key.Down : g.IO.KeySuper) { IMGUI_DEBUG_LOG_IO("[io] Super+Left Click aliased into Right Click\n"); @@ -2121,7 +2117,7 @@ void ImGuiIO::AddFocusEvent(bool focused) ImGuiContext& g = *Ctx; // Filter duplicate - const ImGuiInputEvent* latest_event = ImGui::FindLatestInputEvent(&g, ImGuiInputEventType_Focus); + const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Focus); const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost; if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused)) return; @@ -2265,6 +2261,15 @@ ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, // [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions) //----------------------------------------------------------------------------- +int ImStrcmp(ImStrv str1, ImStrv str2) +{ + int str1_len = str1.length(); + int str2_len = str2.length(); + if (str1_len != str2_len) + return str1_len - str2_len; + return memcmp(str1.Begin, str2.Begin, (size_t)str1_len); +} + // Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more. int ImStricmp(const char* str1, const char* str2) { @@ -2289,6 +2294,13 @@ void ImStrncpy(char* dst, const char* src, size_t count) dst[count - 1] = 0; } +void ImStrncpy(char* dst, ImStrv src, size_t count) +{ + // Even though src does not necessarily include \0 terminator it is ok to include it. ImStrncpy above does not + // actually include that in a copy operation and inserts zero terminator manually. + ImStrncpy(dst, src.Begin, ImMin(count, (size_t)src.length() + 1)); +} + char* ImStrdup(const char* str) { size_t len = ImStrlen(str); @@ -2296,16 +2308,20 @@ char* ImStrdup(const char* str) return (char*)memcpy(buf, (const void*)str, len + 1); } -void* ImMemdup(const void* src, size_t size) +char* ImStrdup(ImStrv str) { - void* dst = IM_ALLOC(size); - return memcpy(dst, src, size); + size_t len = (size_t)str.length(); + void* buf = IM_ALLOC(len + 1); + *((char*)buf + len) = 0; // str may not contain \0, it must be inserted manually. + if (len > 0) + return (char*)memcpy(buf, (const void*)str.Begin, len); + return (char*)buf; } -char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src) +char* ImStrdupcpy(char* dst, size_t* p_dst_size, ImStrv src) { size_t dst_buf_size = p_dst_size ? *p_dst_size : ImStrlen(dst) + 1; - size_t src_size = ImStrlen(src) + 1; + size_t src_size = (size_t)src.length() + 1; if (dst_buf_size < src_size) { IM_FREE(dst); @@ -2313,7 +2329,21 @@ char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src) if (p_dst_size) *p_dst_size = src_size; } - return (char*)memcpy(dst, (const void*)src, src_size); + dst[src_size - 1] = 0; // str may not contain \0, it must be inserted manually. + if (src_size > 1) + return (char*)memcpy(dst, (const void*)src.Begin, src_size - 1); + return dst; +} + +char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src) +{ + return ImStrdupcpy(dst, p_dst_size, ImStrv(src)); +} + +void* ImMemdup(const void* src, size_t size) +{ + void* dst = IM_ALLOC(size); + return memcpy(dst, src, size); } const char* ImStrchrRange(const char* str, const char* str_end, char c) @@ -2367,6 +2397,23 @@ const char* ImStristr(const char* haystack, const char* haystack_end, const char return NULL; } +const char* ImStrstr(ImStrv haystack, ImStrv needle) +{ + const char un0 = (char)*needle.Begin; + const char* p = haystack.Begin; + const size_t needle_len_m1 = (size_t)needle.length() - 1; + while (true) + { + p = (const char*)memchr(p, un0, haystack.End - p); + if (p == NULL || (size_t)(haystack.End - p) - 1u < needle_len_m1) + return NULL; + if (needle_len_m1 == 0 || memcmp(p + 1, needle.Begin + 1, needle_len_m1) == 0) + return p; + p += 1; + } + return NULL; +} + // Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible. void ImStrTrimBlanks(char* buf) { @@ -2448,11 +2495,11 @@ int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args) } #endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS -void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...) +void ImFormatStringToTempBuffer(ImStrv* out_buf, const char* fmt, ...) { va_list args; va_start(args, fmt); - ImFormatStringToTempBufferV(out_buf, out_buf_end, fmt, args); + ImFormatStringToTempBufferV(out_buf, fmt, args); va_end(args); } @@ -2460,7 +2507,7 @@ void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, // by making the caller acquire a temp buffer token, with either explicit or destructor release, e.g. // ImGuiTempBufferToken token; // ImFormatStringToTempBuffer(token, ...); -void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args) +void ImFormatStringToTempBufferV(ImStrv* out_buf, const char* fmt, va_list args) { ImGuiContext& g = *GImGui; if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0) @@ -2468,8 +2515,8 @@ void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* buf = va_arg(args, const char*); // Skip formatting when using "%s" if (buf == NULL) buf = "(null)"; - *out_buf = buf; - if (out_buf_end) { *out_buf_end = buf + ImStrlen(buf); } + out_buf->Begin = buf; + out_buf->End = buf + ImStrlen(buf); } else if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 's' && fmt[4] == 0) { @@ -2480,14 +2527,14 @@ void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, buf = "(null)"; buf_len = ImMin(buf_len, 6); } - *out_buf = buf; - *out_buf_end = buf + buf_len; // Disallow not passing 'out_buf_end' here. User is expected to use it. + out_buf->Begin = buf; + out_buf->End = buf + buf_len; } else { int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args); - *out_buf = g.TempBuffer.Data; - if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; } + out_buf->Begin = g.TempBuffer.Data; + out_buf->End = g.TempBuffer.Data + buf_len; } } @@ -2571,17 +2618,18 @@ ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed) // Zero-terminated string hash, with support for ### to reset back to seed value. // e.g. "label###id" outputs the same hash as "id" (and "label" is generally displayed by the UI functions) // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements. -ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed) +ImGuiID ImHashStr(ImStrv str, ImGuiID seed) { seed = ~seed; ImU32 crc = seed; - const unsigned char* data = (const unsigned char*)data_p; + const unsigned char* data = (const unsigned char*)str.Begin; #ifndef IMGUI_ENABLE_SSE4_2_CRC const ImU32* crc32_lut = GCrc32LookupTable; #endif - if (data_size != 0) + if (str.End != NULL) { - while (data_size-- > 0) + size_t data_size = (size_t)str.length(); + while (data_size-- != 0) { unsigned char c = *data++; if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#') @@ -2620,12 +2668,12 @@ ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID() // FIXME-OPT: This is not designed to be optimal. Use with care. -const char* ImHashSkipUncontributingPrefix(const char* label) +const char* ImHashSkipUncontributingPrefix(ImStrv label) { - const char* result = label; - while (unsigned char c = *label++) - if (c == '#' && label[0] == '#' && label[1] == '#') - result = label + 2; + const char* result = label.Begin; + for (const char* p = label.Begin; p + 2 < label.End; p++) + if (p[0] == '#' && p[1] == '#' && p[2] == '#') + result = p + 3; return result; } @@ -2636,13 +2684,13 @@ const char* ImHashSkipUncontributingPrefix(const char* label) // Default file functions #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS -ImFileHandle ImFileOpen(const char* filename, const char* mode) +ImFileHandle ImFileOpen(ImStrv filename, ImStrv mode) { #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && (defined(__MINGW32__) || (!defined(__CYGWIN__) && !defined(__GNUC__))) // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames. // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32! - const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0); - const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0); + const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename.Begin, filename.length() + 1, NULL, 0); + const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode.Begin, mode.length() + 1, NULL, 0); // Use stack buffer if possible, otherwise heap buffer. Sizes include zero terminator. // We don't rely on current ImGuiContext as this is implied to be a helper function which doesn't depend on it (see #7314). @@ -2652,11 +2700,19 @@ ImFileHandle ImFileOpen(const char* filename, const char* mode) local_temp_heap.resize(filename_wsize + mode_wsize); wchar_t* filename_wbuf = local_temp_heap.Data ? local_temp_heap.Data : local_temp_stack; wchar_t* mode_wbuf = filename_wbuf + filename_wsize; - ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, filename_wbuf, filename_wsize); - ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, mode_wbuf, mode_wsize); + ::MultiByteToWideChar(CP_UTF8, 0, filename.Begin, filename.length(), filename_wbuf, filename_wsize); + ::MultiByteToWideChar(CP_UTF8, 0, mode.Begin, mode.length(), mode_wbuf, mode_wsize); + filename_wbuf[filename_wsize - 1] = mode_wbuf[mode_wsize - 1] = 0; return ::_wfopen(filename_wbuf, mode_wbuf); #else - return fopen(filename, mode); + // ImStrv is not guaranteed to be zero-terminated. + // FIXME-IMSTR: Use TempBuffer to avoid needlessly allocating. + ImStrv filename_0 = ImStrdup(filename); + ImStrv mode_0 = ImStrdup(mode); + ImFileHandle handle = fopen(filename_0.Begin, mode_0.Begin); + IM_FREE((char*)(void*)filename_0.Begin); + IM_FREE((char*)(void*)mode_0.Begin); + return handle; #endif } @@ -2670,7 +2726,7 @@ ImU64 ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f) // Helper: Load file content into memory // Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree() // This can't really be used with "rt" because fseek size won't match read size. -void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes) +void* ImFileLoadToMemory(ImStrv filename, ImStrv mode, size_t* out_file_size, int padding_bytes) { IM_ASSERT(filename && mode); if (out_file_size) @@ -2911,16 +2967,13 @@ const char* ImTextFindValidUtf8CodepointEnd(const char* in_text_start, const cha return prev; } -int ImTextCountLines(const char* in_text, const char* in_text_end) +int ImTextCountLines(ImStrv in_text) { - if (in_text_end == NULL) - in_text_end = in_text + ImStrlen(in_text); // FIXME-OPT: Not optimal approach, discourage use for now. int count = 0; - while (in_text < in_text_end) + for (const char* p = in_text.Begin, * p_end = in_text.End; p < p_end; count++) { - const char* line_end = (const char*)ImMemchr(in_text, '\n', in_text_end - in_text); - in_text = line_end ? line_end + 1 : in_text_end; - count++; + const char* line_end = (const char*)ImMemchr(p, '\n', p_end - p); + p = line_end ? line_end + 1 : p_end; } return count; } @@ -3157,7 +3210,7 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE //----------------------------------------------------------------------------- // Helper: Parse and apply text filters e.g. 'aaa bbb -ccc'. -ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077 +ImGuiTextFilter::ImGuiTextFilter(ImStrv default_filter) //-V1077 { InputBuf[0] = 0; _CountExclude = 0; @@ -3168,13 +3221,13 @@ ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077 } } -bool ImGuiTextFilter::Draw(const char* label) +bool ImGuiTextFilter::Draw(ImStrv label) { return DrawWithHint(label, "incl -excl"); } // Use ImGui::SetNextItemWidth() manually if you want to use this. -bool ImGuiTextFilter::DrawWithHint(const char* label, const char* hint) +bool ImGuiTextFilter::DrawWithHint(ImStrv label, ImStrv hint) { bool value_changed = ImGui::InputTextWithHint(label, hint, InputBuf, IM_COUNTOF(InputBuf)); if (value_changed) @@ -3243,18 +3296,16 @@ void ImGuiTextFilter::Build() } // FIXME: Could use a specialized ImStristr() + pre-convert our filter to uppercase. -bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const +bool ImGuiTextFilter::PassFilter(ImStrv text) const { if (_Items.Size == 0) return true; - if (text == NULL) - text = text_end = ""; // Filters are sorted so that '-' ones are always leading. ImGuiTextFilterItem* seq = _Items.Data; ImGuiTextFilterItem* seq_excl_end = _Items.Data + _CountExclude; for (; seq < seq_excl_end; seq++) - if (ImStristr(text, text_end, seq->Begin, seq->Begin + seq->Len) != NULL) + if (ImStristr(text.Begin, text.End, seq->Begin, seq->Begin + seq->Len) != NULL) return false; // Process includes @@ -3266,7 +3317,7 @@ bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const ImGuiTextFilterItem* seq_incl_end = seq + seq->CountInclude; IM_ASSERT_PARANOID(seq->CountInclude > 0 && seq_incl_end <= seq_end); for (; seq < seq_incl_end; seq++) - if (ImStristr(text, text_end, seq->Begin, seq->Begin + seq->Len) == NULL) + if (ImStristr(text.Begin, text.End, seq->Begin, seq->Begin + seq->Len) == NULL) break; if (seq == seq_incl_end) // All matched return true; @@ -3291,9 +3342,11 @@ bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const char ImGuiTextBuffer::EmptyString[1] = { 0 }; -void ImGuiTextBuffer::append(const char* str, const char* str_end) +void ImGuiTextBuffer::append(ImStrv str) { - int len = str_end ? (int)(str_end - str) : (int)ImStrlen(str); + const int len = str.length(); + if (len == 0) + return; // Add zero-terminator the first time const int write_off = (Buf.Size != 0) ? Buf.Size : 1; @@ -3305,7 +3358,7 @@ void ImGuiTextBuffer::append(const char* str, const char* str_end) } Buf.resize(needed_sz); - memcpy(&Buf[write_off - 1], str, (size_t)len); + memcpy(&Buf[write_off - 1], str.Begin, (size_t)len); Buf[write_off - 1 + len] = 0; } @@ -3977,57 +4030,44 @@ const char* ImGui::GetStyleColorName(ImGuiCol idx) // Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context. //----------------------------------------------------------------------------- -const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end) +const char* ImGui::FindRenderedTextEnd(ImStrv text) { - const char* text_display_end = text; - if (!text_end) - text_end = (const char*)-1; - - while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#')) + const char* text_display_end = text.Begin; + while (text_display_end < text.End && (text_display_end[0] != '#' || text_display_end[1] != '#')) text_display_end++; return text_display_end; } // Internal ImGui functions to render text // RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText() -void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash) +void ImGui::RenderText(ImVec2 pos, ImStrv text, bool hide_text_after_hash) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; // Hide anything after a '##' string - const char* text_display_end; if (hide_text_after_hash) - { - text_display_end = FindRenderedTextEnd(text, text_end); - } - else - { - if (!text_end) - text_end = text + ImStrlen(text); // FIXME-OPT (not reached by our internal calls) - text_display_end = text_end; - } - if (text == text_display_end) - return; + text.End = FindRenderedTextEnd(text); - window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end); - if (g.LogEnabled) - LogRenderedText(&pos, text, text_display_end); + if (text.Begin != text.End) + { + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text); + if (g.LogEnabled) + LogRenderedText(&pos, text); + } } -void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width) +void ImGui::RenderTextWrapped(ImVec2 pos, ImStrv text, float wrap_width) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - if (!text_end) - text_end = text + ImStrlen(text); // FIXME-OPT (not reached by our internal calls) - if (text == text_end) - return; - - window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width); - if (g.LogEnabled) - LogRenderedText(&pos, text, text_end); + if (text.Begin != text.End) + { + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, wrap_width); + if (g.LogEnabled) + LogRenderedText(&pos, text); + } } // Default clip_rect uses (pos_min,pos_max) @@ -4036,14 +4076,11 @@ void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end // Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take // better advantage of the render function taking size into account for coarse clipping. // DOES NOT CALL LogRenderedText(), unlike RenderTextClipped!!! -void ImGui::RenderTextClippedEx(ImDrawList* draw_list, 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) +void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, ImStrv text, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect) { - if (text == text_end) - return; - // Perform CPU side clipping for single clipped element to avoid using scissor state ImVec2 pos = pos_min; - const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end, false, 0.0f); + const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, false, 0.0f); const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min; const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max; @@ -4052,48 +4089,44 @@ void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, co need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y); // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment. - if (align.x > 0.0f) - pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x); - if (align.y > 0.0f) - pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y); + if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x); + if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y); // Render if (need_clipping) { ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y); - draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_end, 0.0f, &fine_clip_rect); + draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, 0.0f, &fine_clip_rect); } else { - draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_end, 0.0f, NULL); + draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, 0.0f, NULL); } } -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) +void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, ImStrv text, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect) { // Hide anything after a '##' string - const char* text_display_end = FindRenderedTextEnd(text, text_end); - const int text_len = (int)(text_display_end - text); - if (text_len == 0) + // FIXME-IMSTR: This is not new but should be moved out of there. + text.End = FindRenderedTextEnd(text); + if (text.Begin == text.End) return; ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect); + RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_size_if_known, align, clip_rect); if (g.LogEnabled) - LogRenderedText(&pos_min, text, text_display_end); + LogRenderedText(&pos_min, text); } // Another overly complex function until we reorganize everything into a nice all-in-one helper. // This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) from 'ellipsis_max_x' which may be beyond it. // This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move. // (BREAKING) On 2025/04/16 we removed the 'float clip_max_x' parameters which was preceding 'float ellipsis_max' and was the same value for 99% of users. -void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known) +void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float ellipsis_max_x, ImStrv text, const ImVec2* text_size_if_known) { ImGuiContext& g = *GImGui; - if (text_end_full == NULL) - text_end_full = FindRenderedTextEnd(text); - const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f); + const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, false, 0.0f); //draw_list->AddLineV(pos_max.x, pos_min.y - 4, pos_max.y + 6, IM_COL32(0, 0, 255, 255)); //draw_list->AddLineV(ellipsis_max_x, pos_min.y - 2, pos_max.y + 3, IM_COL32(0, 255, 0, 255)); @@ -4115,21 +4148,21 @@ void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, con // We can now claim the space between pos_max.x and ellipsis_max.x const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f); - const float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x; + const float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, &text_end_ellipsis).x; // Render text, render ellipsis - RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f)); + RenderTextClippedEx(draw_list, pos_min, pos_max, ImStrv(text.Begin, text_end_ellipsis), &text_size, ImVec2(0.0f, 0.0f)); ImVec4 cpu_fine_clip_rect(pos_min.x, pos_min.y, pos_max.x, pos_max.y); ImVec2 ellipsis_pos = ImTrunc(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y)); font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar, &cpu_fine_clip_rect); } else { - RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_end_full, &text_size, ImVec2(0.0f, 0.0f)); + RenderTextClippedEx(draw_list, pos_min, pos_max, text, &text_size, ImVec2(0.0f, 0.0f)); } if (g.LogEnabled) - LogRenderedText(&pos_min, text, text_end_full); + LogRenderedText(&pos_min, text); } // Render a rectangle shaped with optional rounding and borders @@ -4308,16 +4341,15 @@ static const ImGuiLocEntry GLocalizationEntriesEnUS[] = { ImGuiLocKey_VersionStr, "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" }, { ImGuiLocKey_TableSizeOne, "Size column to fit###SizeOne" }, { ImGuiLocKey_TableSizeAllFit, "Size all columns to fit###SizeAll" }, - { ImGuiLocKey_TableSizeAllDefault, "Size all columns to auto###SizeAll" }, + { ImGuiLocKey_TableSizeAllDefault, "Size all columns to default###SizeAll" }, { ImGuiLocKey_TableReset, "Reset" }, //{ ImGuiLocKey_TableResetAll, "Reset to default###ResetAll" }, { ImGuiLocKey_TableResetOrder, "Reset order###ResetOrder" }, { ImGuiLocKey_TableResetVisibility, "Reset visibility###ResetVisibility" }, - { ImGuiLocKey_TableResetSizing, "Reset sizing###ResetSizing" }, { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)" }, { ImGuiLocKey_WindowingPopup, "(Popup)" }, { ImGuiLocKey_WindowingUntitled, "(Untitled)" }, - { ImGuiLocKey_OpenLink_s, "Open '%s'" }, + { ImGuiLocKey_OpenLink_s, "Open '%.*s'" }, { ImGuiLocKey_CopyLink, "Copy Link###CopyLink" }, }; @@ -4762,12 +4794,12 @@ void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type) //----------------------------------------------------------------------------- // ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods -ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NULL) +ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, ImStrv name) : DrawListInst(NULL) { memset((void*)this, 0, sizeof(*this)); Ctx = ctx; Name = ImStrdup(name); - NameBufLen = (int)ImStrlen(name) + 1; + NameBufLen = name.length() + 1; ID = ImHashStr(name); IDStack.push_back(ID); MoveId = GetID("#MOVE"); @@ -5331,11 +5363,19 @@ const char* ImGui::GetClipboardText() return g.PlatformIO.Platform_GetClipboardTextFn ? g.PlatformIO.Platform_GetClipboardTextFn(&g) : NULL; } -void ImGui::SetClipboardText(const char* text) +void ImGui::SetClipboardText(ImStrv text) { ImGuiContext& g = *GImGui; if (g.PlatformIO.Platform_SetClipboardTextFn != NULL) - g.PlatformIO.Platform_SetClipboardTextFn(&g, text); + { + int len = text.length(); + char* text_p = (char*)IM_ALLOC(len + 1); + if (len > 0) + memcpy(text_p, text.Begin, len); + text_p[len] = 0; // text may not contain \0, it must be inserted manually. + g.PlatformIO.Platform_SetClipboardTextFn(&g, text_p); + IM_FREE(text_p); + } } const char* ImGui::GetVersion() @@ -6126,8 +6166,7 @@ static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 if (draw_list->CmdBuffer.Size == 0) draw_list->AddDrawCmd(); draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // FIXME: Need to strictly ensure ImDrawCmd are not merged (ElemCount==6 checks below will verify that) - draw_list->PrimReserve(6, 4); - draw_list->PrimRect(viewport_rect.Min, viewport_rect.Max, col); + draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col); ImDrawCmd cmd = draw_list->CmdBuffer.back(); IM_ASSERT(cmd.ElemCount == 6); draw_list->CmdBuffer.pop_back(); @@ -6373,21 +6412,18 @@ void ImGui::Render() // Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker. // CalcTextSize("") should return ImVec2(0.0f, g.FontSize) -ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width) +ImVec2 ImGui::CalcTextSize(ImStrv text, bool hide_text_after_double_hash, float wrap_width) { ImGuiContext& g = *GImGui; - const char* text_display_end; if (hide_text_after_double_hash) - text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string - else - text_display_end = text_end; + text.End = FindRenderedTextEnd(text); // Hide anything after a '##' string ImFont* font = g.Font; const float font_size = g.FontSize; - if (text == text_display_end) + if (text.Begin == text.End) return ImVec2(0.0f, font_size); - ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL); + ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, NULL); // Round // (see 7b0bf230, 4622fa4b6, #791 for details about this.) @@ -6622,9 +6658,9 @@ ImGuiItemFlags ImGui::GetItemFlags() return g.LastItemData.ItemFlags; } -// Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'. +// Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool borders = false' parameter instead of 'ImGuiChildFlags child_flags = 0'. // ImGuiChildFlags_Borders is defined as always == 1 in order to allow old code passing 'true'. Read comments in imgui.h for details! -bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags) +bool ImGui::BeginChild(ImStrv str_id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags) { ImGuiID id = GetCurrentWindow()->GetID(str_id); return BeginChildEx(str_id, id, size_arg, child_flags, window_flags); @@ -6635,7 +6671,7 @@ bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child return BeginChildEx(NULL, id, size_arg, child_flags, window_flags); } -bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags) +bool ImGui::BeginChildEx(ImStrv name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags) { ImGuiContext& g = *GImGui; ImGuiWindow* parent_window = g.CurrentWindow; @@ -6711,14 +6747,14 @@ bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, I // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value. // FIXME: 2023/11/14: commented out shorted version. We had an issue with multiple ### in child window path names, which the trailing hash helped workaround. // e.g. "ParentName###ParentIdentifier/ChildName###ChildIdentifier" would get hashed incorrectly by ImHashStr(), trailing _%08X somehow fixes it. - const char* temp_window_name; + ImStrv temp_window_name; /*if (name && parent_window->IDStack.back() == parent_window->ID) - ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s", parent_window->Name, name); // May omit ID if in root of ID stack + ImFormatStringToTempBuffer(&temp_window_name, "%s/%.*s", parent_window->Name, name.length(), name.Begin); // May omit ID if in root of ID stack else*/ if (name) - ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id); + ImFormatStringToTempBuffer(&temp_window_name, "%s/%.*s_%08X", parent_window->Name, name.length(), name.Begin, id); else - ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id); + ImFormatStringToTempBuffer(&temp_window_name, "%s/%08X", parent_window->Name, id); // Set style const float backup_border_size = g.Style.ChildBorderSize; @@ -6831,7 +6867,7 @@ ImGuiWindow* ImGui::FindWindowByID(ImGuiID id) return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id); } -ImGuiWindow* ImGui::FindWindowByName(const char* name) +ImGuiWindow* ImGui::FindWindowByName(ImStrv name) { ImGuiID id = ImHashStr(name); return FindWindowByID(id); @@ -6881,7 +6917,7 @@ static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* s settings->LastUsedDate = g.SessionDate; } -static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags) +static ImGuiWindow* CreateNewWindow(ImStrv name, ImGuiWindowFlags flags) { // Create window the first time //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags); @@ -7479,7 +7515,7 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar } // Render title text, collapse button, close button -void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open) +void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, ImStrv name, bool* p_open) { ImGuiContext& g = *GImGui; ImGuiStyle& style = g.Style; @@ -7538,7 +7574,7 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker) // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code.. const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f; - const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f); + const ImVec2 text_size = CalcTextSize(name, true) + ImVec2(marker_size_x, 0.0f); // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button, // while uncentered title text will still reach edges correctly. @@ -7569,7 +7605,7 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl } //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG] //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG] - RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r); + RenderTextClipped(layout_r.Min, layout_r.Max, name, &text_size, style.WindowTitleAlign, &clip_r); } void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window) @@ -7633,11 +7669,11 @@ static void SetWindowActiveForSkipRefresh(ImGuiWindow* window) // 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. // - 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. // - 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. -bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) +bool ImGui::Begin(ImStrv name, bool* p_open, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; - IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required + IM_ASSERT(name.Begin != name.End); // Window name required IM_ASSERT(g.WithinFrameScope); // Forgot to call ImGui::NewFrame() IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet @@ -7828,7 +7864,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window_title_visible_elsewhere = true; if (flags & ImGuiWindowFlags_ChildMenu) window_title_visible_elsewhere = true; - if ((window_title_visible_elsewhere || window_just_activated_by_user) && !window_just_created && strcmp(name, window->Name) != 0) + if ((window_title_visible_elsewhere || window_just_activated_by_user) && !window_just_created && ImStrcmp(name, window->Name) != 0) { size_t buf_len = (size_t)window->NameBufLen; window->Name = ImStrdupcpy(window->Name, &buf_len, name); @@ -7998,13 +8034,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->Pos = parent_window->DC.CursorPos; } - if (window->SetWindowPosVal.x != FLT_MAX) - { - const ImVec2 backup_pos_val = window->SetWindowPosVal; + const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0); + if (window_pos_with_pivot) SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering) - if (window->HiddenFramesCannotSkipItems != 0) - window->SetWindowPosVal = backup_pos_val; // Restore set request while hidden, so an updated size will be accounted for. (#9568) - } else if ((flags & ImGuiWindowFlags_ChildMenu) != 0) window->Pos = FindBestWindowPosForPopup(window); else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize) @@ -8770,7 +8802,7 @@ void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond) SetWindowPos(window, pos, cond); } -void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond) +void ImGui::SetWindowPos(ImStrv name, const ImVec2& pos, ImGuiCond cond) { if (ImGuiWindow* window = FindWindowByName(name)) SetWindowPos(window, pos, cond); @@ -8816,7 +8848,7 @@ void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond) SetWindowSize(GImGui->CurrentWindow, size, cond); } -void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond) +void ImGui::SetWindowSize(ImStrv name, const ImVec2& size, ImGuiCond cond) { if (ImGuiWindow* window = FindWindowByName(name)) SetWindowSize(window, size, cond); @@ -8865,7 +8897,7 @@ bool ImGui::IsWindowAppearing() return window->Appearing; } -void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond) +void ImGui::SetWindowCollapsed(ImStrv name, bool collapsed, ImGuiCond cond) { if (ImGuiWindow* window = FindWindowByName(name)) SetWindowCollapsed(window, collapsed, cond); @@ -9437,14 +9469,14 @@ void ImGui::PopFont() // This is one of the very rare legacy case where we use ImGuiWindow methods, // it should ideally be flattened at some point but it's been used a lots by widgets. IM_MSVC_RUNTIME_CHECKS_OFF -ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end) +ImGuiID ImGuiWindow::GetID(ImStrv str) { ImGuiID seed = IDStack.back(); - ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed); + ImGuiID id = ImHashStr(str, seed); #ifndef IMGUI_DISABLE_DEBUG_TOOLS ImGuiContext& g = *Ctx; if (g.DebugHookIdInfoId == id) - ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end); + ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str.Begin, str.End); #endif return id; } @@ -9492,7 +9524,7 @@ ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs) return id; } -void ImGui::PushID(const char* str_id) +void ImGui::PushID(ImStrv str_id) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; @@ -9500,14 +9532,6 @@ void ImGui::PushID(const char* str_id) window->IDStack.push_back(id); } -void ImGui::PushID(const char* str_id_begin, const char* str_id_end) -{ - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; - ImGuiID id = window->GetID(str_id_begin, str_id_end); - window->IDStack.push_back(id); -} - void ImGui::PushID(const void* ptr_id) { ImGuiContext& g = *GImGui; @@ -9568,18 +9592,12 @@ void ImGui::PopID() window->IDStack.pop_back(); } -ImGuiID ImGui::GetID(const char* str_id) +ImGuiID ImGui::GetID(ImStrv str_id) { ImGuiWindow* window = GImGui->CurrentWindow; return window->GetID(str_id); } -ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end) -{ - ImGuiWindow* window = GImGui->CurrentWindow; - return window->GetID(str_id_begin, str_id_end); -} - ImGuiID ImGui::GetID(const void* ptr_id) { ImGuiWindow* window = GImGui->CurrentWindow; @@ -11156,10 +11174,10 @@ bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID own // Which is why it is required you put them in your imconfig file (and NOT only before including imgui.h). // Otherwise it is possible that different compilation units would see different structure layout. // If you don't want to modify imconfig.h you can use the IMGUI_USER_CONFIG define to change filename. -bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx) +bool ImGui::DebugCheckVersionAndDataLayout(ImStrv version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx) { bool error = false; - if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); } + if (ImStrcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(0 && "Mismatched version string!"); } if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); } if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); } if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); } @@ -11263,14 +11281,6 @@ static void ImGui::ErrorCheckNewFrameSanityChecks() if (g.IO.ConfigErrorRecovery) IM_ASSERT(g.IO.ConfigErrorRecoveryEnableAssert || g.IO.ConfigErrorRecoveryEnableDebugLog || g.IO.ConfigErrorRecoveryEnableTooltip || g.ErrorCallback != NULL); - // Detect if the parameters leading AddFontDefault() to implicitly select either AddFontDefaultBitmap() or AddFontDefaultVector() have changed. - if (g.FrameCount == 2 && g.IO.Fonts->Builder->LoadedFontDefaultAsVector != -1) - { - const bool old_heuristic_result_for_using_vector_font = (bool)g.IO.Fonts->Builder->LoadedFontDefaultAsVector; - const bool new_heuristic_result_for_using_vector_font = ImFontAtlasHeuristicShouldUseDefaultVectorFont(g.IO.Fonts); - IM_ASSERT_USER_ERROR(old_heuristic_result_for_using_vector_font == new_heuristic_result_for_using_vector_font, "AddFontDefault() font selection heuristic parameters changed between load/init time and now. Verify which parameters have changed or load a default font explicitly!"); - } - #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS if (g.IO.FontGlobalScale > 1.0f) IM_ASSERT(g.Style.FontScaleMain == 1.0f && "Since 1.92: use style.FontScaleMain instead of g.IO.FontGlobalScale!"); @@ -12524,7 +12534,7 @@ bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags) } } -bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags) +bool ImGui::IsPopupOpen(ImStrv str_id, ImGuiPopupFlags popup_flags) { ImGuiContext& g = *GImGui; ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id); @@ -12555,7 +12565,6 @@ ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal() return NULL; } - // When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing) // should be positioned behind that modal window, unless the window was created inside the modal begin-stack. // In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent. @@ -12592,11 +12601,11 @@ ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window) return NULL; } -bool ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags) +bool ImGui::OpenPopup(ImStrv str_id, ImGuiPopupFlags popup_flags) { ImGuiContext& g = *GImGui; ImGuiID id = g.CurrentWindow->GetID(str_id); - IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id); + IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%.*s\" -> 0x%08X\n", (int)(str_id.End - str_id.Begin), str_id.Begin, id); return OpenPopupEx(id, popup_flags); } @@ -12807,7 +12816,7 @@ bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_window_flags) return is_open; } -bool ImGui::BeginPopupMenuEx(ImGuiID id, const char* label, ImGuiWindowFlags extra_window_flags) +bool ImGui::BeginPopupMenuEx(ImGuiID id, ImStrv label, ImGuiWindowFlags extra_window_flags) { ImGuiContext& g = *GImGui; if (!IsPopupOpen(id, ImGuiPopupFlags_None)) @@ -12823,7 +12832,7 @@ bool ImGui::BeginPopupMenuEx(ImGuiID id, const char* label, ImGuiWindowFlags ext char name[128]; IM_ASSERT(extra_window_flags & ImGuiWindowFlags_ChildMenu); - ImFormatString(name, IM_COUNTOF(name), "%s###Menu_%02d", label, g.BeginMenuDepth); // Recycle windows based on depth + ImFormatString(name, IM_COUNTOF(name), "%.*s###Menu_%02d", label.length(), label.Begin, g.BeginMenuDepth); // Recycle windows based on depth bool is_open = Begin(name, NULL, extra_window_flags | ImGuiWindowFlags_Popup); if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display) EndPopup(); @@ -12831,7 +12840,7 @@ bool ImGui::BeginPopupMenuEx(ImGuiID id, const char* label, ImGuiWindowFlags ext return is_open; } -bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags) +bool ImGui::BeginPopup(ImStrv str_id, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance @@ -12848,7 +12857,7 @@ bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags) // Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup). // - *p_open set back to false in BeginPopupModal() when popup is not open. // - if you set *p_open to false before calling BeginPopupModal(), it will close the popup. -bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags) +bool ImGui::BeginPopupModal(ImStrv name, bool* p_open, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; @@ -12942,7 +12951,7 @@ bool ImGui::IsPopupOpenRequestForWindow(ImGuiPopupFlags popup_flags) // Helper to open a popup if mouse button is released over the item // - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup() -bool ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags) +bool ImGui::OpenPopupOnItemClick(ImStrv str_id, ImGuiPopupFlags popup_flags) { ImGuiContext& g = *GImGui; if (IsPopupOpenRequestForItem(popup_flags, g.LastItemData.ID)) @@ -12971,7 +12980,7 @@ bool ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags // OpenPopup(id); // return BeginPopup(id); // The main difference being that this is tweaked to avoid computing the ID twice. -bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags) +bool ImGui::BeginPopupContextItem(ImStrv str_id, ImGuiPopupFlags popup_flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; @@ -12984,7 +12993,7 @@ bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flag return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings); } -bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags) +bool ImGui::BeginPopupContextWindow(ImStrv str_id, ImGuiPopupFlags popup_flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; @@ -12996,7 +13005,7 @@ bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_fl return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings); } -bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags) +bool ImGui::BeginPopupContextVoid(ImStrv str_id, ImGuiPopupFlags popup_flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; @@ -13177,7 +13186,7 @@ void ImGui::SetWindowFocus() FocusWindow(GImGui->CurrentWindow); } -void ImGui::SetWindowFocus(const char* name) +void ImGui::SetWindowFocus(ImStrv name) { if (name) { @@ -15324,15 +15333,15 @@ void ImGui::EndDragDropSource() } // Use 'cond' to choose to submit payload on drag start or every frame -bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond) +bool ImGui::SetDragDropPayload(ImStrv type, const void* data, size_t data_size, ImGuiCond cond) { ImGuiContext& g = *GImGui; ImGuiPayload& payload = g.DragDropPayload; if (cond == 0) cond = ImGuiCond_Always; - IM_ASSERT(type != NULL); - IM_ASSERT(ImStrlen(type) < IM_COUNTOF(payload.DataType) && "Payload type can be at most 32 characters long"); + IM_ASSERT(type.length() > 0 && "Payload type can not be empty"); + IM_ASSERT(type.length() < IM_COUNTOF(payload.DataType) && "Payload type can be at most 32 characters long"); IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0)); IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once); IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource() @@ -15458,13 +15467,13 @@ bool ImGui::IsDragDropPayloadBeingAccepted() return g.DragDropActive && g.DragDropAcceptIdPrev != 0; } -const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags) +const ImGuiPayload* ImGui::AcceptDragDropPayload(ImStrv type, ImGuiDragDropFlags flags) { ImGuiContext& g = *GImGui; ImGuiPayload& payload = g.DragDropPayload; IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ? IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ? - if (type != NULL && !payload.IsDataType(type)) + if (type && !payload.IsDataType(type)) return NULL; // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints. @@ -15600,7 +15609,7 @@ void ImGui::LogTextV(const char* fmt, va_list args) // Internal version that takes a position to decide on newline placement and pad items according to their depth. // We split text into individual lines to add current tree level padding // FIXME: This code is a little complicated perhaps, considering simplifying the whole system. -void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end) +void ImGui::LogRenderedText(const ImVec2* ref_pos, ImStrv text) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; @@ -15609,8 +15618,8 @@ void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* const char* suffix = g.LogNextSuffix; g.LogNextPrefix = g.LogNextSuffix = NULL; - if (!text_end) - text_end = FindRenderedTextEnd(text, text_end); + if (!text.End) + text.End = FindRenderedTextEnd(text); const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + ImMax(g.Style.FramePadding.y, g.Style.ItemSpacing.y) + 1); if (ref_pos) @@ -15629,14 +15638,14 @@ void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* g.LogDepthRef = window->DC.TreeDepth; const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef); - const char* text_remaining = text; + const char* text_remaining = text.Begin; for (;;) { // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry. // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured. const char* line_start = text_remaining; - const char* line_end = ImStreolRange(line_start, text_end); - const bool is_last_line = (line_end == text_end); + const char* line_end = ImStreolRange(line_start, text.End); + const bool is_last_line = (line_end == text.End); if (line_start != line_end || !is_last_line) { const int line_length = (int)(line_end - line_start); @@ -15698,7 +15707,7 @@ void ImGui::LogToTTY(int auto_open_depth) } // Start logging/capturing text output to given file -void ImGui::LogToFile(int auto_open_depth, const char* filename) +void ImGui::LogToFile(int auto_open_depth, ImStrv filename) { ImGuiContext& g = *GImGui; if (g.LogEnabled) @@ -15709,7 +15718,7 @@ void ImGui::LogToFile(int auto_open_depth, const char* filename) // By opening the file in binary mode "ab" we have consistent output everywhere. if (!filename) filename = g.IO.LogFilename; - if (!filename || !filename[0]) + if (filename.empty()) return; ImFileHandle f = ImFileOpen(filename, "ab"); if (!f) @@ -15871,14 +15880,14 @@ void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler) g.SettingsHandlers.push_back(*handler); } -void ImGui::RemoveSettingsHandler(const char* type_name) +void ImGui::RemoveSettingsHandler(ImStrv type_name) { ImGuiContext& g = *GImGui; if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name)) g.SettingsHandlers.erase(handler); } -ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name) +ImGuiSettingsHandler* ImGui::FindSettingsHandler(ImStrv type_name) { ImGuiContext& g = *GImGui; const ImGuiID type_hash = ImHashStr(type_name); @@ -15918,20 +15927,19 @@ void ImGui::CleanupIniSettings(ImGuiSettingsCleanupArgs* args) handler.CleanupFn(&g, &handler, args); } -void ImGui::LoadIniSettingsFromDisk(const char* ini_filename) +void ImGui::LoadIniSettingsFromDisk(ImStrv ini_filename) { size_t file_data_size = 0; char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size); if (!file_data) return; if (file_data_size > 0) - LoadIniSettingsFromMemory(file_data, (size_t)file_data_size); + LoadIniSettingsFromMemory(ImStrv(file_data, file_data + file_data_size)); IM_FREE(file_data); } // Zero-tolerance, no error reporting, cheap .ini parsing -// Set ini_size==0 to let us use strlen(ini_data). Do not call this function with a 0 if your buffer is actually empty! -void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) +void ImGui::LoadIniSettingsFromMemory(ImStrv ini_data) { ImGuiContext& g = *GImGui; IM_ASSERT(g.Initialized); @@ -15940,12 +15948,11 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter). // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy.. - if (ini_size == 0) - ini_size = ImStrlen(ini_data); + const int ini_size = ini_data.length(); g.SettingsIniData.Buf.resize((int)ini_size + 1); char* const buf = g.SettingsIniData.Buf.Data; char* const buf_end = buf + ini_size; - memcpy(buf, ini_data, ini_size); + memcpy(buf, ini_data.Begin, ini_size); buf_end[0] = 0; // Call pre-read handlers @@ -15993,7 +16000,7 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) g.SettingsLoaded = true; // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary) - memcpy(buf, ini_data, ini_size); + memcpy(buf, ini_data.Begin, ini_size); // Call post-read handlers ImGuiSettingsCleanupArgs cleanup_args; @@ -16007,7 +16014,7 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) handler.ApplyAllFn(&g, &handler); } -void ImGui::SaveIniSettingsToDisk(const char* ini_filename) +void ImGui::SaveIniSettingsToDisk(ImStrv ini_filename) { ImGuiContext& g = *GImGui; g.SettingsDirtyTimer = 0.0f; @@ -16037,21 +16044,27 @@ const char* ImGui::SaveIniSettingsToMemory(size_t* out_size) return g.SettingsIniData.c_str(); } -ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name) +ImGuiWindowSettings* ImGui::CreateNewWindowSettings(ImStrv name) { ImGuiContext& g = *GImGui; // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier. if (g.IO.ConfigDebugIniSettings == false) - name = ImHashSkipUncontributingPrefix(name); - const size_t name_len = ImStrlen(name); + name.Begin = ImHashSkipUncontributingPrefix(name); + const size_t name_len = (size_t)name.length(); + if (name_len == 0) + { + IM_ASSERT(false && "Name must not be empty."); + return NULL; + } // Allocate chunk const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1; ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size); IM_PLACEMENT_NEW(settings) ImGuiWindowSettings(); - settings->ID = ImHashStr(name, name_len); - memcpy(settings->GetName(), name, name_len + 1); // Store with zero terminator + settings->ID = ImHashStr(name); + memcpy(settings->GetName(), name.Begin, name_len); + settings->GetName()[name_len] = 0; // name may not contain \0, it must be inserted manually. return settings; } @@ -16077,7 +16090,7 @@ ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window) } // This will revert window to its initial state, including enabling the ImGuiCond_FirstUseEver/ImGuiCond_Once conditions once more. -void ImGui::ClearWindowSettings(const char* name) +void ImGui::ClearWindowSettings(ImStrv name) { //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name); ImGuiWindow* window = FindWindowByName(name); @@ -16624,7 +16637,8 @@ void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul)); window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul)); window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul)); - window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name)); + ImStrv label(thumb_window->Name, FindRenderedTextEnd(thumb_window->Name)); + window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), label); } draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul)); if (viewport->ID == g.DebugMetricsConfig.HighlightViewportID) @@ -16701,9 +16715,9 @@ void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list) } // Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct. -void ImGui::DebugTextEncoding(const char* str) +void ImGui::DebugTextEncoding(ImStrv str) { - Text("Text: \"%s\"", str); + Text("Text: \"%.*s\"", str.length(), str.Begin); if (!BeginTable("##DebugTextEncoding", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable)) return; TableSetupColumn("Offset"); @@ -16711,13 +16725,12 @@ void ImGui::DebugTextEncoding(const char* str) TableSetupColumn("Glyph"); TableSetupColumn("Codepoint"); TableHeadersRow(); - const char* str_end = str + strlen(str); // As we may receive malformed UTF-8, pass an explicit end instead of relying on ImTextCharFromUtf8() assuming enough space. - for (const char* p = str; *p != 0; ) + for (const char* p = str.Begin; p != str.End; ) { unsigned int c; - const int c_utf8_len = ImTextCharFromUtf8(&c, p, str_end); + const int c_utf8_len = ImTextCharFromUtf8(&c, p, str.End); // As we may receive malformed UTF-8, pass an explicit end instead of relying on ImTextCharFromUtf8() assuming enough space. TableNextColumn(); - Text("%d", (int)(p - str)); + Text("%d", (int)(p - str.Begin)); TableNextColumn(); for (int byte_index = 0; byte_index < c_utf8_len; byte_index++) { @@ -16726,7 +16739,7 @@ void ImGui::DebugTextEncoding(const char* str) Text("0x%02X", (int)(unsigned char)p[byte_index]); } TableNextColumn(); - TextUnformatted(p, p + c_utf8_len); + TextUnformatted(ImStrv(p, p + c_utf8_len)); if (!GetFont()->IsGlyphInFont((ImWchar)c)) { SameLine(); @@ -16916,10 +16929,10 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) ImFontAtlasRectId id = ImFontAtlasRectId_Make(atlas->Builder->RectsIndex.index_from_ptr(&entry), entry.Generation); ImFontAtlasRect r = {}; atlas->GetCustomRect(id, &r); - const char* buf; - ImFormatStringToTempBuffer(&buf, NULL, "ID:%08X, used:%d, { w:%3d, h:%3d } { x:%4d, y:%4d }", id, entry.IsUsed, r.w, r.h, r.x, r.y); + ImStrv buf; + ImFormatStringToTempBuffer(&buf, "ID:%08X, used:%d, { w:%3d, h:%3d } { x:%4d, y:%4d }", id, entry.IsUsed, r.w, r.h, r.x, r.y); TableNextColumn(); - Selectable(buf); + Selectable(buf.Begin); if (IsItemHovered()) highlight_r_id = id; TableNextColumn(); @@ -17067,7 +17080,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) { // Debug Break features // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted. - SeparatorTextEx(0, "Debug breaks", NULL, CalcTextSize("(?)").x + g.Style.SeparatorTextPadding.x); + SeparatorTextEx(0, "Debug breaks", CalcTextSize("(?)").x + g.Style.SeparatorTextPadding.x); SameLine(); MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash."); if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive) @@ -17633,7 +17646,7 @@ bool ImGui::DebugBreakButton(const char* label, const char* description_of_locat ImGuiContext& g = *GImGui; const ImGuiID id = window->GetID(label); - const ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImVec2 label_size = CalcTextSize(label, true); ImVec2 pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrLineTextBaseOffset); ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x * 2.0f, label_size.y); @@ -18368,7 +18381,7 @@ void ImGui::ShowDebugLogWindow(bool* p_open) // Display line, search for 0xXXXXXXXX identifiers and call DebugLocateItemOnHover() when hovered. void ImGui::DebugTextUnformattedWithLocateItem(const char* line_begin, const char* line_end) { - TextUnformatted(line_begin, line_end); + TextUnformatted(ImStrv(line_begin, line_end)); if (!IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) return; ImGuiContext& g = *GImGui; @@ -18378,8 +18391,8 @@ void ImGui::DebugTextUnformattedWithLocateItem(const char* line_begin, const cha ImGuiID id = 0; if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1 || ImCharIsXdigitA(p[10])) continue; - ImVec2 p0 = CalcTextSize(line_begin, p); - ImVec2 p1 = CalcTextSize(p, p + 10); + ImVec2 p0 = CalcTextSize(ImStrv(line_begin, p)); + ImVec2 p1 = CalcTextSize(ImStrv(p, p + 10)); g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y)); if (IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true)) DebugLocateItemOnHover(id); @@ -18591,28 +18604,28 @@ void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* dat if (info->DescOffset == -1) { - const char* result = NULL; - const char* result_end = NULL; + ImStrv result; switch (data_type) { case ImGuiDataType_S32: - ImFormatStringToTempBuffer(&result, &result_end, "%d", (int)(intptr_t)data_id); + ImFormatStringToTempBuffer(&result, "%d", (int)(intptr_t)data_id); break; case ImGuiDataType_String: - ImFormatStringToTempBuffer(&result, &result_end, "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)ImStrlen((const char*)data_id), (const char*)data_id); + ImFormatStringToTempBuffer(&result, "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)ImStrlen((const char*)data_id), (const char*)data_id); break; case ImGuiDataType_Pointer: - ImFormatStringToTempBuffer(&result, &result_end, "(void*)0x%p", data_id); + ImFormatStringToTempBuffer(&result, "(void*)0x%p", data_id); break; case ImGuiDataType_ID: // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one. - ImFormatStringToTempBuffer(&result, &result_end, "0x%08X [override]", id); + ImFormatStringToTempBuffer(&result, "0x%08X [override]", id); break; default: IM_ASSERT(0); } info->DescOffset = query->ResultsDescBuf.size(); - query->ResultsDescBuf.append(result, result_end + 1); // Include zero terminator + result.End++; // Include zero terminator + query->ResultsDescBuf.append(result); } info->QuerySuccess = true; if (info->DataType == -1) @@ -18652,7 +18665,7 @@ static const char* DebugItemPathQuery_GetResultAsPath(ImGuiDebugItemPathQuery* q if (c == '/') buf->append("\\"); if (c < 256 || !hex_encode_non_ascii_chars) - buf->append(p, p_next); + buf->append(ImStrv(p, p_next)); else for (; p < p_next; p++) buf->appendf("\\x%02x", (unsigned char)*p); p = p_next; @@ -18678,6 +18691,7 @@ void ImGui::ShowIDStackToolWindow(bool* p_open) tool->LastActiveFrame = g.FrameCount; const char* result_path = DebugItemPathQuery_GetResultAsPath(query, tool->OptHexEncodeNonAsciiChars); Text("0x%08X", query->MainID); + SameLine(); MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details."); @@ -18754,7 +18768,7 @@ void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {} #if !defined(IMGUI_DISABLE_DEMO_WINDOWS) || !defined(IMGUI_DISABLE_DEBUG_TOOLS) // Demo helper function to select among loaded fonts. // Here we use the regular BeginCombo()/EndCombo() api which is the more flexible one. -void ImGui::ShowFontSelector(const char* label) +void ImGui::ShowFontSelector(ImStrv label) { ImGuiIO& io = GetIO(); ImFont* font_current = GetFont(); diff --git a/imgui.h b/imgui.h index 69e061c34..2e5d6a9da 100644 --- a/imgui.h +++ b/imgui.h @@ -30,7 +30,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.93.1 WIP" -#define IMGUI_VERSION_NUM 19303 +#define IMGUI_VERSION_NUM 19301 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 @@ -58,6 +58,8 @@ Index of this file: */ +#define IMGUI_HAS_IMSTR + #pragma once // Configuration file with compile-time options @@ -153,6 +155,7 @@ Index of this file: #pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast #pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe +#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. #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant #pragma clang diagnostic ignored "-Wreserved-identifier" // warning: identifier '_Xxx' is reserved because it starts with '_' followed by a capital letter #pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access @@ -162,6 +165,7 @@ Index of this file: #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind #pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe #pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead +#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format string not a string literal #endif //----------------------------------------------------------------------------- @@ -325,6 +329,26 @@ struct ImVec4 IM_VEC4_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and ImVec4. #endif }; + +// String view (non-owning pair of begin/end pointers, not necessarily zero-terminated) +// ImStrv are used as function parameters instead of passing a pair of const char*. +struct ImStrv +{ + const char* Begin; + const char* End; + IM_NODEBUGSTEP inline ImStrv() { Begin = End = NULL; } + IM_NODEBUGSTEP inline ImStrv(const char* b) { Begin = b; End = b ? b + strlen(b) : NULL; } + IM_NODEBUGSTEP inline ImStrv(const char* b, const char* e){ Begin = b; End = e ? e : b ? b + strlen(b) : NULL; } + IM_NODEBUGSTEP inline int length() const { return (int)(End - Begin); } + IM_NODEBUGSTEP inline bool empty() const { return Begin == End; } // == "" or == NULL + IM_NODEBUGSTEP inline operator bool() const { return Begin != NULL; } // return true when valid ("" is valid, NULL construction is not) +#ifdef IM_STRV_CLASS_EXTRA + IM_STRV_CLASS_EXTRA // Define additional constructor in imconfig.h to convert your string types (e.g. std::string, std::string_view) to ImStrV. +#endif + // private: bool operator==(ImStrv) { return false; } // [DEBUG] Uncomment to catch undesirable uses of operators + // private: bool operator!=(ImStrv) { return false; } +}; + IM_MSVC_RUNTIME_CHECKS_RESTORE //----------------------------------------------------------------------------- @@ -423,8 +447,8 @@ namespace ImGui IMGUI_API void ShowIDStackToolWindow(bool* p_open = NULL); // create Stack Tool window. hover items with mouse to query information about the source of their unique ID. IMGUI_API void ShowAboutWindow(bool* p_open = NULL); // create About window. display Dear ImGui version, credits and build/system information. IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // add style editor block (not a window). you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style) - IMGUI_API bool ShowStyleSelector(const char* label); // add style selector block (not a window), essentially a combo listing the default styles. - IMGUI_API void ShowFontSelector(const char* label); // add font selector block (not a window), essentially a combo listing the loaded fonts. + IMGUI_API bool ShowStyleSelector(ImStrv label); // add style selector block (not a window), essentially a combo listing the default styles. + IMGUI_API void ShowFontSelector(ImStrv label); // add font selector block (not a window), essentially a combo listing the loaded fonts. IMGUI_API void ShowUserGuide(); // add basic help/info block (not a window): how to manipulate ImGui as an end-user (mouse/keyboard controls). IMGUI_API const char* GetVersion(); // get the compiled version string e.g. "1.80 WIP" (essentially the value for IMGUI_VERSION from the compiled version of imgui.cpp) @@ -445,7 +469,7 @@ namespace ImGui // such as BeginMenu/EndMenu, BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding // BeginXXX function returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.] // - Note that the bottom of window stack always contains a window called "Debug". - IMGUI_API bool Begin(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); + IMGUI_API bool Begin(ImStrv name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); IMGUI_API void End(); // Child Windows @@ -466,7 +490,7 @@ namespace ImGui // [Important: due to legacy reason, Begin/End and BeginChild/EndChild are inconsistent with all other functions // such as BeginMenu/EndMenu, BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding // BeginXXX function returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.] - IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0, 0), ImGuiChildFlags child_flags = 0, ImGuiWindowFlags window_flags = 0); + IMGUI_API bool BeginChild(ImStrv str_id, const ImVec2& size = ImVec2(0, 0), ImGuiChildFlags child_flags = 0, ImGuiWindowFlags window_flags = 0); IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0, 0), ImGuiChildFlags child_flags = 0, ImGuiWindowFlags window_flags = 0); IMGUI_API void EndChild(); @@ -496,10 +520,10 @@ namespace ImGui IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiCond cond = 0); // (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0, 0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects. IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed(). IMGUI_API void SetWindowFocus(); // (not recommended) set current window to be focused / top-most. prefer using SetNextWindowFocus(). - IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond = 0); // set named window position. - IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis. - IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond = 0); // set named window collapsed state - IMGUI_API void SetWindowFocus(const char* name); // set named window to be focused / top-most. use NULL to remove focus. + IMGUI_API void SetWindowPos(ImStrv name, const ImVec2& pos, ImGuiCond cond = 0); // set named window position. + IMGUI_API void SetWindowSize(ImStrv name, const ImVec2& size, ImGuiCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis. + IMGUI_API void SetWindowCollapsed(ImStrv name, bool collapsed, ImGuiCond cond = 0); // set named window collapsed state + IMGUI_API void SetWindowFocus(ImStrv name); // set named window to be focused / top-most. use NULL to remove focus. // Windows Scrolling // - Any change of Scroll will be applied at the beginning of next frame in the first call to Begin(). @@ -613,19 +637,17 @@ namespace ImGui // - You can also use the "Label##foobar" syntax within widget label to distinguish them from each others. // - In this header file we use the "label"/"name" terminology to denote a string that will be displayed + used as an ID, // whereas "str_id" denote a string that is only used as an ID and not normally displayed. - IMGUI_API void PushID(const char* str_id); // push string into the ID stack (will hash string). - IMGUI_API void PushID(const char* str_id_begin, const char* str_id_end); // push string into the ID stack (will hash string). + IMGUI_API void PushID(ImStrv str_id); // push string into the ID stack (will hash string). IMGUI_API void PushID(const void* ptr_id); // push pointer into the ID stack (will hash pointer). IMGUI_API void PushID(int int_id); // push integer into the ID stack (will hash integer). IMGUI_API void PopID(); // pop from the ID stack. - IMGUI_API ImGuiID GetID(const char* str_id); // calculate unique ID (hash of whole ID stack + given parameter). e.g. if you want to query into ImGuiStorage yourself - IMGUI_API ImGuiID GetID(const char* str_id_begin, const char* str_id_end); + IMGUI_API ImGuiID GetID(ImStrv str_id); // calculate unique ID (hash of whole ID stack + given parameter). e.g. if you want to query into ImGuiStorage yourself IMGUI_API ImGuiID GetID(const void* ptr_id); IMGUI_API ImGuiID GetID(int int_id); // Widgets: Text // - Note that all functions taking format strings in the API may be passed ("%s", text) or ("%.*s", text_len, text): which will automatically bypass the formatter. - IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // raw text without formatting. Practically equivalent to 'Text("%s", text)' but doesn't require null terminated string if 'text_end' is specified. + IMGUI_API void TextUnformatted(ImStrv text); // raw text without formatting. Practically equivalent to 'Text("%s", text)' but doesn't require null terminated string if 'text_end' is specified. IMGUI_API void Text(const char* fmt, ...) IM_FMTARGS(1); // formatted text IMGUI_API void TextV(const char* fmt, va_list args) IM_FMTLIST(1); IMGUI_API void TextColored(const ImVec4& col, const char* fmt, ...) IM_FMTARGS(2); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor(); @@ -634,28 +656,28 @@ namespace ImGui IMGUI_API void TextDisabledV(const char* fmt, va_list args) IM_FMTLIST(1); IMGUI_API void TextWrapped(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushTextWrapPos(0.0f); Text(fmt, ...); PopTextWrapPos();. Note that this won't work on an auto-resizing window if there's no other widgets to extend the window width, yoy may need to set a size using SetNextWindowSize(). IMGUI_API void TextWrappedV(const char* fmt, va_list args) IM_FMTLIST(1); - IMGUI_API void LabelText(const char* label, const char* fmt, ...) IM_FMTARGS(2); // display text+label aligned the same way as value+label widgets - IMGUI_API void LabelTextV(const char* label, const char* fmt, va_list args) IM_FMTLIST(2); + IMGUI_API void LabelText(ImStrv label, const char* fmt, ...) IM_FMTARGS(2); // display text+label aligned the same way as value+label widgets + IMGUI_API void LabelTextV(ImStrv label, const char* fmt, va_list args) IM_FMTLIST(2); IMGUI_API void BulletText(const char* fmt, ...) IM_FMTARGS(1); // shortcut for Bullet()+Text() IMGUI_API void BulletTextV(const char* fmt, va_list args) IM_FMTLIST(1); - IMGUI_API void SeparatorText(const char* label); // currently: formatted text with a horizontal line + IMGUI_API void SeparatorText(ImStrv label); // currently: formatted text with a horizontal line // Widgets: Main // - Most widgets return true when the value has been changed or when pressed/selected // - You may also use one of the many IsItemXXX functions (e.g. IsItemActive, IsItemHovered, etc.) to query widget state. - IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0, 0)); // button - IMGUI_API bool SmallButton(const char* label); // button with (FramePadding.y == 0) to easily embed within text - IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size, ImGuiButtonFlags flags = 0); // flexible button behavior without the visuals, frequently useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.) - IMGUI_API bool ArrowButton(const char* str_id, ImGuiDir dir); // square button with an arrow shape - IMGUI_API bool Checkbox(const char* label, bool* v); - IMGUI_API bool CheckboxFlags(const char* label, int* flags, int flags_value); - IMGUI_API bool CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value); - IMGUI_API bool RadioButton(const char* label, bool active); // use with e.g. if (RadioButton("one", my_value==1)) { my_value = 1; } - IMGUI_API bool RadioButton(const char* label, int* v, int v_button); // shortcut to handle the above pattern when value is an integer - IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-FLT_MIN, 0), const char* overlay = NULL); + IMGUI_API bool Button(ImStrv label, const ImVec2& size = ImVec2(0, 0)); // button + IMGUI_API bool SmallButton(ImStrv label); // button with (FramePadding.y == 0) to easily embed within text + IMGUI_API bool InvisibleButton(ImStrv str_id, const ImVec2& size, ImGuiButtonFlags flags = 0); // flexible button behavior without the visuals, frequently useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.) + IMGUI_API bool ArrowButton(ImStrv str_id, ImGuiDir dir); // square button with an arrow shape + IMGUI_API bool Checkbox(ImStrv label, bool* v); + IMGUI_API bool CheckboxFlags(ImStrv label, int* flags, int flags_value); + IMGUI_API bool CheckboxFlags(ImStrv label, unsigned int* flags, unsigned int flags_value); + IMGUI_API bool RadioButton(ImStrv label, bool active); // use with e.g. if (RadioButton("one", my_value==1)) { my_value = 1; } + IMGUI_API bool RadioButton(ImStrv label, int* v, int v_button); // shortcut to handle the above pattern when value is an integer + IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-FLT_MIN, 0), ImStrv overlay = ImStrv()); IMGUI_API void Bullet(); // draw a small circle + keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses - IMGUI_API bool TextLink(const char* label); // hyperlink text button, return true when clicked - IMGUI_API bool TextLinkOpenURL(const char* label, const char* url = NULL); // hyperlink text button, automatically open file/url when clicked + IMGUI_API bool TextLink(ImStrv label); // hyperlink text button, return true when clicked + IMGUI_API bool TextLinkOpenURL(ImStrv label, ImStrv url = ImStrv()); // hyperlink text button, automatically open file/url when clicked // Widgets: Images // - Read about ImTextureID/ImTextureRef here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples @@ -665,16 +687,16 @@ namespace ImGui // - An obsolete version of Image(), before 1.91.9 (March 2025), had a 'tint_col' parameter which is now supported by the ImageWithBg() function. IMGUI_API void Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1)); IMGUI_API void ImageWithBg(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)); - IMGUI_API bool ImageButton(const char* str_id, ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)); + IMGUI_API bool ImageButton(ImStrv str_id, ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)); // Widgets: Combo Box (Dropdown) // - The BeginCombo()/EndCombo() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() items. // - The old Combo() api are helpers over BeginCombo()/EndCombo() which are kept available for convenience purpose. This is analogous to how ListBox are created. - IMGUI_API bool BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags = 0); + IMGUI_API bool BeginCombo(ImStrv label, ImStrv preview_value, ImGuiComboFlags flags = 0); IMGUI_API void EndCombo(); // only call EndCombo() if BeginCombo() returns true! - IMGUI_API bool Combo(const char* label, int* current_item, const char* const items[], int items_count, int popup_max_height_in_items = -1); - IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int popup_max_height_in_items = -1); // Separate items with \0 within a string, end item-list with \0\0. e.g. "One\0Two\0Three\0" - IMGUI_API bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), void* user_data, int items_count, int popup_max_height_in_items = -1); + IMGUI_API bool Combo(ImStrv label, int* current_item, const char* const items[], int items_count, int popup_max_height_in_items = -1); + IMGUI_API bool Combo(ImStrv label, int* current_item, ImStrv (*getter)(void* user_data, int idx), void* user_data, int items_count, int popup_max_height_in_items = -1); + IMGUI_API bool Combo(ImStrv label, int* current_item, const char* items_separated_by_zeros, int popup_max_height_in_items = -1); // Separate items with \0 within a string, end item-list with \0\0. e.g. "One\0Two\0Three\0" // Widgets: Drag Sliders // - Ctrl+Click on any drag box to turn them into an input box. Manually input values aren't clamped by default and can go off-bounds. Use ImGuiSliderFlags_AlwaysClamp to always clamp. @@ -688,18 +710,18 @@ namespace ImGui // - We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them. // - Legacy: Pre-1.78 there are DragXXX() function signatures that take a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument. // If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361 - IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); // If v_min >= v_max we have no bound - IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); - IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); - IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); - IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, ImGuiSliderFlags flags = 0); - IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); // If v_min >= v_max we have no bound - IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); - IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); - IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); - IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL, ImGuiSliderFlags flags = 0); - IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed = 1.0f, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiSliderFlags flags = 0); - IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed = 1.0f, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool DragFloat(ImStrv label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); // If v_min >= v_max we have no bound + IMGUI_API bool DragFloat2(ImStrv label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragFloat3(ImStrv label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragFloat4(ImStrv label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragFloatRange2(ImStrv label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool DragInt(ImStrv label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); // If v_min >= v_max we have no bound + IMGUI_API bool DragInt2(ImStrv label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragInt3(ImStrv label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragInt4(ImStrv label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragIntRange2(ImStrv label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool DragScalar(ImStrv label, ImGuiDataType data_type, void* p_data, float v_speed = 1.0f, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool DragScalarN(ImStrv label, ImGuiDataType data_type, void* p_data, int components, float v_speed = 1.0f, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiSliderFlags flags = 0); // Widgets: Regular Sliders // - Ctrl+Click on any slider to turn them into an input box. Manually input values aren't clamped by default and can go off-bounds. Use ImGuiSliderFlags_AlwaysClamp to always clamp. @@ -707,75 +729,76 @@ namespace ImGui // - Format string may also be set to NULL or use the default format ("%f" or "%d"). // - Legacy: Pre-1.78 there are SliderXXX() function signatures that take a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument. // If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361 - IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. - IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); - IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); - IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); - IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f, const char* format = "%.0f deg", ImGuiSliderFlags flags = 0); - IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); - IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); - IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); - IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); - IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); - IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); - IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); - IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); - IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderFloat(ImStrv label, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. + IMGUI_API bool SliderFloat2(ImStrv label, float v[2], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderFloat3(ImStrv label, float v[3], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderFloat4(ImStrv label, float v[4], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderAngle(ImStrv label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f, const char* format = "%.0f deg", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt(ImStrv label, int* v, int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt2(ImStrv label, int v[2], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt3(ImStrv label, int v[3], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt4(ImStrv label, int v[4], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderScalar(ImStrv label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderScalarN(ImStrv label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool VSliderFloat(ImStrv label, const ImVec2& size, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool VSliderInt(ImStrv label, const ImVec2& size, int* v, int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool VSliderScalar(ImStrv label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); // Widgets: Input with Keyboard // - If you want to use InputText() with std::string or any custom dynamic string type, use the wrapper in misc/cpp/imgui_stdlib.h/.cpp! // - Most of the ImGuiInputTextFlags flags are only useful for InputText() and not for InputFloatX, InputIntX, InputDouble etc. - IMGUI_API bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); - IMGUI_API bool InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); - IMGUI_API bool InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); - IMGUI_API bool InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, const char* format = "%.3f", ImGuiInputTextFlags flags = 0); - IMGUI_API bool InputFloat2(const char* label, float v[2], const char* format = "%.3f", ImGuiInputTextFlags flags = 0); - IMGUI_API bool InputFloat3(const char* label, float v[3], const char* format = "%.3f", ImGuiInputTextFlags flags = 0); - IMGUI_API bool InputFloat4(const char* label, float v[4], const char* format = "%.3f", ImGuiInputTextFlags flags = 0); - IMGUI_API bool InputInt(const char* label, int* v, int step = 1, int step_fast = 100, ImGuiInputTextFlags flags = 0); - IMGUI_API bool InputInt2(const char* label, int v[2], ImGuiInputTextFlags flags = 0); - IMGUI_API bool InputInt3(const char* label, int v[3], ImGuiInputTextFlags flags = 0); - IMGUI_API bool InputInt4(const char* label, int v[4], ImGuiInputTextFlags flags = 0); - IMGUI_API bool InputDouble(const char* label, double* v, double step = 0.0, double step_fast = 0.0, const char* format = "%.6f", ImGuiInputTextFlags flags = 0); - IMGUI_API bool InputScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_step = NULL, const void* p_step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0); - IMGUI_API bool InputScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_step = NULL, const void* p_step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0); + // - Format parameter is limited to 63 bytes. + IMGUI_API bool InputText(ImStrv label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputTextMultiline(ImStrv label, char* buf, size_t buf_size, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputTextWithHint(ImStrv label, ImStrv hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputFloat(ImStrv label, float* v, float step = 0.0f, float step_fast = 0.0f, const char* format = "%.3f", ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputFloat2(ImStrv label, float v[2], const char* format = "%.3f", ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputFloat3(ImStrv label, float v[3], const char* format = "%.3f", ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputFloat4(ImStrv label, float v[4], const char* format = "%.3f", ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputInt(ImStrv label, int* v, int step = 1, int step_fast = 100, ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputInt2(ImStrv label, int v[2], ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputInt3(ImStrv label, int v[3], ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputInt4(ImStrv label, int v[4], ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputDouble(ImStrv label, double* v, double step = 0.0, double step_fast = 0.0, const char* format = "%.6f", ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputScalar(ImStrv label, ImGuiDataType data_type, void* p_data, const void* p_step = NULL, const void* p_step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputScalarN(ImStrv label, ImGuiDataType data_type, void* p_data, int components, const void* p_step = NULL, const void* p_step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0); // Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little color square that can be left-clicked to open a picker, and right-clicked to open an option menu.) // - Note that in C++ a 'float v[X]' function argument is the _same_ as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. // - You can pass the address of a first float element out of a contiguous structure, e.g. &myvector.x - IMGUI_API bool ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags = 0); - IMGUI_API bool ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0); - IMGUI_API bool ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags = 0); - IMGUI_API bool ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags = 0, const float* ref_col = NULL); - IMGUI_API bool ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // display a color square/button, hover for details, return true when pressed. + IMGUI_API bool ColorEdit3(ImStrv label, float col[3], ImGuiColorEditFlags flags = 0); + IMGUI_API bool ColorEdit4(ImStrv label, float col[4], ImGuiColorEditFlags flags = 0); + IMGUI_API bool ColorPicker3(ImStrv label, float col[3], ImGuiColorEditFlags flags = 0); + IMGUI_API bool ColorPicker4(ImStrv label, float col[4], ImGuiColorEditFlags flags = 0, const float* ref_col = NULL); + IMGUI_API bool ColorButton(ImStrv desc_id, const ImVec4& col, ImGuiColorEditFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // display a color square/button, hover for details, return true when pressed. // Widgets: Trees // - TreeNode functions return true when the node is open, in which case you need to also call TreePop() when you are finished displaying the tree node contents. - IMGUI_API bool TreeNode(const char* label); - IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...) IM_FMTARGS(2); // helper variation to easily decorrelate the id from the displayed string. Read the FAQ about why and how to use ID. to align arbitrary text at the same level as a TreeNode() you can use Bullet(). + IMGUI_API bool TreeNode(ImStrv label); + IMGUI_API bool TreeNode(ImStrv str_id, const char* fmt, ...) IM_FMTARGS(2); // helper variation to easily decorrelate the id from the displayed string. Read the FAQ about why and how to use ID. to align arbitrary text at the same level as a TreeNode() you can use Bullet(). IMGUI_API bool TreeNode(const void* ptr_id, const char* fmt, ...) IM_FMTARGS(2); // " - IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args) IM_FMTLIST(2); + IMGUI_API bool TreeNodeV(ImStrv str_id, const char* fmt, va_list args) IM_FMTLIST(2); IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args) IM_FMTLIST(2); - IMGUI_API bool TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags = 0); - IMGUI_API bool TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3); + IMGUI_API bool TreeNodeEx(ImStrv label, ImGuiTreeNodeFlags flags = 0); + IMGUI_API bool TreeNodeEx(ImStrv str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3); IMGUI_API bool TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3); - IMGUI_API bool TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3); + IMGUI_API bool TreeNodeExV(ImStrv str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3); IMGUI_API bool TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3); - IMGUI_API void TreePush(const char* str_id); // ~ Indent()+PushID(). Already called by TreeNode() when returning true, but you can call TreePush/TreePop yourself if desired. + IMGUI_API void TreePush(ImStrv str_id); // ~ Indent()+PushID(). Already called by TreeNode() when returning true, but you can call TreePush/TreePop yourself if desired. IMGUI_API void TreePush(const void* ptr_id); // " IMGUI_API void TreePop(); // ~ Unindent()+PopID() IMGUI_API float GetTreeNodeToLabelSpacing(); // horizontal distance preceding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode - IMGUI_API bool CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags = 0); // if returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop(). - IMGUI_API bool CollapsingHeader(const char* label, bool* p_visible, ImGuiTreeNodeFlags flags = 0); // when 'p_visible != NULL': if '*p_visible==true' display an additional small close button on upper right of the header which will set the bool to false when clicked, if '*p_visible==false' don't display the header. + IMGUI_API bool CollapsingHeader(ImStrv label, ImGuiTreeNodeFlags flags = 0); // if returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop(). + IMGUI_API bool CollapsingHeader(ImStrv label, bool* p_visible, ImGuiTreeNodeFlags flags = 0); // when 'p_visible != NULL': if '*p_visible==true' display an additional small close button on upper right of the header which will set the bool to false when clicked, if '*p_visible==false' don't display the header. IMGUI_API void SetNextItemOpen(bool is_open, ImGuiCond cond = 0); // set next TreeNode/CollapsingHeader open state. IMGUI_API void SetNextItemStorageID(ImGuiID storage_id); // set id to use for open/close storage (default to same as item id). - IMGUI_API bool TreeNodeGetOpen(ImGuiID storage_id, ImGuiTreeNodeFlags flags = 0); // retrieve tree node open/close state. + IMGUI_API bool TreeNodeGetOpen(ImGuiID storage_id); // retrieve tree node open/close state. // Widgets: Selectables // - A selectable highlights when hovered, and can display another color when selected. // - Neighbors selectable extend their highlight bounds in order to leave no gap between them. This is so a series of selected Selectable appear contiguous. - IMGUI_API bool Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // "bool selected" carry the selection state (read-only). Selectable() is clicked is returns true so you can modify your selection state. size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height - IMGUI_API bool Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // "bool* p_selected" point to the selection state (read-write), as a convenient helper. + IMGUI_API bool Selectable(ImStrv label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // "bool selected" carry the selection state (read-only). Selectable() is clicked is returns true so you can modify your selection state. size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height + IMGUI_API bool Selectable(ImStrv label, bool* p_selected, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // "bool* p_selected" point to the selection state (read-write), as a convenient helper. // Multi-selection system for Selectable(), Checkbox(), TreeNode() functions [BETA] // - This enables standard multi-selection/range-selection idioms (Ctrl+Mouse/Keyboard, Shift+Mouse/Keyboard, etc.) in a way that also allow a clipper to be used. @@ -796,24 +819,24 @@ namespace ImGui // - The simplified/old ListBox() api are helpers over BeginListBox()/EndListBox() which are kept available for convenience purpose. This is analogous to how Combos are created. // - Choose frame width: size.x > 0.0f: custom / size.x < 0.0f or -FLT_MIN: right-align / size.x = 0.0f (default): use current ItemWidth // - Choose frame height: size.y > 0.0f: custom / size.y < 0.0f or -FLT_MIN: bottom-align / size.y = 0.0f (default): arbitrary default height which can fit ~7 items - IMGUI_API bool BeginListBox(const char* label, const ImVec2& size = ImVec2(0, 0)); // open a framed scrolling region + IMGUI_API bool BeginListBox(ImStrv label, const ImVec2& size = ImVec2(0, 0)); // open a framed scrolling region IMGUI_API void EndListBox(); // only call EndListBox() if BeginListBox() returned true! - IMGUI_API bool ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items = -1); - IMGUI_API bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), void* user_data, int items_count, int height_in_items = -1); + IMGUI_API bool ListBox(ImStrv label, int* current_item, const char* const items[], int items_count, int height_in_items = -1); + IMGUI_API bool ListBox(ImStrv label, int* current_item, ImStrv (*getter)(void* user_data, int idx), void* user_data, int items_count, int height_in_items = -1); // Widgets: Data Plotting // - Consider using ImPlot (https://github.com/epezent/implot) which is much better! - IMGUI_API void PlotLines(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float)); - IMGUI_API void PlotLines(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0)); - IMGUI_API void PlotHistogram(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float)); - IMGUI_API void PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0)); + IMGUI_API void PlotLines(ImStrv label, const float* values, int values_count, int values_offset = 0, ImStrv overlay_text = ImStrv(), float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float)); + IMGUI_API void PlotLines(ImStrv label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, ImStrv overlay_text = ImStrv(), float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0)); + IMGUI_API void PlotHistogram(ImStrv label, const float* values, int values_count, int values_offset = 0, ImStrv overlay_text = ImStrv(), float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float)); + IMGUI_API void PlotHistogram(ImStrv label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, ImStrv overlay_text = ImStrv(), float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0)); // Widgets: Value() Helpers. // - Those are merely shortcut to calling Text() with a format string. Output single value in "name: value" format (tip: freely declare more in your code to handle your types. you can add functions to the ImGui namespace) - IMGUI_API void Value(const char* prefix, bool b); - IMGUI_API void Value(const char* prefix, int v); - IMGUI_API void Value(const char* prefix, unsigned int v); - IMGUI_API void Value(const char* prefix, float v, const char* float_format = NULL); + IMGUI_API void Value(ImStrv prefix, bool b); + IMGUI_API void Value(ImStrv prefix, int v); + IMGUI_API void Value(ImStrv prefix, unsigned int v); + IMGUI_API void Value(ImStrv prefix, float v, ImStrv float_format = ImStrv()); // Widgets: Menus // - Use BeginMenuBar() on a window ImGuiWindowFlags_MenuBar to append to its menu bar. @@ -824,10 +847,10 @@ namespace ImGui IMGUI_API void EndMenuBar(); // only call EndMenuBar() if BeginMenuBar() returns true! IMGUI_API bool BeginMainMenuBar(); // create and append to a full screen menu-bar. IMGUI_API void EndMainMenuBar(); // only call EndMainMenuBar() if BeginMainMenuBar() returns true! - IMGUI_API bool BeginMenu(const char* label, bool enabled = true); // create a sub-menu entry. only call EndMenu() if this returns true! + IMGUI_API bool BeginMenu(ImStrv label, bool enabled = true); // create a sub-menu entry. only call EndMenu() if this returns true! IMGUI_API void EndMenu(); // only call EndMenu() if BeginMenu() returns true! - IMGUI_API bool MenuItem(const char* label, const char* shortcut = NULL, bool selected = false, bool enabled = true); // return true when activated. - IMGUI_API bool MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled = true); // return true when activated + toggle (*p_selected) if p_selected != NULL + IMGUI_API bool MenuItem(ImStrv label, ImStrv shortcut = ImStrv(), bool selected = false, bool enabled = true); // return true when activated. + IMGUI_API bool MenuItem(ImStrv label, ImStrv shortcut, bool* p_selected, bool enabled = true); // return true when activated + toggle (*p_selected) if p_selected != NULL // Tooltips // - Tooltips are windows following the mouse. They do not take focus away. @@ -856,8 +879,8 @@ namespace ImGui // This is sometimes leading to confusing mistakes. May rework this in the future. // - BeginPopup(): query popup state, if open start appending into the window. Call EndPopup() afterwards if returned true. ImGuiWindowFlags are forwarded to the window. // - BeginPopupModal(): block every interaction behind the window, cannot be closed by user, add a dimming background, has a title bar. - IMGUI_API bool BeginPopup(const char* str_id, ImGuiWindowFlags flags = 0); // return true if the popup is open, and you can start outputting to it. - IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // return true if the modal is open, and you can start outputting to it. + IMGUI_API bool BeginPopup(ImStrv str_id, ImGuiWindowFlags flags = 0); // return true if the popup is open, and you can start outputting to it. + IMGUI_API bool BeginPopupModal(ImStrv name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // return true if the modal is open, and you can start outputting to it. IMGUI_API void EndPopup(); // only call EndPopup() if BeginPopupXXX() returns true! // Popups: open/close functions @@ -869,9 +892,9 @@ namespace ImGui // - CloseCurrentPopup() is called by default by Selectable()/MenuItem() when activated (FIXME: need some options). // - Use ImGuiPopupFlags_NoOpenOverExistingPopup to avoid opening a popup if there's already one at the same level. This is equivalent to e.g. testing for !IsAnyPopupOpen() prior to OpenPopup(). // - Use IsWindowAppearing() after BeginPopup() to tell if a window just opened. - IMGUI_API bool OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags = 0); // call to mark popup as open (don't call every frame!). + IMGUI_API bool OpenPopup(ImStrv str_id, ImGuiPopupFlags popup_flags = 0); // call to mark popup as open (don't call every frame!). IMGUI_API bool OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags = 0); // id overload to facilitate calling from nested stacks - IMGUI_API bool OpenPopupOnItemClick(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 0); // helper to open popup when clicked on last item. Default to ImGuiPopupFlags_MouseButtonRight == 1. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors) + IMGUI_API bool OpenPopupOnItemClick(ImStrv str_id = ImStrv(), ImGuiPopupFlags popup_flags = 0); // helper to open popup when clicked on last item. Default to ImGuiPopupFlags_MouseButtonRight == 1. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors) IMGUI_API void CloseCurrentPopup(); // manually close the popup we have begin-ed into. // Popups: Open+Begin popup combined functions helpers to create context menus. @@ -883,15 +906,15 @@ namespace ImGui // - After: The default = 0 means ImGuiPopupFlags_MouseButtonRight. Explicitly passing a literal 1 also means ImGuiPopupFlags_MouseButtonRight (if legacy behavior are enabled) or will assert (if legacy behavior are disabled). // - TL;DR: if you don't want to use right mouse button for popups, always specify it explicitly using a named ImGuiPopupFlags_MouseButtonXXXX value. // - Read "API BREAKING CHANGES" 2026/01/07 (1.92.6) entry in imgui.cpp or GitHub topic #9157 for all details. - IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 0); // open+begin popup when clicked on last item. Use str_id==NULL to associate the popup to previous item. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp! - IMGUI_API bool BeginPopupContextWindow(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 0);// open+begin popup when clicked on current window. - IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 0); // open+begin popup when clicked in void (where there are no windows). + IMGUI_API bool BeginPopupContextItem(ImStrv str_id = ImStrv(), ImGuiPopupFlags popup_flags = 0); // open+begin popup when clicked on last item. Use str_id==NULL to associate the popup to previous item. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp! + IMGUI_API bool BeginPopupContextWindow(ImStrv str_id = ImStrv(), ImGuiPopupFlags popup_flags = 0); // open+begin popup when clicked on current window. + IMGUI_API bool BeginPopupContextVoid(ImStrv str_id = ImStrv(), ImGuiPopupFlags popup_flags = 0); // open+begin popup when clicked in void (where there are no windows). // Popups: query functions // - IsPopupOpen(): return true if the popup is open at the current BeginPopup() level of the popup stack. // - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId: return true if any popup is open at the current BeginPopup() level of the popup stack. // - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId + ImGuiPopupFlags_AnyPopupLevel: return true if any popup is open. - IMGUI_API bool IsPopupOpen(const char* str_id, ImGuiPopupFlags flags = 0); // return true if the popup is open. + IMGUI_API bool IsPopupOpen(ImStrv str_id, ImGuiPopupFlags flags = 0); // return true if the popup is open. // Tables // - Full-featured replacement for old Columns API. @@ -914,7 +937,7 @@ namespace ImGui // - TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK: TableNextColumn() automatically gets to next row! // - TableNextRow() -> Text("Hello 0") // Not OK! Missing TableSetColumnIndex() or TableNextColumn()! Text will not appear! // - 5. Call EndTable() - IMGUI_API bool BeginTable(const char* str_id, int columns, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0.0f, 0.0f), float inner_width = 0.0f); + IMGUI_API bool BeginTable(ImStrv str_id, int columns, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0.0f, 0.0f), float inner_width = 0.0f); IMGUI_API void EndTable(); // only call EndTable() if BeginTable() returns true! IMGUI_API void TableNextRow(ImGuiTableRowFlags row_flags = 0, float min_row_height = 0.0f); // append into the first cell of a new row. 'min_row_height' include the minimum top and bottom padding aka CellPadding.y * 2.0f. IMGUI_API bool TableNextColumn(); // append into the next column (or first column of next row if currently in last column). Return true when column is visible. @@ -929,9 +952,9 @@ namespace ImGui // - You may manually submit headers using TableNextRow() + TableHeader() calls, but this is only useful in // some advanced use cases (e.g. adding custom widgets in header row). // - Use TableSetupScrollFreeze() to lock columns/rows so they stay visible when scrolled. When freezing columns you would usually also use ImGuiTableColumnFlags_NoHide on them. - IMGUI_API void TableSetupColumn(const char* label, ImGuiTableColumnFlags flags = 0, float init_width_or_weight = 0.0f, ImGuiID user_data = 0); + IMGUI_API void TableSetupColumn(ImStrv label, ImGuiTableColumnFlags flags = 0, float init_width_or_weight = 0.0f, ImGuiID user_data = 0); IMGUI_API void TableSetupScrollFreeze(int cols, int rows); // lock columns/rows so they stay visible when scrolled. - IMGUI_API void TableHeader(const char* label); // submit one header cell manually (rarely used) + IMGUI_API void TableHeader(ImStrv label); // submit one header cell manually (rarely used) IMGUI_API void TableHeadersRow(); // submit a row with headers cells based on data provided to TableSetupColumn() + submit context menu IMGUI_API void TableAngledHeadersRow(); // submit a row with angled headers for every column with the ImGuiTableColumnFlags_AngledHeader flag. MUST BE FIRST ROW. @@ -953,7 +976,7 @@ namespace ImGui // Legacy Columns API (prefer using Tables!) // - You can also use SameLine(pos_x) to mimic simplified columns. - IMGUI_API void Columns(int count = 1, const char* id = NULL, bool borders = true); + IMGUI_API void Columns(int count = 1, ImStrv id = ImStrv(), bool borders = true); IMGUI_API void NextColumn(); // next column, defaults to current row or next row if the current row is finished IMGUI_API int GetColumnIndex(); // get current column index IMGUI_API float GetColumnWidth(int column_index = -1); // get column width (in pixels). pass -1 to use current column @@ -964,17 +987,17 @@ namespace ImGui // Tab Bars, Tabs // - Note: Tabs are automatically created by the docking system (when in 'docking' branch). Use this to create tab bars/tabs yourself. - IMGUI_API bool BeginTabBar(const char* str_id, ImGuiTabBarFlags flags = 0); // create and append into a TabBar + IMGUI_API bool BeginTabBar(ImStrv str_id, ImGuiTabBarFlags flags = 0); // create and append into a TabBar IMGUI_API void EndTabBar(); // only call EndTabBar() if BeginTabBar() returns true! - IMGUI_API bool BeginTabItem(const char* label, bool* p_open = NULL, ImGuiTabItemFlags flags = 0); // create a Tab. Returns true if the Tab is selected. + IMGUI_API bool BeginTabItem(ImStrv label, bool* p_open = NULL, ImGuiTabItemFlags flags = 0);// create a Tab. Returns true if the Tab is selected. IMGUI_API void EndTabItem(); // only call EndTabItem() if BeginTabItem() returns true! - IMGUI_API bool TabItemButton(const char* label, ImGuiTabItemFlags flags = 0); // create a Tab behaving like a button. return true when clicked. cannot be selected in the tab bar. - IMGUI_API void SetTabItemClosed(const char* tab_or_docked_window_label); // notify TabBar or Docking system of a closed tab/window ahead (useful to reduce visual flicker on reorderable tab bars). For tab-bar: call after BeginTabBar() and before Tab submissions. Otherwise call with a window name. + IMGUI_API bool TabItemButton(ImStrv label, ImGuiTabItemFlags flags = 0); // create a Tab behaving like a button. return true when clicked. cannot be selected in the tab bar. + IMGUI_API void SetTabItemClosed(ImStrv tab_or_docked_window_label); // notify TabBar or Docking system of a closed tab/window ahead (useful to reduce visual flicker on reorderable tab bars). For tab-bar: call after BeginTabBar() and before Tab submissions. Otherwise call with a window name. // Logging/Capture // - All text output from the interface can be captured into tty/file/clipboard. By default, tree nodes are automatically opened during logging. IMGUI_API void LogToTTY(int auto_open_depth = -1); // start logging to tty (stdout) - IMGUI_API void LogToFile(int auto_open_depth = -1, const char* filename = NULL); // start logging to file + IMGUI_API void LogToFile(int auto_open_depth = -1, ImStrv filename = ImStrv()); // start logging to file IMGUI_API void LogToClipboard(int auto_open_depth = -1); // start logging to OS clipboard IMGUI_API void LogFinish(); // stop logging (close file, etc.) IMGUI_API void LogButtons(); // helper to display buttons for logging to tty/file/clipboard @@ -987,10 +1010,10 @@ namespace ImGui // - If you stop calling BeginDragDropSource() the payload is preserved however it won't have a preview tooltip (we currently display a fallback "..." tooltip, see #1725) // - An item can be both drag source and drop target. IMGUI_API bool BeginDragDropSource(ImGuiDragDropFlags flags = 0); // call after submitting an item which may be dragged. when this return true, you can call SetDragDropPayload() + EndDragDropSource() - IMGUI_API bool SetDragDropPayload(const char* type, const void* data, size_t sz, ImGuiCond cond = 0); // type is a user defined string of maximum 32 characters. Strings starting with '_' are reserved for dear imgui internal types. Data is copied and held by imgui. Return true when payload has been accepted. + IMGUI_API bool SetDragDropPayload(ImStrv type, const void* data, size_t sz, ImGuiCond cond = 0); // type is a user defined string of maximum 32 characters. Strings starting with '_' are reserved for dear imgui internal types. Data is copied and held by imgui. Return true when payload has been accepted. IMGUI_API void EndDragDropSource(); // only call EndDragDropSource() if BeginDragDropSource() returns true! IMGUI_API bool BeginDragDropTarget(); // call after submitting an item that may receive a payload. If this returns true, you can call AcceptDragDropPayload() + EndDragDropTarget() - IMGUI_API const ImGuiPayload* AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags = 0); // accept contents of a given type. If ImGuiDragDropFlags_AcceptBeforeDelivery is set you can peek into the payload before the mouse button is released. + IMGUI_API const ImGuiPayload* AcceptDragDropPayload(ImStrv type, ImGuiDragDropFlags flags = 0); // accept contents of a given type. If ImGuiDragDropFlags_AcceptBeforeDelivery is set you can peek into the payload before the mouse button is released. IMGUI_API void EndDragDropTarget(); // only call EndDragDropTarget() if BeginDragDropTarget() returns true! IMGUI_API const ImGuiPayload* GetDragDropPayload(); // peek directly into the current payload from anywhere. returns NULL when drag and drop is finished or inactive. use ImGuiPayload::IsDataType() to test for the payload type. @@ -1061,7 +1084,7 @@ namespace ImGui IMGUI_API ImGuiStorage* GetStateStorage(); // Text Utilities - IMGUI_API ImVec2 CalcTextSize(const char* text, const char* text_end = NULL, bool hide_text_after_double_hash = false, float wrap_width = -1.0f); + IMGUI_API ImVec2 CalcTextSize(ImStrv text, bool hide_text_after_double_hash = false, float wrap_width = -1.0f); // Color Utilities IMGUI_API ImVec4 ColorConvertU32ToFloat4(ImU32 in); @@ -1138,25 +1161,25 @@ namespace ImGui // Clipboard Utilities // - Also see the LogToClipboard() function to capture GUI into clipboard, or easily output text data to the clipboard. IMGUI_API const char* GetClipboardText(); - IMGUI_API void SetClipboardText(const char* text); + IMGUI_API void SetClipboardText(ImStrv text); // Settings/.Ini Utilities // - The disk functions are automatically called if io.IniFilename != NULL (default is "imgui.ini"). // - Set io.IniFilename to NULL to load/save manually. Read io.WantSaveIniSettings description about handling .ini saving manually. // - Important: default value "imgui.ini" is relative to current working dir! Most apps will want to lock this to an absolute path (e.g. same path as executables). - IMGUI_API void LoadIniSettingsFromDisk(const char* ini_filename); // call after CreateContext() and before the first call to NewFrame(). NewFrame() automatically calls LoadIniSettingsFromDisk(io.IniFilename). - IMGUI_API void LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size=0); // call after CreateContext() and before the first call to NewFrame() to provide .ini data from your own data source. - IMGUI_API void SaveIniSettingsToDisk(const char* ini_filename); // this is automatically called (if io.IniFilename is not empty) a few seconds after any modification that should be reflected in the .ini file (and also by DestroyContext). + IMGUI_API void LoadIniSettingsFromDisk(ImStrv ini_filename); // call after CreateContext() and before the first call to NewFrame(). NewFrame() automatically calls LoadIniSettingsFromDisk(io.IniFilename). + IMGUI_API void LoadIniSettingsFromMemory(ImStrv ini_data); // call after CreateContext() and before the first call to NewFrame() to provide .ini data from your own data source. + IMGUI_API void SaveIniSettingsToDisk(ImStrv ini_filename); // this is automatically called (if io.IniFilename is not empty) a few seconds after any modification that should be reflected in the .ini file (and also by DestroyContext). IMGUI_API const char* SaveIniSettingsToMemory(size_t* out_ini_size = NULL); // return a zero-terminated string with the .ini data which you can save by your own mean. call when io.WantSaveIniSettings is set, then save data by your own mean and clear io.WantSaveIniSettings. // Debug Utilities // - Your main debugging friend is the ShowMetricsWindow() function. // - Interactive tools are all accessible from the 'Dear ImGui Demo->Tools' menu. // - Read https://github.com/ocornut/imgui/wiki/Debug-Tools for a description of all available debug tools. - IMGUI_API void DebugTextEncoding(const char* text); + IMGUI_API void DebugTextEncoding(ImStrv text); IMGUI_API void DebugFlashStyleColor(ImGuiCol idx); IMGUI_API void DebugStartItemPicker(); - IMGUI_API bool DebugCheckVersionAndDataLayout(const char* version_str, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_drawvert, size_t sz_drawidx); // This is called by IMGUI_CHECKVERSION() macro. + IMGUI_API bool DebugCheckVersionAndDataLayout(ImStrv version_str, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_drawvert, size_t sz_drawidx); // This is called by IMGUI_CHECKVERSION() macro. #ifndef IMGUI_DISABLE_DEBUG_TOOLS IMGUI_API void DebugLog(const char* fmt, ...) IM_FMTARGS(1); // Call via IMGUI_DEBUG_LOG() for maximum stripping in caller code! IMGUI_API void DebugLogV(const char* fmt, va_list args) IM_FMTLIST(1); @@ -1173,6 +1196,27 @@ namespace ImGui } // namespace ImGui +namespace ImGui +{ + // FIXME-IMSTR + // Functions which could accept both 'const char*' and 'const void*' now have an ambiguity between 'ImStrv' and 'const void*' when passed literals. + // Binding generators would likely need to ignore those. + // See https://github.com/ocornut/imgui/issues/5079 +IM_MSVC_RUNTIME_CHECKS_OFF + inline void PushID(const char* str_id) { PushID(ImStrv(str_id)); } + inline ImGuiID GetID(const char* str_id) { return GetID(ImStrv(str_id)); } + inline IM_FMTARGS(2) bool TreeNode(const char* str_id, const char* fmt, ...) { va_list args; va_start(args, fmt); bool ret = TreeNodeV(ImStrv(str_id), fmt, args); va_end(args); return ret; } + inline IM_FMTLIST(2) bool TreeNodeV(const char* str_id, const char* fmt, va_list args) { return TreeNodeV(ImStrv(str_id), fmt, args); } + inline IM_FMTARGS(3) bool TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) { va_list args; va_start(args, fmt); bool ret = TreeNodeExV(ImStrv(str_id), flags, fmt, args); va_end(args); return ret; } + inline IM_FMTLIST(3) bool TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) { return TreeNodeEx(ImStrv(str_id), flags, fmt, args); } + inline void TreePush(const char* str_id) { TreePush(ImStrv(str_id)); } +IM_MSVC_RUNTIME_CHECKS_RESTORE + + // Detect misuses (#9321) + // FIXME-IMSTR: Validate that syntax is ok for our minimum target. + ImVec2 CalcTextSize(ImStrv, const char*, bool hide_text_after_double_hash = false, float wrap_width = -1.0f) = delete; +} + //----------------------------------------------------------------------------- // [SECTION] Flags & Enumerations //----------------------------------------------------------------------------- @@ -2396,10 +2440,6 @@ struct ImGuiStyle ImVec2 DisplaySafeAreaPadding; // Apply to every windows, menus, popups, tooltips: amount where we avoid displaying contents. Adjust if you cannot see the edges of your screen (e.g. on a TV where scaling has not been configured). float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). We apply per-monitor DPI scaling over this scale. May be removed later. - // Symbols - ImVec2 SymbolArrowSizeFactor; // Width/height factor of arrows (0.0f..1.0f). - float SymbolArrowThicknessFactor; // Thickness factor of arrows (0.0f..0.5f). 0.0f=Fill. >0.0f=Stroke. - // Rendering & Tessellation bool AntiAliasedLines; // Enable anti-aliased lines/borders. Used at the beginning of the frame to set ImDrawFlags_AALines in all draw-lists. bool AntiAliasedLineEnds; // Enable anti-aliased lines/borders ends. Nicer for thick lines but more expensive. Used at the beginning of the frame to set ImDrawFlags_AALineEnds in all draw-lists. @@ -2737,11 +2777,14 @@ struct ImGuiInputTextCallbackData // Use those function to benefit from the CallbackResize behaviors. Calling those function reset the selection. IMGUI_API ImGuiInputTextCallbackData(); IMGUI_API void DeleteChars(int pos, int bytes_count); - IMGUI_API void InsertChars(int pos, const char* text, const char* text_end = NULL); - void SelectAll() { SelectionStart = 0; CursorPos = SelectionEnd = BufTextLen; } + IMGUI_API void InsertChars(int pos, ImStrv text); + void SelectAll() { SelectionStart = 0; SelectionEnd = BufTextLen; } void SetSelection(int s, int e) { IM_ASSERT(s >= 0 && s <= BufTextLen); IM_ASSERT(e >= 0 && e <= BufTextLen); SelectionStart = s; CursorPos = SelectionEnd = e; } void ClearSelection() { SelectionStart = SelectionEnd = BufTextLen; } bool HasSelection() const { return SelectionStart != SelectionEnd; } +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + inline void InsertChars(int pos, const char* text, const char* text_end) { InsertChars(pos, ImStrv(text, text_end)); } +#endif }; // Resizing callback data to apply custom constraint. As enabled by SetNextWindowSizeConstraints(). Callback is called during the next Begin(). @@ -2771,7 +2814,7 @@ struct ImGuiPayload ImGuiPayload() { Clear(); } void Clear() { SourceId = SourceParentId = 0; Data = NULL; DataSize = 0; memset(DataType, 0, sizeof(DataType)); DataFrameCount = -1; Preview = Delivery = false; } - bool IsDataType(const char* type) const { return DataFrameCount != -1 && strcmp(type, DataType) == 0; } + bool IsDataType(ImStrv type) const { size_t len = (size_t)type.length(); return DataFrameCount != -1 && memcmp(DataType, type.Begin, len) == 0 && DataType[len] == 0; } bool IsPreview() const { return Preview; } bool IsDelivery() const { return Delivery; } }; @@ -2801,17 +2844,19 @@ struct ImGuiOnceUponAFrame struct ImGuiTextFilterItem; struct ImGuiTextFilter { - IMGUI_API ImGuiTextFilter(const char* default_filter = ""); - IMGUI_API bool PassFilter(const char* text, const char* text_end = NULL) const; + // Functions + IMGUI_API ImGuiTextFilter(ImStrv default_filter = ""); + IMGUI_API bool PassFilter(ImStrv label) const; IMGUI_API void Build(); // Update internal data when filter changes inline void Clear() { InputBuf[0] = 0; Build(); } // Clear filter inline bool IsActive() const { return _Items.Size != 0; } // Useful if you need e.g. an alternative code-path when there are no filters // Helper to call InputText() + Build() when buffer is changed. - IMGUI_API bool Draw(const char* label = "Filter"); - IMGUI_API bool DrawWithHint(const char* label = "Filter", const char* hint = "incl -excl"); + IMGUI_API bool Draw(ImStrv label = "Filter"); + IMGUI_API bool DrawWithHint(ImStrv label = "Filter", ImStrv hint = "incl -excl"); #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - inline bool Draw(const char* label, float width) { if (width != 0.0f) ImGui::SetNextItemWidth(width); return Draw(label); } + inline bool Draw(ImStrv label, float width) { if (width != 0.0f) ImGui::SetNextItemWidth(width); return Draw(label); } + inline bool PassFilter(const char* text, const char* text_end = NULL) const { return PassFilter(ImStrv(text, text_end)); } #endif // Members @@ -2837,9 +2882,12 @@ struct ImGuiTextBuffer void resize(int size) { if (Buf.Size > size) Buf.Data[size] = 0; Buf.resize(size ? size + 1 : 0, 0); } // Similar to resize(0) on ImVector: empty string but don't free buffer. void reserve(int capacity) { Buf.reserve(capacity); } const char* c_str() const { return Buf.Data ? Buf.Data : EmptyString; } - IMGUI_API void append(const char* str, const char* str_end = NULL); + IMGUI_API void append(ImStrv str); IMGUI_API void appendf(const char* fmt, ...) IM_FMTARGS(2); IMGUI_API void appendfv(const char* fmt, va_list args) IM_FMTLIST(2); +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + inline void append(const char* str, const char* str_end) { append(ImStrv(str, str_end)); } +#endif }; // [Internal] Key+Value for ImGuiStorage @@ -3472,8 +3520,8 @@ struct ImDrawList IMGUI_API void AddNgonFilled(const ImVec2& center, float radius, ImU32 col, int num_segments); IMGUI_API void AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot = 0.0f, int num_segments = 0, float thickness = 1.0f, ImDrawFlags flags = 0); IMGUI_API void AddEllipseFilled(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot = 0.0f, int num_segments = 0); - IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL); - IMGUI_API void AddText(ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const ImVec4* cpu_fine_clip_rect = NULL); + IMGUI_API void AddText(const ImVec2& pos, ImU32 col, ImStrv text); + IMGUI_API void AddText(ImFont* font, float font_size, const ImVec2& pos, ImU32 col, ImStrv text, float wrap_width = 0.0f, const ImVec4* cpu_fine_clip_rect = NULL); IMGUI_API void AddBezierCubic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments = 0, ImDrawFlags flags = 0); // Cubic Bezier (4 control points) IMGUI_API void AddBezierQuadratic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness, int num_segments = 0, ImDrawFlags flags = 0); // Quadratic Bezier (3 control points) @@ -3484,6 +3532,11 @@ struct ImDrawList IMGUI_API void AddConvexPolyFilled(const ImVec2* points, int num_points, ImU32 col, ImDrawFlags flags = 0); IMGUI_API void AddConcavePolyFilled(const ImVec2* points, int num_points, ImU32 col); +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + inline void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end) { AddText(NULL, 0.0f, pos, col, ImStrv(text_begin, text_end)); } + inline void AddText(ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end, float wrap_width = 0.0f, const ImVec4* cpu_fine_clip_rect = NULL) { AddText(font, font_size, pos, col, ImStrv(text_begin, text_end), wrap_width, cpu_fine_clip_rect); } +#endif + // Image primitives // - Read FAQ to understand what ImTextureID/ImTextureRef are. // - "p_min" and "p_max" represent the upper-left and lower-right corners of the rectangle. @@ -3773,9 +3826,13 @@ struct ImFontGlyphRangesBuilder inline bool GetBit(size_t n) const { int off = (int)(n >> 5); ImU32 mask = 1u << (n & 31); return (UsedChars[off] & mask) != 0; } // Get bit n in the array inline void SetBit(size_t n) { int off = (int)(n >> 5); ImU32 mask = 1u << (n & 31); UsedChars[off] |= mask; } // Set bit n in the array inline void AddChar(ImWchar c) { SetBit(c); } // Add character - IMGUI_API void AddText(const char* text, const char* text_end = NULL); // Add string (each character of the UTF-8 string are added) + IMGUI_API void AddText(ImStrv text); // Add string (each character of the UTF-8 string are added) IMGUI_API void AddRanges(const ImWchar* ranges); // Add ranges, e.g. builder.AddRanges(ImFontAtlas::GetGlyphRangesDefault()) to force add all of ASCII/Latin+Ext IMGUI_API void BuildRanges(ImVector* out_ranges); // Output new ranges + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + inline void AddText(const char* text, const char* text_end = NULL) { AddText(ImStrv(text, text_end)); } +#endif }; // An opaque identifier to a rectangle in the atlas. -1 when invalid. @@ -3832,12 +3889,13 @@ struct ImFontAtlas IMGUI_API ImFont* AddFontDefault(const ImFontConfig* font_cfg = NULL); // Selects between AddFontDefaultVector() and AddFontDefaultBitmap(). IMGUI_API ImFont* AddFontDefaultVector(const ImFontConfig* font_cfg = NULL); // Embedded scalable font. Recommended at any higher size. IMGUI_API ImFont* AddFontDefaultBitmap(const ImFontConfig* font_cfg = NULL); // Embedded classic pixel-clean font. Recommended at Size 13px with no scaling. - IMGUI_API ImFont* AddFontFromFileTTF(const char* filename, float size_pixels = 0.0f, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); - IMGUI_API ImFont* AddFontFromMemoryTTF(void* font_data, int font_data_size, float size_pixels = 0.0f, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Note: Transfer ownership of 'ttf_data' to ImFontAtlas! Will be deleted after destruction of the atlas. Set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed. - IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_font_data, int compressed_font_data_size, float size_pixels = 0.0f, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data' still owned by caller. Compress with binary_to_compressed_c.cpp. - IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* compressed_font_data_base85, float size_pixels = 0.0f, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 parameter. + IMGUI_API ImFont* AddFontFromFileTTF(ImStrv filename, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); + IMGUI_API ImFont* AddFontFromMemoryTTF(void* font_data, int font_data_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Note: Transfer ownership of 'ttf_data' to ImFontAtlas! Will be deleted after destruction of the atlas. Set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed. + IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_font_data, int compressed_font_data_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data' still owned by caller. Compress with binary_to_compressed_c.cpp. + IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(ImStrv compressed_font_data_base85, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 parameter. IMGUI_API void RemoveFont(ImFont* font); // Remove a font IMGUI_API void CompactCache(); // Compact cached glyphs and texture. + IMGUI_API void SetFontLoader(const ImFontLoader* font_loader); // Change font loader at runtime. // Clearing the atlas/fonts has little use nowadays, unless you want to batch remove all fonts. @@ -3845,7 +3903,7 @@ struct ImFontAtlas // - As we are transitioning toward our new font system the semantic for those functions gets increasingly misleading and are often a source of issues. // TL;DR; most likely, don't use any of those functions. We expect to obsolete/rework them. IMGUI_API void Clear(); // Clear everything (fonts + textures). Don't call mid-frame! - IMGUI_API void ClearFonts(); // Clear input+output font data/glyphs. New fonts and textures will be recreated afterwards. + IMGUI_API void ClearFonts(); // Clear input+output font data/glyphs. You can call this mid-frame if you load new fonts afterwards! IMGUI_API void ClearInputData(); // [OBSOLETE] Clear input data (all ImFontConfig structures including sizes, TTF data, glyph ranges, etc.) = all the data used to build the texture and fonts. IMGUI_API void ClearTexData(); // [OBSOLETE] Clear CPU-side copy of the texture data. Saves RAM once the texture has been copied to graphics memory. @@ -4058,12 +4116,17 @@ struct ImFont // 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable. // 'wrap_width' enable automatic word-wrapping across multiple lines to fit into given width. 0.0f to disable. IMGUI_API ImFontBaked* GetFontBaked(float font_size, float density = -1.0f); // Get or create baked data for given size - IMGUI_API ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** out_remaining = NULL); - IMGUI_API const char* CalcWordWrapPosition(float size, const char* text, const char* text_end, float wrap_width); + IMGUI_API ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, ImStrv text, const char** remaining = NULL); // utf8 + IMGUI_API const char* CalcWordWrapPosition(float scale, ImStrv text, float wrap_width); IMGUI_API void RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, ImWchar c, const ImVec4* cpu_fine_clip = NULL); - IMGUI_API void RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, ImDrawTextFlags flags = 0); + IMGUI_API void RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, const ImVec4& clip_rect, ImStrv text, float wrap_width = 0.0f, ImDrawTextFlags flags = 0); + inline void RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, ImDrawTextFlags flags = 0) { RenderText(draw_list, size, pos, col, clip_rect, ImStrv(text_begin, text_end), wrap_width, flags); } + #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - inline const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) { return CalcWordWrapPosition(LegacySize * scale, text, text_end, wrap_width); } // Obsoleted old name in 1.92.0. Note how `scale` was to `size`. + inline ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** remaining = NULL) { return CalcTextSizeA(size, max_width, wrap_width, ImStrv(text_begin, text_end), remaining); } + inline const char* CalcWordWrapPosition(float size, const char* text, const char* text_end, float wrap_width) { return CalcWordWrapPosition(size, ImStrv(text, text_end), wrap_width); } + inline const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) { return CalcWordWrapPosition(LegacySize * scale, ImStrv(text, text_end), wrap_width); } // Obsoleted old name in 1.92.0. Note how `scale` was to `size`. + inline void RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, bool cpu_fine_clip = false) { RenderText(draw_list, size, pos, col, clip_rect, ImStrv(text_begin, text_end), wrap_width, cpu_fine_clip); } #endif // [Internal] Don't use! @@ -4228,6 +4291,13 @@ struct ImGuiPlatformImeData #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS namespace ImGui { + // OBSOLETED in 1.XX (string_view branch) + inline void PushID(const char* str_id_begin, const char* str_id_end){ PushID(ImStrv(str_id_begin, str_id_end)); } + inline ImGuiID GetID(const char* str_id_begin, const char* str_id_end) { return GetID(ImStrv(str_id_begin, str_id_end)); } + inline void TextUnformatted(const char* text, const char* text_end) { TextUnformatted(ImStrv(text, text_end)); } + inline ImVec2 CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash = false, float wrap_width = -1.0f) { return CalcTextSize(ImStrv(text, text_end), hide_text_after_double_hash, wrap_width); } + IMGUI_API bool Combo(ImStrv label, int* current_item, const char* (*getter)(void* user_data, int idx), void* user_data, int items_count, int popup_max_height_in_items = -1); + IMGUI_API bool ListBox(ImStrv label, int* current_item, const char* (*getter)(void* user_data, int idx), void* user_data, int items_count, int height_in_items = -1); // OBSOLETED in 1.92.9 (from July 2026) IMGUI_API void SetColorEditOptions(ImGuiColorEditFlags flags); // set current options for if you want to select a default format, picker type, etc. User will be able to change those settings, unless you pass the _NoOptions flag to your calls. // OBSOLETED in 1.92.0 (from June 2025) @@ -4248,8 +4318,8 @@ namespace ImGui //inline void PushTabStop(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); } //inline void PopTabStop() { PopItemFlag(); } // OBSOLETED in 1.90.0 (from September 2023) - //IMGUI_API bool Combo(const char* label, int* current_item, bool (*old_callback)(void* user_data, int idx, const char** out_text), void* user_data, int items_count, int popup_max_height_in_items = -1); // Getter signature changed. See 2023/09/15 and 2026/02/27 commits. - //IMGUI_API bool ListBox(const char* label, int* current_item, bool (*old_callback)(void* user_data, int idx, const char** out_text), void* user_data, int items_count, int height_in_items = -1); // Getter signature changed. See 2023/09/15 and 2026/02/27 commits. + //IMGUI_API bool Combo(ImStrv label, int* current_item, bool (*old_callback)(void* user_data, int idx, const char** out_text), void* user_data, int items_count, int popup_max_height_in_items = -1); // Getter signature changed. See 2023/09/15 and 2026/02/27 commits. + //IMGUI_API bool ListBox(ImStrv label, int* current_item, bool (*old_callback)(void* user_data, int idx, const char** out_text), void* user_data, int items_count, int height_in_items = -1); // Getter signature changed. See 2023/09/15 and 2026/02/27 commits. //inline bool BeginChild(const char* str_id, const ImVec2& size_arg, bool borders, ImGuiWindowFlags window_flags) { return BeginChild(str_id, size_arg, borders ? ImGuiChildFlags_Borders : ImGuiChildFlags_None, window_flags); } // Unnecessary as true == ImGuiChildFlags_Borders //inline bool BeginChild(ImGuiID id, const ImVec2& size_arg, bool borders, ImGuiWindowFlags window_flags) { return BeginChild(id, size_arg, borders ? ImGuiChildFlags_Borders : ImGuiChildFlags_None, window_flags); } // Unnecessary as true == ImGuiChildFlags_Borders //inline bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags flags = 0) { return BeginChild(id, size, ImGuiChildFlags_FrameStyle, flags); } @@ -4277,7 +4347,7 @@ namespace ImGui //static inline bool ListBoxHeader(const char* label, int items_count, int height_in_items = -1) { float height = GetTextLineHeightWithSpacing() * ((height_in_items < 0 ? ImMin(items_count, 7) : height_in_items) + 0.25f) + GetStyle().FramePadding.y * 2.0f; return BeginListBox(label, ImVec2(0.0f, height)); } // Helper to calculate size from items_count and height_in_items //static inline void ListBoxFooter() { EndListBox(); } //-- OBSOLETED in 1.79 (from August 2020) - //static inline void OpenPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mb = 1) { OpenPopupOnItemClick(str_id, mb); } // Bool return value removed. Use IsWindowAppearing() in BeginPopup() instead. Renamed in 1.77, renamed back in 1.79. Sorry! + //static inline void OpenPopupContextItem(ImStrv str_id = ImStrv(), ImGuiMouseButton mb = 1) { OpenPopupOnItemClick(str_id, mb); } // Bool return value removed. Use IsWindowAppearing() in BeginPopup() instead. Renamed in 1.77, renamed back in 1.79. Sorry! //-- OBSOLETED in 1.78 (from June 2020): Old drag/sliders functions that took a 'float power > 1.0f' argument instead of ImGuiSliderFlags_Logarithmic. See github.com/ocornut/imgui/issues/3361 for details. //IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power = 1.0f) // OBSOLETED in 1.78 (from June 2020) //IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power = 1.0f); // OBSOLETED in 1.78 (from June 2020) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 8d27c9f3f..b4b2761c0 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1487,7 +1487,7 @@ static void DemoWindowWidgetsComboBoxes() // Simplified one-liner Combo() using an accessor function static int item_current_4 = 0; - ImGui::Combo("combo 5 (function)", &item_current_4, [](void* data, int n) { return ((const char**)data)[n]; }, items, IM_COUNTOF(items)); + ImGui::Combo("combo 5 (function)", &item_current_4, [](void* data, int n) { return ImStrv(((const char**)data)[n]); }, items, IM_COUNTOF(items)); ImGui::TreePop(); } @@ -1842,7 +1842,6 @@ static void DemoWindowWidgetsDragsAndSliders() //ImGui::DragFloat("DragFloat (0 -> 0)", &drag_f, 0.005f, 0.0f, 0.0f, "%.3f", flags); // To test ClampZeroRange //ImGui::DragFloat("DragFloat (100 -> 100)", &drag_f, 0.005f, 100.0f, 100.0f, "%.3f", flags); ImGui::DragInt("DragInt (0 -> 100)", &drag_i, 0.5f, 0, 100, "%d", flags); - ImGui::DragFloat("DragFloat (0 -> 100)", &drag_f, 0.2f, 0, 100, "%.2f", flags); ImGui::DragFloat4("DragFloat4 (0 -> 1)", drag_f4, 0.005f, 0.0f, 1.0f, "%.3f", flags); // Multi-component item, mostly here to document the effect of ImGuiSliderFlags_ColorMarkers. // Sliders @@ -1853,7 +1852,7 @@ static void DemoWindowWidgetsDragsAndSliders() ImGui::Text("Underlying float value: %f", slider_f); ImGui::SliderFloat("SliderFloat (0 -> 1)", &slider_f, 0.0f, 1.0f, "%.3f", flags_for_sliders); ImGui::SliderInt("SliderInt (0 -> 100)", &slider_i, 0, 100, "%d", flags_for_sliders); - ImGui::SliderFloat4("SliderFloat4 (0 -> 1)", slider_f4, 0.0f, 1.0f, "%.3f", flags_for_sliders); // Multi-component item, mostly here to document the effect of ImGuiSliderFlags_ColorMarkers. + ImGui::SliderFloat4("SliderFloat4 (0 -> 1)", slider_f4, 0.0f, 1.0f, "%.3f", flags); // Multi-component item, mostly here to document the effect of ImGuiSliderFlags_ColorMarkers. ImGui::TreePop(); } @@ -4431,7 +4430,6 @@ static void DemoWindowWidgetsTreeNodes() ImGui::CheckboxFlags("ImGuiTreeNodeFlags_Framed", &base_flags, ImGuiTreeNodeFlags_Framed); ImGui::SameLine(); HelpMarker("Draw frame with background (e.g. for CollapsingHeader)"); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_FramePadding", &base_flags, ImGuiTreeNodeFlags_FramePadding); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_NavLeftJumpsToParent", &base_flags, ImGuiTreeNodeFlags_NavLeftJumpsToParent); - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_Bullet", &base_flags, ImGuiTreeNodeFlags_Bullet); HelpMarker("Default option for DrawLinesXXX is stored in style.TreeLinesFlags"); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_DrawLinesNone", &base_flags, ImGuiTreeNodeFlags_DrawLinesNone); @@ -4652,8 +4650,6 @@ static void DemoWindowLayout() IMGUI_DEMO_MARKER("Layout/Child windows"); ImGui::SeparatorText("Child windows"); - const float ref_sz = ImGui::GetTextLineHeightWithSpacing(); - HelpMarker("Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window."); static bool disable_mouse_wheel = false; static bool disable_menu = false; @@ -4665,7 +4661,7 @@ static void DemoWindowLayout() ImGuiWindowFlags window_flags = ImGuiWindowFlags_HorizontalScrollbar; if (disable_mouse_wheel) window_flags |= ImGuiWindowFlags_NoScrollWithMouse; - ImGui::BeginChild("ChildL", ImVec2(ImGui::GetContentRegionAvail().x * 0.5f, 15 * ref_sz), ImGuiChildFlags_None, window_flags); + ImGui::BeginChild("ChildL", ImVec2(ImGui::GetContentRegionAvail().x * 0.5f, 260), ImGuiChildFlags_None, window_flags); for (int i = 0; i < 100; i++) ImGui::Text("%04d: scrollable region", i); ImGui::EndChild(); @@ -4681,7 +4677,7 @@ static void DemoWindowLayout() if (!disable_menu) window_flags |= ImGuiWindowFlags_MenuBar; ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f); - ImGui::BeginChild("ChildR", ImVec2(0, 15 * ref_sz), ImGuiChildFlags_Borders, window_flags); + ImGui::BeginChild("ChildR", ImVec2(0, 260), ImGuiChildFlags_Borders, window_flags); if (!disable_menu && ImGui::BeginMenuBar()) { if (ImGui::BeginMenu("Menu")) @@ -4710,11 +4706,11 @@ static void DemoWindowLayout() ImGui::SeparatorText("Manual-resize"); { HelpMarker("Drag bottom border to resize. Double-click bottom border to auto-fit to vertical contents."); - //if (ImGui::Button("Set Height to 300")) - // ImGui::SetNextWindowSize(ImVec2(-FLT_MIN, 300.0f)); + //if (ImGui::Button("Set Height to 200")) + // ImGui::SetNextWindowSize(ImVec2(-FLT_MIN, 200.0f)); ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::GetStyleColorVec4(ImGuiCol_FrameBg)); - if (ImGui::BeginChild("ResizableChild", ImVec2(-FLT_MIN, ref_sz * 8), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeY)) + if (ImGui::BeginChild("ResizableChild", ImVec2(-FLT_MIN, ImGui::GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeY)) for (int n = 0; n < 10; n++) ImGui::Text("Line %04d", n); ImGui::PopStyleColor(); @@ -4726,12 +4722,12 @@ static void DemoWindowLayout() { static int draw_lines = 3; static int max_height_in_lines = 10; - ImGui::SetNextItemWidth(ref_sz * 7); + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); ImGui::DragInt("Lines Count", &draw_lines, 0.2f); - ImGui::SetNextItemWidth(ref_sz * 7); + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); ImGui::DragInt("Max Height (in Lines)", &max_height_in_lines, 0.2f); - ImGui::SetNextWindowSizeConstraints(ImVec2(0.0f, ref_sz * 1), ImVec2(FLT_MAX, ref_sz * max_height_in_lines)); + ImGui::SetNextWindowSizeConstraints(ImVec2(0.0f, ImGui::GetTextLineHeightWithSpacing() * 1), ImVec2(FLT_MAX, ImGui::GetTextLineHeightWithSpacing() * max_height_in_lines)); if (ImGui::BeginChild("ConstrainedChild", ImVec2(-FLT_MIN, 0.0f), ImGuiChildFlags_Borders | ImGuiChildFlags_AutoResizeY)) for (int n = 0; n < draw_lines; n++) ImGui::Text("Line %04d", n); @@ -4751,7 +4747,7 @@ static void DemoWindowLayout() static int offset_x = 0; static bool override_bg_color = true; static ImGuiChildFlags child_flags = ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY; - ImGui::SetNextItemWidth(ref_sz * 7); + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); ImGui::DragInt("Offset X", &offset_x, 1.0f, -1000, 1000); ImGui::Checkbox("Override ChildBg color", &override_bg_color); ImGui::CheckboxFlags("ImGuiChildFlags_Borders", &child_flags, ImGuiChildFlags_Borders); @@ -4766,7 +4762,7 @@ static void DemoWindowLayout() ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (float)offset_x); if (override_bg_color) ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(255, 0, 0, 100)); - ImGui::BeginChild("Red", ImVec2(ref_sz * 12.0f, ref_sz * 6.0f), child_flags, ImGuiWindowFlags_None); + ImGui::BeginChild("Red", ImVec2(200, 100), child_flags, ImGuiWindowFlags_None); if (override_bg_color) ImGui::PopStyleColor(); @@ -4863,7 +4859,7 @@ static void DemoWindowLayout() if (show_indented_items) { ImGui::Indent(); - ImGui::DragFloat("##float6b (indented)", &f); + ImGui::DragFloat("float (indented)##6b", &f); ImGui::Unindent(); } ImGui::PopItemWidth(); @@ -4928,8 +4924,7 @@ static void DemoWindowLayout() static int selection[4] = { 0, 1, 2, 3 }; for (int i = 0; i < 4; i++) { - if (i > 0) - ImGui::SameLine(); + if (i > 0) ImGui::SameLine(); ImGui::PushID(i); ImGui::ListBox("", &selection[i], items, IM_COUNTOF(items)); ImGui::PopID(); @@ -4937,11 +4932,9 @@ static void DemoWindowLayout() } ImGui::PopItemWidth(); - const float ref_sz = ImGui::GetTextLineHeightWithSpacing(); - // Dummy IMGUI_DEMO_MARKER("Layout/Basic Horizontal Layout/Dummy"); - ImVec2 button_sz(ref_sz * 3.0f, ref_sz * 3.0f); + ImVec2 button_sz(40, 40); ImGui::Button("A", button_sz); ImGui::SameLine(); ImGui::Dummy(button_sz); ImGui::SameLine(); ImGui::Button("B", button_sz); @@ -5083,10 +5076,10 @@ static void DemoWindowLayout() ImGui::Indent(); // SmallButton() sets FramePadding to zero. Text baseline is aligned to match baseline of previous Button. - ImGui::Button("120x120", ImVec2(120, 120)); - ImGui::SameLine(); ImGui::Button("80x80", ImVec2(80, 80)); ImGui::SameLine(); + ImGui::Button("50x50", ImVec2(50, 50)); + ImGui::SameLine(); ImGui::Button("Button()"); ImGui::SameLine(); ImGui::SmallButton("SmallButton()"); @@ -5489,7 +5482,7 @@ static void DemoWindowLayout() case 2: ImVec4 clip_rect(p0.x, p0.y, p1.x, p1.y); // AddText() takes a ImVec4* here so let's convert. draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255)); - draw_list->AddText(ImGui::GetFont(), ImGui::GetFontSize(), text_pos, IM_COL32_WHITE, text_str, NULL, 0.0f, &clip_rect); + draw_list->AddText(ImGui::GetFont(), ImGui::GetFontSize(), text_pos, IM_COL32_WHITE, text_str, 0.0f, &clip_rect); break; } } @@ -6131,12 +6124,11 @@ static void DemoWindowTables() ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuter", &flags, ImGuiTableFlags_BordersOuter); ImGui::CheckboxFlags("ImGuiTableFlags_BordersInner", &flags, ImGuiTableFlags_BordersInner); ImGui::Unindent(); - + ImGui::AlignTextToFramePadding(); ImGui::Text("Cell contents:"); ImGui::SameLine(); ImGui::RadioButton("Text", &contents_type, CT_Text); ImGui::SameLine(); ImGui::RadioButton("FillButton", &contents_type, CT_FillButton); ImGui::Checkbox("Display headers", &display_headers); - ImGui::CheckboxFlags("ImGuiTableFlags_PadOuterX", &flags, ImGuiTableFlags_PadOuterX); ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBody", &flags, ImGuiTableFlags_NoBordersInBody); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body (borders will always appear in Headers)"); PopStyleCompact(); @@ -6364,7 +6356,6 @@ static void DemoWindowTables() "Actual padding values are using style.CellPadding.\n\n" "In this demo we don't show horizontal borders to emphasize how they don't affect default horizontal padding."); - ImGui::PushID("flags1"); static ImGuiTableFlags flags1 = ImGuiTableFlags_BordersV; PushStyleCompact(); ImGui::CheckboxFlags("ImGuiTableFlags_PadOuterX", &flags1, ImGuiTableFlags_PadOuterX); @@ -6375,11 +6366,9 @@ static void DemoWindowTables() ImGui::SameLine(); HelpMarker("Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off)"); ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", &flags1, ImGuiTableFlags_BordersOuterV); ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", &flags1, ImGuiTableFlags_BordersInnerV); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", &flags1, ImGuiTableFlags_BordersH); static bool show_headers = false; ImGui::Checkbox("show_headers", &show_headers); PopStyleCompact(); - ImGui::PopID(); if (ImGui::BeginTable("table_padding", 3, flags1)) { @@ -6419,7 +6408,7 @@ static void DemoWindowTables() HelpMarker("Setting style.CellPadding to (0,0) or a custom value."); static ImGuiTableFlags flags2 = ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg; static ImVec2 cell_padding(0.0f, 0.0f); - static bool show_widget_frame_bg = false; + static bool show_widget_frame_bg = true; PushStyleCompact(); ImGui::CheckboxFlags("ImGuiTableFlags_Borders", &flags2, ImGuiTableFlags_Borders); @@ -6438,9 +6427,7 @@ static void DemoWindowTables() { static char text_bufs[3 * 5][16]; // Mini text storage for 3x5 cells static bool init = true; - if (show_widget_frame_bg) - ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0.0f); - else + if (!show_widget_frame_bg) ImGui::PushStyleColor(ImGuiCol_FrameBg, 0); for (int cell = 0; cell < 3 * 5; cell++) { @@ -6452,9 +6439,7 @@ static void DemoWindowTables() ImGui::InputText("##cell", text_bufs[cell], IM_COUNTOF(text_bufs[cell])); ImGui::PopID(); } - if (show_widget_frame_bg) - ImGui::PopStyleVar(); - else + if (!show_widget_frame_bg) ImGui::PopStyleColor(); init = false; ImGui::EndTable(); @@ -6796,20 +6781,19 @@ static void DemoWindowTables() ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags1, ImGuiTableFlags_Resizable); ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", &flags1, ImGuiTableFlags_NoBordersInBodyUntilResize); PopStyleCompact(); - if (ImGui::BeginTable("table1", 4, flags1)) + if (ImGui::BeginTable("table1", 3, flags1)) { - // We could also set ImGuiTableFlags_SizingFixedFit on the table and all columns will default to ImGuiTableColumnFlags_WidthFixed if not specified. + // We could also set ImGuiTableFlags_SizingFixedFit on the table and all columns will default to ImGuiTableColumnFlags_WidthFixed. ImGui::TableSetupColumn("one", ImGuiTableColumnFlags_WidthFixed, 100.0f); // Default to 100.0f ImGui::TableSetupColumn("two", ImGuiTableColumnFlags_WidthFixed, 200.0f); // Default to 200.0f ImGui::TableSetupColumn("three", ImGuiTableColumnFlags_WidthFixed); // Default to auto - ImGui::TableSetupColumn("four", ImGuiTableColumnFlags_WidthStretch); // Default to remaining width ImGui::TableHeadersRow(); for (int row = 0; row < 4; row++) { ImGui::TableNextRow(); - for (int column = 0; column < 4; column++) + for (int column = 0; column < 3; column++) { - ImGui::TableNextColumn(); + ImGui::TableSetColumnIndex(column); if (row == 0) ImGui::Text("(w: %5.1f)", ImGui::GetContentRegionAvail().x); else @@ -6818,29 +6802,18 @@ static void DemoWindowTables() } ImGui::EndTable(); } - if (ImGui::BeginTable("table2", 2, flags1)) - { - // We could also set ImGuiTableFlags_SizingFixedFit on the table and all columns will default to ImGuiTableColumnFlags_WidthFixed. - ImGui::TableSetupColumn("one", ImGuiTableColumnFlags_WidthStretch, 1.0f); // Default weight - ImGui::TableSetupColumn("two", ImGuiTableColumnFlags_WidthStretch, 2.0f); // Default weight - ImGui::TableHeadersRow(); - for (int column = 0; column < 2; column++) - if (ImGui::TableNextColumn()) - ImGui::Text("Default weight %d%%", (column & 1) ? 200 : 100); - ImGui::EndTable(); - } HelpMarker( "Using TableSetupColumn() to setup explicit width.\n\nUnless _NoKeepColumnsVisible is set, " "fixed columns with set width may still be shrunk down if there's not enough space in the host."); - static ImGuiTableFlags flags3 = ImGuiTableFlags_None; + static ImGuiTableFlags flags2 = ImGuiTableFlags_None; PushStyleCompact(); - ImGui::CheckboxFlags("ImGuiTableFlags_NoKeepColumnsVisible", &flags3, ImGuiTableFlags_NoKeepColumnsVisible); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", &flags3, ImGuiTableFlags_BordersInnerV); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", &flags3, ImGuiTableFlags_BordersOuterV); + ImGui::CheckboxFlags("ImGuiTableFlags_NoKeepColumnsVisible", &flags2, ImGuiTableFlags_NoKeepColumnsVisible); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", &flags2, ImGuiTableFlags_BordersInnerV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", &flags2, ImGuiTableFlags_BordersOuterV); PopStyleCompact(); - if (ImGui::BeginTable("table3", 4, flags3)) + if (ImGui::BeginTable("table2", 4, flags2)) { // We could also set ImGuiTableFlags_SizingFixedFit on the table and then all columns // will default to ImGuiTableColumnFlags_WidthFixed. @@ -6980,7 +6953,6 @@ static void DemoWindowTables() if (ImGui::TreeNode("Outer size")) { IMGUI_DEMO_MARKER("Tables/Outer size"); - // Showcasing use of ImGuiTableFlags_NoHostExtendX and ImGuiTableFlags_NoHostExtendY // Important to that note how the two flags have slightly different behaviors! ImGui::Text("Using NoHostExtendX and NoHostExtendY:"); @@ -7076,7 +7048,7 @@ static void DemoWindowTables() // We use a transparent color so we can see the one behind in case our target is RowBg1 and RowBg0 was already targeted by the ImGuiTableFlags_RowBg flag. if (row_bg_type != 0) { - ImU32 row_bg_color = ImGui::GetColorU32(row_bg_type == 1 ? ImVec4(0.7f, 0.3f, 0.3f, 0.40f) : ImVec4(0.2f + row * 0.1f, 0.2f, 0.2f, 0.40f)); // Flat or Gradient? + ImU32 row_bg_color = ImGui::GetColorU32(row_bg_type == 1 ? ImVec4(0.7f, 0.3f, 0.3f, 0.65f) : ImVec4(0.2f + row * 0.1f, 0.2f, 0.2f, 0.65f)); // Flat or Gradient? ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0 + row_bg_target, row_bg_color); } @@ -8642,7 +8614,7 @@ void ImGui::ShowAboutWindow(bool* p_open) //----------------------------------------------------------------------------- // Demo helper function to select among default colors. See ShowStyleEditor() for more advanced options. -bool ImGui::ShowStyleSelector(const char* label) +bool ImGui::ShowStyleSelector(ImStrv label) { // FIXME: This is a bit tricky to get right as style are functions, they don't register a name nor the fact that one is active. // So we keep track of last active one among our limited selection. @@ -8835,10 +8807,6 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) SliderFloat("ImageRounding", &style.ImageRounding, 0.0f, 12.0f, "%.0f"); SliderFloat("ImageBorderSize", &style.ImageBorderSize, 0.0f, max_border_size, "%.0f"); - SeparatorText("Symbols"); - DragFloat2("SymbolArrowSizeFactor", &style.SymbolArrowSizeFactor.x, 0.01f, 0.0f, 1.0f); - DragFloat("SymbolArrowThicknessFactor", &style.SymbolArrowThicknessFactor, 0.01f, 0.0f, 0.5f); - SeparatorText("Tooltips"); for (int n = 0; n < 2; n++) if (TreeNodeEx(n == 0 ? "HoverFlagsForTooltipMouse" : "HoverFlagsForTooltipNav")) @@ -9522,7 +9490,7 @@ struct ExampleAppConsole if (match_len > 0) { data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start)); - data->InsertChars(data->CursorPos, candidates[0], candidates[0] + match_len); + data->InsertChars(data->CursorPos, ImStrv(candidates[0], candidates[0] + match_len)); } // List matches @@ -9680,8 +9648,8 @@ struct ExampleAppLog { const char* line_start = buf + LineOffsets[line_no]; const char* line_end = (line_no + 1 < LineOffsets.Size) ? (buf + LineOffsets[line_no + 1] - 1) : buf_end; - if (Filter.PassFilter(line_start, line_end)) - ImGui::TextUnformatted(line_start, line_end); + if (Filter.PassFilter(ImStrv(line_start, line_end))) + ImGui::TextUnformatted(ImStrv(line_start, line_end)); } } else @@ -9707,7 +9675,7 @@ struct ExampleAppLog { const char* line_start = buf + LineOffsets[line_no]; const char* line_end = (line_no + 1 < LineOffsets.Size) ? (buf + LineOffsets[line_no + 1] - 1) : buf_end; - ImGui::TextUnformatted(line_start, line_end); + ImGui::TextUnformatted(ImStrv(line_start, line_end)); } } clipper.End(); @@ -10107,7 +10075,7 @@ static void ShowExampleAppLongText(bool* p_open) { case 0: // Single call to TextUnformatted() with a big buffer - ImGui::TextUnformatted(log.begin(), log.end()); + ImGui::TextUnformatted(ImStrv(log.begin(), log.end())); break; case 1: { @@ -11577,7 +11545,7 @@ void ImGui::ShowAboutWindow(bool*) {} void ImGui::ShowDemoWindow(bool*) {} void ImGui::ShowUserGuide() {} void ImGui::ShowStyleEditor(ImGuiStyle*) {} -bool ImGui::ShowStyleSelector(const char*) { return false; } +bool ImGui::ShowStyleSelector(ImStrv) { return false; } #endif // #ifndef IMGUI_DISABLE_DEMO_WINDOWS diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 7b2b7138d..c8ecd5d15 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -62,7 +62,6 @@ Index of this file: #pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants ok. #pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is. #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness -#pragma clang diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 #pragma clang diagnostic ignored "-Wcomma" // warning: possible misuse of comma operator here #pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier @@ -113,6 +112,7 @@ namespace IMGUI_STB_NAMESPACE #if defined(__clang__) #pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used #pragma clang diagnostic ignored "-Wmissing-prototypes" #pragma clang diagnostic ignored "-Wimplicit-fallthrough" #endif @@ -191,9 +191,9 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst) colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); colors[ImGuiCol_TextDisabled] = ImVec4(0.58f, 0.58f, 0.58f, 1.00f); - colors[ImGuiCol_WindowBg] = ImVec4(0.15f, 0.15f, 0.15f, 1.00f); - colors[ImGuiCol_ChildBg] = ImVec4(0.17f, 0.17f, 0.17f, 0.00f); - colors[ImGuiCol_PopupBg] = ImVec4(0.14f, 0.14f, 0.14f, 0.94f); + colors[ImGuiCol_WindowBg] = ImVec4(0.18f, 0.18f, 0.18f, 1.00f); + colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_PopupBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f); colors[ImGuiCol_Border] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f); colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_FrameBg] = ImVec4(0.10f, 0.10f, 0.10f, 1.00f); @@ -2947,15 +2947,14 @@ void ImDrawList::AddBezierQuadratic(const ImVec2& p1, const ImVec2& p2, const Im PathStroke(col, thickness, flags); } -void ImDrawList::AddText(ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end, float wrap_width, const ImVec4* cpu_fine_clip_rect) +void ImDrawList::AddText(ImFont* font, float font_size, const ImVec2& pos, ImU32 col, ImStrv text, float wrap_width, const ImVec4* cpu_fine_clip_rect) { if ((col & IM_COL32_A_MASK) == 0) return; // Accept null ranges - if (text_begin == text_end || text_begin[0] == 0) + if (text.Begin == text.End) return; - // No need to strlen() here: font->RenderText() will do it and may early out. // Pull default font/size from the shared ImDrawListSharedData instance if (font == NULL) @@ -2971,12 +2970,12 @@ void ImDrawList::AddText(ImFont* font, float font_size, const ImVec2& pos, ImU32 clip_rect.z = ImMin(clip_rect.z, cpu_fine_clip_rect->z); clip_rect.w = ImMin(clip_rect.w, cpu_fine_clip_rect->w); } - font->RenderText(this, font_size, pos, col, clip_rect, text_begin, text_end, wrap_width, (cpu_fine_clip_rect != NULL) ? ImDrawTextFlags_CpuFineClip : ImDrawTextFlags_None); + font->RenderText(this, font_size, pos, col, clip_rect, text, wrap_width, (cpu_fine_clip_rect != NULL) ? ImDrawTextFlags_CpuFineClip : ImDrawTextFlags_None); } -void ImDrawList::AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end) +void ImDrawList::AddText(const ImVec2& pos, ImU32 col, ImStrv text) { - AddText(_Data->Font, _Data->FontSize, pos, col, text_begin, text_end); + AddText(_Data->Font, _Data->FontSize, pos, col, text); } void ImDrawList::AddImage(ImTextureRef tex_ref, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col) @@ -4363,10 +4362,7 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg_in) ImFontAtlasFontSourceAddToFont(this, font, font_cfg); if (is_first_font) - { ImFontAtlasBuildNotifySetFont(this, NULL, font); - Builder->LoadedFontDefaultAsVector = -1; - } return font; } @@ -4374,13 +4370,15 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg_in) static unsigned int stb_decompress_length(const unsigned char* input); static unsigned int stb_decompress(unsigned char* output, const unsigned char* input, unsigned int length); static unsigned int Decode85Byte(char c) { return c >= '\\' ? c-36 : c-35; } -static void Decode85(const unsigned char* src, unsigned char* dst) +static void Decode85(ImStrv src, unsigned char* dst) { - while (*src) + const char* p = src.Begin; + const char* p_end = src.End; + while (p < p_end) { - unsigned int tmp = Decode85Byte(src[0]) + 85 * (Decode85Byte(src[1]) + 85 * (Decode85Byte(src[2]) + 85 * (Decode85Byte(src[3]) + 85 * Decode85Byte(src[4])))); + unsigned int tmp = Decode85Byte(p[0]) + 85 * (Decode85Byte(p[1]) + 85 * (Decode85Byte(p[2]) + 85 * (Decode85Byte(p[3]) + 85 * Decode85Byte(p[4])))); dst[0] = ((tmp >> 0) & 0xFF); dst[1] = ((tmp >> 8) & 0xFF); dst[2] = ((tmp >> 16) & 0xFF); dst[3] = ((tmp >> 24) & 0xFF); // We can't assume little-endianness. - src += 5; + p += 5; dst += 4; } } @@ -4392,17 +4390,13 @@ const char* ImGui_GetDefaultCompressedFontDataProggyForever(int* out_size); #endif // This duplicates some of the logic in UpdateFontsNewFrame() which is a bit chicken-and-eggy/tricky to extract due to variety of codepaths and possible initialization ordering. -bool ImFontAtlasHeuristicShouldUseDefaultVectorFont(ImFontAtlas* atlas) +static float GetExpectedContextFontSize(ImGuiContext* ctx) { - ImGuiContext* ctx = atlas->OwnerContext; - if (ctx == NULL) - return true; float fb_scale = (ctx->IO.DisplayFramebufferScale.x != 0.0f) ? ctx->IO.DisplayFramebufferScale.x : 1.0f; if (ctx->IO.DisplayFramebufferScale.x == 1.0f && ctx->IO.DisplaySize.x <= 0.0f && ctx->IO.ConfigMacOSXBehaviors) - fb_scale = 2.0f; // If called before backend had a chance to init DisplayFramebufferScale: default to expecting Retina on macOS/iOS. - const float scale = ctx->Style.FontScaleMain * ctx->Style.FontScaleDpi * fb_scale; - const float expected_font_size = ((ctx->Style.FontSizeBase > 0.0f) ? ctx->Style.FontSizeBase : 13.0f) * scale; - return expected_font_size >= 15.0f; + fb_scale = 2.0f; // If called before backend had a chance to init DisplayFramebufferScale. default to expecting Retina. + float scale = ctx->Style.FontScaleMain * ctx->Style.FontScaleDpi * fb_scale; + return ((ctx->Style.FontSizeBase > 0.0f) ? ctx->Style.FontSizeBase : 13.0f) * scale; } // Legacy function with heuristic to select Pixel or Vector font. @@ -4410,11 +4404,10 @@ bool ImFontAtlasHeuristicShouldUseDefaultVectorFont(ImFontAtlas* atlas) // Prefer calling AddFontDefaultVector() or AddFontDefaultBitmap() based on your own logic. ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg) { - const bool use_vector_font = ImFontAtlasHeuristicShouldUseDefaultVectorFont(this); - ImFont* font = use_vector_font ? AddFontDefaultVector(font_cfg) : AddFontDefaultBitmap(font_cfg); - if (Fonts.Size == 1) - Builder->LoadedFontDefaultAsVector = use_vector_font ? 1 : 0; - return font; + if (OwnerContext == NULL || GetExpectedContextFontSize(OwnerContext) >= 15.0f) + return AddFontDefaultVector(font_cfg); + else + return AddFontDefaultBitmap(font_cfg); } // Load embedded ProggyClean.ttf. Default size 13, disable oversampling. @@ -4473,7 +4466,7 @@ ImFont* ImFontAtlas::AddFontDefaultVector(const ImFontConfig* font_cfg_template) #endif } -ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) +ImFont* ImFontAtlas::AddFontFromFileTTF(ImStrv filename, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); size_t data_size = 0; @@ -4482,7 +4475,7 @@ ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, { if (font_cfg_template == NULL || (font_cfg_template->Flags & ImFontFlags_NoLoadError) == 0) { - IMGUI_DEBUG_LOG("While loading '%s'\n", filename); + IMGUI_DEBUG_LOG("While loading '%.*s'\n", filename.length(), filename.Begin); IM_ASSERT_USER_ERROR(0, "Could not load font file!"); } return NULL; @@ -4492,8 +4485,9 @@ ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, { // Store a short copy of filename into the font name for convenience const char* p; - for (p = filename + ImStrlen(filename); p > filename && p[-1] != '/' && p[-1] != '\\'; p--) {} - ImFormatString(font_cfg.Name, IM_COUNTOF(font_cfg.Name), "%s", p); + for (p = filename.End; p > filename.Begin && p[-1] != '/' && p[-1] != '\\'; p--) {} + filename.Begin = p; + ImFormatString(font_cfg.Name, IM_COUNTOF(font_cfg.Name), "%.*s", filename.length(), filename.Begin); } return AddFontFromMemoryTTF(data, (int)data_size, size_pixels, &font_cfg, glyph_ranges); } @@ -4525,11 +4519,11 @@ ImFont* ImFontAtlas::AddFontFromMemoryCompressedTTF(const void* compressed_ttf_d return AddFontFromMemoryTTF(buf_decompressed_data, (int)buf_decompressed_size, size_pixels, &font_cfg, glyph_ranges); } -ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed_ttf_data_base85, float size_pixels, const ImFontConfig* font_cfg, const ImWchar* glyph_ranges) +ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(ImStrv compressed_ttf_data_base85, float size_pixels, const ImFontConfig* font_cfg, const ImWchar* glyph_ranges) { - int compressed_ttf_size = (((int)ImStrlen(compressed_ttf_data_base85) + 4) / 5) * 4; + int compressed_ttf_size = ((compressed_ttf_data_base85.length() + 4) / 5) * 4; void* compressed_ttf = IM_ALLOC((size_t)compressed_ttf_size); - Decode85((const unsigned char*)compressed_ttf_data_base85, (unsigned char*)compressed_ttf); + Decode85(compressed_ttf_data_base85, (unsigned char*)compressed_ttf); ImFont* font = AddFontFromMemoryCompressedTTF(compressed_ttf, compressed_ttf_size, size_pixels, font_cfg, glyph_ranges); IM_FREE(compressed_ttf); return font; @@ -6684,15 +6678,13 @@ const ImWchar* ImFontAtlas::GetGlyphRangesVietnamese() // [SECTION] ImFontGlyphRangesBuilder //----------------------------------------------------------------------------- -void ImFontGlyphRangesBuilder::AddText(const char* text, const char* text_end) +void ImFontGlyphRangesBuilder::AddText(ImStrv text) { - if (text_end == NULL) - text_end = text + strlen(text); - while (text < text_end) + while (text.Begin < text.End) { unsigned int c = 0; - int c_len = ImTextCharFromUtf8(&c, text, text_end); - text += c_len; + int c_len = ImTextCharFromUtf8(&c, text.Begin, text.End); + text.Begin += c_len; if (c_len == 0) break; AddChar((ImWchar)c); @@ -7079,7 +7071,7 @@ void ImTextInitClassifiers() // Simple word-wrapping for English, not full-featured. Please submit failing cases! // This will return the next location to wrap from. If no wrapping if necessary, this will fast-forward to e.g. text_end. // Refer to imgui_test_suite's "drawlist_text_wordwrap_1" for tests. -const char* ImFontCalcWordWrapPositionEx(ImFont* font, float size, const char* text, const char* text_end, float wrap_width, ImDrawTextFlags flags) +const char* ImFontCalcWordWrapPositionEx(ImFont* font, float size, const char* text_begin, const char* text_end, float wrap_width, ImDrawTextFlags flags) { // For references, possible wrap point marked with ^ // "aaa bbb, ccc,ddd. eee fff. ggg!" @@ -7098,7 +7090,7 @@ const char* ImFontCalcWordWrapPositionEx(ImFont* font, float size, const char* t float blank_width = 0.0f; wrap_width /= scale; // We work with unscaled widths to avoid scaling every characters - const char* s = text; + const char* s = text_begin; IM_ASSERT(text_end != NULL); int prev_type = ImWcharClass_Other; @@ -7189,30 +7181,29 @@ const char* ImFontCalcWordWrapPositionEx(ImFont* font, float size, const char* t // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. // +1 may not be a character start point in UTF-8 but it's ok because caller loops use (text >= word_wrap_eol). - if (s == text && text < text_end) + if (s == text_begin && text_begin < text_end) return s + ImTextCountUtf8BytesFromChar(s, text_end); return s; } -const char* ImFont::CalcWordWrapPosition(float size, const char* text, const char* text_end, float wrap_width) +const char* ImFont::CalcWordWrapPosition(float size, ImStrv text, float wrap_width) { - return ImFontCalcWordWrapPositionEx(this, size, text, text_end, wrap_width, ImDrawTextFlags_None); + return ImFontCalcWordWrapPositionEx(this, size, text.Begin, text.End, wrap_width, ImDrawTextFlags_None); } ImVec2 ImFontCalcTextSizeEx(ImFont* font, float size, float max_width, float wrap_width, const char* text_begin, const char* text_end_display, const char* text_end, const char** out_remaining, ImVec2* out_offset, ImDrawTextFlags flags) { - if (!text_end) - text_end = text_begin + ImStrlen(text_begin); // FIXME-OPT: Need to avoid this. - if (!text_end_display) - text_end_display = text_end; - ImFontBaked* baked = font->GetFontBaked(size); + const float line_height = size; const float scale = line_height / baked->Size; ImVec2 text_size = ImVec2(0, 0); float line_width = 0.0f; + if (!text_end_display) + text_end_display = text_end; + const bool word_wrap_enabled = (wrap_width > 0.0f); const char* word_wrap_eol = NULL; @@ -7290,9 +7281,9 @@ ImVec2 ImFontCalcTextSizeEx(ImFont* font, float size, float max_width, float wra return text_size; } -ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** out_remaining) +ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, ImStrv text, const char** out_remaining) { - return ImFontCalcTextSizeEx(this, size, max_width, wrap_width, text_begin, text_end, text_end, out_remaining, NULL, ImDrawTextFlags_None); + return ImFontCalcTextSizeEx(this, size, max_width, wrap_width, text.Begin, text.End, text.End, out_remaining, NULL, ImDrawTextFlags_None); } // Note: as with every ImDrawList drawing function, this expects that the font atlas texture is bound. @@ -7341,7 +7332,7 @@ void ImFont::RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, Im // Note: as with every ImDrawList drawing function, this expects that the font atlas texture is bound. // DO NOT CALL DIRECTLY THIS WILL CHANGE WILDLY IN 2026. Use ImDrawList::AddText(). -void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width, ImDrawTextFlags flags) +void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, const ImVec4& clip_rect, ImStrv text, float wrap_width, ImDrawTextFlags flags) { begin: // Align to be pixel perfect @@ -7356,9 +7347,6 @@ begin: y = IM_TRUNC(y); } - if (!text_end) - text_end = text_begin + ImStrlen(text_begin); // ImGui:: functions generally already provides a valid text_end, so this is merely to handle direct calls. - const float line_height = size; ImFontBaked* baked = GetFontBaked(size); @@ -7367,7 +7355,8 @@ begin: const bool word_wrap_enabled = (wrap_width > 0.0f); // Fast-forward to first visible line - const char* s = text_begin; + const char* s = text.Begin; + const char* text_end = text.End; if (y + line_height < clip_rect.y) while (y + line_height < clip_rect.y && s < text_end) { @@ -7559,6 +7548,7 @@ begin: // - RenderArrow() // - RenderBullet() // - RenderCheckMark() +// - RenderArrowPointingAt() // - RenderRectFilledInRangeH() // - RenderRectFilledWithHole() //----------------------------------------------------------------------------- @@ -7566,47 +7556,36 @@ begin: // - RenderColorRectWithAlphaCheckerboard() //----------------------------------------------------------------------------- -static const ImVec2 g_ImGuiDirCosSin[4] = { { -1.0f, 0.0f }, { +1.0f, 0.0f }, { 0.0f, -1.0f }, { 0.0f, +1.0f } }; - -// arrow_h, arrow_w, arrow_th are normalized: 0.0f..1.0f -// arrow_th: 0.0f == fill, >0.0f == stroke weight. -void ImGui::RenderArrowEx(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float cos_a, float sin_a, float scale, ImVec2 arrow_sizes, float arrow_th) -{ - const bool is_fill = (arrow_th <= 0.0f); - const float r = draw_list->_Data->FontSize * 0.50f * scale; - const float thickness = is_fill ? 0.0f : IM_ROUND(ImClamp(r * arrow_th, 1.0f, r * 0.5f)); - - // Bias for shape to feel more centered - const float bias = is_fill ? (r * 0.05f) : (thickness * 0.8f * 0.7071f); - const ImVec2 center = ImVec2(pos.x + r + bias * cos_a, pos.y + r + bias * sin_a); - - const float arrow_h = arrow_sizes.y * r; - const float arrow_w = arrow_sizes.x * r; - ImVec2 p[3]; - p[0] = ImVec2(center.x - arrow_h * cos_a - arrow_w * -sin_a, center.y - arrow_h * sin_a - arrow_w * cos_a); - p[1] = ImVec2(center.x + arrow_h * cos_a, center.y + arrow_h * sin_a); - p[2] = ImVec2(center.x - arrow_h * cos_a + arrow_w * -sin_a, center.y - arrow_h * sin_a + arrow_w * cos_a); - - // Pixel align when at a right angle - if (is_fill && (cos_a * sin_a >= -FLT_EPSILON) && (cos_a * sin_a <= FLT_EPSILON)) - { - p[0] = ImRoundSigned(p[0]); - p[1] = ImRoundSigned(p[1]); - p[2] = ImRoundSigned(p[2]); - } - - if (is_fill) - draw_list->AddConvexPolyFilled(p, 3, col); - else - draw_list->_AddPolyline(p, 3, col, thickness, ImDrawFlags_StrokeInside | ImDrawFlags_AALineEnds, FLT_MAX); // FIXME-OPT: baked filled shape? -} - -// Render an arrow aimed to be aligned with text. +// Render an arrow aimed to be aligned with text (p_min is a position in the same space text would be positioned). To e.g. denote expanded/collapsed state void ImGui::RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale) { - ImGuiContext& g = *GImGui; - ImVec2 cos_sin = g_ImGuiDirCosSin[dir]; - RenderArrowEx(draw_list, pos, col, cos_sin.x, cos_sin.y, scale, g.Style.SymbolArrowSizeFactor, g.Style.SymbolArrowThicknessFactor); + const float h = draw_list->_Data->FontSize * 1.00f; + float r = h * 0.40f * scale; + ImVec2 center = pos + ImVec2(h * 0.50f, h * 0.50f * scale); + + ImVec2 a, b, c; + switch (dir) + { + case ImGuiDir_Up: + case ImGuiDir_Down: + if (dir == ImGuiDir_Up) r = -r; + a = ImVec2(+0.000f, +0.750f) * r; + b = ImVec2(-0.866f, -0.750f) * r; + c = ImVec2(+0.866f, -0.750f) * r; + break; + case ImGuiDir_Left: + case ImGuiDir_Right: + if (dir == ImGuiDir_Left) r = -r; + a = ImVec2(+0.750f, +0.000f) * r; + b = ImVec2(-0.750f, +0.866f) * r; + c = ImVec2(-0.750f, -0.866f) * r; + break; + case ImGuiDir_None: + case ImGuiDir_COUNT: + IM_ASSERT(0); + break; + } + draw_list->AddTriangleFilled(center + a, center + b, center + c, col); } void ImGui::RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col) @@ -7631,6 +7610,19 @@ void ImGui::RenderCheckMark(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float draw_list->PathStroke(col, thickness, ImDrawFlags_AALineEnds); } +// Render an arrow. 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side. +void ImGui::RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col) +{ + switch (direction) + { + case ImGuiDir_Left: draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), pos, col); return; + case ImGuiDir_Right: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), pos, col); return; + case ImGuiDir_Up: draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), pos, col); return; + case ImGuiDir_Down: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), pos, col); return; + case ImGuiDir_None: case ImGuiDir_COUNT: break; // Fix warnings + } +} + static inline float ImAcos01(float x) { if (x <= 0.0f) return IM_PI * 0.5f; diff --git a/imgui_internal.h b/imgui_internal.h index 9ab5bea1d..268d4c415 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -284,8 +284,8 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer #define IM_MEMALIGN(_OFF,_ALIGN) (((_OFF) + ((_ALIGN) - 1)) & ~((_ALIGN) - 1)) // Memory align e.g. IM_ALIGN(0,4)=0, IM_ALIGN(1,4)=4, IM_ALIGN(4,4)=4, IM_ALIGN(5,4)=8 #define IM_F32_TO_INT8_UNBOUND(_VAL) ((int)((_VAL) * 255.0f + ((_VAL)>=0 ? 0.5f : -0.5f))) // Unsaturated, for display purpose #define IM_F32_TO_INT8_SAT(_VAL) ((int)(ImSaturate(_VAL) * 255.0f + 0.5f)) // Saturated, always output 0..255 -#define IM_TRUNC(_VAL) ((float)(int)(_VAL)) // Positive values only! == ImTrunc() which is not inlined in MSVC debug builds -#define IM_ROUND(_VAL) ((float)(int)((_VAL) + 0.5f)) // Positive values only! == ImRoundPositive() which is not inlined in MSVC debug builds. +#define IM_TRUNC(_VAL) ((float)(int)(_VAL)) // Positive values only! ImTrunc() is not inlined in MSVC debug builds +#define IM_ROUND(_VAL) ((float)(int)((_VAL) + 0.5f)) // Positive values only! //#define IM_FLOOR IM_TRUNC // [OBSOLETE] Renamed in 1.90.0 (Sept 2023) // Hint for branch prediction @@ -374,8 +374,9 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer // Helpers: Hashing IMGUI_API ImGuiID ImHashData(const void* data, size_t data_size, ImGuiID seed = 0); -IMGUI_API ImGuiID ImHashStr(const char* data, size_t data_size = 0, ImGuiID seed = 0); -IMGUI_API const char* ImHashSkipUncontributingPrefix(const char* label); +IMGUI_API ImGuiID ImHashStr(ImStrv str, ImGuiID seed = 0); +static inline ImGuiID ImHashStr(const char* data, size_t data_size = 0, ImGuiID seed = 0) { return ImHashStr(ImStrv(data, data_size ? data + data_size : NULL), seed); } +IMGUI_API const char* ImHashSkipUncontributingPrefix(ImStrv label); // Helpers: Sorting #ifndef ImQsort @@ -394,20 +395,26 @@ inline unsigned int ImCountSetBits(unsigned int v) { unsigned int count // Helpers: String #define ImStrlen strlen #define ImMemchr memchr +IMGUI_API int ImStrcmp(ImStrv str1, ImStrv str2); IMGUI_API int ImStricmp(const char* str1, const char* str2); // Case insensitive compare. IMGUI_API int ImStrnicmp(const char* str1, const char* str2, size_t count); // Case insensitive compare to a certain count. -IMGUI_API void ImStrncpy(char* dst, const char* src, size_t count); // Copy to a certain count and always zero terminate (strncpy doesn't). -IMGUI_API char* ImStrdup(const char* str); // Duplicate a string. +IMGUI_API void ImStrncpy(char* dst, ImStrv src, size_t count); // Copy to a certain count and always zero terminate (strncpy doesn't). +IMGUI_API void ImStrncpy(char* dst, const char* src, size_t count); +IMGUI_API char* ImStrdup(ImStrv str); // Duplicate a string. +IMGUI_API char* ImStrdup(const char* str); +IMGUI_API char* ImStrdupcpy(char* dst, size_t* p_dst_size, ImStrv str); // Copy in provided buffer, recreate buffer if needed. +IMGUI_API char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* str); IMGUI_API void* ImMemdup(const void* src, size_t size); // Duplicate a chunk of memory. -IMGUI_API char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* str); // Copy in provided buffer, recreate buffer if needed. IMGUI_API const char* ImStrchrRange(const char* str_begin, const char* str_end, char c); // Find first occurrence of 'c' in string range. IMGUI_API const char* ImStreolRange(const char* str, const char* str_end); // End end-of-line -IMGUI_API const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end); // Find a substring in a string range. +IMGUI_API const char* ImStrstr(ImStrv haystack, ImStrv needle); // Find a substring in a string range. +IMGUI_API const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end); IMGUI_API void ImStrTrimBlanks(char* str); // Remove leading and trailing blanks from a buffer. IMGUI_API const char* ImStrSkipBlank(const char* str); // Find first non-blank character. IMGUI_API int ImStrlenW(const ImWchar* str); // Computer string length (ImWchar string) IMGUI_API const char* ImStrbol(const char* buf_mid_line, const char* buf_begin); // Find beginning-of-line IM_MSVC_RUNTIME_CHECKS_OFF +inline int ImStrcmp(const char* str1, const char* str2) { return strcmp(str1, str2); } inline char ImToUpper(char c) { return (c >= 'a' && c <= 'z') ? c & ~32 : c; } inline bool ImCharIsBlankA(char c) { return c == ' ' || c == '\t'; } inline bool ImCharIsBlankW(unsigned int c) { return c == ' ' || c == '\t' || c == 0x3000; } @@ -417,8 +424,8 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE // Helpers: Formatting IMGUI_API int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...) IM_FMTARGS(3); IMGUI_API int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args) IM_FMTLIST(3); -IMGUI_API void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...) IM_FMTARGS(3); -IMGUI_API void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args) IM_FMTLIST(3); +IMGUI_API void ImFormatStringToTempBuffer(ImStrv* out_buf, const char* fmt, ...) IM_FMTARGS(2); +IMGUI_API void ImFormatStringToTempBufferV(ImStrv* out_buf, const char* fmt, va_list args) IM_FMTLIST(2); IMGUI_API const char* ImParseFormatFindStart(const char* format); IMGUI_API const char* ImParseFormatFindEnd(const char* format); IMGUI_API const char* ImParseFormatTrimDecorations(const char* format, char* buf, size_t buf_size); @@ -436,7 +443,7 @@ IMGUI_API int ImTextCountUtf8BytesFromChar(const char* in_text, const IMGUI_API int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end); // return number of bytes to express string in UTF-8 IMGUI_API const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_p); // return previous UTF-8 code-point. IMGUI_API const char* ImTextFindValidUtf8CodepointEnd(const char* in_text_start, const char* in_text_end, const char* in_p); // return previous UTF-8 code-point if 'in_p' is not the end of a valid one. -IMGUI_API int ImTextCountLines(const char* in_text, const char* in_text_end); // return number of lines taken by text. trailing carriage return doesn't count as an extra line. +IMGUI_API int ImTextCountLines(ImStrv in_text); // return number of lines taken by text. trailing carriage return doesn't count as an extra line. // Helpers: High-level text functions (DO NOT USE!!! THIS IS A MINIMAL SUBSET OF LARGER UPCOMING CHANGES) enum ImDrawTextFlags_ @@ -464,7 +471,7 @@ IMGUI_API void ImTextClassifierSetCharClassFromStr(ImU32* bits, unsigne #ifdef IMGUI_DISABLE_FILE_FUNCTIONS #define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS typedef void* ImFileHandle; -inline ImFileHandle ImFileOpen(const char*, const char*) { return NULL; } +inline ImFileHandle ImFileOpen(ImStrv, ImStrv) { return NULL; } inline bool ImFileClose(ImFileHandle) { return false; } inline ImU64 ImFileGetSize(ImFileHandle) { return (ImU64)-1; } inline ImU64 ImFileRead(void*, ImU64, ImU64, ImFileHandle) { return 0; } @@ -472,7 +479,7 @@ inline ImU64 ImFileWrite(const void*, ImU64, ImU64, ImFileHandle) #endif #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS typedef FILE* ImFileHandle; -IMGUI_API ImFileHandle ImFileOpen(const char* filename, const char* mode); +IMGUI_API ImFileHandle ImFileOpen(ImStrv filename, ImStrv mode); IMGUI_API bool ImFileClose(ImFileHandle file); IMGUI_API ImU64 ImFileGetSize(ImFileHandle file); IMGUI_API ImU64 ImFileRead(void* data, ImU64 size, ImU64 count, ImFileHandle file); @@ -480,7 +487,7 @@ IMGUI_API ImU64 ImFileWrite(const void* data, ImU64 size, ImU64 coun #else #define IMGUI_DISABLE_TTY_FUNCTIONS // Can't use stdout, fflush if we are not using default file functions #endif -IMGUI_API void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size = NULL, int padding_bytes = 0); +IMGUI_API void* ImFileLoadToMemory(ImStrv filename, ImStrv mode, size_t* out_file_size = NULL, int padding_bytes = 0); // Helpers: Maths IM_MSVC_RUNTIME_CHECKS_OFF @@ -531,9 +538,6 @@ template T ImLerp(T a, T b, float t) { return template void ImSwap(T& a, T& b) { T tmp = a; a = b; b = tmp; } template T ImAddClampOverflow(T a, T b, T mn, T mx) { if (b < 0 && (a < mn - b)) return mn; if (b > 0 && (a > mx - b)) return mx; return a + b; } template T ImSubClampOverflow(T a, T b, T mn, T mx) { if (b > 0 && (a < mn + b)) return mn; if (b < 0 && (a > mx + b)) return mx; return a - b; } -inline float ImMod(float a, float b) { return ImFmod(a, b); } -inline double ImMod(double a, double b) { return (double)ImFmod((float)a, (float)b); } // FIXME -template T ImMod(T a, T b) { return a % b; } // - Misc maths helpers inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x < rhs.x ? lhs.x : rhs.x, lhs.y < rhs.y ? lhs.y : rhs.y); } inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x >= rhs.x ? lhs.x : rhs.x, lhs.y >= rhs.y ? lhs.y : rhs.y); } @@ -545,15 +549,12 @@ inline float ImSaturate(float f) { return inline float ImLengthSqr(const ImVec2& lhs) { return (lhs.x * lhs.x) + (lhs.y * lhs.y); } inline float ImLengthSqr(const ImVec4& lhs) { return (lhs.x * lhs.x) + (lhs.y * lhs.y) + (lhs.z * lhs.z) + (lhs.w * lhs.w); } inline float ImInvLength(const ImVec2& lhs, float fail_value) { float d = (lhs.x * lhs.x) + (lhs.y * lhs.y); if (d > 0.0f) return ImRsqrt(d); return fail_value; } -inline float ImTrunc(float f) { return (float)(int)(f); } // == IM_TRUNC() +inline float ImTrunc(float f) { return (float)(int)(f); } inline ImVec2 ImTrunc(const ImVec2& v) { return ImVec2((float)(int)(v.x), (float)(int)(v.y)); } -inline float ImTrunc64(float f) { return (float)(ImS64)(f); } inline float ImFloor(float f) { return (float)((f >= 0 || (float)(int)f == f) ? (int)f : (int)f - 1); } // Decent replacement for floorf() inline ImVec2 ImFloor(const ImVec2& v) { return ImVec2(ImFloor(v.x), ImFloor(v.y)); } -inline float ImRoundPositive(float f) { return (float)(int)(f + 0.5f); } // == IM_ROUND(). Positive values only. +inline float ImTrunc64(float f) { return (float)(ImS64)(f); } inline float ImRoundPositive64(float f) { return (float)(ImS64)(f + 0.5f); } // Positive values only. -inline float ImRoundSigned(float f) { return (float)(int)(f >= 0.0f ? f + 0.5f : f - 0.5f); } -inline ImVec2 ImRoundSigned(const ImVec2& v) { return ImVec2((float)(int)(v.x >= 0.0f ? v.x + 0.5f : v.x - 0.5f), (float)(int)(v.y >= 0.0f ? v.y + 0.5f : v.y - 0.5f)); } inline float ImRoundSigned64(float f) { return (float)(ImS64)(f >= 0.0f ? f + 0.5f : f - 0.5f); } inline float ImCeilFast(float f) { int i = (int)f; return (float)(i + (f > (float)i)); } // Consider using the bit-hack version (search for "0x1p120f"). inline int ImModPositive(int a, int b) { return (a + b) % b; } @@ -658,7 +659,6 @@ struct IMGUI_API ImRect void TranslateY(float dy) { Min.y += dy; Max.y += dy; } void ClipWith(const ImRect& r) { Min = ImMax(Min, r.Min); Max = ImMin(Max, r.Max); } // Simple version, may lead to an inverted rectangle, which is fine for Contains/Overlaps test but not for display. void ClipWithFull(const ImRect& r) { Min = ImClamp(Min, r.Min, r.Max); Max = ImClamp(Max, r.Min, r.Max); } // Full version, ensure both points are fully clipped. - void ShrinkClamp(const ImVec2& inset_min, const ImVec2& inset_max) { Min.x = ImMin(Min.x + inset_min.x, Max.x); Min.y = ImMin(Min.y + inset_min.y, Max.y); Max.x = ImMax(Max.x - inset_max.x, Min.x); Max.y = ImMax(Max.y - inset_max.y, Min.y); } bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; } ImVec4 ToVec4() const { return ImVec4(Min.x, Min.y, Max.x, Max.y); } const ImVec4& AsVec4() const { return *(const ImVec4*)&Min.x; } @@ -2161,7 +2161,6 @@ enum ImGuiLocKey : int //ImGuiLocKey_TableResetAll, ImGuiLocKey_TableResetOrder, ImGuiLocKey_TableResetVisibility, - ImGuiLocKey_TableResetSizing, ImGuiLocKey_WindowingMainMenuBar, ImGuiLocKey_WindowingPopup, ImGuiLocKey_WindowingUntitled, @@ -2898,10 +2897,12 @@ struct IMGUI_API ImGuiWindow bool MemoryCompacted; // Set when window extraneous data have been garbage collected public: - ImGuiWindow(ImGuiContext* context, const char* name); + ImGuiWindow(ImGuiContext* context, ImStrv name); ~ImGuiWindow(); - ImGuiID GetID(const char* str, const char* str_end = NULL); + ImGuiID GetID(ImStrv str); + ImGuiID GetID(const char* str) { return GetID(ImStrv(str)); } + ImGuiID GetID(const char* str, const char* str_end) { return GetID(ImStrv(str, str_end)); } ImGuiID GetID(const void* ptr); ImGuiID GetID(int n); ImGuiID GetIDFromPos(const ImVec2& p_abs); @@ -2943,7 +2944,7 @@ struct ImGuiTabItem { ImGuiID ID; ImGuiTabItemFlags Flags; - int LastFrameVisible; // TabItem visibility (not contents visibility) + int LastFrameVisible; int LastFrameSelected; // This allows us to infer an ordered list of the last activated tabs with little maintenance float Offset; // Position relative to beginning of tab bar float Width; // Width currently displayed @@ -2953,7 +2954,6 @@ struct ImGuiTabItem ImS16 BeginOrder; // BeginTabItem() order, used to re-order tabs after toggling ImGuiTabBarFlags_Reorderable ImS16 IndexDuringLayout; // Index only used during TabBarLayout(). Tabs gets reordered so 'Tabs[n].IndexDuringLayout == n' but may mismatch during additions. bool WantClose; // Marked as closed by SetTabItemClosed() - bool ContentsIsVisible; ImGuiTabItem() { memset((void*)this, 0, sizeof(*this)); LastFrameVisible = LastFrameSelected = -1; RequestedWidth = -1.0f; NameOffset = -1; BeginOrder = IndexDuringLayout = -1; } }; @@ -2968,7 +2968,7 @@ struct IMGUI_API ImGuiTabBar ImGuiID SelectedTabId; // Selected tab/window ImGuiID NextSelectedTabId; // Next selected tab/window. Will also trigger a scrolling animation ImGuiID NextScrollToTabId; - ImGuiID VisibleTabContentsId; // Can occasionally be != SelectedTabId (e.g. when previewing contents for Ctrl+Tab preview) + ImGuiID VisibleTabId; // Can occasionally be != SelectedTabId (e.g. when previewing contents for Ctrl+Tab preview) int CurrFrameVisible; int PrevFrameVisible; ImRect BarRect; @@ -2990,7 +2990,6 @@ struct IMGUI_API ImGuiTabBar ImS8 BeginCount; bool WantLayout; bool VisibleTabWasSubmitted; - bool LastTabItemContentsAppearing; bool TabsAddedNew; // Set to true when a new tab item or button has been added to the tab bar during last frame bool ScrollButtonEnabled; ImS16 TabsActiveCount; // Number of tabs submitted this frame. @@ -3163,7 +3162,6 @@ struct IMGUI_API ImGuiTable ImU32 BorderColorLight; float BorderX1; float BorderX2; - float BorderSize; float HostIndentX; float MinColumnWidth; float OuterPaddingX; @@ -3242,7 +3240,6 @@ struct IMGUI_API ImGuiTable bool IsResetAllRequest; // Set to queue a call to TableResetSettings() in BeginTable() bool IsResetDisplayOrderRequest; bool IsResetVisibilityRequest; - bool IsResetSizesRequest; bool IsUnfrozenRows; // Set when we got past the frozen row. bool IsDefaultSizingPolicy; // Set if user didn't explicitly set a sizing policy in BeginTable() bool IsActiveIdAliveBeforeTable; @@ -3267,7 +3264,6 @@ struct IMGUI_API ImGuiTableTempData int TableIndex; // Index in g.Tables.Buf[] pool float LastTimeActive; // Last timestamp this structure was used float AngledHeadersExtraWidth; // Used in EndTable() - ImRect BorderOuterSizes; ImVector AngledHeadersRequests; // Used in TableAngledHeadersRow() // FIXME: Single instance is enough? // Topology change @@ -3286,7 +3282,6 @@ struct IMGUI_API ImGuiTableTempData ImVec1 HostBackupColumnsOffset; // Backup of OuterWindow->DC.ColumnsOffset at the end of BeginTable() float HostBackupItemWidth; // Backup of OuterWindow->DC.ItemWidth at the end of BeginTable() int HostBackupItemWidthStackSize;//Backup of OuterWindow->DC.ItemWidthStack.Size at the end of BeginTable() - ImGuiLayoutType HostBackupLayoutType; // Backup of InnerWindow->DC.LayoutType at the end of BeginTable() ImGuiTableTempData() { memset((void*)this, 0, sizeof(*this)); LastTimeActive = -1.0f; } }; @@ -3350,7 +3345,7 @@ namespace ImGui // Tables: Internals inline ImGuiTable* GetCurrentTable() { ImGuiContext& g = *GImGui; return g.CurrentTable; } IMGUI_API ImGuiTable* TableFindByID(ImGuiID id); - IMGUI_API bool BeginTableEx(const char* name, ImGuiID id, int columns_count, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0, 0), float inner_width = 0.0f); + IMGUI_API bool BeginTableEx(ImStrv name, ImGuiID id, int columns_count, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0, 0), float inner_width = 0.0f); IMGUI_API void TableBeginInitMemory(ImGuiTable* table, int columns_count); IMGUI_API void TableApplyQueuedRequests(ImGuiTable* table); IMGUI_API void TableSetupDrawChannels(ImGuiTable* table); @@ -3402,12 +3397,12 @@ namespace ImGui // Legacy Columns API (this is not exposed because we will encourage transitioning to the Tables API) IMGUI_API void SetWindowClipRectBeforeSetChannel(ImGuiWindow* window, const ImRect& clip_rect); - IMGUI_API void BeginColumns(const char* str_id, int count, ImGuiOldColumnFlags flags = 0); // setup number of columns. use an identifier to distinguish multiple column sets. close with EndColumns(). + IMGUI_API void BeginColumns(ImStrv str_id, int count, ImGuiOldColumnFlags flags = 0); // setup number of columns. use an identifier to distinguish multiple column sets. close with EndColumns(). IMGUI_API void EndColumns(); // close columns IMGUI_API void PushColumnClipRect(int column_index); IMGUI_API void PushColumnsBackground(); IMGUI_API void PopColumnsBackground(); - IMGUI_API ImGuiID GetColumnsID(const char* str_id, int count); + IMGUI_API ImGuiID GetColumnsID(ImStrv str_id, int count); IMGUI_API ImGuiOldColumns* FindOrCreateColumns(ImGuiWindow* window, ImGuiID id); IMGUI_API float GetColumnOffsetFromNorm(const ImGuiOldColumns* columns, float offset_norm); IMGUI_API float GetColumnNormFromOffset(const ImGuiOldColumns* columns, float offset); @@ -3431,7 +3426,7 @@ namespace ImGui inline ImGuiWindow* GetCurrentWindowRead() { ImGuiContext& g = *GImGui; return g.CurrentWindow; } inline ImGuiWindow* GetCurrentWindow() { ImGuiContext& g = *GImGui; g.CurrentWindow->WriteAccessed = true; return g.CurrentWindow; } IMGUI_API ImGuiWindow* FindWindowByID(ImGuiID id); - IMGUI_API ImGuiWindow* FindWindowByName(const char* name); + IMGUI_API ImGuiWindow* FindWindowByName(ImStrv name); IMGUI_API void UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window); IMGUI_API void UpdateWindowSkipRefresh(ImGuiWindow* window); IMGUI_API ImVec2 CalcWindowNextAutoFitSize(ImGuiWindow* window); @@ -3502,7 +3497,6 @@ namespace ImGui IMGUI_API void StopMouseMovingWindow(); IMGUI_API void UpdateMouseMovingWindowNewFrame(); IMGUI_API void UpdateMouseMovingWindowEndFrame(); - IMGUI_API ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1); // Viewports inline ImGuiViewport* GetWindowViewport() { return GetMainViewport(); } // For code consistency. This is public API in docking branch. @@ -3515,14 +3509,14 @@ namespace ImGui IMGUI_API void ClearIniSettings(); IMGUI_API void CleanupIniSettings(ImGuiSettingsCleanupArgs* args); // [BETA] Expected to turn into a public API. Please report if you are using this! IMGUI_API void AddSettingsHandler(const ImGuiSettingsHandler* handler); - IMGUI_API void RemoveSettingsHandler(const char* type_name); - IMGUI_API ImGuiSettingsHandler* FindSettingsHandler(const char* type_name); + IMGUI_API void RemoveSettingsHandler(ImStrv type_name); + IMGUI_API ImGuiSettingsHandler* FindSettingsHandler(ImStrv type_name); // Settings - Windows - IMGUI_API ImGuiWindowSettings* CreateNewWindowSettings(const char* name); + IMGUI_API ImGuiWindowSettings* CreateNewWindowSettings(ImStrv name); IMGUI_API ImGuiWindowSettings* FindWindowSettingsByID(ImGuiID id); IMGUI_API ImGuiWindowSettings* FindWindowSettingsByWindow(ImGuiWindow* window); - IMGUI_API void ClearWindowSettings(const char* name); + IMGUI_API void ClearWindowSettings(ImStrv name); // Localization IMGUI_API void LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count); @@ -3579,16 +3573,17 @@ namespace ImGui // Logging/Capture IMGUI_API void LogBegin(ImGuiLogFlags flags, int auto_open_depth); // -> BeginCapture() when we design v2 api, for now stay under the radar by using the old name. IMGUI_API void LogToBuffer(int auto_open_depth = -1); // Start logging/capturing to internal buffer - IMGUI_API void LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end = NULL); + IMGUI_API void LogRenderedText(const ImVec2* ref_pos, ImStrv text); + inline void LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end) { LogRenderedText(ref_pos, ImStrv(text, text_end)); } IMGUI_API void LogSetNextTextDecoration(const char* prefix, const char* suffix); // Childs - IMGUI_API bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags); + IMGUI_API bool BeginChildEx(ImStrv name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags); IMGUI_API ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window); // Popups, Modals IMGUI_API bool BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_window_flags); - IMGUI_API bool BeginPopupMenuEx(ImGuiID id, const char* label, ImGuiWindowFlags extra_window_flags); + IMGUI_API bool BeginPopupMenuEx(ImGuiID id, ImStrv label, ImGuiWindowFlags extra_window_flags); IMGUI_API bool OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags = ImGuiPopupFlags_None); IMGUI_API void ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup); IMGUI_API void ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup); @@ -3609,9 +3604,9 @@ namespace ImGui IMGUI_API bool BeginTooltipHidden(); // Menus - IMGUI_API bool BeginViewportSideBar(const char* name, ImGuiViewport* viewport, ImGuiDir dir, float size, ImGuiWindowFlags window_flags); - IMGUI_API bool BeginMenuEx(const char* label, const char* icon, bool enabled = true); - IMGUI_API bool MenuItemEx(const char* label, const char* icon, const char* shortcut = NULL, bool selected = false, bool enabled = true); + IMGUI_API bool BeginViewportSideBar(ImStrv name, ImGuiViewport* viewport, ImGuiDir dir, float size, ImGuiWindowFlags window_flags); + IMGUI_API bool BeginMenuEx(ImStrv label, ImStrv icon, bool enabled = true); + IMGUI_API bool MenuItemEx(ImStrv label, ImStrv icon, ImStrv shortcut = ImStrv(), bool selected = false, bool enabled = true); // Combos IMGUI_API bool BeginComboPopup(ImGuiID popup_id, const ImRect& bb, ImGuiComboFlags flags); @@ -3789,22 +3784,25 @@ namespace ImGui IMGUI_API void TabBarQueueReorder(ImGuiTabBar* tab_bar, ImGuiTabItem* tab, int offset); IMGUI_API void TabBarQueueReorderFromMousePos(ImGuiTabBar* tab_bar, ImGuiTabItem* tab, ImVec2 mouse_pos); IMGUI_API bool TabBarProcessReorder(ImGuiTabBar* tab_bar); - IMGUI_API bool TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags, ImGuiWindow* docked_window); - IMGUI_API bool TabItemIsContentsAppearing(); - IMGUI_API void TabItemSpacing(const char* str_id, ImGuiTabItemFlags flags, float width); - IMGUI_API ImVec2 TabItemCalcSize(const char* label, bool has_close_button_or_unsaved_marker); + IMGUI_API bool TabItemEx(ImGuiTabBar* tab_bar, ImStrv label, bool* p_open, ImGuiTabItemFlags flags, ImGuiWindow* docked_window); + IMGUI_API void TabItemSpacing(ImStrv str_id, ImGuiTabItemFlags flags, float width); + IMGUI_API ImVec2 TabItemCalcSize(ImStrv label, bool has_close_button_or_unsaved_marker); IMGUI_API ImVec2 TabItemCalcSize(ImGuiWindow* window); IMGUI_API void TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImU32 col); - IMGUI_API void TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id, bool is_contents_visible, bool* out_just_closed, bool* out_text_clipped); + IMGUI_API void TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, ImStrv label, ImGuiID tab_id, ImGuiID close_button_id, bool is_contents_visible, bool* out_just_closed, bool* out_text_clipped); // Render helpers // AVOID USING OUTSIDE OF IMGUI.CPP! NOT FOR PUBLIC CONSUMPTION. THOSE FUNCTIONS ARE A MESS. THEIR SIGNATURE AND BEHAVIOR WILL CHANGE, THEY NEED TO BE REFACTORED INTO SOMETHING DECENT. // NB: All position are in absolute pixels coordinates (we are never using window coordinates internally) - IMGUI_API void RenderText(ImVec2 pos, const char* text, const char* text_end = NULL, bool hide_text_after_hash = true); - IMGUI_API void RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width); - IMGUI_API void 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 = ImVec2(0, 0), const ImRect* clip_rect = NULL); - IMGUI_API void RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0, 0), const ImRect* clip_rect = NULL); - IMGUI_API void RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float ellipsis_max_x, const char* text, const char* text_end, const ImVec2* text_size_if_known); + IMGUI_API void RenderText(ImVec2 pos, ImStrv text, bool hide_text_after_hash = true); + inline void RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash = true) { RenderText(pos, ImStrv(text, text_end), hide_text_after_hash); } + IMGUI_API void RenderTextWrapped(ImVec2 pos, ImStrv text, float wrap_width); + inline void RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width) { RenderTextWrapped(pos, ImStrv(text, text_end), wrap_width); } + IMGUI_API void RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, ImStrv text, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0, 0), const ImRect* clip_rect = NULL); + inline void 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 = ImVec2(0,0), const ImRect* clip_rect = NULL) { RenderTextClipped(pos_min, pos_max, ImStrv(text, text_end), text_size_if_known, align, clip_rect); } + IMGUI_API void RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, ImStrv text, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0, 0), const ImRect* clip_rect = NULL); + inline void RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0, 0), const ImRect* clip_rect = NULL) { RenderTextClippedEx(draw_list, pos_min, pos_max, ImStrv(text, text_end), text_size_if_known, align, clip_rect); } + IMGUI_API void RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float ellipsis_max_x, ImStrv text, const ImVec2* text_size_if_known); IMGUI_API void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool borders = true, float rounding = 0.0f); IMGUI_API void RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding = 0.0f); IMGUI_API void RenderColorComponentMarker(const ImRect& bb, ImU32 col, float rounding); @@ -3813,31 +3811,33 @@ namespace ImGui #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS inline void RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavRenderCursorFlags flags = ImGuiNavRenderCursorFlags_None) { RenderNavCursor(bb, id, flags); } // Renamed in 1.91.4 #endif - IMGUI_API const char* FindRenderedTextEnd(const char* text, const char* text_end = NULL); // Find the optional ## from which we stop displaying text. + IMGUI_API const char* FindRenderedTextEnd(ImStrv text); // Find the optional ## from which we stop displaying text. + inline const char* FindRenderedTextEnd(const char* text, const char* text_end) { return FindRenderedTextEnd(ImStrv(text, text_end)); } IMGUI_API void RenderMouseCursor(ImVec2 pos, float scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow); // Render helpers (those functions don't access any ImGui state!) IMGUI_API void RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale = 1.0f); - IMGUI_API void RenderArrowEx(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float cos_a, float sin_a, float scale, ImVec2 arrow_sizes, float arrow_th); IMGUI_API void RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col); IMGUI_API void RenderCheckMark(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float sz); + IMGUI_API void RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col); IMGUI_API void RenderRectFilledInRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float fill_x0, float fill_x1, float rounding); IMGUI_API void RenderRectFilledWithHole(ImDrawList* draw_list, const ImRect& outer, const ImRect& inner, ImU32 col, float rounding); IMGUI_API ImDrawFlags CalcRoundingFlagsForRectInRect(const ImRect& r_in, const ImRect& r_outer, float threshold); // Widgets: Text - IMGUI_API void TextEx(const char* text, const char* text_end = NULL, ImGuiTextFlags flags = 0); - IMGUI_API void TextAligned(float align_x, float width, const char* fmt, ...) IM_FMTARGS(3); // FIXME-WIP: Works but API is likely to be reworked. - IMGUI_API void TextAlignedV(float align_x, float width, const char* fmt, va_list args) IM_FMTLIST(3); + IMGUI_API void TextEx(ImStrv text, ImGuiTextFlags flags = 0); + inline void TextEx(const char* text, const char* text_end, ImGuiTextFlags flags = 0) { TextEx(ImStrv(text, text_end), flags); } + IMGUI_API void TextAligned(float align_x, float size_x, const char* fmt, ...); // FIXME-WIP: Works but API is likely to be reworked. + IMGUI_API void TextAlignedV(float align_x, float size_x, const char* fmt, va_list args); // Widgets - IMGUI_API bool ButtonEx(const char* label, const ImVec2& size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0); - IMGUI_API bool ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size_arg, ImGuiButtonFlags flags = 0); + IMGUI_API bool ButtonEx(ImStrv label, const ImVec2& size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0); + IMGUI_API bool ArrowButtonEx(ImStrv str_id, ImGuiDir dir, ImVec2 size_arg, ImGuiButtonFlags flags = 0); IMGUI_API bool ImageButtonEx(ImGuiID id, ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col, ImGuiButtonFlags flags = 0); IMGUI_API void SeparatorEx(ImGuiSeparatorFlags flags, float thickness = 1.0f); - IMGUI_API void SeparatorTextEx(ImGuiID id, const char* label, const char* label_end, float extra_width); - IMGUI_API bool CheckboxFlags(const char* label, ImS64* flags, ImS64 flags_value); - IMGUI_API bool CheckboxFlags(const char* label, ImU64* flags, ImU64 flags_value); + IMGUI_API void SeparatorTextEx(ImGuiID id, ImStrv label, float extra_width); + IMGUI_API bool CheckboxFlags(ImStrv label, ImS64* flags, ImS64 flags_value); + IMGUI_API bool CheckboxFlags(ImStrv label, ImU64* flags, ImU64 flags_value); // Widgets: Window Decorations IMGUI_API bool CloseButton(ImGuiID id, const ImVec2& pos); @@ -3857,7 +3857,7 @@ namespace ImGui IMGUI_API bool SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend = 0.0f, float hover_visibility_delay = 0.0f, ImU32 bg_col = 0); // Widgets: Tree Nodes - IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL); + IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, ImStrv label); IMGUI_API void TreeNodeDrawLineToChildNode(const ImVec2& target_pos); IMGUI_API void TreeNodeDrawLineToTreePop(const ImGuiTreeNodeStackData* data); IMGUI_API void TreePushOverrideID(ImGuiID id); @@ -3872,7 +3872,7 @@ namespace ImGui template IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, ImGuiSliderFlags flags); template IMGUI_API bool SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, T* v, T v_min, T v_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb); template IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v); - template IMGUI_API bool CheckboxFlagsT(const char* label, T* flags, T flags_value); + template IMGUI_API bool CheckboxFlagsT(ImStrv label, T* flags, T flags_value); // Data type helpers IMGUI_API const ImGuiDataTypeInfo* DataTypeGetInfo(ImGuiDataType data_type); @@ -3884,23 +3884,23 @@ namespace ImGui IMGUI_API bool DataTypeIsZero(ImGuiDataType data_type, const void* p_data); // InputText - IMGUI_API bool InputTextEx(const char* label, const char* hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputTextEx(ImStrv label, ImStrv hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); IMGUI_API void InputTextDeactivateHook(ImGuiID id); - IMGUI_API bool TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); - IMGUI_API bool TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min = NULL, const void* p_clamp_max = NULL); + IMGUI_API bool TempInputText(const ImRect& bb, ImGuiID id, ImStrv label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool TempInputScalar(const ImRect& bb, ImGuiID id, ImStrv label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min = NULL, const void* p_clamp_max = NULL); inline bool TempInputIsActive(ImGuiID id) { ImGuiContext& g = *GImGui; return (g.TempInputId == id && g.ActiveId == id) || (g.InputTextDeactivatedState.ID == id); } inline ImGuiInputTextState* GetInputTextState(ImGuiID id) { ImGuiContext& g = *GImGui; return (id != 0 && g.InputTextState.ID == id) ? &g.InputTextState : NULL; } // Get input text state if active IMGUI_API void SetNextItemRefVal(ImGuiDataType data_type, void* p_data); inline bool IsItemActiveAsInputText() { ImGuiContext& g = *GImGui; return g.ActiveId != 0 && g.ActiveId == g.LastItemData.ID && g.InputTextState.ID == g.LastItemData.ID; } // This may be useful to apply workaround that a based on distinguish whenever an item is active as a text input field. // Color - IMGUI_API void ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags); + IMGUI_API void ColorTooltip(ImStrv text, const float* col, ImGuiColorEditFlags flags); IMGUI_API void ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags); IMGUI_API void ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags flags); inline void SetNextItemColorMarker(ImU32 col) { ImGuiContext& g = *GImGui; g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasColorMarker; g.NextItemData.ColorMarker = col; } // Plot - IMGUI_API int 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, const ImVec2& size_arg); + IMGUI_API int PlotEx(ImGuiPlotType plot_type, ImStrv label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, ImStrv overlay_text, float scale_min, float scale_max, const ImVec2& size_arg); // Shade functions (write over already created vertices) IMGUI_API void ShadeVertsLinearColorGradientKeepAlpha(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, ImVec2 gradient_p0, ImVec2 gradient_p1, ImU32 col0, ImU32 col1); @@ -4089,8 +4089,7 @@ struct ImFontAtlasBuilder ImVec2i MaxRectSize; // Largest rectangle to pack (de-facto used as a "minimum texture size") ImVec2i MaxRectBounds; // Bottom-right most used pixels bool LockDisableResize; // Disable resizing texture - bool PreloadedAllGlyphsRanges; // Set when missing ImGuiBackendFlags_RendererHasTextures features forces atlas to preload everything. - ImS8 LoadedFontDefaultAsVector; // -1, or record with 0/1 whereas AddFontDefault() picked bitmap or vector font. + bool PreloadedAllGlyphsRanges; // Set when missing ImGuiBackendFlags_RendererHasTextures features forces atlas to preload everything. // Cache of all ImFontBaked ImStableVector BakedPool; @@ -4107,7 +4106,7 @@ struct ImFontAtlasBuilder ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_COUNT]; // UVs for baked anti-aliased lines (u0, u1, v, 1/thickness) ImVec4 TexUvCorners[IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX * IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX]; // UVs for baked anti-aliased corners (0= fill, 1> stroke thickness) - ImFontAtlasBuilder() { memset((void*)this, 0, sizeof(*this)); FrameCount = -1; RectsIndexFreeListStart = -1; LoadedFontDefaultAsVector = -1; PackIdMouseCursors = PackIdLinesTexData = PackIdLineFractTexData = PackIdCornersTexData = -1; } + ImFontAtlasBuilder() { memset((void*)this, 0, sizeof(*this)); FrameCount = -1; RectsIndexFreeListStart = -1; PackIdMouseCursors = PackIdLinesTexData = PackIdLineFractTexData = PackIdCornersTexData = -1; } }; IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas); @@ -4162,7 +4161,6 @@ IMGUI_API void ImFontAtlasAddDrawListSharedData(ImFontAtlas* atlas, IMGUI_API void ImFontAtlasRemoveDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data); IMGUI_API void ImFontAtlasUpdateDrawListsTextures(ImFontAtlas* atlas, ImTextureRef old_tex, ImTextureRef new_tex); IMGUI_API void ImFontAtlasUpdateDrawListsSharedData(ImFontAtlas* atlas); -IMGUI_API bool ImFontAtlasHeuristicShouldUseDefaultVectorFont(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasTextureBlockConvert(const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch, unsigned char* dst_pixels, ImTextureFormat dst_fmt, int dst_pitch, int w, int h); IMGUI_API void ImFontAtlasTextureBlockPostProcess(ImFontAtlasPostProcessData* data); @@ -4189,7 +4187,7 @@ IMGUI_API bool ImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas, ImGuiMo #ifdef IMGUI_ENABLE_TEST_ENGINE extern void ImGuiTestEngineHook_ItemAdd(ImGuiContext* ctx, ImGuiID id, const ImRect& bb, const ImGuiLastItemData* item_data); // item_data may be NULL -extern void ImGuiTestEngineHook_ItemInfo(ImGuiContext* ctx, ImGuiID id, const char* label, ImGuiItemStatusFlags flags); +extern void ImGuiTestEngineHook_ItemInfo(ImGuiContext* ctx, ImGuiID id, ImStrv label, ImGuiItemStatusFlags flags); extern void ImGuiTestEngineHook_Log(ImGuiContext* ctx, const char* fmt, ...); extern const char* ImGuiTestEngine_FindItemDebugLabel(ImGuiContext* ctx, ImGuiID id); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 820b4dde4..8d449136c 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -312,13 +312,13 @@ ImGuiTable* ImGui::TableFindByID(ImGuiID id) } // Read about "TABLE SIZING" at the top of this file. -bool ImGui::BeginTable(const char* str_id, int columns_count, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width) +bool ImGui::BeginTable(ImStrv str_id, int columns_count, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width) { ImGuiID id = GetID(str_id); return BeginTableEx(str_id, id, columns_count, flags, outer_size, inner_width); } -bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width) +bool ImGui::BeginTableEx(ImStrv name, ImGuiID id, int columns_count, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width) { ImGuiContext& g = *GImGui; ImGuiWindow* outer_window = GetCurrentWindow(); @@ -476,28 +476,31 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG temp_data->HostBackupCursorMaxPos = inner_window->DC.CursorMaxPos; temp_data->HostBackupItemWidth = outer_window->DC.ItemWidth; temp_data->HostBackupItemWidthStackSize = outer_window->DC.ItemWidthStack.Size; - temp_data->HostBackupLayoutType = inner_window->DC.LayoutType; inner_window->DC.PrevLineSize = inner_window->DC.CurrLineSize = ImVec2(0.0f, 0.0f); - inner_window->DC.LayoutType = ImGuiLayoutType_Vertical; - // Border size - // FIXME-WIP: Changing this is not currently simple due to ClipRect requirements. Easier to manage with new 1.93 primitives though. - const float border_size = table->BorderSize = TABLE_BORDER_SIZE; - // Make borders not overlap our contents by offsetting HostClipRect (#6765, #7428, #3752) - // - We normally shouldn't alter HostClipRect as we rely on TableMergeDrawChannels() expanding non-clipped column toward the - // limits of that rectangle, in order for ImDrawListSplitter::Merge() to merge the draw commands. However since the overlap - // problem only affect scrolling tables in this case we can get away with doing it without extra cost). - // - (FIXME: Because inner_window's Scrollbar doesn't know about border size, since it's not encoded in window->WindowBorderSize, - // it already overlaps it and doesn't need an extra offset. Ideally we should be able to pass custom border size with - // different x/y values to BeginChild().) - // - For non-scrolling window, this is applied to table->InnerClipRect below. - temp_data->BorderOuterSizes.Min.x = (flags & ImGuiTableFlags_BordersOuterV) ? border_size : 0.0f; - temp_data->BorderOuterSizes.Min.y = (flags & ImGuiTableFlags_BordersOuterH) ? border_size : 0.0f; - temp_data->BorderOuterSizes.Max.x = ((flags & ImGuiTableFlags_BordersOuterV) && ((inner_window == outer_window) || inner_window->DecoOuterSizeX2 == 0.0f)) ? border_size : 0.0f; - temp_data->BorderOuterSizes.Max.y = ((flags & ImGuiTableFlags_BordersOuterH) && ((inner_window == outer_window) || inner_window->DecoOuterSizeY2 == 0.0f)) ? border_size : 0.0f; + // (we normally shouldn't alter HostClipRect as we rely on TableMergeDrawChannels() expanding non-clipped column toward the + // limits of that rectangle, in order for ImDrawListSplitter::Merge() to merge the draw commands. However since the overlap + // problem only affect scrolling tables in this case we can get away with doing it without extra cost). if (inner_window != outer_window) - table->HostClipRect.ShrinkClamp(temp_data->BorderOuterSizes.Min, temp_data->BorderOuterSizes.Max); + { + // FIXME: Because inner_window's Scrollbar doesn't know about border size, since it's not encoded in window->WindowBorderSize, + // it already overlaps it and doesn't need an extra offset. Ideally we should be able to pass custom border size with + // different x/y values to BeginChild(). + const float border_size = TABLE_BORDER_SIZE; + if (flags & ImGuiTableFlags_BordersOuterV) + { + table->HostClipRect.Min.x = ImMin(table->HostClipRect.Min.x + border_size, table->HostClipRect.Max.x); + if (inner_window->DecoOuterSizeX2 == 0.0f) + table->HostClipRect.Max.x = ImMax(table->HostClipRect.Max.x - border_size, table->HostClipRect.Min.x); + } + if (flags & ImGuiTableFlags_BordersOuterH) + { + table->HostClipRect.Min.y = ImMin(table->HostClipRect.Min.y + border_size, table->HostClipRect.Max.y); + if (inner_window->DecoOuterSizeY2 == 0.0f) + table->HostClipRect.Max.y = ImMax(table->HostClipRect.Max.y - border_size, table->HostClipRect.Min.y); + } + } // Padding and Spacing // - None ........Content..... Pad .....Content........ @@ -506,22 +509,29 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG // - PadOuter+PadInner | Pad ..Content.. Pad | Pad ..Content.. Pad | const bool pad_outer_x = (flags & ImGuiTableFlags_NoPadOuterX) ? false : (flags & ImGuiTableFlags_PadOuterX) ? true : (flags & ImGuiTableFlags_BordersOuterV) != 0; const bool pad_inner_x = (flags & ImGuiTableFlags_NoPadInnerX) ? false : true; - const float inner_spacing_for_border = (flags & ImGuiTableFlags_BordersInnerV) ? border_size : 0.0f; + const float inner_spacing_for_border = (flags & ImGuiTableFlags_BordersInnerV) ? TABLE_BORDER_SIZE : 0.0f; const float inner_spacing_explicit = (pad_inner_x && (flags & ImGuiTableFlags_BordersInnerV) == 0) ? g.Style.CellPadding.x : 0.0f; const float inner_padding_explicit = (pad_inner_x && (flags & ImGuiTableFlags_BordersInnerV) != 0) ? g.Style.CellPadding.x : 0.0f; table->CellSpacingX1 = inner_spacing_explicit + inner_spacing_for_border; table->CellSpacingX2 = inner_spacing_explicit; table->CellPaddingX = inner_padding_explicit; - const float outer_padding_for_border = (flags & ImGuiTableFlags_BordersOuterV) ? border_size : 0.0f; + const float outer_padding_for_border = (flags & ImGuiTableFlags_BordersOuterV) ? TABLE_BORDER_SIZE : 0.0f; const float outer_padding_explicit = pad_outer_x ? g.Style.CellPadding.x : 0.0f; table->OuterPaddingX = (outer_padding_for_border + outer_padding_explicit) - table->CellPaddingX; + table->CurrentColumn = -1; + table->CurrentRow = -1; + table->RowBgColorCounter = 0; + table->LastRowFlags = ImGuiTableRowFlags_None; + table->InnerClipRect = (inner_window == outer_window) ? table->WorkRect : inner_window->ClipRect; + table->InnerClipRect.ClipWith(table->WorkRect); // We need this to honor inner_width + table->InnerClipRect.ClipWithFull(table->HostClipRect); + table->InnerClipRect.Max.y = (flags & ImGuiTableFlags_NoHostExtendY) ? ImMin(table->InnerClipRect.Max.y, inner_window->WorkRect.Max.y) : table->HostClipRect.Max.y; + table->RowPosY1 = table->RowPosY2 = table->WorkRect.Min.y; // This is needed somehow table->RowTextBaseline = 0.0f; // This will be cleared again by TableBeginRow() table->RowCellPaddingY = 0.0f; - table->RowBgColorCounter = 0; - table->LastRowFlags = ImGuiTableRowFlags_None; table->FreezeRowsRequest = table->FreezeRowsCount = 0; // This will be setup by TableSetupScrollFreeze(), if any table->FreezeColumnsRequest = table->FreezeColumnsCount = 0; table->IsUnfrozenRows = true; @@ -531,15 +541,6 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG table->AngledHeadersHeight = 0.0f; temp_data->AngledHeadersExtraWidth = 0.0f; - table->CurrentColumn = -1; - table->CurrentRow = -1; - table->InnerClipRect = (inner_window == outer_window) ? table->WorkRect : inner_window->ClipRect; - if (inner_window == outer_window) - table->InnerClipRect.ShrinkClamp(temp_data->BorderOuterSizes.Min, temp_data->BorderOuterSizes.Max); - table->InnerClipRect.ClipWith(table->WorkRect); // We need this to honor inner_width - table->InnerClipRect.ClipWithFull(table->HostClipRect); - if ((flags & ImGuiTableFlags_NoHostExtendY) == 0) - table->InnerClipRect.Max.y = table->HostClipRect.Max.y; // Using opaque colors facilitate overlapping lines of the grid, otherwise we'd need to improve TableDrawBorders() table->BorderColorStrong = GetColorU32(ImGuiCol_TableBorderStrong); table->BorderColorLight = GetColorU32(ImGuiCol_TableBorderLight); @@ -707,10 +708,10 @@ void ImGui::TableApplyQueuedRequests(ImGuiTable* table) // table->ReorderColumn = -1; } - // Handle reset requests (display order / visibility / sizes) + // Handle display order / visibility reset requests if (table->IsResetDisplayOrderRequest) { - for (int n = 0; n < table->ColumnsCount; n++) // Variant of using TableInitColumnDefaults()( + for (int n = 0; n < table->ColumnsCount; n++) table->DisplayOrderToIndex[n] = table->Columns[n].DisplayOrder = (ImGuiTableColumnIdx)n; table->IsResetDisplayOrderRequest = false; table->IsSettingsDirty = true; @@ -718,17 +719,10 @@ void ImGui::TableApplyQueuedRequests(ImGuiTable* table) if (table->IsResetVisibilityRequest) { for (ImGuiTableColumn& column : table->Columns) - TableInitColumnDefaults(table, &column, ImGuiTableFlags_Hideable); + column.IsUserEnabled = column.IsUserEnabledNextFrame = (column.Flags & ImGuiTableColumnFlags_DefaultHide) ? 0 : 1; table->IsResetVisibilityRequest = false; table->IsSettingsDirty = true; } - if (table->IsResetSizesRequest) - { - for (ImGuiTableColumn& column : table->Columns) - TableInitColumnDefaults(table, &column, ImGuiTableFlags_Resizable); - table->IsResetSizesRequest = false; - table->IsSettingsDirty = true; - } } // Apply immediately. See TableQueueSetColumnDisplayOrder() for additional checks/constraints. @@ -1283,7 +1277,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) } if (order_n < table->FreezeColumnsCount) - host_clip_rect.Min.x = ImClamp(column->MaxX + table->BorderSize, host_clip_rect.Min.x, host_clip_rect.Max.x); + host_clip_rect.Min.x = ImClamp(column->MaxX + TABLE_BORDER_SIZE, host_clip_rect.Min.x, host_clip_rect.Max.x); offset_x += column->WidthGiven + table->CellSpacingX1 + table->CellSpacingX2 + table->CellPaddingX * 2.0f; } @@ -1315,12 +1309,10 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) table->Flags &= ~ImGuiTableFlags_NoHostExtendX; if (table->Flags & ImGuiTableFlags_NoHostExtendX) { - const float border_size_outer_w = (table->Flags & ImGuiTableFlags_BordersOuterV) ? table->BorderSize : 0.0f; - table->OuterRect.Max.x = table->WorkRect.Max.x = ImMin(table->OuterRect.Max.x, unused_x1 + border_size_outer_w); - table->InnerClipRect.Max.x = ImClamp(table->OuterRect.Max.x - border_size_outer_w, table->InnerClipRect.Min.x, table->InnerClipRect.Max.x); + table->OuterRect.Max.x = table->WorkRect.Max.x = unused_x1; + table->InnerClipRect.Max.x = ImMin(table->InnerClipRect.Max.x, unused_x1); } - table->InnerWindow->ParentWorkRect = table->WorkRect; // Used by Selectable/TreeNode highlight - table->InnerWindow->ParentWorkRect.ShrinkClamp(temp_data->BorderOuterSizes.Min, temp_data->BorderOuterSizes.Max); + table->InnerWindow->ParentWorkRect = table->WorkRect; table->BorderX1 = table->InnerClipRect.Min.x; table->BorderX2 = table->InnerClipRect.Max.x; @@ -1495,7 +1487,6 @@ void ImGui::EndTable() // Finalize table height ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); inner_window->DC.PrevLineSize = temp_data->HostBackupPrevLineSize; - inner_window->DC.LayoutType = temp_data->HostBackupLayoutType; inner_window->DC.CurrLineSize = temp_data->HostBackupCurrLineSize; inner_window->DC.CursorMaxPos = temp_data->HostBackupCursorMaxPos; const float inner_content_max_y = ImCeil(table->RowPosY2); // Rounding final position is important as we currently don't round row height ('Demo->Tables->Outer Size' demo uses non-integer heights) @@ -1512,10 +1503,10 @@ void ImGui::EndTable() // but since the later is likely to be impossible to do we'd rather update both axes together. if (table->Flags & ImGuiTableFlags_ScrollX) { - const float border_size_outer_w = (table->Flags & ImGuiTableFlags_BordersOuterV) ? table->BorderSize : 0.0f; + const float outer_padding_for_border = (table->Flags & ImGuiTableFlags_BordersOuterV) ? TABLE_BORDER_SIZE : 0.0f; float max_pos_x = inner_window->DC.CursorMaxPos.x; if (table->RightMostEnabledColumn != -1) - max_pos_x = ImMax(max_pos_x, table->Columns[table->RightMostEnabledColumn].WorkMaxX + table->CellPaddingX + table->OuterPaddingX - border_size_outer_w); + max_pos_x = ImMax(max_pos_x, table->Columns[table->RightMostEnabledColumn].WorkMaxX + table->CellPaddingX + table->OuterPaddingX - outer_padding_for_border); if (table->ResizedColumn != -1) max_pos_x = ImMax(max_pos_x, table->ResizeLockMinContentsX2); inner_window->DC.CursorMaxPos.x = max_pos_x + table->TempData->AngledHeadersExtraWidth; @@ -1695,7 +1686,7 @@ void ImGui::TableInitColumnDefaults(ImGuiTable* table, ImGuiTableColumn* column, if (init_mask & ImGuiTableFlags_Resizable) { float init_width_or_weight = column->InitStretchWeightOrWidth; - column->WidthRequest = (init_width_or_weight > 0.0f && (flags & ImGuiTableColumnFlags_WidthFixed)) ? init_width_or_weight : -1.0f; + column->WidthRequest = ((flags & ImGuiTableColumnFlags_WidthFixed) && init_width_or_weight > 0.0f) ? init_width_or_weight : -1.0f; column->StretchWeight = (init_width_or_weight > 0.0f && (flags & ImGuiTableColumnFlags_WidthStretch)) ? init_width_or_weight : -1.0f; if (init_width_or_weight > 0.0f) // Disable auto-fit if an explicit width/weight has been specified column->AutoFitQueue = 0x00; @@ -1741,7 +1732,7 @@ static void TableSetupColumnApply(ImGuiTable* table, int idx, ImGuiID id, ImS16 column->InitStretchWeightOrWidth = init_width_or_weight; } -void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, float init_width_or_weight, ImGuiID user_data) +void ImGui::TableSetupColumn(ImStrv label, ImGuiTableColumnFlags flags, float init_width_or_weight, ImGuiID user_data) { ImGuiContext& g = *GImGui; ImGuiTable* table = g.CurrentTable; @@ -1753,12 +1744,14 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, flo // Store name (append with zero-terminator in contiguous buffer) // FIXME: If we recorded the number of \n in names we could compute header row height ImS16 name_offset = -1; - if (label != NULL && label[0] != 0) + if (!label.empty()) { + char zero_terminator = 0; name_offset = (ImS16)table->ColumnsNames.size(); - table->ColumnsNames.append(label, label + ImStrlen(label) + 1); + table->ColumnsNames.append(label); + table->ColumnsNames.append(ImStrv(&zero_terminator, &zero_terminator + 1)); } - const ImGuiID column_id = (label != NULL && label[0] != 0) ? ImHashStr(label) : 0; + const ImGuiID column_id = label ? ImHashStr(label) : 0; // When ID changed or a column moved: defer the request until layout where we will process full reconcile. const int column_idx = table->DeclColumnsCount++; @@ -2177,6 +2170,7 @@ void ImGui::TableEndRow(ImGuiTable* table) // Decide of top border color ImU32 top_border_col = 0; + const float border_size = TABLE_BORDER_SIZE; if (table->CurrentRow > 0 && (table->Flags & ImGuiTableFlags_BordersInnerH)) top_border_col = (table->LastRowFlags & ImGuiTableRowFlags_Headers) ? table->BorderColorStrong : table->BorderColorLight; @@ -2223,11 +2217,11 @@ void ImGui::TableEndRow(ImGuiTable* table) // Draw top border if (top_border_col && bg_y1 >= table->BgClipRect.Min.y && bg_y1 < table->BgClipRect.Max.y) - window->DrawList->AddLineH(table->BorderX1, table->BorderX2, bg_y1, top_border_col, table->BorderSize, ImDrawFlags_StrokeCenterBiased); + window->DrawList->AddLineH(table->BorderX1, table->BorderX2, bg_y1, top_border_col, border_size); // Draw bottom border at the row unfreezing mark (always strong) if (draw_strong_bottom_border && bg_y2 >= table->BgClipRect.Min.y && bg_y2 < table->BgClipRect.Max.y) - window->DrawList->AddLineH(table->BorderX1, table->BorderX2, bg_y2, table->BorderColorStrong, table->BorderSize, ImDrawFlags_StrokeCenterBiased); + window->DrawList->AddLineH(table->BorderX1, table->BorderX2, bg_y2, table->BorderColorStrong, border_size); } // End frozen rows (when we are past the last frozen row line, teleport cursor and alter clipping rectangle) @@ -2425,7 +2419,7 @@ void ImGui::TableEndCell(ImGuiTable* table) //------------------------------------------------------------------------- // [SECTION] Tables: Columns width management //------------------------------------------------------------------------- -// - TableCalcMaxColumnWidth() [Internal] +// - TableGetMaxColumnWidth() [Internal] // - TableGetColumnWidthAuto() [Internal] // - TableSetColumnWidth() // - TableSetColumnWidthAutoSingle() [Internal] @@ -2578,7 +2572,6 @@ void ImGui::TableSetColumnWidthAutoSingle(ImGuiTable* table, int column_n) table->AutoFitSingleColumn = (ImGuiTableColumnIdx)column_n; } -// FIXME: AutoFitQueue for Stretch columns can do a "reset" if InitStretchWeightOrWidth is valid, therefore might be misnamed. void ImGui::TableSetColumnWidthAutoAll(ImGuiTable* table) { for (int column_n = 0; column_n < table->ColumnsCount; column_n++) @@ -2743,10 +2736,6 @@ void ImGui::TableSetupDrawChannels(ImGuiTable* table) table->Bg0ClipRectForDrawCmd = table->OuterWindow->ClipRect; table->Bg2ClipRectForDrawCmd = table->HostClipRect; IM_ASSERT(table->BgClipRect.Min.y <= table->BgClipRect.Max.y); - if (table->Flags & ImGuiTableFlags_NoHostExtendX) - table->Bg2ClipRectForDrawCmd.Max.x = ImMin(table->Bg2ClipRectForDrawCmd.Max.x, table->BgClipRect.Max.x); // Don't apply to Bg0: shapes in Bg0 are already CPU clipped and it makes merging fails. - if (table->Flags & ImGuiTableFlags_NoHostExtendY) - table->Bg2ClipRectForDrawCmd.Max.y = ImMin(table->Bg2ClipRectForDrawCmd.Max.y, table->BgClipRect.Max.y); // " } // This function reorder draw channels based on matching clip rectangle, to facilitate merging them. Called by EndTable(). @@ -2904,7 +2893,7 @@ void ImGui::TableMergeDrawChannels(ImGuiTable* table) merge_clip_rect.Min.x = ImMin(merge_clip_rect.Min.x, host_rect.Min.x); if ((merge_group_n & 2) == 0 || !has_freeze_v) merge_clip_rect.Min.y = ImMin(merge_clip_rect.Min.y, host_rect.Min.y); - if ((merge_group_n & 1) != 0 && (table->Flags & ImGuiTableFlags_NoHostExtendX) == 0) + if ((merge_group_n & 1) != 0) merge_clip_rect.Max.x = ImMax(merge_clip_rect.Max.x, host_rect.Max.x); if ((merge_group_n & 2) != 0 && (table->Flags & ImGuiTableFlags_NoHostExtendY) == 0) merge_clip_rect.Max.y = ImMax(merge_clip_rect.Max.y, host_rect.Max.y); @@ -2964,52 +2953,19 @@ static ImU32 TableGetColumnBorderCol(ImGuiTable* table, int order_n, int column_ void ImGui::TableDrawBorders(ImGuiTable* table) { ImGuiWindow* inner_window = table->InnerWindow; - if (!table->OuterWindow->ClipRect.Overlaps(table->OuterRect)) // Note how OuterWindow->ClipRect == table->Bg0ClipRectForDrawCmd + if (!table->OuterWindow->ClipRect.Overlaps(table->OuterRect)) return; ImDrawList* inner_drawlist = inner_window->DrawList; table->DrawSplitter->SetCurrentChannel(inner_drawlist, TABLE_DRAW_CHANNEL_BG0); - inner_drawlist->PushClipRect(table->OuterWindow->ClipRect.Min, table->OuterWindow->ClipRect.Max, false); - - // For e.g. non scrolling table we limit vertex coordinates in order to keep ImDrawCmd AABB roughly within visible range. - const float border_size_outer_w = (table->Flags & ImGuiTableFlags_BordersOuterV) ? table->BorderSize : 0.0f; - const float border_size_outer_h = (table->Flags & ImGuiTableFlags_BordersOuterH) ? table->BorderSize : 0.0f; - const float border_size_inner = table->BorderSize; - const float draw_y2_limit = table->OuterWindow->ClipRect.Max.y + (2.0f * ImMax(border_size_outer_h, inner_drawlist->_FringeScale)); - - // Draw outer border - if (table->Flags & ImGuiTableFlags_BordersOuter) - { - // Display outer border offset by 1 which is a simple way to display it without adding an extra draw call - // (Without the offset, in outer_window it would be rendered behind cells, because child windows are above their - // parent. In inner_window, it won't reach out over scrollbars. Another weird solution would be to display part - // of it in inner window, and the part that's over scrollbars in the outer window..) - // Either solution currently won't allow us to use a larger border size: the border would clipped. - ImRect outer_border = table->OuterRect; - outer_border.Max.y = ImMin(outer_border.Max.y, draw_y2_limit); // Clamp but keep bottom border non-visible. - const ImU32 outer_col = table->BorderColorStrong; - if ((table->Flags & ImGuiTableFlags_BordersOuter) == ImGuiTableFlags_BordersOuter) - { - inner_drawlist->AddRect(outer_border.Min, outer_border.Max, outer_col, 0.0f, border_size_outer_w); - } - else if (table->Flags & ImGuiTableFlags_BordersOuterV) - { - inner_drawlist->AddLineV(outer_border.Min.x, outer_border.Min.y, outer_border.Max.y, outer_col, border_size_outer_w); - inner_drawlist->AddLineV(outer_border.Max.x - border_size_outer_w, outer_border.Min.y, outer_border.Max.y, outer_col, border_size_outer_w); - } - else if (table->Flags & ImGuiTableFlags_BordersOuterH) - { - inner_drawlist->AddLineH(outer_border.Min.x, outer_border.Max.x, outer_border.Min.y, outer_col, border_size_outer_h); - inner_drawlist->AddLineH(outer_border.Min.x, outer_border.Max.x, outer_border.Max.y - border_size_outer_h, outer_col, border_size_outer_h); - } - } + inner_drawlist->PushClipRect(table->Bg0ClipRectForDrawCmd.Min, table->Bg0ClipRectForDrawCmd.Max, false); // Draw inner border and resizing feedback ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); - const float draw_y1 = ImMax(table->InnerRect.Min.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table->AngledHeadersHeight) + ((table->Flags & ImGuiTableFlags_BordersOuterH) ? border_size_outer_h : 0.0f); - const float draw_y2_body = ImMin(table->InnerRect.Max.y - border_size_outer_h, draw_y2_limit); - const float draw_y2_head = table->IsUsingHeaders ? ImMin(draw_y2_body, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table_instance->LastTopHeadersRowHeight) : draw_y1; - + const float border_size = TABLE_BORDER_SIZE; + const float draw_y1 = ImMax(table->InnerRect.Min.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table->AngledHeadersHeight) + ((table->Flags & ImGuiTableFlags_BordersOuterH) ? border_size : 0.0f); + const float draw_y2_body = table->InnerRect.Max.y; + const float draw_y2_head = table->IsUsingHeaders ? ImMin(table->InnerRect.Max.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table_instance->LastTopHeadersRowHeight) : draw_y1; if (table->Flags & ImGuiTableFlags_BordersInnerV) { for (int order_n = 0; order_n < table->ColumnsCount; order_n++) @@ -3023,21 +2979,14 @@ void ImGui::TableDrawBorders(ImGuiTable* table) const bool is_resized = (table->ResizedColumn == column_n) && (table->InstanceInteracted == table->InstanceCurrent); const bool is_resizable = (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_)) == 0; const bool is_frozen_separator = (table->FreezeColumnsCount == order_n + 1); - - // FIXME-TABLE: 1-off display hack for right-most column when resizable (!Scroll && Resizable && (NoHostExtendX || RightMostIsFixed)). - // Fixing actual width would involve altering width_avail in layout and TableCalcMaxColumnWidth(), which would drop the property - // ColumnsGivenWidth == Outer Allocated Width. Worth reworking, but would only make sense if we accept that BorderSize affects layout. - float draw_x2 = column->MaxX; - if (draw_x2 >= table->InnerClipRect.Max.x && draw_x2 - 1.0f <= table->InnerClipRect.Max.x) - draw_x2 = table->InnerClipRect.Max.x; - if (draw_x2 >= table->InnerClipRect.Max.x && !is_resized && !is_hovered) + if (column->MaxX > table->InnerClipRect.Max.x && !is_resized) continue; // Decide whether right-most column is visible if (column->NextEnabledColumn == -1 && !is_resizable) if ((table->Flags & ImGuiTableFlags_SizingMask_) != ImGuiTableFlags_SizingFixedSame || (table->Flags & ImGuiTableFlags_NoHostExtendX)) continue; - if (draw_x2 <= column->ClipRect.Min.x) // FIXME-TABLE FIXME-STYLE: Assume BorderSize==1, this is problematic if we want to increase the border size.. + if (column->MaxX <= column->ClipRect.Min.x) // FIXME-TABLE FIXME-STYLE: Assume BorderSize==1, this is problematic if we want to increase the border size.. continue; // Draw in outer window so right-most column won't be clipped @@ -3049,16 +2998,43 @@ void ImGui::TableDrawBorders(ImGuiTable* table) else if ((table->Flags & (ImGuiTableFlags_NoBordersInBodyUntilResize | ImGuiTableFlags_NoBordersInBody)) == 0) draw_y2 = draw_y2_body; if (draw_y2 > draw_y1) - inner_drawlist->AddLineV(draw_x2, draw_y1, draw_y2, TableGetColumnBorderCol(table, order_n, column_n), border_size_inner); + inner_drawlist->AddLineV(column->MaxX, draw_y1, draw_y2, TableGetColumnBorderCol(table, order_n, column_n), border_size); } } + // Draw outer border + // FIXME: could use AddRect or explicit VLine/HLine helper? + if (table->Flags & ImGuiTableFlags_BordersOuter) + { + // Display outer border offset by 1 which is a simple way to display it without adding an extra draw call + // (Without the offset, in outer_window it would be rendered behind cells, because child windows are above their + // parent. In inner_window, it won't reach out over scrollbars. Another weird solution would be to display part + // of it in inner window, and the part that's over scrollbars in the outer window..) + // Either solution currently won't allow us to use a larger border size: the border would clipped. + const ImRect outer_border = table->OuterRect; + const ImU32 outer_col = table->BorderColorStrong; + if ((table->Flags & ImGuiTableFlags_BordersOuter) == ImGuiTableFlags_BordersOuter) + { + inner_drawlist->AddRect(outer_border.Min, outer_border.Max, outer_col, 0.0f, border_size); + } + else if (table->Flags & ImGuiTableFlags_BordersOuterV) + { + inner_drawlist->AddLineV(outer_border.Min.x, outer_border.Min.y, outer_border.Max.y, outer_col, border_size); + inner_drawlist->AddLineV(outer_border.Max.x - border_size, outer_border.Min.y, outer_border.Max.y, outer_col, border_size); + } + else if (table->Flags & ImGuiTableFlags_BordersOuterH) + { + inner_drawlist->AddLineH(outer_border.Min.x, outer_border.Max.x, outer_border.Min.y, outer_col, border_size); + inner_drawlist->AddLineH(outer_border.Min.x, outer_border.Max.x, outer_border.Max.y - border_size, outer_col, border_size); + } + } if ((table->Flags & ImGuiTableFlags_BordersInnerH) && table->RowPosY2 < table->OuterRect.Max.y) { - // Draw bottom-most row border between it and above outer border. + // Draw bottom-most row border between it is above outer border. + const float h_inset = (table->Flags & ImGuiTableFlags_BordersOuterV) ? border_size : 0.0f; const float border_y = table->RowPosY2; if (border_y >= table->BgClipRect.Min.y && border_y < table->BgClipRect.Max.y) - inner_drawlist->AddLineH(table->BorderX1, table->BorderX2, border_y, table->BorderColorLight, border_size_inner); + inner_drawlist->AddLineH(table->BorderX1 + h_inset, table->BorderX2 - h_inset, border_y, table->BorderColorLight, border_size); } inner_drawlist->PopClipRect(); @@ -3294,7 +3270,7 @@ float ImGui::TableGetHeaderAngledMaxLabelWidth() for (int column_n = 0; column_n < table->ColumnsCount; column_n++) if (IM_BITARRAY_TESTBIT(table->EnabledMaskByIndex, column_n)) if (table->Columns[column_n].Flags & ImGuiTableColumnFlags_AngledHeader) - width = ImMax(width, CalcTextSize(TableGetColumnName(table, column_n), NULL, true).x); + width = ImMax(width, CalcTextSize(TableGetColumnName(table, column_n), true).x); return width + g.Style.CellPadding.y * 2.0f; // Swap padding } @@ -3346,7 +3322,7 @@ void ImGui::TableHeadersRow() // Emit a column header (text + optional sort order) // We cpu-clip text here so that all columns headers can be merged into a same draw call. // Note that because of how we cpu-clip and display sorting indicators, you _cannot_ use SameLine() after a TableHeader() -void ImGui::TableHeader(const char* label) +void ImGui::TableHeader(ImStrv label) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; @@ -3360,10 +3336,11 @@ void ImGui::TableHeader(const char* label) ImGuiTableColumn* column = &table->Columns[column_n]; // Label - if (label == NULL) + if (!label) label = ""; - const char* label_end = FindRenderedTextEnd(label); - ImVec2 label_size = CalcTextSize(label, label_end, false); + ImGuiID id = window->GetID(label); + const ImStrv label_for_display(label.Begin, FindRenderedTextEnd(label)); + const ImVec2 label_size = CalcTextSize(label_for_display, false); ImVec2 label_pos = window->DC.CursorPos; // If we already got a row height, there's use that. @@ -3395,7 +3372,6 @@ void ImGui::TableHeader(const char* label) column->ContentMaxXHeadersIdeal = ImMax(column->ContentMaxXHeadersIdeal, max_pos_x); // Keep header highlighted when context menu is open. - ImGuiID id = window->GetID(label); ImRect bb(cell_r.Min.x, cell_r.Min.y, cell_r.Max.x, ImMax(cell_r.Max.y, cell_r.Min.y + label_height + g.Style.CellPadding.y * 2.0f)); ItemSize(ImVec2(0.0f, label_height)); // Don't declare unclipped width, it'll be fed ContentMaxPosHeadersIdeal if (!ItemAdd(bb, id)) @@ -3461,7 +3437,7 @@ void ImGui::TableHeader(const char* label) PopStyleColor(); x += w_sort_text; } - RenderArrow(window->DrawList, ImVec2(x + (g.FontSize * (1.0f - ARROW_SCALE) * 0.5f) , y), GetColorU32(ImGuiCol_Text), column->SortDirection == ImGuiSortDirection_Ascending ? ImGuiDir_Up : ImGuiDir_Down, ARROW_SCALE); + RenderArrow(window->DrawList, ImVec2(x, y), GetColorU32(ImGuiCol_Text), column->SortDirection == ImGuiSortDirection_Ascending ? ImGuiDir_Up : ImGuiDir_Down, ARROW_SCALE); } // Handle clicking on column header to adjust Sort Order @@ -3475,11 +3451,11 @@ void ImGui::TableHeader(const char* label) // Render clipped label. Clipping here ensure that in the majority of situations, all our header cells will // be merged into a single draw call. //window->DrawList->AddCircleFilled(ImVec2(ellipsis_max, label_pos.y), 40, IM_COL32_WHITE); - RenderTextEllipsis(window->DrawList, label_pos, ImVec2(ellipsis_max, bb.Max.y), ellipsis_max, label, label_end, &label_size); + RenderTextEllipsis(window->DrawList, label_pos, ImVec2(ellipsis_max, bb.Max.y), ellipsis_max, label_for_display, &label_size); const bool text_clipped = label_size.x > (ellipsis_max - label_pos.x); if (text_clipped && hovered && g.ActiveId == 0) - SetItemTooltip("%.*s", (int)(label_end - label), label); + SetItemTooltip("%.*s", (int)(label_for_display.End - label_for_display.Begin), label_for_display.Begin); // We don't use BeginPopupContextItem() because we want the popup to stay up even after the column is hidden if (IsPopupOpenRequestForItem(ImGuiPopupFlags_None, id)) @@ -3600,10 +3576,10 @@ void ImGui::TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label // Draw label // - First draw at an offset where RenderTextXXX() function won't meddle with applying current ClipRect, then transform to final offset. // - Handle multiple lines manually, as we want each lines to follow on the horizontal border, rather than see a whole block rotated. - const char* label_name = TableGetColumnName(table, column_n); - const char* label_name_end = FindRenderedTextEnd(label_name); + const char* label_name_s = TableGetColumnName(table, column_n); + ImStrv label_name(label_name_s, FindRenderedTextEnd(label_name_s)); const float line_off_step_x = (g.FontSize / -sin_a); - const int label_lines = ImTextCountLines(label_name, label_name_end); + const int label_lines = ImTextCountLines(label_name); // Left<>Right alignment float line_off_curr_x = flip_label ? (label_lines - 1) * line_off_step_x : 0.0f; @@ -3613,20 +3589,20 @@ void ImGui::TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label // Register header width column->ContentMaxXHeadersUsed = column->ContentMaxXHeadersIdeal = column->WorkMinX + ImCeil(label_lines * line_off_step_x - line_off_for_align_x); - while (label_name < label_name_end) + while (label_name.Begin < label_name.End) { - const char* label_name_eol = strchr(label_name, '\n'); + const char* label_name_eol = ImStrchrRange(label_name.Begin, label_name.End, '\n'); if (label_name_eol == NULL) - label_name_eol = label_name_end; + label_name_eol = label_name.End; // FIXME: Individual line clipping for right-most column is broken for negative angles. - ImVec2 label_size = CalcTextSize(label_name, label_name_eol); + ImVec2 label_size = CalcTextSize(ImStrv(label_name.Begin, label_name_eol)); float clip_width = max_label_width - padding.y; // Using padding.y*2.0f would be symmetrical but hide more text. float clip_height = ImMin(label_size.y, column->ClipRect.Max.x - column->WorkMinX - line_off_curr_x); ImRect clip_r(window->ClipRect.Min, window->ClipRect.Min + ImVec2(clip_width, clip_height)); int vtx_idx_begin = draw_list->_VtxCurrentIdx; PushStyleColor(ImGuiCol_Text, request->TextColor); - RenderTextEllipsis(draw_list, clip_r.Min, clip_r.Max, clip_r.Max.x, label_name, label_name_eol, &label_size); + RenderTextEllipsis(draw_list, clip_r.Min, clip_r.Max, clip_r.Max.x, ImStrv(label_name.Begin, label_name_eol), &label_size); PopStyleColor(); int vtx_idx_end = draw_list->_VtxCurrentIdx; @@ -3651,9 +3627,8 @@ void ImGui::TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label if (pass == 1) { // Draw border - draw_list->AddLine( - bg_shape[0] + ImVec2(table->BorderSize * 0.5f, 0.0f), - bg_shape[3] + ImVec2(table->BorderSize * 0.5f, 0.0f), TableGetColumnBorderCol(table, order_n, column_n), table->BorderSize); + const float border_size = TABLE_BORDER_SIZE; + draw_list->AddLine(bg_shape[0] + ImVec2(border_size * 0.5f, 0.0f), bg_shape[3] + ImVec2(border_size * 0.5f, 0.0f), TableGetColumnBorderCol(table, order_n, column_n), border_size); } } PopClipRect(); @@ -3701,13 +3676,13 @@ bool ImGui::TableBeginContextMenuPopup(ImGuiTable* table) } // FIXME: Copied from MenuItem() for the purpose of being able to pass _SelectOnRelease (#9312) -static bool MenuItemForColumnReorder(const char* label, bool selected, bool enabled) +static bool MenuItemForColumnReorder(ImStrv label, bool selected, bool enabled) { using namespace ImGui; ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - ImVec2 label_size = CalcTextSize(label, NULL, true); + ImVec2 label_size = CalcTextSize(label, true); ImGuiMenuColumns* offsets = &window->DC.MenuColumns; float checkmark_w = IM_TRUNC(g.FontSize * 1.20f); float min_w = offsets->DeclColumns(0.0f, label_size.x, 0.0f, checkmark_w); // Feedback for next frame @@ -3770,7 +3745,7 @@ void ImGui::TableDrawDefaultContextMenu(ImGuiTable* table, ImGuiTableFlags flags } // Reset Order/Visibility etc. - if (flags_for_section_to_display & (ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Resizable)) + if (flags_for_section_to_display & (ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable)) if (BeginMenu(LocalizeGetMsg(ImGuiLocKey_TableReset))) { //if (MenuItem(LocalizeGetMsg(ImGuiLocKey_TableResetAll))) // FIXME: Hiding because altering Sort Order + requesting auto-fit simultaneously has a tendency to exhibit a sizing glitch. @@ -3781,9 +3756,6 @@ void ImGui::TableDrawDefaultContextMenu(ImGuiTable* table, ImGuiTableFlags flags if (flags_for_section_to_display & ImGuiTableFlags_Hideable) if (MenuItem(LocalizeGetMsg(ImGuiLocKey_TableResetVisibility), NULL, false, !table->IsDefaultVisibility)) table->IsResetVisibilityRequest = true; - if (flags_for_section_to_display & ImGuiTableFlags_Resizable) - if (MenuItem(LocalizeGetMsg(ImGuiLocKey_TableResetSizing), NULL, false)) // Can't easily implement IsDefaultSize - table->IsResetSizesRequest = true; EndMenu(); } @@ -4693,7 +4665,7 @@ ImGuiOldColumns* ImGui::FindOrCreateColumns(ImGuiWindow* window, ImGuiID id) return columns; } -ImGuiID ImGui::GetColumnsID(const char* str_id, int columns_count) +ImGuiID ImGui::GetColumnsID(ImStrv str_id, int columns_count) { ImGuiWindow* window = GetCurrentWindow(); @@ -4706,7 +4678,7 @@ ImGuiID ImGui::GetColumnsID(const char* str_id, int columns_count) return id; } -void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiOldColumnFlags flags) +void ImGui::BeginColumns(ImStrv str_id, int columns_count, ImGuiOldColumnFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); @@ -4917,7 +4889,7 @@ void ImGui::EndColumns() NavUpdateCurrentWindowIsScrollPushableX(); } -void ImGui::Columns(int columns_count, const char* id, bool borders) +void ImGui::Columns(int columns_count, ImStrv id, bool borders) { ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(columns_count >= 1); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f54a91160..01fb1756b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -54,7 +54,6 @@ Index of this file: // Visual Studio warnings #ifdef _MSC_VER #pragma warning (disable: 4127) // condition expression is constant -#pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff) #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen #if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later #pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types @@ -74,7 +73,6 @@ Index of this file: #pragma clang diagnostic ignored "-Wformat" // warning: format specifies type 'int' but the argument has type 'unsigned int' #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. #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness -#pragma clang diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used #pragma clang diagnostic ignored "-Wunused-macros" // warning: macro is not used // we define snprintf/vsnprintf on Windows so they are available, but not always used. #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 #pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. @@ -86,7 +84,6 @@ Index of this file: #pragma clang diagnostic ignored "-Wswitch-default" // warning: 'switch' missing 'default' label #elif defined(__GNUC__) #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind -#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used #pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe #pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'int'/'void*', but argument X has type 'unsigned int'/'ImGuiWindow*' #pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked @@ -161,30 +158,24 @@ static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, // - BulletTextV() //------------------------------------------------------------------------- -void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags) +void ImGui::TextEx(ImStrv text, ImGuiTextFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; - // Accept null ranges - if (text == text_end) - text = text_end = ""; - - // Calculate length - const char* text_begin = text; - if (text_end == NULL) - text_end = text + ImStrlen(text); // FIXME-OPT + const char* text_begin = text.Begin; + const char* text_end = text.End; const ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset); const float wrap_pos_x = window->DC.TextWrapPos; const bool wrap_enabled = (wrap_pos_x >= 0.0f); - if (text_end - text <= 2000 || wrap_enabled) + if (text_end - text_begin <= 2000 || wrap_enabled) { // Common case const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f; - const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width); + const ImVec2 text_size = CalcTextSize(text, false, wrap_width); ImRect bb(text_pos, text_pos + text_size); ItemSize(text_size, 0.0f); @@ -192,7 +183,7 @@ void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags) return; // Render (we don't hide text after ## in this end-user function) - RenderTextWrapped(bb.Min, text_begin, text_end, wrap_width); + RenderTextWrapped(bb.Min, text, wrap_width); } else { @@ -201,7 +192,7 @@ void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags) // - From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled. // - 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. // - We use memchr(), pay attention that well optimized versions of those str/mem functions are much faster than a casually written loop. - const char* line = text; + const char* line = text_begin; const float line_height = GetTextLineHeight(); ImVec2 text_size(0, 0); @@ -219,7 +210,7 @@ void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags) if (!line_end) line_end = text_end; if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0) - text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x); + text_size.x = ImMax(text_size.x, CalcTextSize(ImStrv(line, line_end)).x); line = line_end + 1; lines_skipped++; } @@ -239,8 +230,8 @@ void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags) const char* line_end = (const char*)ImMemchr(line, '\n', text_end - line); if (!line_end) line_end = text_end; - text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x); - RenderText(pos, line, line_end, false); + text_size.x = ImMax(text_size.x, CalcTextSize(ImStrv(line, line_end)).x); + RenderText(pos, ImStrv(line, line_end), false); line = line_end + 1; line_rect.Min.y += line_height; line_rect.Max.y += line_height; @@ -255,7 +246,7 @@ void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags) if (!line_end) line_end = text_end; if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0) - text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x); + text_size.x = ImMax(text_size.x, CalcTextSize(ImStrv(line, line_end)).x); line = line_end + 1; lines_skipped++; } @@ -271,9 +262,9 @@ void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags) // Note that all functions taking format strings in the API may be passed ("%s", text) or ("%.*s", text_len, text), // which will automatically bypass the formatter. -void ImGui::TextUnformatted(const char* text, const char* text_end) +void ImGui::TextUnformatted(ImStrv text) { - TextEx(text, text_end, ImGuiTextFlags_NoWidthForLargeClippedText); + TextEx(text, ImGuiTextFlags_NoWidthForLargeClippedText); } void ImGui::Text(const char* fmt, ...) @@ -290,9 +281,9 @@ void ImGui::TextV(const char* fmt, va_list args) if (window->SkipItems) return; - const char* text, *text_end; - ImFormatStringToTempBufferV(&text, &text_end, fmt, args); - TextEx(text, text_end, ImGuiTextFlags_NoWidthForLargeClippedText); + ImStrv text; + ImFormatStringToTempBufferV(&text, fmt, args); + TextEx(text, ImGuiTextFlags_NoWidthForLargeClippedText); } void ImGui::TextColored(const ImVec4& col, const char* fmt, ...) @@ -362,9 +353,9 @@ void ImGui::TextAlignedV(float align_x, float width, const char* fmt, va_list ar if (window->SkipItems) return; - const char* text, *text_end; - ImFormatStringToTempBufferV(&text, &text_end, fmt, args); - const ImVec2 text_size = CalcTextSize(text, text_end); + ImStrv text; + ImFormatStringToTempBufferV(&text, fmt, args); + const ImVec2 text_size = CalcTextSize(text); const ImVec2 size = CalcItemSize(ImVec2(width, 0.0f), 0.0f, text_size.y); ImVec2 pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset); @@ -381,13 +372,13 @@ void ImGui::TextAlignedV(float align_x, float width, const char* fmt, va_list ar if (align_x > 0.0f && text_size.x < size.x) pos.x += ImTrunc((size.x - text_size.x) * align_x); - RenderTextEllipsis(window->DrawList, pos, pos_max, pos_max.x, text, text_end, &text_size); + RenderTextEllipsis(window->DrawList, pos, pos_max, pos_max.x, text, &text_size); if (size.x < text_size.x && IsItemHovered(ImGuiHoveredFlags_NoNavOverride | ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_ForTooltip)) - SetTooltip("%.*s", (int)(text_end - text), text); + SetTooltip("%.*s", (int)(text.End - text.Begin), text.Begin); } -void ImGui::LabelText(const char* label, const char* fmt, ...) +void ImGui::LabelText(ImStrv label, const char* fmt, ...) { va_list args; va_start(args, fmt); @@ -396,7 +387,7 @@ void ImGui::LabelText(const char* label, const char* fmt, ...) } // Add a label+text combo aligned to other label+value widgets -void ImGui::LabelTextV(const char* label, const char* fmt, va_list args) +void ImGui::LabelTextV(ImStrv label, const char* fmt, va_list args) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -406,12 +397,11 @@ void ImGui::LabelTextV(const char* label, const char* fmt, va_list args) const ImGuiStyle& style = g.Style; const float w = CalcItemWidth(); - const char* value_text_begin, *value_text_end; - ImFormatStringToTempBufferV(&value_text_begin, &value_text_end, fmt, args); - const ImVec2 value_size = CalcTextSize(value_text_begin, value_text_end, false); - const char* label_end = FindRenderedTextEnd(label); - const ImVec2 label_size = CalcTextSize(label, label_end, false); - + ImStrv value_text; + ImFormatStringToTempBufferV(&value_text, fmt, args); + const ImVec2 value_size = CalcTextSize(value_text, false); + const ImStrv label_for_display(label.Begin, FindRenderedTextEnd(label)); + const ImVec2 label_size = CalcTextSize(label_for_display, false); const ImVec2 pos = window->DC.CursorPos; const ImRect value_bb(pos, pos + ImVec2(w, value_size.y + style.FramePadding.y * 2)); const ImRect total_bb(pos, pos + ImVec2(w + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), ImMax(value_size.y, label_size.y) + style.FramePadding.y * 2)); @@ -420,9 +410,9 @@ void ImGui::LabelTextV(const char* label, const char* fmt, va_list args) return; // Render - RenderTextClipped(value_bb.Min + style.FramePadding, value_bb.Max, value_text_begin, value_text_end, &value_size, ImVec2(0.0f, 0.0f)); + RenderTextClipped(value_bb.Min + style.FramePadding, value_bb.Max, value_text, &value_size, ImVec2(0.0f, 0.0f)); if (label_size.x > 0.0f) - RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label, label_end, false); + RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label_for_display, false); } void ImGui::BulletText(const char* fmt, ...) @@ -443,9 +433,9 @@ void ImGui::BulletTextV(const char* fmt, va_list args) ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; - const char* text_begin, *text_end; - ImFormatStringToTempBufferV(&text_begin, &text_end, fmt, args); - const ImVec2 label_size = CalcTextSize(text_begin, text_end, false); + ImStrv text; + ImFormatStringToTempBufferV(&text, fmt, args); + const ImVec2 label_size = CalcTextSize(text, false); const ImVec2 total_size = ImVec2(g.FontSize + (label_size.x > 0.0f ? (label_size.x + style.FramePadding.x * 2) : 0.0f), label_size.y); // Empty text doesn't add padding ImVec2 pos = window->DC.CursorPos; pos.y += window->DC.CurrLineTextBaseOffset; @@ -457,7 +447,7 @@ void ImGui::BulletTextV(const char* fmt, va_list args) // Render ImU32 text_col = GetColorU32(ImGuiCol_Text); RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize * 0.5f, g.FontSize * 0.5f), text_col); - RenderText(bb.Min + ImVec2(g.FontSize + style.FramePadding.x * 2, 0.0f), text_begin, text_end, false); + RenderText(bb.Min + ImVec2(g.FontSize + style.FramePadding.x * 2, 0.0f), text, false); } //------------------------------------------------------------------------- @@ -788,7 +778,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool return pressed; } -bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags) +bool ImGui::ButtonEx(ImStrv label, const ImVec2& size_arg, ImGuiButtonFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -797,8 +787,8 @@ bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); - const char* label_end = FindRenderedTextEnd(label); - const ImVec2 label_size = CalcTextSize(label, label_end, false); + const ImStrv label_for_display(label.Begin, FindRenderedTextEnd(label)); + const ImVec2 label_size = CalcTextSize(label_for_display, false); ImVec2 pos = window->DC.CursorPos; if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrLineTextBaseOffset) // 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) @@ -820,7 +810,7 @@ bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags if (g.LogEnabled) LogSetNextTextDecoration("[", "]"); - RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, label_end, &label_size, style.ButtonTextAlign, &bb); + RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label_for_display, &label_size, style.ButtonTextAlign, &bb); // Automatically close popups //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) @@ -830,13 +820,13 @@ bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags return pressed; } -bool ImGui::Button(const char* label, const ImVec2& size_arg) +bool ImGui::Button(ImStrv label, const ImVec2& size_arg) { return ButtonEx(label, size_arg, ImGuiButtonFlags_None); } // Small buttons fits within text without additional vertical spacing. -bool ImGui::SmallButton(const char* label) +bool ImGui::SmallButton(ImStrv label) { ImGuiContext& g = *GImGui; float backup_padding_y = g.Style.FramePadding.y; @@ -848,7 +838,7 @@ bool ImGui::SmallButton(const char* label) // Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack. // 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) -bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg, ImGuiButtonFlags flags) +bool ImGui::InvisibleButton(ImStrv str_id, const ImVec2& size_arg, ImGuiButtonFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); @@ -872,7 +862,7 @@ bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg, ImGuiBut return pressed; } -bool ImGui::ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size, ImGuiButtonFlags flags) +bool ImGui::ArrowButtonEx(ImStrv str_id, ImGuiDir dir, ImVec2 size, ImGuiButtonFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); @@ -900,7 +890,7 @@ bool ImGui::ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size, ImGuiBu return pressed; } -bool ImGui::ArrowButton(const char* str_id, ImGuiDir dir) +bool ImGui::ArrowButton(ImStrv str_id, ImGuiDir dir) { float sz = GetFrameHeight(); return ArrowButtonEx(str_id, dir, ImVec2(sz, sz), ImGuiButtonFlags_None); @@ -1212,7 +1202,7 @@ bool ImGui::ImageButtonEx(ImGuiID id, ImTextureRef tex_ref, const ImVec2& image_ // - ImageButton() adds style.FramePadding*2.0f to provided size. This is in order to facilitate fitting an image in a button. // - ImageButton() draws a background based on regular Button() color + optionally an inner background if specified. (#8165) // FIXME: Maybe that's not the best design? -bool ImGui::ImageButton(const char* str_id, ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col) +bool ImGui::ImageButton(ImStrv str_id, ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; @@ -1244,7 +1234,7 @@ bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const I */ #endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS -bool ImGui::Checkbox(const char* label, bool* v) +bool ImGui::Checkbox(ImStrv label, bool* v) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -1253,8 +1243,9 @@ bool ImGui::Checkbox(const char* label, bool* v) ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); - const char* label_end = FindRenderedTextEnd(label); - const ImVec2 label_size = CalcTextSize(label, label_end, false); + + const ImStrv label_for_display(label.Begin, FindRenderedTextEnd(label)); + const ImVec2 label_size = CalcTextSize(label_for_display, false); const float square_sz = GetFrameHeight(); const ImVec2 pos = window->DC.CursorPos; @@ -1302,9 +1293,8 @@ bool ImGui::Checkbox(const char* label, bool* v) { // Undocumented tristate/mixed/indeterminate checkbox (#2644) // This may seem awkwardly designed because the aim is to make ImGuiItemFlags_MixedValue supported by all widgets (not just checkbox) - const float pad = ImMax(1.0f, IM_TRUNC(square_sz / 3.6f)); - const float rounding = 0.0f;// IM_TRUNC(ImMin((square_sz - pad * 2.0f) * 0.20f, style.FrameRounding)); // Clamp rounding - window->DrawList->AddRectFilled(check_bb.Min + ImVec2(pad, pad), check_bb.Max - ImVec2(pad, pad), check_col, rounding); + ImVec2 pad(ImMax(1.0f, IM_TRUNC(square_sz / 3.6f)), ImMax(1.0f, IM_TRUNC(square_sz / 3.6f))); + window->DrawList->AddRectFilled(check_bb.Min + pad, check_bb.Max - pad, check_col, style.FrameRounding); } else if (*v) { @@ -1316,14 +1306,14 @@ bool ImGui::Checkbox(const char* label, bool* v) if (g.LogEnabled) LogRenderedText(&label_pos, mixed_value ? "[~]" : *v ? "[x]" : "[ ]"); if (is_visible && label_size.x > 0.0f) - RenderText(label_pos, label, label_end, false); + RenderText(label_pos, label_for_display, false); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0)); return pressed; } template -bool ImGui::CheckboxFlagsT(const char* label, T* flags, T flags_value) +bool ImGui::CheckboxFlagsT(ImStrv label, T* flags, T flags_value) { bool all_on = (*flags & flags_value) == flags_value; bool any_on = (*flags & flags_value) != 0; @@ -1349,27 +1339,27 @@ bool ImGui::CheckboxFlagsT(const char* label, T* flags, T flags_value) return pressed; } -bool ImGui::CheckboxFlags(const char* label, int* flags, int flags_value) +bool ImGui::CheckboxFlags(ImStrv label, int* flags, int flags_value) { return CheckboxFlagsT(label, flags, flags_value); } -bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value) +bool ImGui::CheckboxFlags(ImStrv label, unsigned int* flags, unsigned int flags_value) { return CheckboxFlagsT(label, flags, flags_value); } -bool ImGui::CheckboxFlags(const char* label, ImS64* flags, ImS64 flags_value) +bool ImGui::CheckboxFlags(ImStrv label, ImS64* flags, ImS64 flags_value) { return CheckboxFlagsT(label, flags, flags_value); } -bool ImGui::CheckboxFlags(const char* label, ImU64* flags, ImU64 flags_value) +bool ImGui::CheckboxFlags(ImStrv label, ImU64* flags, ImU64 flags_value) { return CheckboxFlagsT(label, flags, flags_value); } -bool ImGui::RadioButton(const char* label, bool active) +bool ImGui::RadioButton(ImStrv label, bool active) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -1378,8 +1368,9 @@ bool ImGui::RadioButton(const char* label, bool active) ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); - const char* label_end = FindRenderedTextEnd(label); - const ImVec2 label_size = CalcTextSize(label, label_end, false); + + const ImStrv label_for_display(label.Begin, FindRenderedTextEnd(label)); + const ImVec2 label_size = CalcTextSize(label_for_display, false); const float square_sz = GetFrameHeight(); const ImVec2 pos = window->DC.CursorPos; @@ -1418,14 +1409,14 @@ bool ImGui::RadioButton(const char* label, bool active) if (g.LogEnabled) LogRenderedText(&label_pos, active ? "(x)" : "( )"); if (label_size.x > 0.0f) - RenderText(label_pos, label, label_end, false); + RenderText(label_pos, label_for_display, false); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); return pressed; } // FIXME: This would work nicely if it was a public template, e.g. 'template RadioButton(const char* label, T* v, T v_button)', but I'm not sure how we would expose it.. -bool ImGui::RadioButton(const char* label, int* v, int v_button) +bool ImGui::RadioButton(ImStrv label, int* v, int v_button) { const bool pressed = RadioButton(label, *v == v_button); if (pressed) @@ -1434,7 +1425,7 @@ bool ImGui::RadioButton(const char* label, int* v, int v_button) } // size_arg (for each axis) < 0.0f: align to end, 0.0f: auto, > 0.0f: specified size -void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* overlay) +void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, ImStrv overlay) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -1479,7 +1470,7 @@ void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* over // Default displaying the fraction as percentage string, but user can override it // Don't display text for indeterminate bars by default char overlay_buf[32]; - if (!is_indeterminate || overlay != NULL) + if (!is_indeterminate || overlay) { if (!overlay) { @@ -1487,11 +1478,11 @@ void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* over overlay = overlay_buf; } - ImVec2 overlay_size = CalcTextSize(overlay, NULL); + ImVec2 overlay_size = CalcTextSize(overlay); if (overlay_size.x > 0.0f) { float text_x = is_indeterminate ? (bb.Min.x + bb.Max.x - overlay_size.x) * 0.5f : fill_x1 + style.ItemSpacing.x; - RenderTextClipped(ImVec2(ImClamp(text_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); + RenderTextClipped(ImVec2(ImClamp(text_x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, &overlay_size, ImVec2(0.0f, 0.5f), &bb); } } } @@ -1523,7 +1514,7 @@ void ImGui::Bullet() // FIXME-STYLE: we delayed adding as there is a larger plan to revamp the styling system. // Because of this we currently don't provide many styling options for this widget // (e.g. hovered/active colors are automatically inferred from a single color). -bool ImGui::TextLink(const char* label) +bool ImGui::TextLink(ImStrv label) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -1531,10 +1522,9 @@ bool ImGui::TextLink(const char* label) ImGuiContext& g = *GImGui; const ImGuiID id = window->GetID(label); - const char* label_end = FindRenderedTextEnd(label); - + const ImStrv label_for_display(label.Begin, FindRenderedTextEnd(label)); ImVec2 pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset); - ImVec2 size = CalcTextSize(label, label_end, false); + ImVec2 size = CalcTextSize(label_for_display, false); ImRect bb(pos, pos + size); ItemSize(size, 0.0f); if (!ItemAdd(bb, id)) @@ -1564,27 +1554,31 @@ bool ImGui::TextLink(const char* label) ColorConvertHSVtoRGB(h, s, v, line_colf.x, line_colf.y, line_colf.z); } - // FIXME-TEXT FIXME-DPI: Underline mode. Note how stb_truetype now expose stbtt_GetFontUnderlineMetrics(). float line_y = bb.Max.y + ImFloor(g.FontBaked->Descent * g.FontBakedScale * 0.20f); - window->DrawList->AddLineH(bb.Min.x, bb.Max.x, line_y, GetColorU32(line_colf), 1.0f * (float)(int)g.Style._MainScale); + window->DrawList->AddLineH(bb.Min.x, bb.Max.x, line_y, GetColorU32(line_colf), 1.0f * (float)(int)g.Style._MainScale); // FIXME-TEXT: Underline mode // FIXME-DPI PushStyleColor(ImGuiCol_Text, GetColorU32(text_colf)); - RenderText(bb.Min, label, label_end, false); + RenderText(bb.Min, label_for_display, false); PopStyleColor(); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); return pressed; } -bool ImGui::TextLinkOpenURL(const char* label, const char* url) +bool ImGui::TextLinkOpenURL(ImStrv label, ImStrv url) { ImGuiContext& g = *GImGui; - if (url == NULL) - url = label; bool pressed = TextLink(label); + label.End = FindRenderedTextEnd(label.Begin); + if (!url) + url = label; if (pressed && g.PlatformIO.Platform_OpenInShellFn != NULL) - g.PlatformIO.Platform_OpenInShellFn(&g, url); - SetItemTooltip(LocalizeGetMsg(ImGuiLocKey_OpenLink_s), url); // It is more reassuring for user to _always_ display URL when it is the same as the label. + { + ImStrv url_zt; + ImFormatStringToTempBuffer(&url_zt, "%.*s", url.length(), url.Begin); + g.PlatformIO.Platform_OpenInShellFn(&g, url_zt.Begin); + } + SetItemTooltip(LocalizeGetMsg(ImGuiLocKey_OpenLink_s), url.length(), url.Begin); // It is more reassuring for user to _always_ display URL when it is the same as the label. if (BeginPopupContextItem()) { if (MenuItem(LocalizeGetMsg(ImGuiLocKey_CopyLink))) @@ -1742,13 +1736,13 @@ void ImGui::Separator() SeparatorEx(flags, ImMax(g.Style.SeparatorSize, 1.0f)); } -void ImGui::SeparatorTextEx(ImGuiID id, const char* label, const char* label_end, float extra_w) +void ImGui::SeparatorTextEx(ImGuiID id, ImStrv label, float extra_w) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImGuiStyle& style = g.Style; - const ImVec2 label_size = CalcTextSize(label, label_end, false); + const ImVec2 label_size = CalcTextSize(label, false); const ImVec2 pos = window->DC.CursorPos; const ImVec2 padding = style.SeparatorTextPadding; @@ -1781,7 +1775,7 @@ void ImGui::SeparatorTextEx(ImGuiID id, const char* label, const char* label_end window->DrawList->AddLineH(sep2_x1, sep2_x2, seps_y, separator_col, separator_thickness, ImDrawFlags_StrokeCenterBiased); if (g.LogEnabled) LogSetNextTextDecoration("---", NULL); - RenderTextEllipsis(window->DrawList, label_pos, ImVec2(bb.Max.x, bb.Max.y + style.ItemSpacing.y), bb.Max.x, label, label_end, &label_size); + RenderTextEllipsis(window->DrawList, label_pos, ImVec2(bb.Max.x, bb.Max.y + style.ItemSpacing.y), bb.Max.x, label, &label_size); } else { @@ -1792,7 +1786,7 @@ void ImGui::SeparatorTextEx(ImGuiID id, const char* label, const char* label_end } } -void ImGui::SeparatorText(const char* label) +void ImGui::SeparatorText(ImStrv label) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -1804,7 +1798,7 @@ void ImGui::SeparatorText(const char* label) // - because of this we probably can't turn 'const char* label' into 'const char* fmt, ...' // Otherwise, we can decide that users wanting to drag this would layout a dedicated drag-item, // and then we can turn this into a format function. - SeparatorTextEx(0, label, FindRenderedTextEnd(label), 0.0f); + SeparatorTextEx(0, ImStrv(label.Begin, FindRenderedTextEnd(label)), 0.0f); } // Using 'hover_visibility_delay' allows us to hide the highlight and mouse cursor for a short time, which can be convenient to reduce visual noise. @@ -1942,7 +1936,7 @@ static float CalcMaxPopupHeightFromItemCount(int items_count) return (g.FontSize + g.Style.ItemSpacing.y) * items_count - g.Style.ItemSpacing.y + (g.Style.WindowPadding.y * 2); } -bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags) +bool ImGui::BeginCombo(ImStrv label, ImStrv preview_value, ImGuiComboFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); @@ -1959,9 +1953,9 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF IM_ASSERT((flags & ImGuiComboFlags_NoPreview) == 0); const float arrow_size = (flags & ImGuiComboFlags_NoArrowButton) ? 0.0f : GetFrameHeight(); - const char* label_end = FindRenderedTextEnd(label); - const ImVec2 label_size = CalcTextSize(label, label_end, false); - const float preview_width = ((flags & ImGuiComboFlags_WidthFitPreview) && (preview_value != NULL)) ? CalcTextSize(preview_value, NULL, false).x : 0.0f; + const ImStrv label_for_display(label.Begin, FindRenderedTextEnd(label)); + const ImVec2 label_size = CalcTextSize(label_for_display, false); + const float preview_width = ((flags & ImGuiComboFlags_WidthFitPreview) && preview_value) ? CalcTextSize(preview_value, false).x : 0.0f; const float w = (flags & ImGuiComboFlags_NoPreview) ? arrow_size : ((flags & ImGuiComboFlags_WidthFitPreview) ? (arrow_size + preview_width + style.FramePadding.x * 2.0f) : CalcItemWidth()); const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0f)); const ImRect total_bb(bb.Min, bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); @@ -2000,14 +1994,14 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF g.ComboPreviewData.PreviewRect = (flags & ImGuiComboFlags_NoPreview) ? ImRect() : ImRect(bb.Min.x, bb.Min.y, value_x2, bb.Max.y); // Render preview and label - if (preview_value != NULL && !(flags & ImGuiComboFlags_NoPreview)) + if (!preview_value.empty() && !(flags & ImGuiComboFlags_NoPreview)) { if (g.LogEnabled) LogSetNextTextDecoration("{", "}"); - RenderTextClipped(bb.Min + style.FramePadding, ImVec2(value_x2, bb.Max.y), preview_value, NULL, NULL); + RenderTextClipped(bb.Min + style.FramePadding, ImVec2(value_x2, bb.Max.y), preview_value, NULL); } if (label_size.x > 0) - RenderText(ImVec2(bb.Max.x + style.ItemInnerSpacing.x, bb.Min.y + style.FramePadding.y), label, label_end, false); + RenderText(ImVec2(bb.Max.x + style.ItemInnerSpacing.x, bb.Min.y + style.FramePadding.y), label_for_display, false); if (!popup_open) return false; @@ -2161,15 +2155,15 @@ void ImGui::EndComboPreview() preview_data->WithinPreview = false; } -// Getter for the old Combo() API: const char*[] -static const char* Items_ArrayGetter(void* data, int idx) +// Getter for the old Combo()/ListBox() API: const char*[] +static ImStrv Items_CharArrayGetter(void* data, int idx) { const char* const* items = (const char* const*)data; return items[idx]; } // Getter for the old Combo() API: "item1\0item2\0item3\0" -static const char* Items_SingleStringGetter(void* data, int idx) +static ImStrv Items_SingleStringGetter(void* data, int idx) { const char* items_separated_by_zeros = (const char*)data; int items_count = 0; @@ -2177,24 +2171,23 @@ static const char* Items_SingleStringGetter(void* data, int idx) while (*p) { if (idx == items_count) - break; + return p; p += ImStrlen(p) + 1; items_count++; } - return *p ? p : NULL; + return NULL; } // Old API, prefer using BeginCombo() nowadays if you can. -bool ImGui::Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), void* user_data, int items_count, int popup_max_height_in_items) +bool ImGui::Combo(ImStrv label, int* current_item, ImStrv (*getter)(void* user_data, int idx), void* user_data, int items_count, int popup_max_height_in_items) { ImGuiContext& g = *GImGui; // Call the getter to obtain the preview string which is a parameter to BeginCombo() - const char* preview_value = NULL; - if ((g.NextItemData.ItemFlagsSet | g.CurrentItemFlags) & ImGuiItemFlags_MixedValue) - preview_value = ""; - else if (*current_item >= 0 && *current_item < items_count) - preview_value = getter(user_data, *current_item); + ImStrv preview_value = NULL; + if (((g.NextItemData.ItemFlagsSet | g.CurrentItemFlags) & ImGuiItemFlags_MixedValue) == 0) + if (*current_item >= 0 && *current_item < items_count) + preview_value = getter(user_data, *current_item); // The old Combo() API exposed "popup_max_height_in_items". The new more general BeginCombo() API doesn't have/need it, but we emulate it here. if (popup_max_height_in_items != -1 && !(g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSizeConstraint)) @@ -2211,8 +2204,8 @@ bool ImGui::Combo(const char* label, int* current_item, const char* (*getter)(vo while (clipper.Step()) for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) { - const char* item_text = getter(user_data, i); - if (item_text == NULL) + ImStrv item_text = getter(user_data, i); + if (!item_text) item_text = "*Unknown item*"; PushID(i); @@ -2235,24 +2228,41 @@ bool ImGui::Combo(const char* label, int* current_item, const char* (*getter)(vo } // Combo box helper allowing to pass an array of strings. -bool ImGui::Combo(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items) +// We cannot easily obsolete the 'const char* []' version as this would be stored on user side.. +bool ImGui::Combo(ImStrv label, int* current_item, const char* const items[], int items_count, int height_in_items) { - const bool value_changed = Combo(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_in_items); - return value_changed; + return Combo(label, current_item, Items_CharArrayGetter, (void*)items, items_count, height_in_items); } +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +struct GetterProxyData { void* UserData; const char* (*UserGetter)(void* user_data, int idx); }; +static ImStrv ConstCharToStrvProxy(void* user_data, int idx) +{ + GetterProxyData* p_proxy_data = (GetterProxyData*)user_data; + return ImStrv(p_proxy_data->UserGetter(p_proxy_data->UserData, idx)); +} +bool ImGui::Combo(ImStrv label, int* current_item, const char* (*getter)(void* user_data, int idx), void* user_data, int items_count, int popup_max_height_in_items) +{ + // Convert 'const char*' getter to ImStrv version via a proxy. Cumbersome but no way out. + GetterProxyData proxy_data = { user_data, getter }; + return Combo(label, current_item, ConstCharToStrvProxy, &proxy_data, items_count, popup_max_height_in_items); +} +#endif + // Combo box helper allowing to pass all items in a single string literal holding multiple zero-terminated items "item1\0item2\0" -bool ImGui::Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items) +// We don't support an ImStrv version of this, because passing the typical "hello\0world" to a ImStrv constructor wouldn't yield the expected result. +// FIXME-OPT: Avoid computing count, or at least only when combo is open +// FIXME-OPT: The dual pass is stupid, at least could build an index on first pass. +bool ImGui::Combo(ImStrv label, int* current_item, const char* items_separated_by_zeros, int height_in_items) { int items_count = 0; - const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this, or at least only when combo is open + const char* p = items_separated_by_zeros; while (*p) { p += ImStrlen(p) + 1; items_count++; } - bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items); - return value_changed; + return Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items); } //------------------------------------------------------------------------- @@ -2655,12 +2665,10 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const if (is_wrapped) { // Wrap values - const TYPE range = v_max - v_min + (is_floating_point ? 0 : 1); - TYPE offset = ImMod((TYPE)(v_cur - v_min), range); - if (offset < 0) - offset += range; - v_cur = (TYPE)(v_min + offset); - IM_ASSERT_PARANOID(v_cur >= v_min && v_cur <= v_max); + if (v_cur < v_min) + v_cur += v_max - v_min + (is_floating_point ? 0 : 1); + if (v_cur > v_max) + v_cur -= v_max - v_min + (is_floating_point ? 0 : 1); } else { @@ -2752,7 +2760,7 @@ static bool TempInputIsClampEnabled(ImGuiSliderFlags flags, ImGuiDataType data_t // Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a Drag widget, p_min and p_max are optional. // Read code of e.g. DragFloat(), DragInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. -bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) +bool ImGui::DragScalar(ImStrv label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2764,8 +2772,8 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, const float w = CalcItemWidth(); const ImU32 color_marker = (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasColorMarker) ? g.NextItemData.ColorMarker : 0; - const char* label_end = FindRenderedTextEnd(label); - const ImVec2 label_size = CalcTextSize(label, label_end, false); + const ImStrv label_for_display(label.Begin, FindRenderedTextEnd(label)); + const ImVec2 label_size = CalcTextSize(label_for_display, false); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0f)); 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)); @@ -2841,18 +2849,18 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, LogSetNextTextDecoration("{", "}"); if (is_mixed) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextMixedValue]); - RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f)); + RenderTextClipped(frame_bb.Min, frame_bb.Max, ImStrv(value_buf, value_buf_end), NULL, ImVec2(0.5f, 0.5f)); if (is_mixed) PopStyleColor(); if (label_size.x > 0.0f) - RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label, label_end, false); + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label_for_display, false); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | (temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0)); return value_changed; } -bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) +bool ImGui::DragScalarN(ImStrv label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2878,39 +2886,39 @@ bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data } PopID(); - const char* label_end = FindRenderedTextEnd(label); - if (label != label_end) + label.End = FindRenderedTextEnd(label); + if (label.Begin != label.End) { SameLine(0, g.Style.ItemInnerSpacing.x); - TextEx(label, label_end); + TextEx(label); } EndGroup(); return value_changed; } -bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +bool ImGui::DragFloat(ImStrv label, float* v, float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +bool ImGui::DragFloat2(ImStrv label, float v[2], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +bool ImGui::DragFloat3(ImStrv label, float v[3], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +bool ImGui::DragFloat4(ImStrv label, float v[4], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, flags); } // NB: You likely want to specify the ImGuiSliderFlags_AlwaysClamp when using this. -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* format, const char* format_max, ImGuiSliderFlags flags) +bool ImGui::DragFloatRange2(ImStrv label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2935,7 +2943,8 @@ bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_cu PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); - TextEx(label, FindRenderedTextEnd(label)); + label.End = FindRenderedTextEnd(label); + TextEx(label); EndGroup(); PopID(); @@ -2943,28 +2952,28 @@ bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_cu } // NB: v_speed is float to allow adjusting the drag speed with more precision -bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +bool ImGui::DragInt(ImStrv label, int* v, float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return DragScalar(label, ImGuiDataType_S32, v, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +bool ImGui::DragInt2(ImStrv label, int v[2], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return DragScalarN(label, ImGuiDataType_S32, v, 2, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +bool ImGui::DragInt3(ImStrv label, int v[3], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return DragScalarN(label, ImGuiDataType_S32, v, 3, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +bool ImGui::DragInt4(ImStrv label, int v[4], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return DragScalarN(label, ImGuiDataType_S32, v, 4, v_speed, &v_min, &v_max, format, flags); } // NB: You likely want to specify the ImGuiSliderFlags_AlwaysClamp when using this. -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* format, const char* format_max, ImGuiSliderFlags flags) +bool ImGui::DragIntRange2(ImStrv label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2989,7 +2998,8 @@ bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_ PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); - TextEx(label, FindRenderedTextEnd(label)); + label.End = FindRenderedTextEnd(label); + TextEx(label); EndGroup(); PopID(); @@ -3368,7 +3378,7 @@ bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type // Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a slider, they are all required. // Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. -bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) +bool ImGui::SliderScalar(ImStrv label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -3380,8 +3390,8 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat const float w = CalcItemWidth(); const ImU32 color_marker = (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasColorMarker) ? g.NextItemData.ColorMarker : 0; - const char* label_end = FindRenderedTextEnd(label); - const ImVec2 label_size = CalcTextSize(label, label_end, false); + const ImStrv label_for_display(label.Begin, FindRenderedTextEnd(label)); + const ImVec2 label_size = CalcTextSize(label_for_display, false); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0f)); 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)); @@ -3453,19 +3463,19 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat LogSetNextTextDecoration("{", "}"); if (is_mixed) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextMixedValue]); - RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f)); + RenderTextClipped(frame_bb.Min, frame_bb.Max, ImStrv(value_buf, value_buf_end), NULL, ImVec2(0.5f, 0.5f)); if (is_mixed) PopStyleColor(); if (label_size.x > 0.0f) - RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label, label_end, false); + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label_for_display, false); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | (temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0)); return value_changed; } // Add multiple sliders on 1 line for compact edition of multiple components -bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, ImGuiSliderFlags flags) +bool ImGui::SliderScalarN(ImStrv label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -3491,40 +3501,40 @@ bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, i } PopID(); - const char* label_end = FindRenderedTextEnd(label); - if (label != label_end) + label.End = FindRenderedTextEnd(label); + if (label.Begin != label.End) { SameLine(0, g.Style.ItemInnerSpacing.x); - TextEx(label, label_end); + TextEx(label); } EndGroup(); return value_changed; } -bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +bool ImGui::SliderFloat(ImStrv label, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, flags); } -bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +bool ImGui::SliderFloat2(ImStrv label, float v[2], float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, flags); } -bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +bool ImGui::SliderFloat3(ImStrv label, float v[3], float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, flags); } -bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +bool ImGui::SliderFloat4(ImStrv label, float v[4], float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, flags); } -bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max, const char* format, ImGuiSliderFlags flags) +bool ImGui::SliderAngle(ImStrv label, float* v_rad, float v_degrees_min, float v_degrees_max, const char* format, ImGuiSliderFlags flags) { - if (format == NULL) + if (!format) format = "%.0f deg"; float v_deg = (*v_rad) * 360.0f / (2 * IM_PI); bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, format, flags); @@ -3533,27 +3543,27 @@ bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, fl return value_changed; } -bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +bool ImGui::SliderInt(ImStrv label, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalar(label, ImGuiDataType_S32, v, &v_min, &v_max, format, flags); } -bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +bool ImGui::SliderInt2(ImStrv label, int v[2], int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalarN(label, ImGuiDataType_S32, v, 2, &v_min, &v_max, format, flags); } -bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +bool ImGui::SliderInt3(ImStrv label, int v[3], int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalarN(label, ImGuiDataType_S32, v, 3, &v_min, &v_max, format, flags); } -bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +bool ImGui::SliderInt4(ImStrv label, int v[4], int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalarN(label, ImGuiDataType_S32, v, 4, &v_min, &v_max, format, flags); } -bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) +bool ImGui::VSliderScalar(ImStrv label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -3563,8 +3573,8 @@ bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType d const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); - const char* label_end = FindRenderedTextEnd(label); - const ImVec2 label_size = CalcTextSize(label, label_end, false); + const ImStrv label_for_display(label.Begin, FindRenderedTextEnd(label)); + const ImVec2 label_size = CalcTextSize(label_for_display, false); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size); 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)); @@ -3610,23 +3620,23 @@ bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType d const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_COUNTOF(value_buf), data_type, p_data, (is_mixed && g.MixedValueLabel != NULL) ? g.MixedValueLabel : format); if (is_mixed) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextMixedValue]); - 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)); + RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, ImStrv(value_buf, value_buf_end), NULL, ImVec2(0.5f, 0.0f)); if (is_mixed) PopStyleColor(); if (label_size.x > 0.0f) - RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label, label_end, false); + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label_for_display, false); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); return value_changed; } -bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +bool ImGui::VSliderFloat(ImStrv label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, flags); } -bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +bool ImGui::VSliderInt(ImStrv label, const ImVec2& size, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return VSliderScalar(label, size, ImGuiDataType_S32, v, &v_min, &v_max, format, flags); } @@ -3782,7 +3792,7 @@ int ImParseFormatPrecision(const char* fmt, int default_precision) // Create text input in place of another active widget (e.g. used when doing a Ctrl+Click on drag/slider widgets) // - This must be submitted right after the item it is overlaying. // FIXME: Facilitate using this in variety of other situations. -bool ImGui::TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) +bool ImGui::TempInputText(const ImRect& bb, ImGuiID id, ImStrv label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) { // On the first frame, g.TempInputTextId == 0, then on subsequent frames it becomes == id. // We clear ActiveID on the first frame to allow the InputText() taking it back. @@ -3814,7 +3824,7 @@ bool ImGui::TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* // Note that Drag/Slider functions are only forwarding the min/max values clamping values if the ImGuiSliderFlags_AlwaysClamp flag is set! // This is intended: this way we allow Ctrl+Click manual input to set a value out of bounds, for maximum flexibility. // However this may not be ideal for all uses, as some user code may break on out of bound values. -bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min, const void* p_clamp_max) +bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, ImStrv label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min, const void* p_clamp_max) { // FIXME: May need to clarify display behavior if format doesn't contain %. // "%d" -> "%d" / "There are %d items" -> "%d" / "items" -> "%d" (fallback). Also see #6405 @@ -3869,7 +3879,7 @@ void ImGui::SetNextItemRefVal(ImGuiDataType data_type, void* p_data) // Note: p_data, p_step, p_step_fast are _pointers_ to a memory address holding the data. For an Input widget, p_step and p_step_fast are optional. // Read code of e.g. InputFloat(), InputInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. -bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_step, const void* p_step_fast, const char* format, ImGuiInputTextFlags flags) +bool ImGui::InputScalar(ImStrv label, ImGuiDataType data_type, void* p_data, const void* p_step, const void* p_step_fast, const char* format, ImGuiInputTextFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -3959,11 +3969,11 @@ bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* p_data if (flags & ImGuiInputTextFlags_ReadOnly) EndDisabled(); - const char* label_end = FindRenderedTextEnd(label); - if (label != label_end) + label.End = FindRenderedTextEnd(label); + if (label.Begin != label.End) { SameLine(0, style.ItemInnerSpacing.x); - TextEx(label, label_end); + TextEx(label); } style.FramePadding = backup_frame_padding; @@ -3980,7 +3990,7 @@ bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* p_data return value_changed; } -bool ImGui::InputScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_step, const void* p_step_fast, const char* format, ImGuiInputTextFlags flags) +bool ImGui::InputScalarN(ImStrv label, ImGuiDataType data_type, void* p_data, int components, const void* p_step, const void* p_step_fast, const char* format, ImGuiInputTextFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -4004,60 +4014,60 @@ bool ImGui::InputScalarN(const char* label, ImGuiDataType data_type, void* p_dat } PopID(); - const char* label_end = FindRenderedTextEnd(label); - if (label != label_end) + label.End = FindRenderedTextEnd(label); + if (label.Begin != label.End) { SameLine(0.0f, g.Style.ItemInnerSpacing.x); - TextEx(label, label_end); + TextEx(label); } EndGroup(); return value_changed; } -bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, const char* format, ImGuiInputTextFlags flags) +bool ImGui::InputFloat(ImStrv label, float* v, float step, float step_fast, const char* format, ImGuiInputTextFlags flags) { return InputScalar(label, ImGuiDataType_Float, (void*)v, (void*)(step > 0.0f ? &step : NULL), (void*)(step_fast > 0.0f ? &step_fast : NULL), format, flags); } -bool ImGui::InputFloat2(const char* label, float v[2], const char* format, ImGuiInputTextFlags flags) +bool ImGui::InputFloat2(ImStrv label, float v[2], const char* format, ImGuiInputTextFlags flags) { return InputScalarN(label, ImGuiDataType_Float, v, 2, NULL, NULL, format, flags); } -bool ImGui::InputFloat3(const char* label, float v[3], const char* format, ImGuiInputTextFlags flags) +bool ImGui::InputFloat3(ImStrv label, float v[3], const char* format, ImGuiInputTextFlags flags) { return InputScalarN(label, ImGuiDataType_Float, v, 3, NULL, NULL, format, flags); } -bool ImGui::InputFloat4(const char* label, float v[4], const char* format, ImGuiInputTextFlags flags) +bool ImGui::InputFloat4(ImStrv label, float v[4], const char* format, ImGuiInputTextFlags flags) { return InputScalarN(label, ImGuiDataType_Float, v, 4, NULL, NULL, format, flags); } -bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags flags) +bool ImGui::InputInt(ImStrv label, int* v, int step, int step_fast, ImGuiInputTextFlags flags) { // 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. const char* format = (flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d"; return InputScalar(label, ImGuiDataType_S32, (void*)v, (void*)(step > 0 ? &step : NULL), (void*)(step_fast > 0 ? &step_fast : NULL), format, flags); } -bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags flags) +bool ImGui::InputInt2(ImStrv label, int v[2], ImGuiInputTextFlags flags) { return InputScalarN(label, ImGuiDataType_S32, v, 2, NULL, NULL, "%d", flags); } -bool ImGui::InputInt3(const char* label, int v[3], ImGuiInputTextFlags flags) +bool ImGui::InputInt3(ImStrv label, int v[3], ImGuiInputTextFlags flags) { return InputScalarN(label, ImGuiDataType_S32, v, 3, NULL, NULL, "%d", flags); } -bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags flags) +bool ImGui::InputInt4(ImStrv label, int v[4], ImGuiInputTextFlags flags) { return InputScalarN(label, ImGuiDataType_S32, v, 4, NULL, NULL, "%d", flags); } -bool ImGui::InputDouble(const char* label, double* v, double step, double step_fast, const char* format, ImGuiInputTextFlags flags) +bool ImGui::InputDouble(ImStrv label, double* v, double step, double step_fast, const char* format, ImGuiInputTextFlags flags) { return InputScalar(label, ImGuiDataType_Double, (void*)v, (void*)(step > 0.0 ? &step : NULL), (void*)(step_fast > 0.0 ? &step_fast : NULL), format, flags); } @@ -4079,18 +4089,18 @@ namespace ImStb } // If you want to use InputText() with std::string or any custom dynamic string type, use the wrapper in misc/cpp/imgui_stdlib.h/.cpp! -bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) +bool ImGui::InputText(ImStrv label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) { IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline() return InputTextEx(label, NULL, buf, (int)buf_size, ImVec2(0, 0), flags, callback, user_data); } -bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) +bool ImGui::InputTextMultiline(ImStrv label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) { return InputTextEx(label, NULL, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data); } -bool ImGui::InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) +bool ImGui::InputTextWithHint(ImStrv label, ImStrv hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) { IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline() or InputTextEx() manually if you need multi-line + hint. return InputTextEx(label, hint, buf, (int)buf_size, ImVec2(0, 0), flags, callback, user_data); @@ -4355,7 +4365,6 @@ static int STB_TEXTEDIT_INSERTCHARS(ImGuiInputTextState* obj, int pos, const cha #define IMSTB_TEXTEDIT_IMPLEMENTATION #define IMSTB_TEXTEDIT_memmove memmove - #include "imstb_textedit.h" // stb_textedit internally allows for a single undo record to do addition and deletion, but somehow, calling @@ -4455,10 +4464,10 @@ void ImGuiInputTextCallbackData::DeleteChars(int pos, int bytes_count) BufTextLen -= bytes_count; } -void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end) +void ImGuiInputTextCallbackData::InsertChars(int pos, ImStrv new_text) { // Accept null ranges - if (new_text == new_text_end) + if (new_text.Begin == new_text.End) return; ImGuiContext& g = *Ctx; @@ -4466,20 +4475,21 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons IM_ASSERT(obj->ID != 0 && g.ActiveId == obj->ID); const bool is_resizable = (Flags & ImGuiInputTextFlags_CallbackResize) != 0; const bool is_readonly = (Flags & ImGuiInputTextFlags_ReadOnly) != 0; - int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)ImStrlen(new_text); + int new_text_len = new_text.length(); // We support partial insertion (with a mod in stb_textedit.h) const int avail = BufSize - 1 - BufTextLen; if (!is_resizable && new_text_len > avail) - new_text_len = (int)(ImTextFindValidUtf8CodepointEnd(new_text, new_text + new_text_len, new_text + avail) - new_text); // Truncate to closest UTF-8 codepoint. Alternative: return 0 to cancel insertion. + new_text_len = (int)(ImTextFindValidUtf8CodepointEnd(new_text.Begin, new_text.Begin + new_text_len, new_text.Begin + avail) - new_text.Begin); // Truncate to closest UTF-8 codepoint. Alternative: return 0 to cancel insertion. if (new_text_len == 0) return; + new_text.End = new_text.Begin + new_text_len; // Grow internal buffer if needed if (new_text_len + BufTextLen + 1 > obj->TextA.Size && is_resizable && !is_readonly) { IM_ASSERT(Buf == obj->TextA.Data); - int new_buf_size = BufTextLen + ImClamp(new_text_len, 32, ImMax(256, new_text_len)) + 1; + int new_buf_size = BufTextLen + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1; obj->TextA.resize(new_buf_size + 1); obj->TextSrc = obj->TextA.Data; Buf = obj->TextA.Data; @@ -4488,7 +4498,8 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons if (BufTextLen != pos) memmove(Buf + pos + new_text_len, Buf + pos, (size_t)(BufTextLen - pos)); - memcpy(Buf + pos, new_text, (size_t)new_text_len * sizeof(char)); + if (new_text_len > 0) + memcpy(Buf + pos, new_text.Begin, (size_t)new_text_len * sizeof(char)); Buf[BufTextLen + new_text_len] = '\0'; BufDirty = true; @@ -4794,7 +4805,7 @@ static ImVec2 InputTextLineIndexGetPosOffset(ImGuiContext& g, ImGuiInputTextStat // Note that in std::string world, capacity() would omit 1 byte used by the zero-terminator. // - When active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while the InputText is active has no effect. // - If you want to use InputText() with std::string or any custom dynamic string type, use the wrapper in misc/cpp/imgui_stdlib.h/.cpp! -bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* callback_user_data) +bool ImGui::InputTextEx(ImStrv label, ImStrv hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* callback_user_data) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -4817,8 +4828,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (is_multiline) // Open group before calling GetID() because groups tracks id created within their scope (including the scrollbar) BeginGroup(); const ImGuiID id = window->GetID(label); - const char* label_end = FindRenderedTextEnd(label); - const ImVec2 label_size = CalcTextSize(label, label_end, false); + const ImStrv label_for_display(label.Begin, FindRenderedTextEnd(label)); + const ImVec2 label_size = CalcTextSize(label_for_display, false); const ImVec2 frame_size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? g.FontSize * 8.0f : label_size.y) + style.FramePadding.y * 2.0f); // Arbitrary default of 8 lines high for multi-line const ImVec2 total_size = ImVec2(frame_size.x + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), frame_size.y); @@ -5065,7 +5076,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // Select the buffer to render. const bool buf_display_from_state = (render_cursor || render_selection || g.ActiveId == id) && !is_readonly && state; - bool is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextSrc : buf)[0] == 0) && !is_mixed; + bool is_displaying_hint = (!hint.empty() && (buf_display_from_state ? state->TextSrc : buf)[0] == 0) && !is_mixed; // Password pushes a temporary font with only a fallback glyph if (is_password && !is_displaying_hint) @@ -5340,17 +5351,16 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ } else if (is_paste) { - if (const char* clipboard = GetClipboardText()) + if (ImStrv clipboard = GetClipboardText()) { // Filter pasted buffer - const int clipboard_len = (int)ImStrlen(clipboard); - const char* clipboard_end = clipboard + clipboard_len; + const int clipboard_len = clipboard.length(); ImVector clipboard_filtered; clipboard_filtered.reserve(clipboard_len + 1); - for (const char* s = clipboard; *s != 0; ) + for (const char* s = clipboard.Begin; *s != 0; ) { unsigned int c; - int in_len = ImTextCharFromUtf8(&c, s, clipboard_end); + int in_len = ImTextCharFromUtf8(&c, s, clipboard.End); s += in_len; if (!InputTextFilterCharacter(&g, state, &c, callback, callback_user_data, true)) continue; @@ -5587,7 +5597,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // Display hint when contents is empty // At this point we need to handle the possibility that a callback could have modified the underlying buffer (#8368) - const bool new_is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0) && !is_mixed; + const bool new_is_displaying_hint = (!hint.empty() && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0) && !is_mixed; if (new_is_displaying_hint != is_displaying_hint) { if (is_password && !is_displaying_hint) @@ -5605,8 +5615,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ } else if (is_displaying_hint) { - buf_display = hint; - buf_display_end = buf_display + ImStrlen(buf_display); + buf_display = hint.Begin; + buf_display_end = hint.End; } else { @@ -5729,14 +5739,14 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ float rect_width = 0.0f; if (line_selected_begin < line_selected_end) - rect_width += CalcTextSize(line_selected_begin, line_selected_end).x; + rect_width += CalcTextSize(ImStrv(line_selected_begin, line_selected_end)).x; if (text_selected_begin <= p_eol && text_selected_end > p_eol && !p_eol_is_wrap) rect_width += bg_eol_width; // So we can see selected empty lines if (rect_width == 0.0f) continue; ImRect rect; - rect.Min.x = draw_pos.x - draw_scroll.x + CalcTextSize(p, line_selected_begin).x; + rect.Min.x = draw_pos.x - draw_scroll.x + CalcTextSize(ImStrv(p, line_selected_begin)).x; rect.Min.y = draw_pos.y - draw_scroll.y + line_n * g.FontSize; rect.Max.x = rect.Min.x + rect_width; rect.Max.y = rect.Min.y + bg_offy_dn + g.FontSize; @@ -5749,7 +5759,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // Find render position for right alignment (single-line only) if (g.ActiveId != id && (flags & ImGuiInputTextFlags_ElideLeft) && !render_cursor && !render_selection) - draw_pos.x = ImMin(draw_pos.x, frame_bb.Max.x - CalcTextSize(buf_display, NULL).x - style.FramePadding.x); + draw_pos.x = ImMin(draw_pos.x, frame_bb.Max.x - CalcTextSize(buf_display).x - style.FramePadding.x); //draw_scroll.x = state->Scroll.x; // Preserve scroll when inactive? // Render text @@ -5757,8 +5767,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ g.Font->RenderText(draw_window->DrawList, g.FontSize, draw_pos - draw_scroll + ImVec2(0.0f, line_visible_n0 * g.FontSize), text_col, clip_rect.AsVec4(), - line_index->get_line_begin(buf_display, line_visible_n0), - line_index->get_line_end(buf_display, line_visible_n1 - 1), + ImStrv(line_index->get_line_begin(buf_display, line_visible_n0), line_index->get_line_end(buf_display, line_visible_n1 - 1)), wrap_width, ImDrawTextFlags_WrapKeepBlanks | ImDrawTextFlags_CpuFineClip); // Render blinking cursor @@ -5813,11 +5822,11 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (g.LogEnabled && (!is_password || is_displaying_hint)) { LogSetNextTextDecoration("{", "}"); - LogRenderedText(&draw_pos, buf_display, buf_display_end); + LogRenderedText(&draw_pos, ImStrv(buf_display, buf_display_end)); } if (label_size.x > 0) - RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label, label_end, false); + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label_for_display, false); if (state && validated) state->ValidatedThisFrame = true; @@ -5884,7 +5893,7 @@ void ImGui::DebugNodeInputTextState(ImGuiInputTextState* state) // - ColorPickerOptionsPopup() [Internal] //------------------------------------------------------------------------- -bool ImGui::ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags) +bool ImGui::ColorEdit3(ImStrv label, float col[3], ImGuiColorEditFlags flags) { return ColorEdit4(label, col, flags | ImGuiColorEditFlags_NoAlpha); } @@ -5920,7 +5929,7 @@ static void ColorEditRestoreHS(const float* col, float* H, float* S, float* V) // Edit colors components (each component in 0.0f..1.0f range). // See enum ImGuiColorEditFlags_ for available options. e.g. Only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set. // With typical options: Left-click on color square to open color picker. Right-click to open option menu. Ctrl+Click over input fields to edit them and TAB to go to next item. -bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags) +bool ImGui::ColorEdit4(ImStrv label, float col[4], ImGuiColorEditFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -5929,7 +5938,6 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const float square_sz = GetFrameHeight(); - const char* label_display_end = FindRenderedTextEnd(label); float w_full = CalcItemWidth(); g.NextItemData.ClearFlags(); @@ -5938,6 +5946,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag const bool set_current_color_edit_id = (g.ColorEditCurrentID == 0); if (set_current_color_edit_id) g.ColorEditCurrentID = window->IDStack.back(); + const ImStrv label_for_display(label.Begin, FindRenderedTextEnd(label)); // If we're not showing any slider there's no point in doing any HSV conversions const ImGuiColorEditFlags flags_untouched = flags; @@ -6089,9 +6098,9 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag if (g.CurrentWindow->BeginCount == 1) { picker_active_window = g.CurrentWindow; - if (label != label_display_end) + if (label_for_display.Begin != label_for_display.End) { - TextEx(label, label_display_end); + TextEx(label_for_display); Spacing(); } ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags_DataTypeMask_ | ImGuiColorEditFlags_PickerMask_ | ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar; @@ -6105,13 +6114,13 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag } } - if (label != label_display_end && !(flags & ImGuiColorEditFlags_NoLabel)) + if (label_for_display.Begin != label_for_display.End && !(flags & ImGuiColorEditFlags_NoLabel)) { // Position not necessarily next to last submitted button (e.g. if style.ColorButtonPosition == ImGuiDir_Left), // but we need to use SameLine() to setup baseline correctly. Might want to refactor SameLine() to simplify this. SameLine(0.0f, style.ItemInnerSpacing.x); window->DC.CursorPos.x = pos.x + ((flags & ImGuiColorEditFlags_NoInputs) ? w_button : w_full + style.ItemInnerSpacing.x); - TextEx(label, label_display_end); + TextEx(label_for_display); } // Convert back @@ -6175,7 +6184,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag return value_changed; } -bool ImGui::ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags) +bool ImGui::ColorPicker3(ImStrv label, float col[3], ImGuiColorEditFlags flags) { float col4[4] = { col[0], col[1], col[2], 1.0f }; if (!ColorPicker4(label, col4, flags | ImGuiColorEditFlags_NoAlpha)) @@ -6184,30 +6193,21 @@ bool ImGui::ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags fl return true; } -// Helper for RenderArrowsForVerticalBar(). 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side. -static void RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 p, ImVec2 half_sz, ImGuiDir direction, ImU32 col) -{ - if (direction == ImGuiDir_Left) { draw_list->AddTriangleFilled(ImVec2(p.x + half_sz.x, p.y - half_sz.y), ImVec2(p.x + half_sz.x, p.y + half_sz.y), p, col); } - if (direction == ImGuiDir_Right) { draw_list->AddTriangleFilled(ImVec2(p.x - half_sz.x, p.y + half_sz.y), ImVec2(p.x - half_sz.x, p.y - half_sz.y), p, col); } - //if (direction == ImGuiDir_Up) { draw_list->AddTriangleFilled(ImVec2(p.x + half_sz.x, p.y + half_sz.y), ImVec2(p.x - half_sz.x, p.y + half_sz.y), p, col); } - //if (direction == ImGuiDir_Down){ draw_list->AddTriangleFilled(ImVec2(p.x - half_sz.x, p.y - half_sz.y), ImVec2(p.x + half_sz.x, p.y - half_sz.y), p, col); } -} - // Helper for ColorPicker4() -static void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 p, ImVec2 half_sz, float bar_w, float alpha) +static void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, float bar_w, float alpha) { ImU32 alpha8 = IM_F32_TO_INT8_SAT(alpha); - RenderArrowPointingAt(draw_list, ImVec2(p.x + half_sz.x + 1, p.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Right, IM_COL32(0,0,0,alpha8)); - RenderArrowPointingAt(draw_list, ImVec2(p.x + half_sz.x, p.y), half_sz, ImGuiDir_Right, IM_COL32(255,255,255,alpha8)); - RenderArrowPointingAt(draw_list, ImVec2(p.x + bar_w - half_sz.x - 1, p.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Left, IM_COL32(0,0,0,alpha8)); - RenderArrowPointingAt(draw_list, ImVec2(p.x + bar_w - half_sz.x, p.y), half_sz, ImGuiDir_Left, IM_COL32(255,255,255,alpha8)); + ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x + 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Right, IM_COL32(0,0,0,alpha8)); + ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x, pos.y), half_sz, ImGuiDir_Right, IM_COL32(255,255,255,alpha8)); + ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x - 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Left, IM_COL32(0,0,0,alpha8)); + ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x, pos.y), half_sz, ImGuiDir_Left, IM_COL32(255,255,255,alpha8)); } // Note: ColorPicker4() only accesses 3 floats if ImGuiColorEditFlags_NoAlpha flag is set. // (In C++ the 'float col[4]' notation for a function argument is equivalent to 'float* col', we only specify a size to facilitate understanding of the code.) // FIXME: we adjust the big color square height based on item width, which may cause a flickering feedback loop (if automatic height makes a vertical scrollbar appears, affecting automatic width..) // FIXME: this is trying to be aware of style.Alpha but not fully correct. Also, the color wheel will have overlapping glitches with (style.Alpha < 1.0) -bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags, const float* ref_col) +bool ImGui::ColorPicker4(ImStrv label, float col[4], ImGuiColorEditFlags flags, const float* ref_col) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); @@ -6223,8 +6223,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl g.NextItemData.ClearFlags(); const float backup_alpha = g.Style.Alpha; - const bool is_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0 && (g.DisabledStackSize > 0); // Intentionally not check ItemFlagsSet - if (is_disabled) + if (g.DisabledStackSize > 0) g.Style.Alpha = g.DisabledAlphaBackup; // Cancel out effect of BeginDisabled() for color swatches. PushID(label); @@ -6372,12 +6371,12 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl if (!(flags & ImGuiColorEditFlags_NoLabel)) { - const char* label_display_end = FindRenderedTextEnd(label); - if (label != label_display_end) + const ImStrv label_for_display(label.Begin, FindRenderedTextEnd(label)); + if (!label_for_display.empty()) { if ((flags & ImGuiColorEditFlags_NoSidePreview)) SameLine(0, style.ItemInnerSpacing.x); - TextEx(label, label_display_end); + TextEx(label_for_display); } } @@ -6586,7 +6585,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl g.ColorEditCurrentID = 0; PopID(); - if (is_disabled) + if (g.DisabledStackSize > 0) g.Style.Alpha = backup_alpha; return value_changed; @@ -6596,7 +6595,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl // FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip. // 'desc_id' is not called 'label' because we don't display it next to the button, but only in the tooltip. // Note that 'col' may be encoded in HSV if ImGuiColorEditFlags_InputHSV is set. -bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags, const ImVec2& size_arg) +bool ImGui::ColorButton(ImStrv desc_id, const ImVec4& col, ImGuiColorEditFlags flags, const ImVec2& size_arg) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -6627,8 +6626,7 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl const bool is_mixed = (g.LastItemData.ItemFlags & ImGuiItemFlags_MixedValue) != 0; const float backup_alpha = g.Style.Alpha; - const bool is_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0 && (g.DisabledStackSize > 0); // Intentionally not use LastItemData.ItemFlags here. - if (is_disabled) + if (g.DisabledStackSize > 0) g.Style.Alpha = g.DisabledAlphaBackup; // Cancel out effect of BeginDisabled() for color swatches. if (is_mixed) { @@ -6656,7 +6654,7 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl else window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(col_source), rounding); } - if (is_disabled) + if (g.DisabledStackSize > 0) g.Style.Alpha = backup_alpha; RenderNavCursor(bb, id); if ((flags & ImGuiColorEditFlags_NoBorder) == 0) @@ -6704,16 +6702,16 @@ void ImGui::SetColorEditOptions(ImGuiColorEditFlags flags) #endif // Note: only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set. -void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags) +void ImGui::ColorTooltip(ImStrv text, const float* col, ImGuiColorEditFlags flags) { ImGuiContext& g = *GImGui; if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePrevious, ImGuiWindowFlags_None)) return; - const char* text_end = text ? FindRenderedTextEnd(text, NULL) : text; - if (text_end > text) + text.End = FindRenderedTextEnd(text); + if (text.Begin != text.End) { - TextEx(text, text_end); + TextEx(text); Separator(); } @@ -6853,7 +6851,7 @@ void ImGui::ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags fl // - CollapsingHeader() //------------------------------------------------------------------------- -bool ImGui::TreeNode(const char* str_id, const char* fmt, ...) +bool ImGui::TreeNode(ImStrv str_id, const char* fmt, ...) { va_list args; va_start(args, fmt); @@ -6871,16 +6869,16 @@ bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...) return is_open; } -bool ImGui::TreeNode(const char* label) +bool ImGui::TreeNode(ImStrv label) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiID id = window->GetID(label); - return TreeNodeBehavior(id, ImGuiTreeNodeFlags_None, label, NULL); + return TreeNodeBehavior(id, ImGuiTreeNodeFlags_None, label); } -bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args) +bool ImGui::TreeNodeV(ImStrv str_id, const char* fmt, va_list args) { return TreeNodeExV(str_id, 0, fmt, args); } @@ -6890,16 +6888,16 @@ bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args) return TreeNodeExV(ptr_id, 0, fmt, args); } -bool ImGui::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags) +bool ImGui::TreeNodeEx(ImStrv label, ImGuiTreeNodeFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiID id = window->GetID(label); - return TreeNodeBehavior(id, flags, label, NULL); + return TreeNodeBehavior(id, flags, label); } -bool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) +bool ImGui::TreeNodeEx(ImStrv str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) { va_list args; va_start(args, fmt); @@ -6917,16 +6915,16 @@ bool ImGui::TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* return is_open; } -bool ImGui::TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) +bool ImGui::TreeNodeExV(ImStrv str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiID id = window->GetID(str_id); - const char* label, *label_end; - ImFormatStringToTempBufferV(&label, &label_end, fmt, args); - return TreeNodeBehavior(id, flags, label, label_end); + ImStrv label; + ImFormatStringToTempBufferV(&label, fmt, args); + return TreeNodeBehavior(id, flags, label); } bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) @@ -6936,20 +6934,18 @@ bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char return false; ImGuiID id = window->GetID(ptr_id); - const char* label, *label_end; - ImFormatStringToTempBufferV(&label, &label_end, fmt, args); - return TreeNodeBehavior(id, flags, label, label_end); + ImStrv label; + ImFormatStringToTempBufferV(&label, fmt, args); + return TreeNodeBehavior(id, flags, label); } -// I would like to design a more feature-full and generic API for this. -// (cc: #3823, #9251, #7553, #6754, #5423, #2958, #2079, #1947, #1131, #722, #9569) -bool ImGui::TreeNodeGetOpen(ImGuiID storage_id, ImGuiTreeNodeFlags flags) +// The reason those two functions are not yet in public API is because I would like to design a more feature-full and generic API for this. +// They are otherwise function (cc: #3823, #9251, #7553, #6754, #5423, #2958, #2079, #1947, #1131, #722) +bool ImGui::TreeNodeGetOpen(ImGuiID storage_id) { - if (flags & ImGuiTreeNodeFlags_Leaf) - return true; ImGuiContext& g = *GImGui; ImGuiStorage* storage = g.CurrentWindow->DC.StateStorage; - return storage->GetInt(storage_id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0; + return storage->GetInt(storage_id, 0) != 0; } void ImGui::TreeNodeSetOpen(ImGuiID storage_id, bool is_open) @@ -7033,7 +7029,7 @@ static void TreeNodeStoreStackData(ImGuiTreeNodeFlags flags, float x1) #define TREE_NODE_MAX_DEPTH 32 #define TREE_NODE_GET_DEPTH_MASK(_DEPTH) (((ImU32)(_DEPTH) < TREE_NODE_MAX_DEPTH) ? (1u << (_DEPTH)) : 0u) -bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end) +bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, ImStrv label) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -7047,14 +7043,12 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l const bool use_frame_padding = (display_frame || (flags & ImGuiTreeNodeFlags_FramePadding)); const ImVec2 padding = use_frame_padding ? style.FramePadding : ImVec2(style.FramePadding.x, ImMin(window->DC.CurrLineTextBaseOffset, style.FramePadding.y)); - if (!label_end) - label_end = FindRenderedTextEnd(label); - const ImVec2 label_size = CalcTextSize(label, label_end, false); + const ImStrv label_for_display(label.Begin, FindRenderedTextEnd(label)); + const ImVec2 label_size = CalcTextSize(label_for_display, false); - const float icon_width = g.FontSize + padding.x * 2; - const float text_offset_x = display_frame ? icon_width + padding.x : icon_width; // Collapsing arrow width + Spacing + const float text_offset_x = g.FontSize + (display_frame ? padding.x * 3 : padding.x * 2); // Collapsing arrow width + Spacing const float text_offset_y = use_frame_padding ? ImMax(style.FramePadding.y, window->DC.CurrLineTextBaseOffset) : window->DC.CurrLineTextBaseOffset; // Latch before ItemSize changes it - const float text_width = icon_width + label_size.x; // Include collapsing arrow + const float text_width = g.FontSize + label_size.x + padding.x * 2; // Include collapsing arrow const float frame_height = label_size.y + padding.y * 2; const bool span_all_columns = (flags & ImGuiTreeNodeFlags_SpanAllColumns) != 0 && (g.CurrentTable != NULL); @@ -7087,7 +7081,6 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l if (span_all_columns || span_all_columns_label) { // Modify ClipRect for the ItemAdd(), faster than doing a PushColumnsBackground/PushTableBackgroundChannel for every Selectable.. - // FIXME: Investigate moving this to an item flag, along duplicate code in Selectable(). How to do optimally? const float backup_clip_rect_min_x = window->ClipRect.Min.x; const float backup_clip_rect_max_x = window->ClipRect.Max.x; window->ClipRect.Min.x = window->ParentWorkRect.Min.x; @@ -7295,7 +7288,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l if (flags & ImGuiTreeNodeFlags_Bullet) RenderBullet(window->DrawList, ImVec2(text_pos.x - text_offset_x * 0.5f, text_pos.y + g.FontSize * 0.5f), text_col); else if (!is_leaf) - RenderArrow(window->DrawList, ImVec2(text_pos.x + g.FontSize * 0.15f - text_offset_x + padding.x, text_pos.y + g.FontSize * 0.15f), text_col, is_open ? ((flags & ImGuiTreeNodeFlags_UpsideDownArrow) ? ImGuiDir_Up : ImGuiDir_Down) : ImGuiDir_Right, 0.70f); + RenderArrow(window->DrawList, ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y + g.FontSize * 0.15f), text_col, is_open ? ((flags & ImGuiTreeNodeFlags_UpsideDownArrow) ? ImGuiDir_Up : ImGuiDir_Down) : ImGuiDir_Right, 0.70f); if (g.LogEnabled) LogSetNextTextDecoration(">", NULL); } @@ -7305,9 +7298,9 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l // Label if (display_frame) - RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size); + RenderTextClipped(text_pos, frame_bb.Max, label_for_display, &label_size); else - RenderText(text_pos, label, label_end, false); + RenderText(text_pos, label_for_display, false); if (span_all_columns_label) TablePopBackgroundChannel(); @@ -7387,7 +7380,7 @@ void ImGui::TreeNodeDrawLineToTreePop(const ImGuiTreeNodeStackData* data) TablePopColumnChannel(); } -void ImGui::TreePush(const char* str_id) +void ImGui::TreePush(ImStrv str_id) { ImGuiWindow* window = GetCurrentWindow(); Indent(); @@ -7473,7 +7466,7 @@ void ImGui::SetNextItemStorageID(ImGuiID storage_id) // CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags_NoTreePushOnOpen flag). // This is basically the same as calling TreeNodeEx(label, ImGuiTreeNodeFlags_CollapsingHeader). You can remove the _NoTreePushOnOpen flag if you want behavior closer to normal TreeNode(). -bool ImGui::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags) +bool ImGui::CollapsingHeader(ImStrv label, ImGuiTreeNodeFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -7486,7 +7479,7 @@ bool ImGui::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags) // p_visible != NULL && *p_visible == true : show a small close button on the corner of the header, clicking the button will set *p_visible = false // p_visible != NULL && *p_visible == false : do not show the header at all // Do not mistake this with the Open state of the header itself, which you can adjust with SetNextItemOpen() or ImGuiTreeNodeFlags_DefaultOpen. -bool ImGui::CollapsingHeader(const char* label, bool* p_visible, ImGuiTreeNodeFlags flags) +bool ImGui::CollapsingHeader(ImStrv label, bool* p_visible, ImGuiTreeNodeFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -7529,7 +7522,7 @@ bool ImGui::CollapsingHeader(const char* label, bool* p_visible, ImGuiTreeNodeFl // But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID or use ##unique_id. // With this scheme, ImGuiSelectableFlags_SpanAllColumns and ImGuiSelectableFlags_AllowOverlap are also frequently used flags. // FIXME: Selectable() with (size.x == 0.0f) and (SelectableTextAlign.x > 0.0f) followed by SameLine() is currently not supported. -bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) +bool ImGui::Selectable(ImStrv label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -7540,8 +7533,9 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl // Submit label or explicit size to ItemSize(), whereas ItemAdd() will submit a larger/spanning rectangle. ImGuiID id = window->GetID(label); - const char* label_end = FindRenderedTextEnd(label); - ImVec2 label_size = CalcTextSize(label, label_end, false); + + const ImStrv label_for_display(label.Begin, FindRenderedTextEnd(label)); + ImVec2 label_size = CalcTextSize(label_for_display, false); ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y); ImVec2 pos = window->DC.CursorPos; pos.y += window->DC.CurrLineTextBaseOffset; @@ -7701,10 +7695,10 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl // Text stays at the submission position. Alignment/clipping extents ignore SpanAllColumns. if (is_visible) - RenderTextClipped(pos, ImVec2(ImMin(pos.x + size.x, window->WorkRect.Max.x), pos.y + size.y), label, label_end, &label_size, style.SelectableTextAlign, &bb); + RenderTextClipped(pos, ImVec2(ImMin(pos.x + size.x, window->WorkRect.Max.x), pos.y + size.y), label_for_display, &label_size, style.SelectableTextAlign, &bb); #ifdef IMGUI_DEBUG_BOXSELECT - if (g.BoxSelectState.UnclipMode) { GetForegroundDrawList()->AddText(pos, IM_COL32(255,255,0,200), label, label_end); } + if (g.BoxSelectState.UnclipMode) { GetForegroundDrawList()->AddText(pos, IM_COL32(255,255,0,200), label_for_display); } #endif // Automatically close popups @@ -7721,7 +7715,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl return pressed; //-V1020 } -bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) +bool ImGui::Selectable(ImStrv label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) { if (Selectable(label, *p_selected, flags, size_arg)) { @@ -8813,7 +8807,7 @@ bool ImGuiSelectionBasicStorage::GetNextSelectedItem(void** opaque_it, ImGuiID* it = _Storage.Data.Data; IM_ASSERT(it >= _Storage.Data.Data && it <= it_end); if (it != it_end) - while (it < it_end && it->val_i == 0) + while (it->val_i == 0 && it < it_end) it++; const bool has_more = (it != it_end); *opaque_it = has_more ? (void**)(it + 1) : (void**)(it); @@ -8964,7 +8958,7 @@ void ImGuiSelectionExternalStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io) // If you don't need a label you can pretty much directly use ImGui::BeginChild() with ImGuiChildFlags_FrameStyle. // Tip: To have a list filling the entire window width, use size.x = -FLT_MIN and pass an non-visible label e.g. "##empty" // Tip: If your vertical size is calculated from an item count (e.g. 10 * item_height) consider adding a fractional part to facilitate seeing scrolling boundaries (e.g. 10.5f * item_height). -bool ImGui::BeginListBox(const char* label, const ImVec2& size_arg) +bool ImGui::BeginListBox(ImStrv label, const ImVec2& size_arg) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); @@ -8973,8 +8967,8 @@ bool ImGui::BeginListBox(const char* label, const ImVec2& size_arg) const ImGuiStyle& style = g.Style; const ImGuiID id = GetID(label); - const char* label_end = FindRenderedTextEnd(label); - const ImVec2 label_size = CalcTextSize(label, label_end, false); + const ImStrv label_for_display(label.Begin, FindRenderedTextEnd(label)); + const ImVec2 label_size = CalcTextSize(label_for_display, false); // Size default to hold ~7.25 items. // Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar. @@ -8997,7 +8991,7 @@ bool ImGui::BeginListBox(const char* label, const ImVec2& size_arg) if (label_size.x > 0.0f) { ImVec2 label_pos = ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y); - RenderText(label_pos, label, label_end, false); + RenderText(label_pos, label_for_display, false); window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, label_pos + label_size); AlignTextToFramePadding(); } @@ -9017,15 +9011,16 @@ void ImGui::EndListBox() EndGroup(); // This is only required to be able to do IsItemXXX query on the whole ListBox including label } -bool ImGui::ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_items) +// List box helper allowing to pass an array of strings. +// We cannot easily obsolete the 'const char* []' version as this would be stored on user side.. +bool ImGui::ListBox(ImStrv label, int* current_item, const char* const items[], int items_count, int height_items) { - const bool value_changed = ListBox(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_items); - return value_changed; + return ListBox(label, current_item, Items_CharArrayGetter, (void*)items, items_count, height_items); } // This is merely a helper around BeginListBox(), EndListBox(). // Considering using those directly to submit custom data or store selection differently. -bool ImGui::ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), void* user_data, int items_count, int height_in_items) +bool ImGui::ListBox(ImStrv label, int* current_item, ImStrv (*getter)(void* user_data, int idx), void* user_data, int items_count, int height_in_items) { ImGuiContext& g = *GImGui; @@ -9047,8 +9042,8 @@ bool ImGui::ListBox(const char* label, int* current_item, const char* (*getter)( while (clipper.Step()) for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) { - const char* item_text = getter(user_data, i); - if (item_text == NULL) + ImStrv item_text = getter(user_data, i); + if (!item_text) item_text = "*Unknown item*"; PushID(i); @@ -9070,6 +9065,15 @@ bool ImGui::ListBox(const char* label, int* current_item, const char* (*getter)( return value_changed; } +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +bool ImGui::ListBox(ImStrv label, int* current_item, const char* (*getter)(void* user_data, int idx), void* user_data, int items_count, int height_in_items) +{ + // Convert 'const char*' getter to ImStrv version via a proxy. Cumbersome but no way out. + GetterProxyData proxy_data = { user_data, getter }; + return ListBox(label, current_item, ConstCharToStrvProxy, &proxy_data, items_count, height_in_items); +} +#endif + //------------------------------------------------------------------------- // [SECTION] Widgets: PlotLines, PlotHistogram //------------------------------------------------------------------------- @@ -9081,7 +9085,7 @@ bool ImGui::ListBox(const char* label, int* current_item, const char* (*getter)( // Consider using ImPlot (https://github.com/epezent/implot) which is much better! //------------------------------------------------------------------------- -int 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, const ImVec2& size_arg) +int ImGui::PlotEx(ImGuiPlotType plot_type, ImStrv label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, ImStrv overlay_text, float scale_min, float scale_max, const ImVec2& size_arg) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); @@ -9090,9 +9094,8 @@ int ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_get const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); - - const char* label_end = FindRenderedTextEnd(label); - const ImVec2 label_size = CalcTextSize(label, label_end, false); + const ImStrv label_for_display(label.Begin, FindRenderedTextEnd(label)); + const ImVec2 label_size = CalcTextSize(label_for_display, false); const ImVec2 frame_size = CalcItemSize(size_arg, CalcItemWidth(), label_size.y + style.FramePadding.y * 2.0f); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); @@ -9190,10 +9193,10 @@ int ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_get // Text overlay if (overlay_text) - 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)); + RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, NULL, ImVec2(0.5f, 0.0f)); if (label_size.x > 0.0f) - RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label, label_end, false); + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label_for_display, false); // Return hovered index or -1 if none are hovered. // This is currently not exposed in the public API because we need a larger redesign of the whole thing, but in the short-term we are making it available in PlotEx(). @@ -9216,25 +9219,25 @@ static float Plot_ArrayGetter(void* data, int idx) return v; } -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) +void ImGui::PlotLines(ImStrv label, const float* values, int values_count, int values_offset, ImStrv overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride) { ImGuiPlotArrayGetterData data(values, stride); PlotEx(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } -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) +void ImGui::PlotLines(ImStrv label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, ImStrv overlay_text, float scale_min, float scale_max, ImVec2 graph_size) { PlotEx(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } // Plot Histogram (the data provided _is_ histogram data. it doesn't compute the histogram of your data) -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) +void ImGui::PlotHistogram(ImStrv label, const float* values, int values_count, int values_offset, ImStrv overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride) { ImGuiPlotArrayGetterData data(values, stride); PlotEx(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } -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) +void ImGui::PlotHistogram(ImStrv label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, ImStrv overlay_text, float scale_min, float scale_max, ImVec2 graph_size) { PlotEx(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } @@ -9246,32 +9249,32 @@ void ImGui::PlotHistogram(const char* label, float (*values_getter)(void* data, // - Value() //------------------------------------------------------------------------- -void ImGui::Value(const char* prefix, bool b) +void ImGui::Value(ImStrv prefix, bool b) { - Text("%s: %s", prefix, (b ? "true" : "false")); + Text("%.*s: %s", prefix.length(), prefix.Begin, (b ? "true" : "false")); } -void ImGui::Value(const char* prefix, int v) +void ImGui::Value(ImStrv prefix, int v) { - Text("%s: %d", prefix, v); + Text("%.*s: %d", prefix.length(), prefix.Begin, v); } -void ImGui::Value(const char* prefix, unsigned int v) +void ImGui::Value(ImStrv prefix, unsigned int v) { - Text("%s: %d", prefix, v); + Text("%.*s: %d", prefix.length(), prefix.Begin, v); } -void ImGui::Value(const char* prefix, float v, const char* float_format) +void ImGui::Value(ImStrv prefix, float v, ImStrv float_format) { if (float_format) { char fmt[64]; - ImFormatString(fmt, IM_COUNTOF(fmt), "%%s: %s", float_format); - Text(fmt, prefix, v); + ImFormatString(fmt, IM_COUNTOF(fmt), "%%.*s: %.*s", float_format.length(), float_format.Begin); + Text(fmt, prefix.length(), prefix.Begin, v); } else { - Text("%s: %.3f", prefix, v); + Text("%.*s: %.3f", prefix.length(), prefix.Begin, v); } } @@ -9428,7 +9431,7 @@ void ImGui::EndMenuBar() // Important: calling order matters! // FIXME: Somehow overlapping with docking tech. // FIXME: The "rect-cut" aspect of this could be formalized into a lower-level helper (rect-cut: https://halt.software/dead-simple-layouts) -bool ImGui::BeginViewportSideBar(const char* name, ImGuiViewport* viewport_p, ImGuiDir dir, float axis_size, ImGuiWindowFlags window_flags) +bool ImGui::BeginViewportSideBar(ImStrv name, ImGuiViewport* viewport_p, ImGuiDir dir, float axis_size, ImGuiWindowFlags window_flags) { IM_ASSERT(dir != ImGuiDir_None); @@ -9528,7 +9531,7 @@ static bool IsRootOfOpenMenuSet() return upper_popup->Window && (upper_popup->Window->Flags & ImGuiWindowFlags_ChildMenu) && ImGui::IsWindowChildOf(upper_popup->Window, window, true); } -bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled) +bool ImGui::BeginMenuEx(ImStrv label, ImStrv icon, bool enabled) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -9560,8 +9563,8 @@ bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled) // Tag menu as used. Next time BeginMenu() with same ID is called it will append to existing menu g.MenusIdSubmittedThisFrame.push_back(id); - const char* label_end = FindRenderedTextEnd(label); - ImVec2 label_size = CalcTextSize(label, label_end, false); + const ImStrv label_for_display(label.Begin, FindRenderedTextEnd(label)); + ImVec2 label_size = CalcTextSize(label, false); // Odd hack to allow hovering across menus of a same menu-set (otherwise we wouldn't be able to hover parent without always being a Child window) // This is only done for items for the menu set and not the full parent window. @@ -9594,7 +9597,7 @@ bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled) ImVec2 text_pos(window->DC.CursorPos.x + offsets->OffsetLabel, pos.y + window->DC.CurrLineTextBaseOffset); pressed = Selectable("", menu_is_open, selectable_flags, label_size); LogSetNextTextDecoration("[", "]"); - RenderText(text_pos, label, label_end, false); + RenderText(text_pos, label_for_display, false); PopStyleVar(); window->DC.CursorPos.x += IM_TRUNC(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar(). popup_pos = ImVec2(pos.x - 1.0f - IM_TRUNC(style.ItemSpacing.x * 0.5f), text_pos.y - style.FramePadding.y + window->MenuBarHeight); @@ -9604,14 +9607,14 @@ bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled) // Menu inside a regular/vertical menu // (In a typical menu window where all items are BeginMenu() or MenuItem() calls, extra_w will always be 0.0f. // Only when they are other items sticking out we're going to add spacing, yet only register minimum width into the layout system.) - float icon_w = (icon && icon[0]) ? CalcTextSize(icon, NULL).x : 0.0f; + float icon_w = !icon.empty() ? CalcTextSize(icon).x : 0.0f; float checkmark_w = IM_TRUNC(g.FontSize * 1.20f); float min_w = offsets->DeclColumns(icon_w, label_size.x, 0.0f, checkmark_w); // Feedback to next frame float extra_w = ImMax(0.0f, GetContentRegionAvail().x - min_w); ImVec2 text_pos(window->DC.CursorPos.x, pos.y + window->DC.CurrLineTextBaseOffset); pressed = Selectable("", menu_is_open, selectable_flags | ImGuiSelectableFlags_SpanAvailWidth, ImVec2(min_w, label_size.y)); LogSetNextTextDecoration("", ">"); - RenderText(ImVec2(text_pos.x + offsets->OffsetLabel, text_pos.y), label, label_end, false); + RenderText(ImVec2(text_pos.x + offsets->OffsetLabel, text_pos.y), label_for_display, false); if (icon_w > 0.0f) RenderText(ImVec2(text_pos.x + offsets->OffsetIcon, text_pos.y), icon); RenderArrow(window->DrawList, ImVec2(text_pos.x + offsets->OffsetMark + extra_w + g.FontSize * 0.30f, text_pos.y), GetColorU32(ImGuiCol_Text), ImGuiDir_Right); @@ -9753,7 +9756,7 @@ bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled) return menu_is_open; } -bool ImGui::BeginMenu(const char* label, bool enabled) +bool ImGui::BeginMenu(ImStrv label, bool enabled) { return BeginMenuEx(label, NULL, enabled); } @@ -9777,7 +9780,7 @@ void ImGui::EndMenu() EndPopup(); } -bool ImGui::MenuItemEx(const char* label, const char* icon, const char* shortcut, bool selected, bool enabled) +bool ImGui::MenuItemEx(ImStrv label, ImStrv icon, ImStrv shortcut, bool selected, bool enabled) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -9786,8 +9789,8 @@ bool ImGui::MenuItemEx(const char* label, const char* icon, const char* shortcut ImGuiContext& g = *GImGui; ImGuiStyle& style = g.Style; ImVec2 pos = window->DC.CursorPos; - const char* label_end = FindRenderedTextEnd(label); - ImVec2 label_size = CalcTextSize(label, label_end, false); + const ImStrv label_for_display(label.Begin, FindRenderedTextEnd(label)); + ImVec2 label_size = CalcTextSize(label, false); // See BeginMenuEx() for comments about this. const bool menuset_is_open = IsRootOfOpenMenuSet(); @@ -9816,7 +9819,7 @@ bool ImGui::MenuItemEx(const char* label, const char* icon, const char* shortcut pressed = Selectable("", selected, selectable_flags, ImVec2(label_size.x, 0.0f)); PopStyleVar(); if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) - RenderText(text_pos, label, label_end, false); + RenderText(text_pos, label_for_display, false); window->DC.CursorPos.x += IM_TRUNC(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar(). } else @@ -9824,8 +9827,8 @@ bool ImGui::MenuItemEx(const char* label, const char* icon, const char* shortcut // Menu item inside a vertical menu // (In a typical menu window where all items are BeginMenu() or MenuItem() calls, extra_w will always be 0.0f. // Only when they are other items sticking out we're going to add spacing, yet only register minimum width into the layout system.) - float icon_w = (icon && icon[0]) ? CalcTextSize(icon, NULL).x : 0.0f; - float shortcut_w = (shortcut && shortcut[0]) ? CalcTextSize(shortcut, NULL).x : 0.0f; + float icon_w = !icon.empty() ? CalcTextSize(icon).x : 0.0f; + float shortcut_w = !shortcut.empty() ? CalcTextSize(shortcut).x : 0.0f; float checkmark_w = IM_TRUNC(g.FontSize * 1.20f); // FIXME: Always accounted for, even in a menu with none, because 'selected' has no neutral setting. float min_w = offsets->DeclColumns(icon_w, label_size.x, shortcut_w, checkmark_w); // Feedback for next frame float stretch_w = ImMax(0.0f, GetContentRegionAvail().x - min_w); @@ -9833,14 +9836,14 @@ bool ImGui::MenuItemEx(const char* label, const char* icon, const char* shortcut pressed = Selectable("", false, selectable_flags | ImGuiSelectableFlags_SpanAvailWidth, ImVec2(min_w, label_size.y)); if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) { - RenderText(text_pos + ImVec2(offsets->OffsetLabel, 0.0f), label, label_end, false); + RenderText(text_pos + ImVec2(offsets->OffsetLabel, 0.0f), label_for_display, false); if (icon_w > 0.0f) RenderText(text_pos + ImVec2(offsets->OffsetIcon, 0.0f), icon); if (shortcut_w > 0.0f) { PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); LogSetNextTextDecoration("(", ")"); - RenderText(text_pos + ImVec2(offsets->OffsetShortcut + stretch_w, 0.0f), shortcut, NULL, false); + RenderText(text_pos + ImVec2(offsets->OffsetShortcut + stretch_w, 0.0f), shortcut, false); PopStyleColor(); } if (selected) @@ -9867,12 +9870,12 @@ bool ImGui::MenuItemEx(const char* label, const char* icon, const char* shortcut return pressed; } -bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, bool enabled) +bool ImGui::MenuItem(ImStrv label, ImStrv shortcut, bool selected, bool enabled) { return MenuItemEx(label, NULL, shortcut, selected, enabled); } -bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled) +bool ImGui::MenuItem(ImStrv label, ImStrv shortcut, bool* p_selected, bool enabled) { if (MenuItemEx(label, NULL, shortcut, p_selected ? *p_selected : false, enabled)) { @@ -9921,7 +9924,7 @@ struct ImGuiTabBarSection namespace ImGui { static void TabBarLayout(ImGuiTabBar* tab_bar); - static ImU32 TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label, ImGuiWindow* docked_window); + static ImU32 TabBarCalcTabID(ImGuiTabBar* tab_bar, ImStrv label, ImGuiWindow* docked_window); static float TabBarCalcMaxTabWidth(); static float TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling); static void TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiID tab_id, ImGuiTabBarSection* sections); @@ -9986,7 +9989,7 @@ void ImGui::TabBarRemove(ImGuiTabBar* tab_bar) g.TabBars.Remove(tab_bar->ID, tab_bar); } -bool ImGui::BeginTabBar(const char* str_id, ImGuiTabBarFlags flags) +bool ImGui::BeginTabBar(ImStrv str_id, ImGuiTabBarFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; @@ -10081,7 +10084,7 @@ void ImGui::EndTabBar() // Restore the last visible height if no tab is visible, this reduce vertical flicker/movement when a tabs gets removed without calling SetTabItemClosed(). const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount); - if (tab_bar->VisibleTabWasSubmitted || tab_bar->VisibleTabContentsId == 0 || tab_bar_appearing) + if (tab_bar->VisibleTabWasSubmitted || tab_bar->VisibleTabId == 0 || tab_bar_appearing) { tab_bar->CurrTabsContentsHeight = ImMax(window->DC.CursorPos.y - tab_bar->BarRect.Max.y, tab_bar->CurrTabsContentsHeight); window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->CurrTabsContentsHeight; @@ -10129,7 +10132,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) if (tab->LastFrameVisible < tab_bar->PrevFrameVisible || tab->WantClose) { // Remove tab - if (tab_bar->VisibleTabContentsId == tab->ID) { tab_bar->VisibleTabContentsId = 0; } + if (tab_bar->VisibleTabId == tab->ID) { tab_bar->VisibleTabId = 0; } if (tab_bar->SelectedTabId == tab->ID) { tab_bar->SelectedTabId = 0; } if (tab_bar->NextSelectedTabId == tab->ID) { tab_bar->NextSelectedTabId = 0; } continue; @@ -10334,8 +10337,8 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) scroll_to_tab_id = tab_bar->SelectedTabId = most_recently_selected_tab->ID; // Lock in visible tab - tab_bar->VisibleTabContentsId = tab_bar->SelectedTabId; - tab_bar->VisibleTabWasSubmitted = tab_bar->LastTabItemContentsAppearing = false; + tab_bar->VisibleTabId = tab_bar->SelectedTabId; + tab_bar->VisibleTabWasSubmitted = false; // Apply request requests if (scroll_to_tab_id != 0) @@ -10380,7 +10383,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) } // Dockable windows uses Name/ID in the global namespace. Non-dockable items use the ID stack. -static ImU32 ImGui::TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label, ImGuiWindow* docked_window) +static ImU32 ImGui::TabBarCalcTabID(ImGuiTabBar* tab_bar, ImStrv label, ImGuiWindow* docked_window) { IM_ASSERT(docked_window == NULL); // master branch only IM_UNUSED(docked_window); @@ -10448,9 +10451,9 @@ void ImGui::TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id) { if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id)) tab_bar->Tabs.erase(tab); - if (tab_bar->VisibleTabContentsId == tab_id){ tab_bar->VisibleTabContentsId = 0; } - if (tab_bar->SelectedTabId == tab_id) { tab_bar->SelectedTabId = 0; } - if (tab_bar->NextSelectedTabId == tab_id) { tab_bar->NextSelectedTabId = 0; } + if (tab_bar->VisibleTabId == tab_id) { tab_bar->VisibleTabId = 0; } + if (tab_bar->SelectedTabId == tab_id) { tab_bar->SelectedTabId = 0; } + if (tab_bar->NextSelectedTabId == tab_id) { tab_bar->NextSelectedTabId = 0; } } // Called on manual closure attempt @@ -10464,7 +10467,7 @@ void ImGui::TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) // This will remove a frame of lag for selecting another tab on closure. // However we don't run it in the case where the 'Unsaved' flag is set, so user gets a chance to fully undo the closure tab->WantClose = true; - if (tab_bar->VisibleTabContentsId == tab->ID) + if (tab_bar->VisibleTabId == tab->ID) { tab->LastFrameVisible = -1; tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = 0; @@ -10473,7 +10476,7 @@ void ImGui::TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) else { // Actually select before expecting closure attempt (on an UnsavedDocument tab user is expect to e.g. show a popup) - if (tab_bar->VisibleTabContentsId != tab->ID) + if (tab_bar->VisibleTabId != tab->ID) TabBarQueueFocus(tab_bar, tab); } } @@ -10729,7 +10732,7 @@ static ImGuiTabItem* ImGui::TabBarTabListPopupButton(ImGuiTabBar* tab_bar) // - TabItemLabelAndCloseButton() [Internal] //------------------------------------------------------------------------- -bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags flags) +bool ImGui::BeginTabItem(ImStrv label, bool* p_open, ImGuiTabItemFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; @@ -10764,13 +10767,7 @@ void ImGui::EndTabItem() PopID(); } -bool ImGui::TabItemIsContentsAppearing() -{ - ImGuiContext& g = *GImGui; - return g.CurrentTabBar->LastTabItemContentsAppearing; -} - -bool ImGui::TabItemButton(const char* label, ImGuiTabItemFlags flags) +bool ImGui::TabItemButton(ImStrv label, ImGuiTabItemFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; @@ -10782,7 +10779,7 @@ bool ImGui::TabItemButton(const char* label, ImGuiTabItemFlags flags) return TabItemEx(tab_bar, label, NULL, flags | ImGuiTabItemFlags_Button | ImGuiTabItemFlags_NoReorder, NULL); } -void ImGui::TabItemSpacing(const char* str_id, ImGuiTabItemFlags flags, float width) +void ImGui::TabItemSpacing(ImStrv str_id, ImGuiTabItemFlags flags, float width) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; @@ -10795,7 +10792,7 @@ void ImGui::TabItemSpacing(const char* str_id, ImGuiTabItemFlags flags, float TabItemEx(tab_bar, str_id, NULL, flags | ImGuiTabItemFlags_Button | ImGuiTabItemFlags_NoReorder | ImGuiTabItemFlags_Invisible, NULL); } -bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags, ImGuiWindow* docked_window) +bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, ImStrv label, bool* p_open, ImGuiTabItemFlags flags, ImGuiWindow* docked_window) { // Layout whole tab bar if not already done ImGuiContext& g = *GImGui; @@ -10843,7 +10840,8 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, tab_bar->LastTabItemIdx = (ImS16)tab_bar->Tabs.index_from_ptr(tab); // Calculate tab contents size - ImVec2 size = TabItemCalcSize(label, (p_open != NULL) || (flags & ImGuiTabItemFlags_UnsavedDocument)); + ImStrv label_for_display(label.Begin, FindRenderedTextEnd(label)); + ImVec2 size = TabItemCalcSize(label_for_display, (p_open != NULL) || (flags & ImGuiTabItemFlags_UnsavedDocument)); tab->RequestedWidth = -1.0f; if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasWidth) size.x = tab->RequestedWidth = g.NextItemData.Width; @@ -10867,8 +10865,10 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, } else { + char zero_c = 0; tab->NameOffset = (ImS32)tab_bar->TabsNames.size(); - tab_bar->TabsNames.append(label, label + ImStrlen(label) + 1); + tab_bar->TabsNames.append(label_for_display); + tab_bar->TabsNames.append(ImStrv(&zero_c, &zero_c + 1)); } // Update selected tab @@ -10881,24 +10881,21 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, TabBarQueueFocus(tab_bar, tab); } - // On the very first frame of a tab bar we let first tab contents be visible to minimize appearing glitches - if (tab_bar->VisibleTabContentsId == 0 && tab_bar->SelectedTabId == 0 && tab_bar_appearing) - if (tab_bar->Tabs.Size == 1 && !(tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs)) - tab_bar->VisibleTabContentsId = id; - // Lock visibility // (Note: tab_contents_visible != tab_selected... because Ctrl+Tab operations may preview some tabs without selecting them!) - const bool tab_contents_visible = (tab_bar->VisibleTabContentsId == id); + bool tab_contents_visible = (tab_bar->VisibleTabId == id); if (tab_contents_visible) tab_bar->VisibleTabWasSubmitted = true; - tab_bar->LastTabItemContentsAppearing = tab_contents_visible && !tab->ContentsIsVisible; - tab->ContentsIsVisible = tab_contents_visible; + + // On the very first frame of a tab bar we let first tab contents be visible to minimize appearing glitches + if (!tab_contents_visible && tab_bar->SelectedTabId == 0 && tab_bar_appearing) + if (tab_bar->Tabs.Size == 1 && !(tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs)) + tab_contents_visible = true; // Note that tab_is_new is not necessarily the same as tab_appearing! When a tab bar stops being submitted // and then gets submitted again, the tabs will have 'tab_appearing=true' but 'tab_is_new=false'. if (tab_appearing && (!tab_bar_appearing || tab_is_new)) { - // This path doesn't render the tab. ItemAdd(ImRect(), id, NULL, ImGuiItemFlags_NoNav); if (is_tab_button) return false; @@ -11028,7 +11025,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, // FIXME: We may want disabled tab to still display the tooltip? if (text_clipped && g.HoveredId == id && !held) if (!(tab_bar->Flags & ImGuiTabBarFlags_NoTooltip) && !(tab->Flags & ImGuiTabItemFlags_NoTooltip)) - SetItemTooltip("%.*s", (int)(FindRenderedTextEnd(label) - label), label); + SetItemTooltip("%.*s", (int)(label_for_display.End - label_for_display.Begin), label_for_display.Begin); } // Restore main window position so user can draw there @@ -11045,7 +11042,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, // [Public] This is call is 100% optional but it allows to remove some one-frame glitches when a tab has been unexpectedly removed. // To use it to need to call the function SetTabItemClosed() between BeginTabBar() and EndTabBar(). // Tabs closed by the close button will automatically be flagged to avoid this issue. -void ImGui::SetTabItemClosed(const char* label) +void ImGui::SetTabItemClosed(ImStrv label) { ImGuiContext& g = *GImGui; bool is_within_manual_tab_bar = g.CurrentTabBar && !(g.CurrentTabBar->Flags & ImGuiTabBarFlags_DockNode); @@ -11058,10 +11055,10 @@ void ImGui::SetTabItemClosed(const char* label) } } -ImVec2 ImGui::TabItemCalcSize(const char* label, bool has_close_button_or_unsaved_marker) +ImVec2 ImGui::TabItemCalcSize(ImStrv label, bool has_close_button_or_unsaved_marker) { ImGuiContext& g = *GImGui; - ImVec2 label_size = CalcTextSize(label, NULL, true); + ImVec2 label_size = CalcTextSize(label, true); ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x, label_size.y + g.Style.FramePadding.y * 2.0f); if (has_close_button_or_unsaved_marker) size.x += g.Style.FramePadding.x + (g.Style.ItemInnerSpacing.x + g.FontSize); // We use Y intentionally to fit the close button circle. @@ -11099,11 +11096,11 @@ void ImGui::TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabI // Render text label (with custom clipping) + Unsaved Document marker + Close Button logic // We tend to lock style.FramePadding for a given tab-bar, hence the 'frame_padding' parameter. -void ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id, bool is_contents_visible, bool* out_just_closed, bool* out_text_clipped) +void ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, ImStrv label, ImGuiID tab_id, ImGuiID close_button_id, bool is_contents_visible, bool* out_just_closed, bool* out_text_clipped) { ImGuiContext& g = *GImGui; - const char* label_end = FindRenderedTextEnd(label); - ImVec2 label_size = CalcTextSize(label, label_end, false); + label.End = FindRenderedTextEnd(label); + ImVec2 label_size = CalcTextSize(label, false); if (out_just_closed) *out_just_closed = false; @@ -11188,7 +11185,7 @@ void ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, } } LogSetNextTextDecoration("/", "\\"); - RenderTextEllipsis(draw_list, text_ellipsis_clip_bb.Min, text_ellipsis_clip_bb.Max, ellipsis_max_x, label, label_end, &label_size); + RenderTextEllipsis(draw_list, text_ellipsis_clip_bb.Min, text_ellipsis_clip_bb.Max, ellipsis_max_x, label, &label_size); #if 0 if (!is_contents_visible) @@ -11199,5 +11196,4 @@ void ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, *out_just_closed = close_button_pressed; } - #endif // #ifndef IMGUI_DISABLE diff --git a/imstb_rectpack.h b/imstb_rectpack.h index a80217382..ad0892130 100644 --- a/imstb_rectpack.h +++ b/imstb_rectpack.h @@ -2,7 +2,7 @@ // This is a slightly modified version of stb_rect_pack.h 1.01. // Grep for [DEAR IMGUI] to find the changes. // -// stb_rect_pack.h - v1.02 - public domain - rectangle packing +// stb_rect_pack.h - v1.01 - public domain - rectangle packing // Sean Barrett 2014 // // Useful for e.g. packing rectangular textures into an atlas. @@ -42,7 +42,6 @@ // Bugfixes / warning fixes // Jeremy Jaussaud // Fabian Giesen -// Joshua Simmons // // Version history: // @@ -534,11 +533,7 @@ static int STBRP__CDECL rect_height_compare(const void *a, const void *b) return -1; if (p->h < q->h) return 1; - if (p->w > q->w) - return -1; - if (p->w < q->w) - return 1; - return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed); + return (p->w > q->w) ? -1 : (p->w < q->w); } static int STBRP__CDECL rect_original_order(const void *a, const void *b) diff --git a/imstb_textedit.h b/imstb_textedit.h index a5b0b2687..583508f0b 100644 --- a/imstb_textedit.h +++ b/imstb_textedit.h @@ -1,15 +1,15 @@ // [DEAR IMGUI] -// This is a slightly modified version of stb_textedit.h 1.15. +// This is a slightly modified version of stb_textedit.h 1.14. // Those changes would need to be pushed into nothings/stb: // - Fix in stb_textedit_discard_redo (see https://github.com/nothings/stb/issues/321) -// - Added line movement hooks and cursor-side tracking for word-wrapping. +// - Fix in stb_textedit_find_charpos to handle last line (see https://github.com/ocornut/imgui/issues/6000 + #6783) // - Added name to struct or it may be forward declared in our code. // - Added UTF-8 support (see https://github.com/nothings/stb/issues/188 + https://github.com/ocornut/imgui/pull/7925) // - Changed STB_TEXTEDIT_INSERTCHARS() to return inserted count (instead of 0/1 bool), allowing partial insertion. // Grep for [DEAR IMGUI] to find some changes. // - Also renamed macros used or defined outside of IMSTB_TEXTEDIT_IMPLEMENTATION block from STB_TEXTEDIT_* to IMSTB_TEXTEDIT_* -// stb_textedit.h - v1.15 - public domain - Sean Barrett +// stb_textedit.h - v1.14 - public domain - Sean Barrett // Development of this library was sponsored by RAD Game Tools // // This C header file implements the guts of a multi-line text-editing @@ -40,9 +40,7 @@ // // VERSION HISTORY // -// x.xx (2026-11-12) changed STB_TEXTEDIT_INSERTCHARS() to return inserted count (instead of 0/1 bool), allowing partial insertion. -// x.xx (2026-11-12) add stb_textedit_text(), STB_TEXTEDIT_GETPREVCHARINDEX(), STB_TEXTEDIT_GETNEXTCHARINDEX() to facilitate UTF-8 support while preserving byte indices. -// 1.15 (2026-11-08) various fixes +// !!!! (2025-10-23) changed STB_TEXTEDIT_INSERTCHARS() to return inserted count (instead of 0/1 bool), allowing partial insertion. // 1.14 (2021-07-11) page up/down, various fixes // 1.13 (2019-02-07) fix bug in undo size management // 1.12 (2018-01-29) user can change STB_TEXTEDIT_KEYTYPE, fix redo to avoid crash @@ -184,12 +182,12 @@ // STB_TEXTEDIT_K_TEXTSTART2 secondary keyboard input to move cursor to start of text // STB_TEXTEDIT_K_TEXTEND2 secondary keyboard input to move cursor to end of text // -// To support UTF-8 while using indices to _bytes_ (instead of indices to _codepoints_): +// To support UTF-8: // // STB_TEXTEDIT_GETPREVCHARINDEX returns index of previous character // STB_TEXTEDIT_GETNEXTCHARINDEX returns index of next character -// Call stb_textedit_text() directly to submit text contents. // Do NOT define STB_TEXTEDIT_KEYTOTEXT. +// Instead, call stb_textedit_text() directly for text contents. // // Keyboard input must be encoded as a single integer value; e.g. a character code // and some bitflags that represent shift states. to simplify the interface, SHIFT must @@ -223,9 +221,8 @@ // void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) // int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) // int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len) -// void stb_textedit_char(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE ch) -// void stb_textedit_text(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int text_len) // void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXEDIT_KEYTYPE key) +// void stb_textedit_text(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int text_len) // // Each of these functions potentially updates the string and updates the // state. @@ -252,18 +249,6 @@ // call this to paste text at the current cursor point or over the current // selection if there is one. // -// char: -// (optional) call this for character input sent to the textfield. if the -// framework you are using supplies you with a character or text event, it -// makes sense to use this function. -// make sure to set STB_TEXTEDIT_KEYTOTEXT to 0 for any key that generates -// a corresponding character or text event. -// -// text: -// (optional) call this to directly send text input the textfield, which is -// helpful for UTF-8 support, because stb_textedit_key() + STB_TEXTEDIT_KEYTOTEXT() -// cannot infer text length. -// // key: // call this for keyboard inputs sent to the textfield. you can use it // for "key down" events or for "translated" key events. if you need to @@ -272,10 +257,15 @@ // various definitions like STB_TEXTEDIT_K_LEFT have the is-key-event bit // set, and make STB_TEXTEDIT_KEYTOCHAR check that the is-key-event bit is // clear. STB_TEXTEDIT_KEYTYPE defaults to int, but you can #define it to -// any other type you want before including. +// anything other type you want before including. // if the STB_TEXTEDIT_KEYTOTEXT function is defined, selected keys are // transformed into text and stb_textedit_text() is automatically called. // +// text: (added 2025) +// call this to directly send text input the textfield, which is required +// for UTF-8 support, because stb_textedit_key() + STB_TEXTEDIT_KEYTOTEXT() +// cannot infer text length. +// // // When rendering, you can read the cursor position and selection state from // the STB_TexteditState. @@ -423,9 +413,12 @@ typedef struct #define IMSTB_TEXTEDIT_memmove memmove #endif -// Functions must be implemented for UTF-8 support with indices to bytes. -#ifndef STB_TEXTEDIT_GETPREVCHARINDEX -#define STB_TEXTEDIT_GETPREVCHARINDEX(OBJ, IDX) ((IDX) - 1) +// [DEAR IMGUI] +// Functions must be implemented for UTF8 support +// Code in this file that uses those functions is modified for [DEAR IMGUI] and deviates from the original stb_textedit. +// There is not necessarily a '[DEAR IMGUI]' at the usage sites. +#ifndef IMSTB_TEXTEDIT_GETPREVCHARINDEX +#define IMSTB_TEXTEDIT_GETPREVCHARINDEX(OBJ, IDX) ((IDX) - 1) #endif #ifndef IMSTB_TEXTEDIT_GETNEXTCHARINDEX #define IMSTB_TEXTEDIT_GETNEXTCHARINDEX(OBJ, IDX) ((IDX) + 1) @@ -574,25 +567,36 @@ static void stb_textedit_find_charpos(StbFindState *find, IMSTB_TEXTEDIT_STRING int z = STB_TEXTEDIT_STRINGLEN(str); int i=0, first; + if (n == z && single_line) { + // special case if it's at the end (may not be needed?) + STB_TEXTEDIT_LAYOUTROW(&r, str, 0); + find->y = 0; + find->first_char = 0; + find->length = z; + find->height = r.ymax - r.ymin; + find->x = r.x1; + return; + } + // search rows to find the one that straddles character n find->y = 0; for(;;) { STB_TEXTEDIT_LAYOUTROW(&r, str, i); - - // Use the regular layout scan for EOF, including an empty final row. - // [DEAR IMGUI] At a soft-wrap boundary, the cursor side determines the row. - // A row without a newline is not necessarily the last row when word-wrapping. - if (n <= i + r.num_chars) { - if (n < i + r.num_chars || r.num_chars == 0 || single_line) - break; - if (STB_TEXTEDIT_GETCHAR(str, i + r.num_chars - 1) != STB_TEXTEDIT_NEWLINE && (n == z || str->LastMoveDirectionLR == ImGuiDir_Right)) - break; - } - + if (n < i + r.num_chars) + break; + if (str->LastMoveDirectionLR == ImGuiDir_Right && str->Stb->cursor > 0 && str->Stb->cursor == i + r.num_chars && STB_TEXTEDIT_GETCHAR(str, i + r.num_chars - 1) != STB_TEXTEDIT_NEWLINE) // [DEAR IMGUI] Wrapping point handling + break; + if (i + r.num_chars == z && z > 0 && STB_TEXTEDIT_GETCHAR(str, z - 1) != STB_TEXTEDIT_NEWLINE) // [DEAR IMGUI] special handling for last line + break; // [DEAR IMGUI] prev_start = i; i += r.num_chars; find->y += r.baseline_y_delta; + if (i == z) // [DEAR IMGUI] + { + r.num_chars = 0; // [DEAR IMGUI] + break; // [DEAR IMGUI] + } } find->first_char = first = i; @@ -785,11 +789,16 @@ static int stb_textedit_paste_internal(IMSTB_TEXTEDIT_STRING *str, STB_TexteditS return 0; } +#ifndef STB_TEXTEDIT_KEYTYPE +#define STB_TEXTEDIT_KEYTYPE int +#endif + // API key: process text input +// [DEAR IMGUI] Added stb_textedit_text(), extracted out and called by stb_textedit_key() for backward compatibility. static void stb_textedit_text(IMSTB_TEXTEDIT_STRING* str, STB_TexteditState* state, const IMSTB_TEXTEDIT_CHARTYPE* text, int text_len) { // can't add newline in single-line mode - if (text[0] == STB_TEXTEDIT_NEWLINE && state->single_line) + if (text[0] == '\n' && state->single_line) return; if (state->insert_mode && !STB_TEXT_HAS_SELECTION(state) && state->cursor < STB_TEXTEDIT_STRINGLEN(str)) { @@ -811,16 +820,6 @@ static void stb_textedit_text(IMSTB_TEXTEDIT_STRING* str, STB_TexteditState* sta } } -// API char: process a character input -static void stb_textedit_char(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, IMSTB_TEXTEDIT_CHARTYPE ch) -{ - stb_textedit_text(str, state, &ch, 1); -} - -#ifndef STB_TEXTEDIT_KEYTYPE -#define STB_TEXTEDIT_KEYTYPE int -#endif - // API key: process a keyboard input static void stb_textedit_key(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_KEYTYPE key) { @@ -828,11 +827,11 @@ retry: switch (key) { default: { #ifdef STB_TEXTEDIT_KEYTOTEXT - // This is not suitable for UTF-8 support with indices to bytes. + // This is not suitable for UTF-8 support. int c = STB_TEXTEDIT_KEYTOTEXT(key); if (c > 0) { - IMSTB_TEXTEDIT_CHARTYPE ch = (IMSTB_TEXTEDIT_CHARTYPE) c; - stb_textedit_char(str, state, ch); + IMSTB_TEXTEDIT_CHARTYPE ch = (IMSTB_TEXTEDIT_CHARTYPE)c; + stb_textedit_text(str, state, &ch, 1); } #endif break; @@ -1034,15 +1033,9 @@ retry: for (j = 0; j < row_count; ++j) { float x, goal_x = state->has_preferred_x ? state->preferred_x : find.x; - // if there's no previous row set cursor to start of the line - if (find.prev_first == find.first_char) { - state->cursor = find.first_char; - stb_textedit_clamp(str, state); - - if (sel) - state->select_end = state->cursor; + // can only go up if there's a previous row + if (find.prev_first == find.first_char) break; - } // now find character position up a row state->cursor = find.prev_first; @@ -1370,7 +1363,6 @@ static void stb_text_undo(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state) } state->cursor = u.where + u.insert_length; - state->select_start = state->select_end = state->cursor; s->undo_point--; s->redo_point--; @@ -1422,7 +1414,6 @@ static void stb_text_redo(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state) } state->cursor = r.where + r.insert_length; - state->select_start = state->select_end = state->cursor; s->undo_point++; s->redo_point++; diff --git a/imstb_truetype.h b/imstb_truetype.h index 0bc602f6c..ec4d42c7d 100644 --- a/imstb_truetype.h +++ b/imstb_truetype.h @@ -1,9 +1,9 @@ // [DEAR IMGUI] -// This is a slightly modified version of stb_truetype.h 1.27. +// This is a slightly modified version of stb_truetype.h 1.26. // Mostly fixing for compiler and static analyzer warnings. // Grep for [DEAR IMGUI] to find the changes. -// stb_truetype.h - v1.27 - public domain +// stb_truetype.h - v1.26 - public domain // authored from 2009-2021 by Sean Barrett / RAD Game Tools // // ======================================================================= @@ -50,7 +50,7 @@ // Cass Everitt Martins Mozeiko github:aloucks // stoiko (Haemimont Games) Cap Petschulat github:oyvindjam // Brian Hook Omar Cornut github:vassvik -// Walter van Niftrik Ryan Griege github:Cerallin +// Walter van Niftrik Ryan Griege // David Gow Peter LaValle // David Given Sergey Popov // Ivan-Assen Ivanov Giumo X. Clanjor @@ -59,13 +59,10 @@ // Hou Qiming Derek Vinyard // Rob Loach Cort Stratton // Kenney Phillis Jr. Brian Costabile -// Ken Voskuil (kaesve) Yakov Galka -// Neil Bickford Matthias Dorfelt -// Isaac "Atridas" Serrano +// Ken Voskuil (kaesve) // // VERSION HISTORY // -// 1.27 (2026-11-08) many fixes, support vertical layout, underlines, font name // 1.26 (2021-08-28) fix broken rasterizer // 1.25 (2021-07-11) many fixes // 1.24 (2020-02-05) fix warning @@ -209,10 +206,10 @@ // Baseline: // You need to select a y-coordinate that is the baseline of where // your text will appear. Call GetFontBoundingBox to get the baseline-relative -// bounding box for all characters. SF*y1 will be the distance in pixels +// bounding box for all characters. SF*-y0 will be the distance in pixels // that the worst-case character could extend above the baseline, so if // you want the top edge of characters to appear at the top of the -// screen where y=0, then you would set the baseline to SF*y1. +// screen where y=0, then you would set the baseline to SF*-y0. // // Current point: // Set the current point where the first character will appear. The @@ -223,10 +220,10 @@ // the current point based on that. // // Displaying a character: -// Call a function to compute the bounding box of the character. It will contain -// signed values relative to . I.e. if it returns x0,y0, -// x1,y1, then the character should be displayed in the rectangle from -// to . +// Compute the bounding box of the character. It will contain signed values +// relative to . I.e. if it returns x0,y0,x1,y1, +// then the character should be displayed in the rectangle from +// to @@ -345,10 +342,10 @@ int main(int argc, char **argv) unsigned char *bitmap; int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20); - fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb")); // fclose() omitted for clarity + fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb")); stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0)); - bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0); // stbtt_FreeBitmap() omitted for clarity + bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0); for (j=0; j < h; ++j) { for (i=0; i < w; ++i) @@ -374,7 +371,7 @@ int main(int argc, char **argv) // ////////////////////////////////////////////////////////////////////////////// // -// Complete program: print "Hello World!" banner, with bugs & no cleanup +// Complete program: print "Hello World!" banner, with bugs // #if 0 char buffer[24<<20]; @@ -628,7 +625,7 @@ typedef struct { float font_size; int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint - const int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints + int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints int num_chars; stbtt_packedchar *chardata_for_range; // output unsigned char h_oversample, v_oversample; // don't set these, they're used internally @@ -726,7 +723,7 @@ struct stbtt_fontinfo int numGlyphs; // number of glyphs, needed for range checking - int loca,head,glyf,hhea,hmtx,vhea,vmtx,kern,gpos,svg; // table locations as offset from start of .ttf + int loca,head,glyf,hhea,hmtx,kern,gpos,svg; // table locations as offset from start of .ttf int index_map; // a cmap mapping for our chosen character encoding int indexToLocFormat; // format needed to map from glyph index to glyph @@ -748,7 +745,7 @@ STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, in ////////////////////////////////////////////////////////////////////////////// // -// CHARACTER TO GLYPH-INDEX CONVERSION +// CHARACTER TO GLYPH-INDEX CONVERSIOn STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint); // If you're going to perform multiple operations on the same character @@ -771,10 +768,6 @@ STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixe // scale = pixels / (ascent - descent) // so if you prefer to measure height by the ascent only, use a similar calculation. -STBTT_DEF float stbtt_ScaleForPixelWidth(const stbtt_fontinfo *info, float pixels); -// computes a scale factor to produce a font whose width is 'pixels' wide. -// Width is measured as the distance from the left-side-bearing to the right-side-bearing - STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels); // computes a scale factor to produce a font whose EM size is mapped to // 'pixels' tall. This is probably what traditional APIs compute, but @@ -788,9 +781,6 @@ STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, in // these are expressed in unscaled coordinates, so you must multiply by // the scale factor for a given size -STBTT_DEF void stbtt_GetFontHMetrics(const stbtt_fontinfo *info, int *vertTypoAscender, int *vertTypoDescender, int *vertTypoLineGap); - - STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap); // analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2 // table (specific to MS/Windows TTF files). @@ -800,11 +790,6 @@ STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAsc STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1); // the bounding box around all possible characters -STBTT_DEF int stbtt_GetFontUnderlineMetrics(const stbtt_fontinfo *info, int *position, int *thickness); -// the underline position and thickness as defined in the "post" table -// -// Returns 1 on success (table present), 0 on failure. - STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing); // leftSideBearing is the offset from the current horizontal position to the left edge of the character // advanceWidth is the offset from the current horizontal position to the next horizontal position @@ -817,7 +802,6 @@ STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, i // Gets the bounding box of the visible part of the glyph, in unscaled coordinates STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing); -STBTT_DEF void stbtt_GetGlyphVMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceHeight, int *topSideBearing); STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2); STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); // as above, but takes one or more glyph indices for greater efficiency @@ -1059,12 +1043,9 @@ STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *l // and puts the length in bytes in *length. // // some of the values for the IDs are below; for more see the truetype spec: -// https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6name.html +// http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html // http://www.microsoft.com/typography/otspec/name.htm -STBTT_DEF int stbtt_GetFontNameDefault(const stbtt_fontinfo *font, char *output_buffer, size_t output_buffer_len); -// return the default english full name of the font as utf-8 - enum { // platformID STBTT_PLATFORM_ID_UNICODE =0, STBTT_PLATFORM_ID_MAC =1, @@ -1408,7 +1389,6 @@ static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, in { stbtt_uint32 cmap, t; stbtt_int32 i,numTables; - stbtt_uint32 symbol_map=0; info->data = data; info->fontstart = fontstart; @@ -1420,8 +1400,6 @@ static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, in info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required - info->vhea = stbtt__find_table(data, fontstart, "vhea"); // not required - info->vmtx = stbtt__find_table(data, fontstart, "vmtx"); // not required info->kern = stbtt__find_table(data, fontstart, "kern"); // not required info->gpos = stbtt__find_table(data, fontstart, "GPOS"); // not required @@ -1504,9 +1482,6 @@ static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, in // MS/Unicode info->index_map = cmap + ttULONG(data+encoding_record+4); break; - case STBTT_MS_EID_SYMBOL: - symbol_map = cmap + ttULONG(data+encoding_record+4); - break; } break; case STBTT_PLATFORM_ID_UNICODE: @@ -1516,9 +1491,6 @@ static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, in break; } } - if (info->index_map == 0) - info->index_map = symbol_map; - if (info->index_map == 0) return 0; @@ -1532,7 +1504,6 @@ STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codep stbtt_uint32 index_map = info->index_map; stbtt_uint16 format = ttUSHORT(data + index_map + 0); - if (format == 0) { // apple byte encoding stbtt_int32 bytes = ttUSHORT(data + index_map + 2); if (unicode_codepoint < bytes-6) @@ -1578,35 +1549,19 @@ STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codep search += 2; { - stbtt_uint16 offset, start, last, index; - stbtt_int16 delta; + stbtt_uint16 offset, start, last; stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1); - // get the actual range for this segment start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item); last = ttUSHORT(data + endCount + 2*item); if (unicode_codepoint < start || unicode_codepoint > last) return 0; offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item); - delta = ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item); - - // "if idRangeOffset is 0, the idDelta value is added directly to the character code" if (offset == 0) - return (stbtt_uint16) (unicode_codepoint + delta); + return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item)); - // "If the idRangeOffset value for the segment is not 0, ..." - // "glyphIndexAddress = idRangeOffset[i] + 2 * (c - startCode[i]) + (Ptr) &idRangeOffset[i]" - index = ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); - - // "Once the glyph indexing operation is complete, the glyph ID at the indicated address - // is checked. If it's not 0 (that is, if it's not the missing glyph), the value is added - // to idDelta[i] to get the actual glyph ID to use." - if (index != 0) { - index = (stbtt_uint16) (index + delta); - } - - return index; + return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); } } else if (format == 12 || format == 13) { stbtt_uint32 ngroups = ttULONG(data+index_map+12); @@ -1675,7 +1630,7 @@ static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, in STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) { if (info->cff.size) { - return stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1); + stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1); } else { int g = stbtt__GetGlyfOffset(info, glyph_index); if (g < 0) return 0; @@ -1817,8 +1772,8 @@ static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, s if (i != 0) num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); - // now start the new one... avoid looking ahead if we're at the end of a contour - start_off = !(flags & 1) && i < ttUSHORT(endPtsOfContours+j*2); + // now start the new one + start_off = !(flags & 1); if (start_off) { // if we start off with an off-curve point, then when we need to find a point on the curve // where we can start, and we need to save some state for when we wraparound. @@ -1901,35 +1856,23 @@ static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, s mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; } - // Find transformation scales. Per TrueType spec, these are used - // ONLY to rescale the offsets (mtx[4], mtx[5]) when - // SCALED_COMPONENT_OFFSET (flag bit 11, 0x800) is set. They must - // NOT scale the linear part of the transform — doing so squares - // the scale factor and is the cause of composite sub-components - // rendering at wrong sizes in COLR emoji fonts (OpenMoji, Noto - // Color Emoji, Microsoft Fluent Emoji). + // Find transformation scales. m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]); n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]); - // Default: UNSCALED offsets (Microsoft convention; matches modern - // font tooling). Only SCALED_COMPONENT_OFFSET (bit 11) set without - // UNSCALED_COMPONENT_OFFSET (bit 12) triggers the offset rescale. - if ((flags & (1<<11)) && !(flags & (1<<12))) { - mtx[4] *= m; mtx[5] *= n; - } // Get indexed glyph. comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts); if (comp_num_verts > 0) { - // Transform vertices: v' = M·v + t. No double-scaling. + // Transform vertices. for (i = 0; i < comp_num_verts; ++i) { stbtt_vertex* v = &comp_verts[i]; stbtt_vertex_type x,y; x=v->x; y=v->y; - v->x = (stbtt_vertex_type)(mtx[0]*x + mtx[2]*y + mtx[4]); - v->y = (stbtt_vertex_type)(mtx[1]*x + mtx[3]*y + mtx[5]); + v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); + v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); x=v->cx; y=v->cy; - v->cx = (stbtt_vertex_type)(mtx[0]*x + mtx[2]*y + mtx[4]); - v->cy = (stbtt_vertex_type)(mtx[1]*x + mtx[3]*y + mtx[5]); + v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); + v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); } // Append vertices. tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata); @@ -2065,7 +2008,7 @@ static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int gly start = end; } } - if (fdselector == -1) return stbtt__new_buf(NULL, 0); + if (fdselector == -1) return stbtt__new_buf(NULL, 0); // [DEAR IMGUI] fixed, see #6007 and nothings/stb#1422 return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector)); } @@ -2376,12 +2319,6 @@ STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_inde } } -STBTT_DEF void stbtt_GetGlyphVMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceHeight, int *topSideBearing) -{ - if (advanceHeight) *advanceHeight = ttSHORT(info->data + info->vmtx + 4*glyph_index); - if (topSideBearing) *topSideBearing = ttSHORT(info->data + info->vmtx + 4*glyph_index + 2); -} - STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info) { stbtt_uint8 *data = info->data + info->kern; @@ -2574,7 +2511,7 @@ static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, in data = info->data + info->gpos; if (ttUSHORT(data+0) != 1) return 0; // Major version 1 - if (ttUSHORT(data+2) > 1) return 0; // Minor version 0, or 1 + if (ttUSHORT(data+2) != 0) return 0; // Minor version 0 lookupListOffset = ttUSHORT(data+8); lookupList = data + lookupListOffset; @@ -2587,28 +2524,15 @@ static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, in stbtt_uint16 lookupType = ttUSHORT(lookupTable); stbtt_uint16 subTableCount = ttUSHORT(lookupTable + 4); stbtt_uint8 *subTableOffsets = lookupTable + 6; - if (lookupType != 2 && // Pair Adjustment Positioning Subtable - lookupType != 9) // Positioning Subtable Extension + if (lookupType != 2) // Pair Adjustment Positioning Subtable continue; for (sti=0; sti= class1Count) return 0; // malformed if (glyph2class < 0 || glyph2class >= class2Count) return 0; // malformed - valueRecordPairSizeInBytes = valueFormat1 == 68 ? 4 : 2; - class1Records = table + 16; - class2Records = class1Records + valueRecordPairSizeInBytes * (glyph1class * class2Count); - xAdvance = ttSHORT(class2Records + valueRecordPairSizeInBytes * glyph2class); + class2Records = class1Records + 2 * (glyph1class * class2Count); + xAdvance = ttSHORT(class2Records + 2 * glyph2class); return xAdvance; } else return 0; @@ -2700,10 +2617,9 @@ STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int g1, int int xAdvance = 0; if (info->gpos) - xAdvance = stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2); - - if (info->kern && xAdvance == 0) - xAdvance = stbtt__GetGlyphKernInfoAdvance(info, g1, g2); + xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2); + else if (info->kern) + xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2); return xAdvance; } @@ -2720,11 +2636,6 @@ STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepo stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing); } -STBTT_DEF void stbtt_GetCodepointVMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceHeight, int *topSideBearing) -{ - stbtt_GetGlyphVMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceHeight, topSideBearing); -} - STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap) { if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4); @@ -2732,13 +2643,6 @@ STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, in if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8); } -STBTT_DEF void stbtt_GetFontHMetrics(const stbtt_fontinfo *info, int *vertTypoAscender, int *vertTypoDescender, int *vertTypoLineGap) -{ - if (vertTypoAscender ) *vertTypoAscender = ttSHORT(info->data+info->vhea + 4); - if (vertTypoDescender) *vertTypoDescender = ttSHORT(info->data+info->vhea + 6); - if (vertTypoLineGap) *vertTypoLineGap = ttSHORT(info->data+info->vhea + 8); -} - STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap) { int tab = stbtt__find_table(info->data, info->fontstart, "OS/2"); @@ -2758,28 +2662,12 @@ STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y1 = ttSHORT(info->data + info->head + 42); } -STBTT_DEF int stbtt_GetFontUnderlineMetrics(const stbtt_fontinfo *info, int *position, int *thickness) -{ - int tab = stbtt__find_table(info->data, info->fontstart, "post"); - if (!tab) - return 0; - *position = ttSHORT(info->data + tab + 8); - *thickness = ttSHORT(info->data + tab + 10); - return 1; -} - STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height) { int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6); return (float) height / fheight; } -STBTT_DEF float stbtt_ScaleForPixelWidth(const stbtt_fontinfo *info, float width) -{ - int fwidth = ttSHORT(info->data + info->hhea + 10) - ttSHORT(info->data + info->hhea + 12); - return (float) width / fwidth; -} - STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels) { int unitsPerEm = ttUSHORT(info->data + info->head + 18); @@ -3314,8 +3202,9 @@ static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, if (y_final > y_bottom) { int denom = (x2 - (x1+1)); y_final = y_bottom; - if (denom != 0) + if (denom != 0) { // [DEAR IMGUI] Avoid div by zero (https://github.com/nothings/stb/issues/1316) dy = (y_final - y_crossing ) / denom; // if denom=0, y_final = y_crossing, so y_final <= y_bottom + } } // in second pixel, area covered by line segment found in first pixel @@ -4326,7 +4215,7 @@ STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info // rects array must be big enough to accommodate all characters in the given ranges STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) { - int i,j,k, missing_range = -1, missing_glyph = -1, return_value = 1; + int i,j,k, missing_glyph = -1, return_value = 1; // save current values int old_h_over = spc->h_oversample; @@ -4392,14 +4281,12 @@ STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const bc->xoff2 = (x0 + r->w) * recip_h + sub_x; bc->yoff2 = (y0 + r->h) * recip_v + sub_y; - if (glyph == 0) { - missing_range = i; + if (glyph == 0) missing_glyph = j; - } } else if (spc->skip_missing) { return_value = 0; } else if (r->was_packed && r->w == 0 && r->h == 0 && missing_glyph >= 0) { - ranges[i].chardata_for_range[j] = ranges[missing_range].chardata_for_range[missing_glyph]; + ranges[i].chardata_for_range[j] = ranges[i].chardata_for_range[missing_glyph]; } else { return_value = 0; // if any fail, report failure } @@ -4423,7 +4310,7 @@ STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges) { stbtt_fontinfo info; - int i, j, n, return_value; + int i, j, n, return_value; // [DEAR IMGUI] removed = 1; //stbrp_context *context = (stbrp_context *) spc->pack_info; stbrp_rect *rects; @@ -4580,7 +4467,7 @@ static int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], } } -static int stbtt__equal(float *a, float *b) +static int equal(float *a, float *b) { return (a[0] == b[0] && a[1] == b[1]); } @@ -4628,7 +4515,7 @@ static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex q1[1] = (float)y1; q2[0] = (float)x2; q2[1] = (float)y2; - if (stbtt__equal(q0,q1) || stbtt__equal(q1,q2)) { + if (equal(q0,q1) || equal(q1,q2)) { x0 = (int)verts[i-1].x; //-V1048 y0 = (int)verts[i-1].y; //-V1048 x1 = (int)verts[i ].x; @@ -4705,13 +4592,8 @@ STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float sc stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f,0.0f, &ix0,&iy0,&ix1,&iy1); // if empty, return NULL - if (ix0 == ix1 || iy0 == iy1) { - if (width) *width = 0; - if (height) *height = 0; - if (xoff) *xoff = 0; - if (yoff) *yoff = 0; + if (ix0 == ix1 || iy0 == iy1) return NULL; - } ix0 -= padding; iy0 -= padding; @@ -4730,8 +4612,6 @@ STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float sc scale_y = -scale_y; { - // distance from singular values (in the same units as the pixel grid) - const float eps = 1./1024, eps2 = eps*eps; int x,y,i,j; float *precompute; stbtt_vertex *verts; @@ -4744,15 +4624,15 @@ STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float sc float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y; float x1 = verts[j].x*scale_x, y1 = verts[j].y*scale_y; float dist = (float) STBTT_sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)); - precompute[i] = (dist < eps) ? 0.0f : 1.0f / dist; + precompute[i] = (dist == 0) ? 0.0f : 1.0f / dist; } else if (verts[i].type == STBTT_vcurve) { float x2 = verts[j].x *scale_x, y2 = verts[j].y *scale_y; float x1 = verts[i].cx*scale_x, y1 = verts[i].cy*scale_y; float x0 = verts[i].x *scale_x, y0 = verts[i].y *scale_y; float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2; float len2 = bx*bx + by*by; - if (len2 >= eps2) - precompute[i] = 1.0f / len2; + if (len2 != 0.0f) + precompute[i] = 1.0f / (bx*bx + by*by); else precompute[i] = 0.0f; } else @@ -4817,8 +4697,8 @@ STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float sc float a = 3*(ax*bx + ay*by); float b = 2*(ax*ax + ay*ay) + (mx*bx+my*by); float c = mx*ax+my*ay; - if (STBTT_fabs(a) < eps2) { // if a is 0, it's linear - if (STBTT_fabs(b) >= eps2) { + if (a == 0.0) { // if a is 0, it's linear + if (b != 0.0) { res[num++] = -c/b; } } else { @@ -4968,126 +4848,6 @@ STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *l return NULL; } -// convert utf16 to utf8 and return the length required to output NUL-terminated; buffer_len of 0 means to just query length -// if you pass a buffer that's too small, it'll NULL terminate and return the actual length computed -STBTT_DEF int stbtt__ConvertUTF16BEtoUTF8(char *buffer, size_t buffer_len, unsigned char *src, size_t src_len_raw) -{ - int src_len = (int) src_len_raw; - int write_max = 0; - int i = 0, write, off = 0; - write = (buffer_len != 0); - write_max = (int) (buffer_len-1); - - if ((size_t) src_len != src_len_raw) - return -1; - - if (write) { - if (write_max < 0 || ((size_t) write_max+1 != buffer_len && write_max != 0)) - return -1; - } - - if (buffer_len == 1) { - buffer[0] = 0; - return 1; - } - - while (off < src_len) { - stbtt_uint16 ch = src[off+0]*256 + src[off+1]; - off += 2; - if (ch < 0x80) { - if (write) { - if (i >= write_max) { buffer[i] = 0; return i+1; } - buffer[i] = (char) ch; - } - ++i; - } else if (ch < 0x800) { - if (write) { - if (i+1 >= write_max) { buffer[i] = 0; return i+1; } - buffer[i+0] = (char) ( 0xc0 + (ch >> 6) ); - buffer[i+1] = (char) ( 0x80 + (ch & 0x3f) ); - } - i += 2; - } else if (ch >= 0xd800 && ch < 0xdc00) { - stbtt_uint32 c; - stbtt_uint16 ch2 = src[off+0]*256 + src[off+1]; - off += 2; - if (write) { - if (i+3 >= write_max) { buffer[i] = 0; return i+1; } - c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000; - buffer[i+0] = (char) ( 0xf0 + (c >> 18) ); - buffer[i+1] = (char) ( 0x80 + ((c >> 12) & 0x3f) ); - buffer[i+2] = (char) ( 0x80 + ((c >> 6) & 0x3f) ); - buffer[i+3] = (char) ( 0x80 + ((c ) & 0x3f) ); - } - i += 4; - } else if (ch >= 0xdc00 && ch < 0xe000) { - if (write) - buffer[i] = 0; - return -1; - } else { - if (write) { - if (i+2 >= write_max) { buffer[i] = 0; return i+1; } - buffer[i+0] = (char) ( 0xe0 + (ch >> 12) ); - buffer[i+1] = (char) ( 0x80 + ((ch >> 6) & 0x3f) ); - buffer[i+2] = (char) ( 0x80 + ((ch ) & 0x3f) ); - } - i += 3; - } - } - if (write) { - STBTT_assert(i <= write_max); - buffer[i] = 0; - } - return i+1; -} - -// Returns the english full name of the font as UTF-8 -STBTT_DEF int stbtt_GetFontNameDefault(const stbtt_fontinfo *font, char *buffer, size_t buffer_len) -{ - stbtt_int32 i,count,stringOffset; - stbtt_uint8 *fc = font->data; - stbtt_uint32 offset = font->fontstart; - stbtt_uint32 nm = stbtt__find_table(fc, offset, "name"); - if (!nm) return -1; - - count = ttUSHORT(fc+nm+2); - stringOffset = nm + ttUSHORT(fc+nm+4); - for (i=0; i < count; ++i) { - char* str; - stbtt_uint16 platformId; - stbtt_uint16 encodingId; - stbtt_uint16 languageId; - size_t length; - stbtt_uint32 loc = nm + 6 + 12 * i; - if (ttUSHORT(fc+loc+6) != 4) continue; - platformId = ttUSHORT(fc+loc+0); - encodingId = ttUSHORT(fc+loc+2); - languageId = ttUSHORT(fc+loc+4); - if (!(platformId == STBTT_PLATFORM_ID_MAC && languageId == STBTT_MAC_LANG_ENGLISH) && !(platformId == STBTT_PLATFORM_ID_MICROSOFT && languageId == STBTT_MS_LANG_ENGLISH)) - continue; - - length = ttUSHORT(fc+loc+8); - str = (char *) (fc+stringOffset+ttUSHORT(fc+loc+10)); - if (platformId == STBTT_PLATFORM_ID_UNICODE || (platformId == STBTT_PLATFORM_ID_MICROSOFT && (encodingId == 1 || encodingId == 10))) //-V560 - return stbtt__ConvertUTF16BEtoUTF8(buffer, buffer_len, (unsigned char *) str, length); - else { - if (buffer == NULL) - return (int) length; - - if (length < buffer_len) { - memcpy(buffer, str, length); - buffer[length] = 0; - return (int) length; - } else { - memcpy(buffer, str, buffer_len-1); - buffer[buffer_len-1] = 0; - return (int) length; - } - } - } - return -1; -} - static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id) { stbtt_int32 i; diff --git a/misc/debuggers/imgui.natvis b/misc/debuggers/imgui.natvis index 13b636008..8dbc7eacf 100644 --- a/misc/debuggers/imgui.natvis +++ b/misc/debuggers/imgui.natvis @@ -51,6 +51,12 @@ More information at: https://docs.microsoft.com/en-us/visualstudio/debugger/crea + + + {Begin,[End-Begin]s8} ({End-Begin,d}) + Begin,[End-Begin]s8 + + {{Name {Name,s} Active {(Active||WasActive)?1:0,d} Child {(Flags & 0x01000000)?1:0,d} Popup {(Flags & 0x04000000)?1:0,d} Hidden {(Hidden)?1:0,d}} diff --git a/misc/debuggers/imgui_lldb.py b/misc/debuggers/imgui_lldb.py index 7d3c6bfcb..790669add 100644 --- a/misc/debuggers/imgui_lldb.py +++ b/misc/debuggers/imgui_lldb.py @@ -91,6 +91,35 @@ class ImRectSummary(object): return f"Min=({minX}, {minY}) Max=({maxX}, {maxY}) Size=({maxX - minX}, {maxY - minY})" +class ImStrvSummary(object): + def __init__(self, valobj, internal_dict): + self.valobj = valobj + + def update(self): + pass + + def get_summary(self): + begin = self.valobj.GetChildMemberWithName("Begin").GetValueAsUnsigned() + end = self.valobj.GetChildMemberWithName("End").GetValueAsUnsigned() + + if begin == 0: + return "" + + if end < begin: + return "" + + error = lldb.SBError() + data = self.valobj.GetProcess().ReadMemory(begin, end - begin, error) + + if not error.Success(): + return "" + + # Turn the byte sequence into utf-8, escape non-printables + data = data.decode("utf-8", errors="backslashreplace") + data = repr(data)[1:-1] + + return f'"{data}"' + def get_active_enum_flags(valobj): flag_set = set() @@ -187,3 +216,4 @@ def __lldb_init_module(debugger, internal_dict): add_summary("^ImVec4$", "x=${var.x} y=${var.y} z=${var.z} w=${var.w}") add_summary("^ImRect$", ImRectSummary) add_summary("^ImGuiWindow$", ImGuiWindowSummary) + add_summary("^ImStrv", ImStrvSummary) diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index d0d6b8950..975374554 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -295,7 +295,7 @@ static void ImGui_ImplFreeType_BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* d case FT_PIXEL_MODE_BGRA: { // FIXME: Converting pre-multiplied alpha to straight. Doesn't smell good. - #define DE_MULTIPLY(color, alpha) (ImU32)ImMin(255.0f * (float)color / (float)(alpha + FLT_MIN) + 0.5f, 255.0f) + #define DE_MULTIPLY(color, alpha) ImMin((ImU32)(255.0f * (float)color / (float)(alpha + FLT_MIN) + 0.5f), 255u) for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) for (uint32_t x = 0; x < w; x++) {